Files
cleveragents-core/docs/development/agent-system-specification.md
T
clever-agent c29975de8f docs(spec): thirteenth pass documenting body template field enforcement
- Added v1.28.0: all 18 status-creating agents now have Estimated Cycle Interval
  in their actual body templates, not just in reference notes
2026-04-10 16:15:44 -04:00

201 KiB
Raw Blame History

CleverAgents Autonomous Development Agent System Specification

!!! abstract "Purpose"

This document is the **authoritative specification** for the CleverAgents autonomous development agent system. It describes, in precise natural language, the intended behavior, interactions, permissions, workflows, coordination mechanisms, and design rationale for every agent that participates in the automated development lifecycle. This specification serves as the **source of truth** from which agent definition files (`.opencode/agents/*.md`) are derived; when an agent's behavior diverges from this document, this document is correct and the agent definition must be updated.

!!! warning "Normative Status"

All statements in this document are **normative** unless explicitly marked otherwise. The words "must", "shall", and "will" indicate mandatory behavior. The words "should" and "may" indicate recommended and optional behavior respectively.

1. System Overview

1.1 Design Philosophy

The CleverAgents autonomous development system is a multi-agent architecture that builds software products end-to-end with minimal human intervention. It is designed around five foundational principles:

  1. Pool-Supervisor Parallelism: A single top-level orchestrator (the Product Builder) launches exactly eighteen long-running supervisor agents. Each supervisor manages its own pool of workers internally, creating a two-tier hierarchy that eliminates batch-and-wait bottlenecks.

  2. Forgejo-Centric Coordination: All inter-agent coordination occurs exclusively through the Forgejo issue tracker. Agents never pass data directly to one another; instead, they read and write Forgejo issues, pull requests, comments, and labels. This makes the system inherently crash-recoverable because the entire state is persisted in Forgejo.

  3. Clone Isolation: No agent ever modifies the primary working directory (/app). Every agent that touches the filesystem creates an isolated clone in /tmp/, works within it, pushes results to the remote, and deletes the clone on exit. This prevents conflicts between parallel agents.

  4. Progressive Escalation: Implementation work begins with the cheapest viable model tier (Haiku) and automatically escalates through Codex, Sonnet, and Opus as failures accumulate. This optimizes cost while ensuring complex tasks eventually receive sufficient reasoning power.

  5. Automation Tracking: Every supervisor creates structured tracking issues on Forgejo with standardized prefixes and cycle numbers. These issues serve as health signals, coordination points, and an audit trail.

1.2 Architecture Diagram

The following diagram illustrates the complete agent hierarchy, showing how the Product Builder launches supervisors, how supervisors launch workers, and how agents coordinate through Forgejo.

blockdiag {
  orientation = portrait;
  node_width = 200;
  node_height = 60;

  group {
    label = "Tier 0: Orchestrator";
    color = "#E8F5E9";
    "Product Builder";
  }

  group {
    label = "Tier 1: Pool Supervisors (7)";
    color = "#E3F2FD";
    "Implementation Pool" [color = "#1565C0", textcolor = "#fff"];
    "PR Review Pool" [color = "#1565C0", textcolor = "#fff"];
    "PR Fix Pool" [color = "#1565C0", textcolor = "#fff"];
    "PR Merge" [color = "#1565C0", textcolor = "#fff"];
    "UAT Test Pool" [color = "#1565C0", textcolor = "#fff"];
    "Bug Hunt Pool" [color = "#1565C0", textcolor = "#fff"];
    "Test Infra Pool" [color = "#1565C0", textcolor = "#fff"];
  }

  group {
    label = "Tier 1: Singleton Supervisors (11)";
    color = "#FFF3E0";
    "Architecture" [color = "#E65100", textcolor = "#fff"];
    "Epic Planning" [color = "#E65100", textcolor = "#fff"];
    "Human Liaison" [color = "#E65100", textcolor = "#fff"];
    "Agent Evolution" [color = "#E65100", textcolor = "#fff"];
    "Architecture Guard" [color = "#E65100", textcolor = "#fff"];
    "Spec Evolution" [color = "#E65100", textcolor = "#fff"];
    "Backlog Grooming" [color = "#E65100", textcolor = "#fff"];
    "Documentation" [color = "#E65100", textcolor = "#fff"];
    "Timeline Updates" [color = "#E65100", textcolor = "#fff"];
    "Project Owner" [color = "#E65100", textcolor = "#fff"];
    "System Watchdog" [color = "#E65100", textcolor = "#fff"];
  }

  group {
    label = "Tier 2: Workers";
    color = "#FCE4EC";
    "Implementation Worker\n(issue-impl mode)" [color = "#C62828", textcolor = "#fff"];
    "Implementation Worker\n(pr-fix mode)" [color = "#C62828", textcolor = "#fff"];
    "PR Reviewer" [color = "#C62828", textcolor = "#fff"];
    "UAT Worker" [color = "#C62828", textcolor = "#fff"];
    "Bug Hunter Worker" [color = "#C62828", textcolor = "#fff"];
    "Test Infra Worker" [color = "#C62828", textcolor = "#fff"];
  }

  group {
    label = "Tier 3: Specialized Subagents";
    color = "#F3E5F5";
    "Implementer" [color = "#6A1B9A", textcolor = "#fff"];
    "Behave Tester" [color = "#6A1B9A", textcolor = "#fff"];
    "Robot Tester" [color = "#6A1B9A", textcolor = "#fff"];
    "Lint Fixer" [color = "#6A1B9A", textcolor = "#fff"];
    "Typecheck Fixer" [color = "#6A1B9A", textcolor = "#fff"];
    "Test Fixer" [color = "#6A1B9A", textcolor = "#fff"];
    "Coverage Improver" [color = "#6A1B9A", textcolor = "#fff"];
    "Unit Test Runner" [color = "#6A1B9A", textcolor = "#fff"];
    "Integration Test Runner" [color = "#6A1B9A", textcolor = "#fff"];
    "ASV Benchmarker" [color = "#6A1B9A", textcolor = "#fff"];
  }

  "Product Builder" -> "Implementation Pool";
  "Product Builder" -> "PR Review Pool";
  "Product Builder" -> "PR Fix Pool";
  "Product Builder" -> "PR Merge";
  "Product Builder" -> "UAT Test Pool";
  "Product Builder" -> "Bug Hunt Pool";
  "Product Builder" -> "Test Infra Pool";
  "Product Builder" -> "Architecture";
  "Product Builder" -> "Epic Planning";
  "Product Builder" -> "Human Liaison";
  "Product Builder" -> "Agent Evolution";
  "Product Builder" -> "Architecture Guard";
  "Product Builder" -> "Spec Evolution";
  "Product Builder" -> "Backlog Grooming";
  "Product Builder" -> "Documentation";
  "Product Builder" -> "Timeline Updates";
  "Product Builder" -> "Project Owner";
  "Product Builder" -> "System Watchdog";

  "Implementation Pool" -> "Implementation Worker\n(issue-impl mode)";
  "PR Review Pool" -> "PR Reviewer";
  "PR Fix Pool" -> "Implementation Worker\n(pr-fix mode)";
  "UAT Test Pool" -> "UAT Worker";
  "Bug Hunt Pool" -> "Bug Hunter Worker";
  "Test Infra Pool" -> "Test Infra Worker";

  "Implementation Worker\n(issue-impl mode)" -> "Implementer";
  "Implementation Worker\n(issue-impl mode)" -> "Behave Tester";
  "Implementation Worker\n(issue-impl mode)" -> "Robot Tester";
  "Implementation Worker\n(issue-impl mode)" -> "Lint Fixer";
  "Implementation Worker\n(issue-impl mode)" -> "Typecheck Fixer";
  "Implementation Worker\n(issue-impl mode)" -> "Test Fixer";
  "Implementation Worker\n(issue-impl mode)" -> "Coverage Improver";
  "Implementation Worker\n(issue-impl mode)" -> "Unit Test Runner";
  "Implementation Worker\n(issue-impl mode)" -> "Integration Test Runner";
}

1.3 Worker Allocation Tiers

The system allocates parallel workers according to a tiered formula derived from the environment variable CA_MAX_PARALLEL_WORKERS (denoted N, default 4):

Tier Formula Supervisors Rationale
Full (N) N Implementation Pool Closes issues; maximum throughput needed
Half (N/2) max(1, N // 2) PR Review Pool Must keep pace with implementation but not 1:1
Quarter (N/4) max(1, N // 4) PR Fix, UAT Test, Bug Hunt, Test Infra Discovery/fix agents; capping prevents scope explosion
Singleton 1 All other 12 supervisors (11 named + PR Merge) Strategic work requiring single-threaded coherence

!!! note "PR Merge Dual Categorization"

The PR Merge Pool Supervisor is grouped under "Pool Supervisors" in Section 6 because it polls a queue of PRs (like other pool supervisors). However, for capacity purposes it operates as a singleton: it does not dispatch separate workers but performs merges itself. The capacity table counts it under Singletons (12 = 11 named singletons from Section 7 + PR Merge from Section 8.3).

Capacity examples:

N Implementation PR Review PR Fix UAT Bug Hunt Test Infra Singletons Total
4 4 2 1 1 1 1 12 22
8 8 4 2 2 2 2 12 32
16 16 8 4 4 4 4 12 52

2. Agent Definition Format

Every agent in the system is defined by a single markdown file in .opencode/agents/. This section specifies the file format so that new agents can be created from this specification alone.

2.1 File Structure

Each agent definition file has two parts:

  1. YAML Frontmatter — enclosed between --- delimiters at the top of the file. Contains metadata and permissions.
  2. Markdown Body — everything after the closing ---. This is the agent's system prompt: the instructions the LLM receives when the agent is invoked.

2.2 Frontmatter Schema

Field Type Required Default Description
description string Yes Brief description of the agent's purpose. Shown in agent selection UI.
mode enum No all primary (user-invocable only), subagent (programmatic-only), all (both)
model string No (system default) LLM model in provider/model-id format (e.g., anthropic/claude-sonnet-4-6, openai/gpt-5-codex, google/gemini-2.5-pro)
temperature float No (system default) Response randomness, 0.0 (deterministic) to 1.0 (creative)
color string No Hex color (e.g., "#1565C0") or theme color name (e.g., primary, info, warning)
hidden boolean No false If true, agent is hidden from the user-facing selection UI. Used for subagents.
permission object No (all allowed) Tool access control block (see Section 4.3)

2.3 Permission Block Syntax

The permission block controls which tools the agent may use. Each top-level key is a tool category:

permission:
  edit: allow | deny                # File editing tool
  bash:
    "*": allow | deny               # Default for all bash commands
    "pattern": allow | deny         # Glob pattern override
  task:
    "*": allow | deny               # Default for all subagent calls
    "agent-name": allow | deny      # Specific subagent override
  forgejo:
    "*": allow | deny               # Default for all Forgejo MCP tools
    "tool_name": allow | deny       # Specific tool override
  webfetch: allow | deny            # Internet access

Evaluation order: Specific patterns override the wildcard "*". More specific patterns override less specific ones. Deny takes precedence when ambiguous.

Bash glob patterns: Bash permissions use shell glob matching against the full command string. For example, "sleep *": allow permits any command starting with sleep.

Common permission patterns used across all agents:

# Universal label creation prohibition (every agent must have these)
bash:
  "*api/v1/orgs/*/labels*": deny
  "*api/v1/repos/*/labels*": deny
forgejo:
  "forgejo_create_label": deny
  "forgejo_create_org_label": deny
  "forgejo_create_repo_label": deny
  "forgejo_add_issue_labels": deny   # Label APPLICATION delegated to Label Manager

2.4 Markdown Body as System Prompt

The markdown body is sent to the LLM as the system prompt. It should contain:

  1. Role description: What the agent is and what it does
  2. Repository context: Owner, repo name (typically cleveragents/cleveragents-core)
  3. Credential handling: How to access environment variables
  4. Behavioral rules: MUST/NEVER/ALWAYS constraints in bold or ALL CAPS
  5. Workflow pseudocode: Step-by-step algorithms for the agent's main loop
  6. Error handling: Recovery protocols for expected failure modes
  7. Output format: What the agent returns to its caller
  8. Signature block: The bot signature template (Section 5.7)

Inherited model pattern: Some agents (all specialists in Tier 3) omit the model field. They inherit the model from their tier selector caller. The spec notes these as "(inherited)" in Appendix A.

2.4 Directory Layout

.opencode/
├── agents/
│   ├── config/
│   │   ├── models.yaml       # Aspirational model-tier assignments (Section 20.2)
│   │   └── resources.yaml    # Worker allocation, timeouts, retry policies
│   ├── shared/               # Reusable protocol modules (Section 13)
│   │   ├── coordination_protocols.md
│   │   ├── credential_security.md
│   │   ├── error_handling.md
│   │   ├── logging.md
│   │   ├── merge_safety.md
│   │   ├── performance_monitoring.md
│   │   ├── session_state.md
│   │   ├── tracking_discovery_guide.md
│   │   └── bug_hunter_tracking_update.md
│   ├── <agent-name>.md       # Active agent definitions (79 files)
│   └── <deprecated-name>.md  # Deprecated stubs (15 files, Section 17)
├── scripts/                  # Historical migration utilities (not active)
│   ├── apply_tracking_updates.py
│   ├── update_tracking_agents.sh
│   └── validate_remediation.sh
└── .gitignore                # Excludes node_modules, package.json, lock files

Active agent files: 79 files containing YAML frontmatter and system prompts. Deprecated stubs: 15 files containing only a deprecation notice; they exist to prevent OpenCode from displaying "agent not found" errors for old invocations. Shared modules: 9 files that define reusable protocols (coordination, credentials, error handling, logging, merge safety, monitoring, session state, tracking coordination, and a bug hunter tracking migration note). Config files: 2 YAML files that serve as aspirational reference (Section 20.2). Scripts: 3 historical utility scripts from the tracking system migration; not part of the active agent system.


3. Glossary of Key Terms

Term Definition
OpenCode The AI agent execution platform that hosts and runs all agents. Provides session management, tool access, and the prompt_async API at localhost:4096.
Forgejo Self-hosted Git forge (similar to GitHub/GitLab) used for source control, issue tracking, PR management, and inter-agent coordination. All state is persisted here.
MCP Model Context Protocol. The standard protocol through which agents access external tools (Forgejo API, filesystem, etc.) via MCP tool adapters.
nox Python task runner (similar to tox/make). All build, test, lint, and typecheck commands must be routed through nox sessions. Defined in noxfile.py.
Behave Python BDD (Behavior-Driven Development) testing framework using Gherkin syntax (Given/When/Then). Used for all unit tests in features/.
Robot Framework Keyword-driven integration testing framework. Used for all integration tests in robot/. No mocking allowed.
ASV Airspeed Velocity. Python benchmarking framework. Performance benchmarks live in benchmarks/.
Pyright Static type checker for Python. Used via nox -e typecheck. No # type: ignore comments allowed.
Commitizen Tool enforcing Conventional Changelog commit message format (e.g., feat(module): description).
Kroki Diagram rendering service. Used in mkdocs documentation for blockdiag, activitydiag, and PlantUML diagrams.
HAL9000 The shared Forgejo bot account used by all automated agents. Named after the AI from 2001: A Space Odyssey.
Pool Supervisor A long-running agent that manages a pool of parallel workers, dispatching and monitoring them.
Singleton Supervisor A long-running agent that performs its work directly without spawning workers.
Progressive Escalation The pattern of starting work at the cheapest model tier and automatically promoting to more expensive tiers on failure.
Tracking Issue A Forgejo issue with the Automation Tracking label, created by supervisors to report status and coordinate.
Announcement Issue A persistent Forgejo issue used for cross-agent communication of important events.

4. Asynchronous Execution Model

4.1 Why prompt_async

The system uses the OpenCode Server HTTP API's prompt_async endpoint rather than the synchronous Task tool for launching supervisors. The reason is fundamental: the Task tool blocks the calling agent until the subagent completes. Since supervisors are designed to run indefinitely (they are services, not batch jobs), launching eighteen supervisors via the Task tool would block the Product Builder forever, eliminating its ability to monitor, detect failures, or re-launch dead supervisors.

The prompt_async endpoint (POST /session/:id/prompt_async) sends a message to a session without waiting for the response, returning 204 No Content immediately. This gives true fire-and-forget semantics. The Product Builder then enters a bash-driven monitoring loop, polling session status every sixty seconds and re-launching any dead supervisor instantly.

4.2 The Async Agent Manager

All asynchronous operations are centralized through a single agent: the Async Agent Manager. This agent is the only component in the system permitted to make direct HTTP calls to the OpenCode Server API at localhost:4096. All other agents that need to launch, monitor, or clean up asynchronous sessions must invoke the Async Agent Manager as a subagent.

This centralization exists for three reasons:

  1. Security: Restricting direct API access to a single agent prevents accidental or malicious session manipulation by other agents.
  2. Consistency: Session naming conventions, tag prefixes, retry logic, and error handling are implemented in one place.
  3. Debuggability: All async operations flow through a single audit point.

The Async Agent Manager supports the following operations:

  • Start Async Agent: Creates a session with tagged naming ([TAG] display-name), launches the agent asynchronously, and returns the session ID.
  • Get Session Status: Returns the status of a specific session, sessions matching a tag pattern, or all sessions.
  • Get Session Messages: Retrieves recent messages from a session with pagination support.
  • Search Sessions: Searches sessions by tag, agent type, status, or age.
  • Close/Cleanup Session: Terminates sessions gracefully or forcefully.
  • Monitor Session Health: Detects idle, stuck, or finished sessions with configurable thresholds.

4.2.1 Session Naming Convention

Every session created through the Async Agent Manager follows a strict naming convention:

[TAG] display-name

The registered tag prefixes are:

Tag Agent Purpose
AUTO-IMP-SUP implementation-pool-supervisor Implementation pool supervisor
AUTO-REV-SUP pr-review-pool-supervisor PR review pool supervisor
AUTO-PRFIX-SUP pr-fix-pool-supervisor PR fix pool supervisor
AUTO-PRMRG-SUP pr-merge-pool-supervisor PR merge pool supervisor
AUTO-UAT-SUP uat-test-pool-supervisor UAT testing pool supervisor
AUTO-BUG-SUP bug-hunt-pool-supervisor Bug hunting pool supervisor
AUTO-INF-SUP test-infra-pool-supervisor Test infrastructure pool supervisor
AUTO-ARCH architecture-pool-supervisor Architecture designer
AUTO-EPIC epic-planning-pool-supervisor Epic planner
AUTO-HUMAN human-liaison-pool-supervisor Human liaison
AUTO-EVLV agent-evolution-pool-supervisor Agent evolver
AUTO-GUARD architecture-guard-pool-supervisor Architecture guard
AUTO-SPEC spec-update-pool-supervisor Specification updater
AUTO-BLOG backlog-grooming-pool-supervisor Backlog groomer
AUTO-DOCS documentation-pool-supervisor Documentation writer
AUTO-TIME timeline-update-pool-supervisor Timeline updater
AUTO-OWNR project-owner-pool-supervisor Project owner/triager
AUTO-WDOG system-watchdog-pool-supervisor System watchdog
AUTO-MERGE pr-merge-pool-supervisor PR merge supervisor
AUTO-ONEOFF (various) One-off dispatched agents
AUTO-IMP implementation-worker Implementation worker
AUTO-REV pr-reviewer PR reviewer worker
AUTO-UAT uat-test-pool-supervisor (worker mode) UAT test worker
AUTO-BUG bug-hunt-pool-supervisor (worker mode) Bug hunt worker
AUTO-INF test-infra-pool-supervisor (worker mode) Test infra worker

4.3 The Monitoring Loop

After launching all eighteen supervisors, the Product Builder enters its monitoring loop, which constitutes ninety-nine percent of its runtime. The loop executes the following steps on each iteration:

  1. Sleep sixty seconds using bash("sleep 60", timeout=120000). This is a genuine blocking wait; the Product Builder genuinely pauses.

  2. Query session status for all supervisor sessions via the Async Agent Manager.

  3. Detect dead supervisors by comparing recorded session IDs against active sessions. Any supervisor whose session has completed, errored, or disappeared is immediately re-launched using the same parameters.

  4. Deep inspection of pool supervisors (every five heartbeats): read the last messages from each pool supervisor's session to verify it is actively dispatching workers, not merely sleeping in an infinite loop.

  5. Convergence check (every ten cycles, approximately ten minutes): query Forgejo to assess whether all milestones are complete. If so, invoke the Product Verifier to confirm completion.

  6. Session state persistence (every ten cycles): update the automation tracking issue with current status.

activitydiag {
  "Launch 18 Supervisors" -> "Sleep 60s";
  "Sleep 60s" -> "Query Session Status";
  "Query Session Status" -> "Any Dead?";
  "Any Dead?" -> "Re-launch Dead" [label = "yes"];
  "Any Dead?" -> "Deep Inspection Due?" [label = "no"];
  "Re-launch Dead" -> "Deep Inspection Due?";
  "Deep Inspection Due?" -> "Inspect Pool Supervisors" [label = "every 5 cycles"];
  "Deep Inspection Due?" -> "Convergence Check Due?" [label = "not yet"];
  "Inspect Pool Supervisors" -> "Convergence Check Due?";
  "Convergence Check Due?" -> "Check All Milestones" [label = "every 10 cycles"];
  "Convergence Check Due?" -> "Update Tracking" [label = "not yet"];
  "Check All Milestones" -> "Product Complete?";
  "Product Complete?" -> "Final Report & Exit" [label = "COMPLETE"];
  "Product Complete?" -> "Update Tracking" [label = "INCOMPLETE"];
  "Update Tracking" -> "Sleep 60s";
}

5. Automation Tracking System

5.1 Overview

Every supervisor in the system creates automation tracking issues on Forgejo to report its status, announce important events, and coordinate with other agents. This system replaces direct inter-agent communication with a persistent, auditable, crash-recoverable coordination mechanism.

All tracking operations are centralized through the Automation Tracking Manager subagent. No agent creates or manages tracking issues directly; they all delegate to this centralized manager to ensure consistency.

5.2 Status Issues

Status issues are periodic health reports. Every supervisor and the Product Builder creates exactly one open status issue at a time. The title format is:

[AGENT-PREFIX] Status: <Tracking Type> (Cycle N)

The Status: prefix is mandatory — it distinguishes status issues from announcement issues.

Examples:

  • [AUTO-PROD-BLDR] Status: Product Builder Status (Cycle 3)
  • [AUTO-IMP-POOL] Status: Implementation Pool Tracking (Cycle 12)
  • [AUTO-WATCHDOG] Status: System Health Report (Cycle 7)

Required labels: Automation Tracking. Status issues do NOT carry priority labels (they are routine health reports, not events requiring attention).

5.2.1 Status Issue Lifecycle: One-at-a-Time Protocol

!!! danger "Critical Invariant"

At any point in time, each supervisor MUST have **at most one** open status issue. The Product Builder also maintains exactly one. Workers do not create status issues.

Every cycle, the creating agent MUST:

  1. Close ALL existing status issues from itself — not just the "previous" one, but every open issue whose title starts with [{PREFIX}] Status:. This catches orphaned status issues from previous sessions, crashed agents, or any other source. The search MUST use state: "open" and labels: "Automation Tracking" with no pagination limits.

  2. Only after ALL are closed, create the new status issue with the next cycle number.

This two-step protocol (close-all-then-create) is implemented in the Automation Tracking Manager's CREATE_TRACKING_ISSUE operation. The ATM closes orphaned issues by posting a comment "Superseded by Cycle N" and then closing them via forgejo_issue_state_change.

Why close-all? Agents crash, sessions restart, and the OpenCode server may recycle. A new session has no memory of what its predecessor created. By unconditionally closing ALL open status issues matching its prefix, an agent guarantees the one-at-a-time invariant even after crashes, restarts, or duplicate launches.

5.3 Announcement Issues

Announcement issues are event-driven notifications that persist until explicitly resolved. They represent conditions or events that other agents (and humans) should be aware of. The title format is:

[AGENT-PREFIX] Announce: <message summary>

Examples:

  • [AUTO-WATCHDOG] Announce: Quality Gate Violation
  • [AUTO-IMP-POOL] Announce: Worker Capacity Alert
  • [AUTO-ARCH] Announce: Spec Change Required

Required labels: Automation Tracking plus a priority label indicating severity:

  • Priority/Critical — requires immediate attention from all agents
  • Priority/High — affects multiple agents, should be read promptly
  • Priority/Medium — informational, should be read on next cycle
  • Priority/Low — background information, read when convenient

5.3.1 Announcement Issue Lifecycle

Announcements differ from status issues in three ways:

  1. They persist across cycles — creating a new status issue does NOT close existing announcements.
  2. Multiple announcements can coexist — an agent can have several open announcements simultaneously if multiple conditions are active.
  3. They are closed when resolved — the agent that created an announcement MUST periodically review its own open announcements (via REVIEW_OWN_ANNOUNCEMENTS) and close any whose condition is no longer relevant, valid, or correct.

Every agent that creates announcements MUST also review them. Specifically, every supervisor that calls CREATE_ANNOUNCEMENT_ISSUE must also call REVIEW_OWN_ANNOUNCEMENTS at least once every 3 cycles to close stale announcements. Failing to do so causes announcement accumulation that degrades the signal quality for consuming agents.

5.3.2 Tracking Issue Consumption Protocol

!!! info "How agents decide what to read and how deeply"

Not all tracking issues are equally relevant to all agents. The consumption protocol defines a triage system based on three axes: **who posted it** (source agent), **what kind** (Status vs Announce), and **how urgent** (priority label). Each agent reads tracking issues at a depth proportional to their relevance.

Consumption rules for each agent:

Consumer Agent Reads Status Issues From Reads Announcements From Minimum Priority Read Depth
System Watchdog All supervisors All agents All Full (body + comments) — it is the system health monitor
Product Builder All supervisors (via monitoring loop) All agents Medium+ Full — it is the top-level orchestrator
Human Liaison None (delegates to humans) All agents High+ Full — surfaces important events to humans
Implementation Pool None Watchdog, Liaison, Groomer High+ Summary only — adjusts worker priorities
PR Review Pool None Watchdog, Liaison Critical only Summary only — adjusts review priorities
PR Merge Pool None Watchdog Critical only Summary only — pauses merging if critical
Backlog Grooming None Watchdog, Liaison, Owner Medium+ Summary only — adjusts grooming focus
All other supervisors None Watchdog Critical only Title + priority label only

Read depth levels:

  • Title + priority label only: Read the issue title and priority label. No API calls to fetch body or comments. Fastest; used for low-relevance triage.
  • Summary only: Read the issue title, labels, and first paragraph of the body. One API call. Used when the agent needs to know the nature of the event but not the details.
  • Full (body + comments): Read the complete issue body and all comments. Multiple API calls. Used by the Watchdog and Product Builder for comprehensive situational awareness.

Priority-based triage:

When an agent calls READ_ANNOUNCEMENTS, it provides a min_priority parameter. The Automation Tracking Manager returns only announcements at or above that priority level. This prevents low-priority noise from cluttering high-priority processing loops.

5.3.3 Startup State Recovery Protocol

!!! danger "Critical: Every supervisor MUST recover state before deleting old tracking issues"

When a supervisor starts (or restarts after a crash), its **very first action** must be to read its most recent tracking issue to understand where it left off. Only AFTER recovering state may it proceed to delete old status issues and create a new one.

Mandatory startup sequence for every supervisor:

# Step 1: RECOVER STATE (before anything else)
recovered_state = task automation-tracking-manager "READ_TRACKING_STATE" \
  --agent-prefix "{PREFIX}" \
  --tracking-type "{TRACKING_TYPE}" \
  --repo-owner "$owner" \
  --repo-name "$repo"

# Extract recovery information
last_cycle = recovered_state.cycle_number
offline_minutes = recovered_state.offline_duration_minutes
last_body = recovered_state.issue_body
last_comments = recovered_state.comments

# Step 2: ANALYZE RECOVERED STATE
# Parse the last tracking body for agent-specific state:
# - What work items were active (PRs, issues, branches)
# - What was queued but not started
# - What had failed and might need retry
# - Health indicators from the last cycle

# Step 3: NOW delete old status issues and create new one
result = task automation-tracking-manager "CREATE_TRACKING_ISSUE" \
  --agent-prefix "{PREFIX}" \
  --tracking-type "{TRACKING_TYPE}" \
  --body "$initial_tracking_body" \
  --repo-owner "$owner" \
  --repo-name "$repo"

# Step 4: Use recovered state to inform first cycle
# e.g., check specific PRs/branches from last session before scanning for new work

Why this order matters: CREATE_TRACKING_ISSUE closes ALL existing status issues. If the agent creates first and reads second, it reads its own brand-new empty issue instead of the state from its previous session. The state is lost.

Agent-specific recovery behaviors:

Agent Recovery Action
Implementation Pool Parse worker table for PR numbers and issue numbers. Check each PR/issue on Forgejo to determine if it was completed, is still open, or needs a new worker. Resume in-progress work before scanning for new work.
PR Review Pool Parse recently-reviewed PR list. Check if those PRs still need review attention (new commits since review).
PR Merge Pool Parse merge candidate list. Re-check those PRs for merge readiness.
System Watchdog Parse health indicators. Compare against current state to detect changes during offline period.
Product Builder Parse supervisor session list. Cross-reference with current active sessions to detect which supervisors need re-launching.
All other supervisors Parse cycle number and summary. Use offline duration to adjust first-cycle urgency (longer offline = more aggressive scanning).

Offline duration affects behavior: An agent that has been offline for 5 minutes treats the situation as a normal restart. An agent offline for 2+ hours should assume significant state drift and perform a full re-scan of its domain before resuming normal operations.

5.3.4 Estimated Cycle Interval (Rolling Average)

Every status issue MUST include an **Estimated Cycle Interval**: Nmin field in its header. This tells the System Watchdog and Product Builder how often the agent is expected to update, enabling them to detect frozen agents.

Calculation (rolling average with 90/10 weighting):

# On startup (no previous interval data):
estimated_interval = AGENT_SLEEP_SECONDS / 60   # default = the sleep duration

# On subsequent cycles (before creating new status issue):
old_interval = parse "Estimated Cycle Interval" from recovered_state.issue_body
old_created_at = recovered_state.created_at
actual_interval = (now - old_created_at) in minutes

# Rolling average: 90% previous estimate + 10% actual measurement
estimated_interval = old_interval * 0.90 + actual_interval * 0.10

How the Watchdog uses it: If a status issue's age exceeds 2 × estimated_interval, the agent is likely frozen. The Watchdog should investigate the agent's session health before restarting it. The 2× threshold accounts for natural variance (network delays, long operations, heavy Forgejo API load).

Why a rolling average? A simple static timeout would either be too tight (causing false positives during occasional slow cycles) or too loose (failing to detect genuine freezes). The rolling average adapts to each agent's actual cadence while smoothing out outliers. The 90/10 weighting means occasional slow cycles barely affect the estimate, but a sustained slowdown gradually shifts it.

5.3.5 Dual Status Issue Cleanup

Two independent mechanisms ensure the one-at-a-time invariant for status issues:

  1. Primary cleanup (agent-side): Every agent, via CREATE_TRACKING_ISSUE, closes ALL open status issues with its prefix before creating the new one. This is the normal path.

  2. Redundant cleanup (groomer-side): The Backlog Grooming Supervisor periodically scans for violations of the one-at-a-time invariant. If it finds more than one open status issue from the same agent prefix, it closes all but the newest. This catches edge cases where:

    • Two instances of the same agent launched simultaneously (race condition)
    • An agent crashed after creating a new issue but before closing the old one
    • The Forgejo API returned success for close but didn't actually close the issue

This dual mechanism is defense-in-depth. Under normal operation, the agent-side cleanup handles everything. The groomer is a safety net.

5.3.6 Cycle Number Continuity Across Sessions

Cycle numbers MUST be globally unique per agent prefix — no two status issues (open or closed) from the same agent may share a cycle number. This is enforced by the GET_NEXT_CYCLE_NUMBER operation, which searches ALL issues (state: "all", including closed) and returns max(existing_cycle_numbers) + 1.

When an agent starts a new session, it does NOT reset to Cycle 1. It reads the highest cycle number from any previous status issue and continues from there. This enables:

  • Monotonic cycle numbering across crashes, restarts, and session recycling
  • Easy identification of the most recent status issue (highest cycle number wins)
  • Audit trail continuity (gaps in cycle numbers indicate periods when the agent was down)

5.4 Tracking Operations

The Automation Tracking Manager provides ten operations:

Operation Purpose
CREATE_TRACKING_ISSUE Close old tracking issue, determine next cycle number, create new issue
UPDATE_TRACKING_ISSUE Add a comment to the current cycle's tracking issue
CLOSE_TRACKING_ISSUE Find and close the current tracking issue
READ_TRACKING_STATE Read the latest tracking issue and extract state data
GET_NEXT_CYCLE_NUMBER Determine the next sequential cycle number
CREATE_ANNOUNCEMENT_ISSUE Create a persistent cross-cycle announcement
CLOSE_ANNOUNCEMENT_ISSUE Close a specific announcement when it is resolved
LIST_TRACKING_ISSUES List all tracking issues for a given agent prefix
READ_ANNOUNCEMENTS Read open announcements from specified agents with priority filtering
REVIEW_OWN_ANNOUNCEMENTS Review own announcements for continued relevance

5.5 Agent Prefix Registry

Prefix Agent
AUTO-SESSION Session Persister
AUTO-WATCHDOG System Watchdog
AUTO-GROOMER Backlog Grooming
AUTO-LIAISON Human Liaison
AUTO-IMP-POOL Implementation Pool Supervisor
AUTO-REV-POOL PR Review Pool Supervisor
AUTO-UAT-POOL UAT Test Pool Supervisor
AUTO-BUG-POOL Bug Hunt Pool Supervisor
AUTO-INF-POOL Test Infrastructure Pool Supervisor
AUTO-ARCH Architecture Supervisor
AUTO-EPIC Epic Planning Supervisor
AUTO-EVLV Agent Evolution Supervisor
AUTO-GUARD Architecture Guard
AUTO-SPEC Specification Update Supervisor
AUTO-TIME Timeline Update Supervisor
AUTO-DOCS Documentation Supervisor
AUTO-PROJ-OWN Project Owner Supervisor
AUTO-PROD-BLDR Product Builder
AUTO-IMP-WRK Implementation Worker
AUTO-MERGE PR Merge Supervisor

5.5.1 Session Tags vs Tracking Prefixes: Two Naming Schemes

!!! warning "Important Distinction"

The system uses **two different naming schemes** for the same agents. Session tags (Section 4.2.1) identify OpenCode sessions; tracking prefixes (Section 5.5) identify Forgejo tracking issues. For eight agents, these names are **different**. Agents and operators must use the correct scheme for the correct context.

The following table maps between the two schemes for agents where they differ:

Agent Session Tag (OpenCode) Tracking Prefix (Forgejo)
Implementation Pool AUTO-IMP-SUP AUTO-IMP-POOL
PR Review Pool AUTO-REV-SUP AUTO-REV-POOL
UAT Test Pool AUTO-UAT-SUP AUTO-UAT-POOL
Bug Hunt Pool AUTO-BUG-SUP AUTO-BUG-POOL
Test Infrastructure Pool AUTO-INF-SUP AUTO-INF-POOL
Human Liaison AUTO-HUMAN AUTO-LIAISON
Backlog Grooming AUTO-BLOG AUTO-GROOMER
Project Owner AUTO-OWNR AUTO-PROJ-OWN
System Watchdog AUTO-WDOG AUTO-WATCHDOG

For the remaining nine supervisors (Architecture, Epic Planning, Agent Evolution, Architecture Guard, Spec Update, Documentation, Timeline, PR Merge, PR Fix Pool), both schemes use the same prefix.

When to use which:

  • Session tags: When querying the OpenCode Server API, launching async agents, or searching for running sessions.
  • Tracking prefixes: When creating or searching for Forgejo tracking issues, reading announcements, or filtering the Automation Tracking label.

Notable absences:

  • AUTO-PROD-BLDR and AUTO-SESSION exist only as tracking prefixes (the Product Builder and Session Persister are not launched via the Async Agent Manager).
  • AUTO-ONEOFF exists only as a session tag (one-off dispatched agents don't create tracking issues).
  • AUTO-PRFIX-SUP exists only as a session tag (the PR Fix Pool Supervisor does not create tracking issues).
  • Worker-level session tags (AUTO-IMP, AUTO-REV, AUTO-UAT, AUTO-BUG, AUTO-INF) have no tracking prefix counterpart except AUTO-IMP-WRK.

5.6 Tracking Issue Body Template

Every status tracking issue body MUST include these standardized fields in the header. Additional agent-specific content follows after.

# [Agent Display Name] Status -- YYYY-MM-DD HH:MM:SS

**Agent**: <agent-definition-filename>
**Cycle**: N
**Estimated Cycle Interval**: Nmin
**Status**: active | idle | error

## Summary

<One paragraph describing current state>

## Detailed Status

<Agent-specific detailed status section with tables, metrics, etc.>

## Health Indicators

- **Key Metric 1**: value
- **Key Metric 2**: value

## Next Actions

- <Planned next steps>
- Next status update in ~N cycles

---
**Automated by CleverAgents Bot**
Supervisor: <Display Name> | Agent: <agent-filename>

5.7 Bot Signature Block

Every piece of content that any agent creates on Forgejo (issue bodies, comments, PR descriptions, review comments) must end with this signature block:

---
**Automated by CleverAgents Bot**
Supervisor: <Supervisor Display Name> | Agent: <agent-filename>

The signature block serves three purposes:

  1. Attribution: Clearly identifies automated content for human readers.
  2. Filtering: Enables agents to distinguish bot-generated content from human content.
  3. Tracing: Identifies which specific agent and supervisor produced the content.

The signature must appear at the very end of the content, preceded by a horizontal rule (---).


6. Universal Agent Constraints

The following constraints apply to every agent in the system without exception.

6.1 Label Creation Prohibition

No agent in the system is permitted to create new labels. All labels exist at the organization level and are pre-configured during project bootstrapping. This constraint is enforced through three mechanisms:

  1. Permission denial: Every agent's permission block explicitly denies forgejo_create_label, forgejo_create_org_label, and forgejo_create_repo_label.
  2. Bash URL blocking: Every agent's bash permissions deny any command containing label creation API URL patterns (*api/v1/orgs/*/labels*, *api/v1/repos/*/labels*).
  3. Label Manager delegation: Agents that need to apply labels to issues must do so through the Forgejo Label Manager subagent, which itself cannot create labels but can apply existing organization-level labels.

6.2 Clone Isolation Protocol

Every agent that touches the filesystem must create its own isolated clone:

  1. Create a unique directory: /tmp/<agent-type>-<instance-id>-<timestamp>/
  2. Clone the repository into this directory with HTTPS authentication.
  3. Configure git identity (name, email) within the clone.
  4. Perform all work within the clone.
  5. Push results to the remote repository.
  6. Delete the clone directory on exit.

The Product Builder itself does not need a clone because it only orchestrates via the Async Agent Manager, the Task tool, and the Forgejo API. All file work is delegated to workers.

6.3 Bash Sleep for Genuine Waiting

Long-running agents (supervisors) must use bash sleep commands for genuine blocking waits between polling cycles. They must never return to their caller to "wait" because returning means exiting. The bash timeout parameter must always be set to at least 1.5 times the sleep duration.

6.4 CONTRIBUTING.md Compliance

Every agent that writes code, creates issues, or reviews pull requests must strictly adhere to the project's CONTRIBUTING.md. Key rules enforced:

  • File organization: Source in src/cleveragents/, unit tests in features/, integration tests in robot/, mocks in features/mocks/
  • Testing: BDD with Behave for unit tests, Robot Framework for integration tests. Never xUnit. Coverage threshold of 97%.
  • Commit messages: Conventional Changelog format via Commitizen.
  • Code standards: Full static typing, no # type: ignore, proper error handling patterns.
  • Tool routing: ALL build, test, lint, and typecheck commands must be routed through nox sessions. Agents must never install software directly (no pip install, no npm install). The only approved commands are nox -e lint, nox -e typecheck, nox -e unit_tests, nox -e integration_tests, nox -s coverage_report, etc.
  • PR requirements: Closing keywords, dependency links, milestone assignment, type labels.

6.5 Agent Visibility: Hidden vs User-Facing

Of the 95 agent definition files, only 10 are user-facing (visible in the OpenCode agent selection UI). The remaining 85 have hidden: true in their frontmatter, meaning they exist solely as subagents invoked by other agents or the Async Agent Manager.

User-facing agents (the only agents a human operator should invoke directly):

Agent Purpose
product-builder Launch the full autonomous development system
build General-purpose development (replaces default build agent)
build-opencode Edit .opencode/ agent definition files
fix-pr Manually fix a specific pull request
plan Create implementation plans
pr-manager Manually manage pull requests
implementation-pool-supervisor Standalone implementation pool (can run without Product Builder)
implementation-worker Standalone implementation worker (for single-issue work)
session-cleanup Clean up stale async sessions

All other agents (hidden: true) must never be invoked directly by a human. They are designed to be called programmatically with specific parameters.

6.6 File Edit Permission Model

Agents are divided into three categories based on their file edit permissions:

Agents with edit: allow (22 agents -- these can modify files):

Category Agents
Code writers implementer, behave-tester, robot-tester, lint-fixer, typecheck-fixer, test-fixer, coverage-improver, unit-test-runner, integration-test-runner, asv-benchmarker
Worker orchestrators implementation-worker, subtask-loop, pr-ci-test-fixer, pr-fix-pool-supervisor
File-writing supervisors architecture-pool-supervisor, documentation-pool-supervisor, spec-update-pool-supervisor, timeline-update-pool-supervisor, agent-evolution-pool-supervisor
Bootstrap & primary project-bootstrapper, build, build-opencode

Agents with edit: deny (41 agents -- these can never modify files):

All review agents, all issue management agents, all PR management agents (except PR CI Test Fixer), all session management agents, all tracking/label agents, and all read-only analysis agents.

Agents with no explicit edit permission (31 agents -- defaults apply):

All deprecated agents, all tier selectors, and several infrastructure agents. The OpenCode default permission for edit applies.

Design principle: An agent has edit: allow if and only if its core function requires writing or modifying files. Orchestrators that delegate all file work to subagents have edit: deny to prevent accidental file corruption.

6.7 Internet Access Restriction

Only three agents have webfetch: allow permission (internet access): build, build-opencode, and plan. All three are user-facing primary agents invoked directly by humans.

No autonomous agent (no supervisor, no worker, no subagent) has internet access. This is a deliberate security design choice: autonomous agents must work entirely from local files, the Forgejo API, and the OpenCode Server API. They must never fetch external resources, download dependencies, or access external services.

6.8 Reference Material Loading

Before performing any substantive work, agents must load project reference materials via the Ref Reader subagent, which reads and summarizes docs/specification.md, CONTRIBUTING.md, and docs/timeline.md. The resulting summary is passed to every worker to ensure consistent adherence to project standards.

6.9 Complete Label Taxonomy

All labels exist at the organization level. No agent may create new labels. The complete label set is:

State Labels (exactly one per issue):

Label Meaning Terminal?
State/Unverified Newly created, not yet triaged No
State/Verified Triaged and approved for work No
State/In Progress Actively being implemented No
State/Paused Work suspended (must have Blocked label) No
State/In Review PR created and under review No
State/Completed PR merged, issue closed Yes
State/Wont Do Deliberately not implementing Yes

Type Labels (exactly one per issue):

Label Purpose
Type/Bug Defect in existing functionality
Type/Feature New capability
Type/Task Technical work not directly visible to users
Type/Testing Test infrastructure or test-only changes
Type/Epic Parent grouping of related issues
Type/Legendary Top-level grouping of related epics
Type/Documentation Documentation-only changes
Type/Refactor Code restructuring without behavior change
Type/Automation Agent system or CI automation changes

Priority Labels (exactly one per non-Unverified issue):

Label Urgency
Priority/Critical Blocks other work, must fix immediately
Priority/High Important, schedule promptly
Priority/Medium Normal priority
Priority/Low Do when convenient
Priority/Backlog Someday; not scheduled
Priority/CI-Blocker Breaks CI pipeline; absolute highest priority

MoSCoW Labels (Project Owner exclusive):

Label Meaning
MoSCoW/Must Have Required for milestone completion
MoSCoW/Should Have Important but milestone can ship without
MoSCoW/Could Have Nice to have

Story Points: Points/1, Points/2, Points/3, Points/5, Points/8, Points/13

Special Labels: Blocked, Duplicate, Signed-off, Automation Tracking, needs feedback

6.9.1 Special Label Lifecycles

The five special labels have distinct lifecycles that cross agent boundaries:

needs feedback — Signals that automated work has stalled and a human decision is required.

Event Applied By Removed By
Proposal issue awaiting human approval Architecture Supervisor, Agent Evolution, Spec Evolution Human developer (signals approval)
PR awaiting human review of significant change Architecture Supervisor, Agent Evolution, Spec Evolution Human developer
Implementation worker stuck after 3+ failed fix attempts Implementation Worker, PR Fix Pool, System Watchdog Human developer (after providing guidance)
Project Owner skips triaging an issue Project Owner (skips it for Human Liaison) Human Liaison (after triaging)

Merge gate: PRs with needs feedback cannot be merged (Section 8.3.2, criterion 4).

Blocked — Signals that an issue cannot proceed due to an unresolved dependency.

Event Applied By Removed By
Issue depends on an incomplete issue Issue State Updater (when transitioning to State/Paused) Issue State Updater (when the blocking issue is completed)
Manual block by a human Human developer Human developer

Transition rule: Applying Blocked requires simultaneously transitioning to State/Paused. Removing Blocked requires simultaneously transitioning from State/Paused to State/In Progress.

Duplicate — Signals that an issue is a duplicate of another.

Event Applied By Removed By
Backlog groomer detects duplicate (pass 1) Backlog Grooming Supervisor Never removed (issue is closed)

The groomer always comments with a reference to the original issue before closing the duplicate. Only issues (never PRs) can be marked as duplicates.

Signed-off — Signals that a human has explicitly approved an automated action or decision.

Event Applied By Removed By
Human approves an agent's proposal Human developer Never removed

This label is applied manually by humans to indicate they have reviewed and approved agent-created content (specification changes, architecture decisions, agent evolution proposals). It is never applied by automated agents.

Automation Tracking — Identifies tracking and announcement issues created by the automation system.

Event Applied By Removed By
New tracking issue created Automation Tracking Manager (via Forgejo Label Manager) Never removed (issue is closed by next cycle)
New announcement created Automation Tracking Manager (via Forgejo Label Manager) Never removed (issue is closed when resolved)

This label is the key filter for agents reading system state: querying for issues with Automation Tracking returns all active tracking and announcement issues.

6.10 Issue State Transitions

Issues must follow these valid state transitions. The Issue State Updater agent enforces these rules:

@startuml
!theme plain
skinparam state {
  BackgroundColor<<terminal>> #90EE90
}

[*] --> Unverified : issue created
Unverified --> Verified : triaged and approved
Unverified --> WontDo <<terminal>> : out of scope
Verified --> InProgress : worker claims issue
InProgress --> Paused : blocked by dependency\n(adds Blocked label)
Paused --> InProgress : blocker resolved\n(removes Blocked label)
InProgress --> InReview : PR created
InReview --> Completed <<terminal>> : PR merged
Unverified -[dashed]-> WontDo <<terminal>>
Verified -[dashed]-> WontDo <<terminal>>
InProgress -[dashed]-> WontDo <<terminal>>
InProgress -[dashed]-> Completed <<terminal>>

state "State/Unverified" as Unverified
state "State/Verified" as Verified
state "State/In Progress" as InProgress
state "State/Paused" as Paused
state "State/In Review" as InReview
state "State/Completed" as Completed <<terminal>>
state "State/Wont Do" as WontDo <<terminal>>
@enduml

Transition rules:

  • An issue must have exactly one State label at all times.
  • Transitioning to State/Paused requires adding the Blocked label.
  • Transitioning from State/Paused requires that the blocking issue is resolved.
  • Transitioning to terminal states (State/Completed, State/Wont Do) closes the issue.
  • Transitioning to State/In Review requires that an open PR exists referencing the issue.

6.11 Dependency Direction Rules

Forgejo dependency links follow a strict directional convention:

  • Child issue BLOCKS parent Epic: An implementation issue is a dependency that blocks its parent Epic.
  • Epic BLOCKS parent Legendary: An Epic is a dependency that blocks its parent Legendary.
  • PR BLOCKS linked issue: A pull request is a dependency that blocks the issue it closes.

This means: to find children of an Epic, query the Epic's "blocked by" dependencies. To find the parent of an issue, query its "blocks" dependencies. Reversing these directions is a compliance violation that the System Watchdog and State Reconciler will detect and correct.

6.12 Work Item Claiming Protocol

When an Implementation Worker begins work on an issue, it must claim the work item to prevent other workers from starting on the same issue. The protocol uses Forgejo comments with structured prefixes:

Constants:

  • Claim duration: 2 hours
  • Heartbeat interval: 10 minutes

Claim Comment Format:

[CLAIM: agent=<agent-name>, session=<session-id>, timestamp=<ISO-8601>]
Claiming this issue for implementation.

Heartbeat Comment Format:

[HEARTBEAT: agent=<agent-name>, session=<session-id>, timestamp=<ISO-8601>]
Still working on this issue.

Release Comment Format:

[RELEASE: agent=<agent-name>, session=<session-id>, timestamp=<ISO-8601>, reason=<completed|failed|timeout>]
Releasing claim on this issue.

Rules:

  1. No work without a claim. Before starting any work, post a [CLAIM: comment.
  2. Respect existing claims. Check for unexpired claims before claiming.
  3. Send regular heartbeats every 10 minutes using [HEARTBEAT:.
  4. Always release claims using [RELEASE: (use try/finally to ensure this).
  5. Stale claims (>2 hours without heartbeat) may be overridden.

6.13 TDD Issue Test Tags System

When a bug issue is filed, the testing agents write tests that are expected to fail (proving the bug exists) before the implementation fix is applied. This follows the Test-Driven Development workflow using three special tags:

For Behave (unit tests) -- uses @ prefix:

Tag Purpose
@tdd_issue Marks a scenario as part of TDD workflow
@tdd_issue_<N> Links the scenario to Forgejo issue #N
@tdd_expected_fail Indicates the test is expected to fail until the bug is fixed

For Robot Framework (integration tests) -- no @ prefix:

Tag Purpose
tdd_issue Marks a test case as part of TDD workflow
tdd_issue_<N> Links the test case to Forgejo issue #N
tdd_expected_fail Indicates the test is expected to fail

TDD Lifecycle:

  1. Bug filed: Bug issue created with Type/Bug label.
  2. Tests written: Behave Tester or Robot Tester writes tests tagged with all three tags. Tests are expected to fail.
  3. Bug fixed: Implementer fixes the bug. Tests now pass.
  4. Tags cleaned: Implementer removes only the @tdd_expected_fail tag. The @tdd_issue and @tdd_issue_<N> tags remain permanently as documentation.

Test Fixer special handling:

  • If a test has @tdd_expected_fail and is FAILING: The bug still exists. Do not modify the test.
  • If a test has @tdd_expected_fail and is PASSING: The bug was fixed. Remove only @tdd_expected_fail.

Coverage Improver rule: Never write TDD-tagged tests just for coverage. Never modify existing TDD tests.

6.14 Standard Issue Body Format

Every issue created by the system follows this body format:

## Metadata

| Key | Value |
|-----|-------|
| Branch | `<branch-name>` |
| Commit Message | `<type>(scope): description` |
| Parent Epic | #<epic-number> |

## Subtasks

- [ ] Subtask 1 description
- [ ] Subtask 2 description
- [ ] Subtask 3 description

## Definition of Done

- [ ] All subtasks completed
- [ ] Unit tests written (Behave, >=97% coverage)
- [ ] Integration tests written (Robot Framework)
- [ ] All quality gates pass (lint, typecheck, unit, integration, coverage)
- [ ] PR created and approved
- [ ] PR merged to master

6.15 Standard PR Description Format

Pull requests created by the system follow this format:

## Summary

<Brief description of what this PR implements>

## Changes

- <Change 1>
- <Change 2>

## Design Decisions

- <Decision 1 with rationale>

## Testing

- Unit tests: <count> scenarios in <files>
- Integration tests: <count> test cases in <files>
- Coverage: <percentage>%

## Modules Affected

- `src/cleveragents/<module>/`

## Related Issues

Closes #<issue-number>

## Checklist

- [x] Code follows CONTRIBUTING.md
- [x] Tests pass locally
- [x] Coverage >= 97%
- [x] No `# type: ignore`
- [x] Commit message follows Conventional Changelog

---
**Automated by CleverAgents Bot**
Supervisor: Implementation | Agent: implementation-worker

6.16 Priority Ordering Rules

When the Issue Finder queries open issues, it returns them in this priority order:

  1. Priority/CI-Blocker issues have ABSOLUTE priority over everything else, regardless of milestone.
  2. Type/Bug + Priority/Critical issues across ALL milestones come before any other issue type.
  3. Lowest milestone first: Within the same priority level, issues in earlier milestones are preferred. Never work on milestone N+1 while Critical/Must-Have issues in milestone N remain open.
  4. State/In Progress before State/Verified: Resume incomplete work before starting new work.
  5. Priority label: Critical > High > Medium > Low > Backlog.
  6. MoSCoW tiebreaker: Must Have > Should Have > Could Have.
  7. Unblocking factor: Issues that unblock the most other issues are preferred.

6.17 The Shared Bot Account Problem and 3-Tier Approval Detection

!!! danger "Critical Design Constraint"

All automated agents in the system share a single Forgejo bot account (HAL9000). This creates a fundamental problem: Forgejo rejects formal `APPROVED` reviews when the reviewer is the same user who created the PR ("approve your own pull is not allowed"). Since every PR is both authored and reviewed by the same bot account, formal `APPROVED` reviews are impossible for bot-to-bot workflows. This constraint drives the entire approval detection architecture.

6.17.1 Three-Tier Approval Detection

To work around the self-approval limitation, every agent that checks for approval must inspect three sources, in order:

Tier Source Mechanism Why It Exists
1 Formal Reviews Reviews with state == "APPROVED" Standard Forgejo review; works for non-self PRs
2 Review Bodies Reviews with state in ("COMMENT", "PENDING") whose body contains approval keywords Primary path for bot PRs; the PR Reviewer posts a COMMENT-state review with approval language when Forgejo blocks the formal APPROVED state
3 Issue Comments Issue comments containing approval keywords Durable fallback; the PR Reviewer always posts an issue comment as a backup approval signal

Any single tier matching is sufficient to constitute a valid approval. All three tiers are checked by:

  • The PR Merge Pool Supervisor (check_pr_approval())
  • The Implementation Worker (has_required_approvals(), two instances)
  • The Shared Merge Safety utilities (check_flexible_approval())

Approval keywords (case-insensitive, recognized across all three tiers):

lgtm, approved, decision: approved, ready to merge, looks good,
ship it, merge it, good to go

Plus emoji variants: , :white_check_mark:, 👍, :+1:

Blocking review detection must also account for all three tiers: a REQUEST_CHANGES review only blocks a merge if it is more recent than the latest approval signal from any tier. This prevents stale rejections from blocking PRs that have been re-approved via comment or review body.

6.17.2 Two-Step Review Protocol

The PR Reviewer agent implements a mandatory two-step protocol for every review decision:

  1. Step 1 -- Post an issue comment via forgejo_create_issue_comment containing the full review text and a clear decision line with an approval keyword (e.g., "Decision: APPROVED ✅" or "Decision: REQUEST CHANGES"). This comment is the durable approval signal that merge automation detects. It succeeds regardless of the reviewer/author relationship.

  2. Step 2 -- Attempt a formal review via forgejo_create_pull_review with the appropriate state (APPROVED or REQUEST_CHANGES). This will succeed when the reviewer is not the PR author. If Forgejo rejects it with the self-approval error, the agent logs the rejection and moves on -- the issue comment from Step 1 already records the decision and is sufficient on its own.

Why both steps? The issue comment (Step 1) guarantees that the approval is always recorded, regardless of Forgejo's self-approval restrictions. The formal review (Step 2) provides the standard Forgejo review UX when possible. Together they ensure both humans and agents can always detect the review decision.

activitydiag {
  "Review PR" -> "Decision: APPROVE or REQUEST CHANGES";
  "Decision: APPROVE or REQUEST CHANGES" -> "Step 1: Post Issue Comment\n(with approval keyword)";
  "Step 1: Post Issue Comment\n(with approval keyword)" -> "Step 2: Attempt Formal Review";
  "Step 2: Attempt Formal Review" -> "Self-approval error?";
  "Self-approval error?" -> "Log and continue\n(comment is sufficient)" [label = "yes"];
  "Self-approval error?" -> "Formal review recorded" [label = "no"];
  "Log and continue\n(comment is sufficient)" -> "Done";
  "Formal review recorded" -> "Done";
}

6.17.3 Approval Count Policy

All pull requests require exactly one approval before merge. This is enforced at three levels:

  1. Branch protection: The Project Bootstrapper configures required_approvals: 1.
  2. Merge gate: The PR Merge Pool Supervisor and safe_merge_pr() require at least one approval from any of the three tiers.
  3. Watchdog enforcement: The System Watchdog audits branch protection and flags required_approvals < 1 as a HIGH severity finding.

Self-approval is explicitly permitted. This is necessary because all automated agents share a single bot account.

6.18 Merge Safety Protocol

All merge operations must use the shared merge safety utilities (shared/merge_safety.md). Direct calls to forgejo_merge_pull_request without pre-merge safety checks are forbidden.

The safe_merge_pr() function enforces:

  1. PR is open and not already merged
  2. CI status is passing (verified via web scraping when API is unavailable)
  3. Required approvals met via the 3-tier flexible approval detection (Section 6.17.1)
  4. No unresolved change requests (REQUEST_CHANGES more recent than latest approval signal from any tier)
  5. No merge conflicts
  6. force_merge is stripped if provided (never force-merge)
  7. Post-merge verification: After calling forgejo_merge_pull_request, the function calls forgejo_get_pull_request_by_index and confirms merged == true and state == "closed". Returns failure if verification fails, even if the merge API claimed success. See Section 8.3.4 for the full rationale.
  8. Default merge style: squash with branch deletion

6.19 Label Application Delegation

All agents in the system have forgejo_add_issue_labels: deny in their permission block, with exactly two exceptions:

  1. Forgejo Label Manager — the designated label applicator, which handles the label-name-to-organization-ID mapping correctly.
  2. Issue State Updater — which needs direct label access to perform atomic state transitions (removing old State/* labels and applying new ones).

Every other agent that needs to apply labels must delegate to the Forgejo Label Manager subagent. This prevents "invalid label ID" errors that occur when agents attempt to apply labels by name rather than by the organization-level label ID.

This rule is enforced universally across all 77 non-exception agent permission blocks.

6.20 Forgejo API Pagination Requirement

!!! warning "Critical: Forgejo List APIs Are Paginated"

The Forgejo REST API returns at most **50 items per page** by default for all list endpoints (`/repos/{owner}/{repo}/issues`, `/repos/{owner}/{repo}/pulls`, etc.). Any agent that queries a list endpoint MUST paginate through ALL pages. Failure to paginate causes silent data loss: the agent believes it has retrieved all items when it has only retrieved the first page.

Mandatory Pagination Pattern:

all_items = []
page = 1
while True:
    page_items = forgejo_list_*(owner, repo, state="open", page=page, limit=50)
    if not page_items:
        break
    all_items.extend(page_items)
    if len(page_items) < 50:  # Last page (partial)
        break
    page += 1

Rules:

  1. Never call a Forgejo list API without pagination when the result set could exceed 50 items.
  2. Continue fetching until a page returns fewer items than the page size (indicating it is the last page) or returns an empty result.
  3. Log the total count after pagination for debugging (e.g., Found {N} total open PRs to analyze).

Agents most affected by this requirement: The Implementation Pool Supervisor (which must analyze every open PR) and the Backlog Grooming Supervisor (which scans all open issues). Both operate on potentially large result sets where missing items has severe consequences.

6.21 PR Ownership Detection

When an agent needs to determine whether a pull request was created by the autonomous system (and therefore requires automated shepherding) versus created by a human developer (and should be left for human workflows), ownership must be determined by the PR author's login identity:

if pr.user.login == FORGEJO_USERNAME:
    # This is OUR PR — it needs an automated worker
else:
    # This is an external/human PR — skip automated dispatch

Forbidden ownership checks:

  • Checking pr.body for "Closes #" or "Fixes #" text — many valid bot PRs do not contain these exact strings
  • Checking PR labels for bot-specific markers — labels can be added or removed independently
  • Checking the branch name pattern — branch names are not a reliable ownership signal

This rule applies to: the Implementation Pool Supervisor (PR dispatch), the PR Review Pool Supervisor (review queue filtering), and the Backlog Grooming Supervisor (PR health checks).


7. Product Builder (Tier 0 Orchestrator)

7.1 Identity

Property Value
Agent File product-builder.md
Mode primary
Model anthropic/claude-sonnet-4-6
Temperature 0.1
Tracking Prefix AUTO-PROD-BLDR

7.2 Purpose

The Product Builder is the top-level orchestrator of the entire autonomous development system. It takes a product vision -- either from the user's prompt or from existing project documentation -- and builds the entire product through iterative milestones. It acts as a process supervisor (analogous to systemd), not a worker. Its only jobs are to launch supervisors, keep them alive, check for convergence, and exit when the product is verified complete.

7.3 What the Product Builder Must Never Do

  • Implement issues itself
  • Edit code directly
  • Create or merge pull requests
  • Use the Task tool for launching supervisors (must use Async Agent Manager)
  • Return to the user before the Product Verifier confirms COMPLETE
  • Make direct HTTP calls to the OpenCode Server (must use Async Agent Manager)

7.4 Permissions Rationale

Permission Setting Rationale
edit deny The Product Builder never edits files directly
bash.* deny (with exceptions) Only echo, sleep, and jq are needed for env vars, waiting, and JSON parsing
bash.curl deny Direct API calls are forbidden; must use Async Agent Manager
task.async-agent-manager allow The sole mechanism for launching and monitoring supervisors
task.project-bootstrapper allow One-shot bootstrap of project structure
task.ref-reader allow Load project reference materials
task.product-verifier allow Verify product completion
task.session-persister allow Checkpoint session state
task.automation-tracking-manager allow Manage tracking issues
forgejo.* allow Read Forgejo state for convergence checking
forgejo.forgejo_add_issue_labels deny Labels managed by specialized agents only

7.5 Execution Flow

activitydiag {
  "Gather Required Info" -> "Detect Project State";
  "Detect Project State" -> "Fresh?";
  "Fresh?" -> "Phase A: Bootstrap" [label = "yes"];
  "Fresh?" -> "Phase C: Launch Supervisors" [label = "no"];
  "Phase A: Bootstrap" -> "Phase C: Launch Supervisors";
  "Phase C: Launch Supervisors" -> "Launch 18 via async-agent-manager";
  "Launch 18 via async-agent-manager" -> "Validate All 18 Running";
  "Validate All 18 Running" -> "Monitoring Loop";
  "Monitoring Loop" -> "Sleep 60s" -> "Check Health" -> "Re-launch Dead" -> "Convergence Check" -> "Product Complete?" -> "Exit" [label = "yes"];
  "Product Complete?" -> "Sleep 60s" [label = "no"];
}

7.6 Phase Details

Phase 0: State Detection

The Product Builder first detects the project's current state by checking for existing tracking issues, assessing project maturity (spec, pyproject.toml, noxfile.py, CONTRIBUTING.md, milestones, issues, CI configuration, branch protection), and classifying the project as Fresh, Bootstrapped, Designed, In Progress, or Near Complete.

Phase A: Bootstrap

If the project lacks basic infrastructure, the Product Builder invokes the Project Bootstrapper subagent, which sets up pyproject.toml, noxfile.py, CI pipelines, CONTRIBUTING.md, Forgejo labels, milestones, and branch protection rules. This phase is skipped entirely if the infrastructure already exists.

Phase B: Architecture (Skipped)

Architecture design is no longer a one-shot phase. The Architecture Supervisor runs continuously as one of the eighteen supervisors, monitoring for specification needs throughout the build.

Phase C.0: Resume Existing Sessions

Before launching new supervisors, the Product Builder queries the OpenCode Server for existing supervisor sessions from a previous run. If found, it adopts them into the monitoring loop instead of launching duplicates, enabling seamless resumption after a restart.

Phase C.2: Launch All 18 Supervisors

For each supervisor not already running, the Product Builder invokes the Async Agent Manager with the supervisor's agent name, tag, display name, and prompt text. Each launch returns within seconds.

Phase C.3: Monitoring Loop

The infinite monitoring loop that constitutes the Product Builder's steady state. See Section 4.3 for details.

7.7 Subagent Interactions

blockdiag {
  "Product Builder" -> "async-agent-manager" [label = "launch/monitor supervisors"];
  "Product Builder" -> "project-bootstrapper" [label = "one-shot: setup"];
  "Product Builder" -> "ref-reader" [label = "one-shot: load refs"];
  "Product Builder" -> "issue-finder" [label = "one-shot: find issues"];
  "Product Builder" -> "session-persister" [label = "checkpoint state"];
  "Product Builder" -> "product-verifier" [label = "verify completion"];
  "Product Builder" -> "milestone-reviewer" [label = "review milestones"];
  "Product Builder" -> "final-reporter" [label = "generate report"];
  "Product Builder" -> "automation-tracking-manager" [label = "tracking issues"];
}

8. Pool Supervisors (Tier 1)

8.1 Implementation Pool Supervisor

Property Value
Agent File implementation-pool-supervisor.md
Mode all (primary + subagent)
Model Not specified (inherits from launcher)
Temperature 0.1
Tracking Prefix AUTO-IMP-POOL
Worker Count N (full allocation)
Workers implementation-worker
Polling Interval 2 seconds (optimized)

8.1.1 Purpose

The Implementation Pool Supervisor is the primary engine for closing issues. It finds failing PRs and open issues, then dispatches parallel implementation workers to handle them. It enforces an absolute PR-first priority: no new issues are worked on until every PR has an active worker or is blocked by human feedback.

8.1.2 PR-First Priority Gate

!!! danger "Mandatory First Action: Analyze ALL Open PRs"

Before doing ANYTHING else — before loading references, before finding issues, before dispatching any workers — the Implementation Pool Supervisor MUST call `forgejo_list_repo_pull_requests(owner, repo, state="open")` with NO limit parameter, read the FULL result (including from saved output files when tool output is truncated), and analyze every PR for work needed. Only after this analysis is complete may the supervisor proceed. This rule exists because a previous failure mode had the supervisor treating truncated tool output as complete data and dispatching issue workers while 30+ PRs were waiting.

Tool output truncation rule: When a tool response shows ...N bytes truncated... Full output saved to: /path/to/file, the supervisor MUST read that file with jq or Read before proceeding. Never treat truncated tool output as analyzed data.

The dispatch logic operates on a strict hierarchy:

  1. Priority/CI-Blocker issues (highest): These break the CI pipeline and create deadlocks. They are the only exception to the PR-first rule.
  2. PRs needing work (second): All open PRs that need fixes, review responses, or conflict resolution. Issue dispatch is BLOCKED until the pr_work_queue length is exactly 0.
  3. New issues (lowest): Only when all PRs have workers assigned.

Three Mandatory PR Dispatch Rules:

  1. ALL HAL9000 PRs need workers — Every open PR created by the bot account needs a worker assigned to shepherd it to merge. No PR is ever skipped because it is "too new" or has no reviews yet. The analyze_pr_state() function always returns needs_work: True for bot PRs; the only question is what type of work is needed.

  2. NEVER classify HAL9000 PRs as "external" — The "external-pr" classification applies exclusively to PRs created by human users. Ownership is determined by pr.user.login == FORGEJO_USERNAME (Section 6.21), never by the presence of closing keywords in the PR body.

  3. PAGINATION IS REQUIRED — The Forgejo API returns at most 50 PRs per page. The check_pr_work_needed() function must paginate through ALL pages per Section 6.20.

PR work is scored by priority:

Work Type Score Trigger Condition
Ready to merge 95 Has approval, CI passing, no conflicts
Review feedback (REQUEST_CHANGES) 90 Reviewer requested changes
Review feedback (COMMENT reviews) 85 Reviewer left comment-only reviews without formal decision
CI fix needed 85 CI checks are failing
Merge conflicts 80 Has approval but merge conflicts detected
Awaiting review 60 No reviews yet — PR needs monitoring and shepherding
Age bonus +0 to +10 min(age_days * 2, 10) — older PRs get a slight priority boost

8.1.3 Sliding Window Dispatch

The supervisor maintains a sliding window of N active workers. When a worker completes, its slot is immediately filled from the priority queue. Workers are launched via the Async Agent Manager (never via the Task tool) to ensure non-blocking dispatch.

8.1.4 Worker Adoption

On startup, the supervisor checks for existing worker sessions from a previous run. If found, it adopts them into its tracking instead of launching duplicates. This enables crash recovery without losing work in progress.

8.1.5 Activity Diagram

activitydiag {
  "Startup" -> "Load References" -> "Find Issues" -> "Adopt Existing Workers";
  "Adopt Existing Workers" -> "Main Loop";
  "Main Loop" -> "Check PR Work Needed";
  "Check PR Work Needed" -> "PRs Need Work?";
  "PRs Need Work?" -> "Dispatch PR Workers" [label = "yes"];
  "PRs Need Work?" -> "Check Issue Queue" [label = "no"];
  "Dispatch PR Workers" -> "Check Worker Health";
  "Check Issue Queue" -> "Slots Available?";
  "Slots Available?" -> "Dispatch Issue Workers" [label = "yes"];
  "Slots Available?" -> "Check Worker Health" [label = "no"];
  "Dispatch Issue Workers" -> "Check Worker Health";
  "Check Worker Health" -> "Clean Dead Workers" -> "Enforce Limits" -> "Post Status" -> "Sleep 2s" -> "Main Loop";
}

8.1.6 Permissions Rationale

Permission Setting Rationale
edit deny Supervisor never edits files; delegates to workers
task.implementation-worker deny Workers launched via async-agent-manager, not Task tool
task.async-agent-manager allow Required for launching workers asynchronously

8.2 PR Review Pool Supervisor

Property Value
Agent File pr-review-pool-supervisor.md
Mode subagent
Model anthropic/claude-sonnet-4-6
Temperature 0.1
Tracking Prefix AUTO-REV-POOL
Worker Count N/2 (half allocation)
Workers pr-reviewer
Polling Interval 30 seconds

8.2.1 Purpose

Continuously polls for pull requests needing code review and dispatches parallel PR Reviewer instances. Focuses purely on code quality assessment. Does not handle fixes, merges, or PR lifecycle management.

8.2.2 Review Determination

A PR needs review when:

  • No reviews exist and PR is older than 2 hours (initial review)
  • Changes were requested but new commits were pushed (changes addressed)
  • No review activity for 24+ hours and no approval (stale review)
  • Approved but not merged for 1+ hours (stuck investigation)

CI-failing PRs are skipped (let the implementation worker fix CI first).

8.2.3 Dynamic Review Focus

Each review session receives specific focus areas that rotate through ten categories:

  1. Architecture alignment, module boundaries, interface contracts
  2. Error handling patterns, edge cases, boundary conditions
  3. Test coverage quality, scenario completeness, maintainability
  4. API consistency, naming conventions, code patterns
  5. Security concerns, input validation, access control
  6. Performance implications, resource usage, scalability
  7. Code maintainability, readability, documentation
  8. Concurrency safety, race conditions, deadlock risks
  9. Resource management, memory leaks, cleanup patterns
  10. Specification compliance, requirements coverage, behavior correctness

Every third cycle creates a custom mix for serendipitous discovery.


8.3 PR Merge Pool Supervisor

Property Value
Agent File pr-merge-pool-supervisor.md
Mode subagent
Model anthropic/claude-sonnet-4-6
Temperature 0.1
Tracking Prefix AUTO-MERGE
Polling Interval 5 minutes

8.3.1 Purpose

A singleton supervisor that continuously monitors pull requests for merge readiness. It verifies all merge criteria are met, automatically rebases PRs without conflicts, and merges using fast-forward when possible.

8.3.2 Merge Criteria

All of the following must be true:

  1. Has at least one valid approval signal detected via the 3-Tier Approval Detection system (Section 6.17.1)
  2. All CI checks pass with no pending checks
  3. No merge conflicts (mergeable != false)
  4. Branch is up-to-date with the base branch (merge_base == base.sha). If the branch is behind, it must be rebased before merging. Forgejo silently fails to merge branches that are behind, even when mergeable is true. This check is mandatory before every merge attempt.
  5. Not labeled needs feedback or Blocked
  6. No blocking REQUEST_CHANGES reviews more recent than the latest approval signal (from any of the three tiers)
  7. Linked issues in correct state (State/In Review)

Self-approval is explicitly allowed. See Section 6.17 for the rationale.

8.3.3 Approval Detection via 3-Tier System

The supervisor uses the check_pr_approval() function which implements the 3-Tier Approval Detection specified in Section 6.17.1. The function returns a structured result including has_approval, approval_type (one of formal_review, review_body_approval, or comment_approval), the approver identity, and the approval_source description.

The has_blocking_reviews() function compares the timestamp of the latest REQUEST_CHANGES review against the timestamp of the latest approval signal from all three tiers. A blocking review only prevents merge if it is more recent than the newest approval from any source.

8.3.4 Mandatory Merge Verification Protocol

!!! danger "The forgejo_merge_pull_request MCP Tool Cannot Be Trusted"

The `forgejo_merge_pull_request` MCP tool returns "Pull request merged successfully" even when the merge **did not actually happen**. This occurs because Forgejo silently rejects merges when the branch is behind the base branch, but the MCP tool does not detect this failure. This caused false "Automatically merged" comments on PRs that were never actually merged (e.g., issues #6726, #6695, #5276, #6571).

Every merge attempt must follow this exact sequence:

  1. Pre-merge staleness check: Call forgejo_get_pull_request_by_index and compare merge_base against base.sha. If they differ, the branch is behind and must be rebased before merging (see Section 8.3.5).
  2. Attempt merge: Call forgejo_merge_pull_request.
  3. Mandatory post-merge verification: Immediately call forgejo_get_pull_request_by_index and check that merged == true AND state == "closed".
  4. Only on verified success: Post the "Automatically merged (verified)" comment with the ✓ Merge verified via API (PR state: closed, merged: true) line.
  5. On verification failure (merged is false or state is open): The merge silently failed. Attempt automatic rebase and schedule retry for the next cycle. Never post a merge success comment.

This verification protocol is enforced in three locations:

  • The PR Merge Pool Supervisor's merge_pr() function
  • The shared safe_merge_pr() utility (Section 13.6)
  • The Implementation Worker's ready-to-merge workflow

The System Watchdog now monitors for "merged successfully" comments on PRs that are still open as an additional safety net.

8.3.5 Pre-Merge Rebase Protocol

When a branch is behind the base branch (merge_base != base.sha), the PR Merge supervisor handles it based on whether conflicts exist:

Condition Action
Behind, no conflicts Automatic rebase via clone → git rebase--force-with-lease push. Post rebase comment. Wait for CI. Merge on next cycle.
Behind, with conflicts Post comment requesting manual rebase. Skip PR. Merge automatically when conflicts are resolved and CI passes.
Up-to-date Proceed directly to merge.

Critical rule: After a successful rebase, the supervisor must NOT attempt to merge immediately. The rebased commits need CI to run first. The merge happens on the next polling cycle after CI passes.

Subagents: ref-reader, pr-status-analyzer, automation-tracking-manager, repo-isolator, git-commit-helper


8.4 PR Fix Pool Supervisor

Property Value
Agent File pr-fix-pool-supervisor.md
Mode subagent
Model openai/gpt-5-codex
Temperature 0.1
Worker Count N/4 (quarter allocation)
Workers implementation-worker (in pr-fix mode)

8.4.1 Purpose

Analyzes CI failures for common root causes and dispatches parallel implementation workers to fix different failure categories. Focuses on intelligent orchestration: grouping failures by root cause rather than individual test, detecting stuck PRs, and requesting human help after repeated failures.

8.4.2 Common Cause Analysis

Before dispatching workers, failures are grouped into categories:

  • Unit test failures, integration test failures
  • Lint failures, typecheck failures
  • Coverage failures, build failures

Common root causes are identified (e.g., if >3 tests fail with the same import error, a single worker handles the import fix). This prevents redundant work.


8.5 UAT Test Pool Supervisor

Property Value
Agent File uat-test-pool-supervisor.md
Mode subagent
Model anthropic/claude-sonnet-4-6
Temperature 0.3
Tracking Prefix AUTO-UAT-POOL
Worker Count N/4 (quarter allocation)

8.5.1 Purpose

Discovers testable feature areas from the specification, dispatches parallel workers to test each area against the spec, files bug issues for gaps, and captures successful workflows as documentation examples.

8.5.2 Dual-Mode Operation

This agent operates in two modes:

  • Pool Supervisor Mode (max_workers > 1): Discovers feature areas, dispatches N workers, monitors completion, immediately refills slots.
  • Worker Mode (max_workers = 1 or specific feature area): Clones the repo, tests one feature area, files bugs, generates documentation.

8.5.3 Milestone Scope Guard

Only critical bugs get assigned to the active milestone. Non-critical issues go to the backlog with no milestone. This prevents scope explosion in converging milestones.


8.6 Bug Hunt Pool Supervisor

Property Value
Agent File bug-hunt-pool-supervisor.md
Mode subagent
Model google/gemini-2.5-pro
Temperature 0.1
Tracking Prefix AUTO-BUG-POOL
Worker Count N/4 (quarter allocation)

8.6.1 Purpose

Proactive bug detection through deep code analysis combined with specification comparison. Maps all source modules and dispatches parallel workers, each scanning one module through nine analysis passes.

8.6.2 Nine Analysis Passes

  1. Error handling analysis
  2. Concurrency analysis
  3. Security analysis
  4. Boundary condition analysis
  5. Resource management analysis
  6. Type safety analysis
  7. Specification alignment analysis
  8. Code consistency analysis
  9. Data flow analysis

8.6.3 Model Choice Rationale

Uses google/gemini-2.5-pro for its massive context window, which allows holding the entire codebase in mind for cross-module analysis.


8.7 Test Infrastructure Pool Supervisor

Property Value
Agent File test-infra-pool-supervisor.md
Mode subagent
Model google/gemini-2.5-pro
Temperature 0.2
Tracking Prefix AUTO-INF-POOL
Worker Count N/4 (quarter allocation)

8.7.1 Purpose

Analyzes testing infrastructure and proposes improvements. Never disables or weakens existing checks; only proposes additions and optimizations.

8.7.2 Eight Analysis Areas

  1. CI execution time
  2. Coverage gaps
  3. Test architecture
  4. Flaky tests
  5. CI pipeline design
  6. Test data quality
  7. Missing test levels
  8. Dependency security

8.7.3 Duplicate Avoidance

Documented as the "#1 problem with this agent" due to historical creation of 48+ issues with massive duplication. Five mandatory checks before filing any issue: keyword search, cross-area search, closed issues search, dedup proof in issue body, and uncertainty avoidance.


9. Singleton Supervisors (Tier 1)

9.1 Architecture Supervisor

Property Value
Agent File architecture-pool-supervisor.md
Mode subagent
Model anthropic/claude-sonnet-4-6
Temperature 0.3
Tracking Prefix AUTO-ARCH
Polling Interval 30 minutes

Purpose: Continuously monitors for specification needs. Writes or extends docs/specification.md. Defines module boundaries, interfaces, data models, and patterns. Major changes go through PRs with "needs feedback" label for human approval. Described as "the most consequential agent -- bad architecture cascades everywhere."

Subagents: ref-reader, automation-tracking-manager

Workflow: Checks for triggers every 30 minutes: new milestones without spec coverage, spec ambiguities reported by implementers, human requests for clarification, or initial bootstrap (no spec exists). When the spec grows beyond approximately 3,000 lines, transitions from a single docs/specification.md file to a docs/specification/ directory with one file per module. Major architectural changes go through PRs with the needs feedback label; minor clarifications are committed directly.

Specification Structure: Must contain Overview, Module Definitions (boundaries, responsibilities, public interfaces), Cross-Cutting Concerns (error handling, logging, configuration), Integration Points, and Milestone Plan.

9.2 Epic Planning Supervisor

Property Value
Agent File epic-planning-pool-supervisor.md
Mode subagent
Model anthropic/claude-sonnet-4-6
Temperature 0.2
Tracking Prefix AUTO-EPIC
Polling Interval 10 minutes

Purpose: Monitors for milestones without issues, epics without children, and human requests for breakdown. Decomposes architecture into Forgejo Epics and Issues with proper dependency chains. Enforces ticket hierarchy (Legendary -> Epic -> Issue) with correct dependency directions (child BLOCKS parent).

Subagents: ref-reader, spec-reader, forgejo-label-manager

Four Phases Per Cycle:

  1. Hierarchical Compliance Enforcement: Find and fix orphaned issues (no parent Epic), orphaned Epics (no parent Legendary), incorrect dependency directions, and incomplete user-created Epics/Legendaries.
  2. Closure Evaluation: Identify Legendary and Epic closure candidates where all children are completed.
  3. Specification-First Compliance: Identify work requiring specification changes and create ADR -> Spec -> Implementation chains.
  4. Traditional Planning: Plan empty milestones, complete Epic planning, with Milestone Scope Guard preventing new issue creation in converging milestones.

Milestone Scope Guard: The Epic Planner must not create new issues in milestones that are converging (most issues completed). New discovered work goes to backlog.

9.3 Human Liaison Supervisor

Property Value
Agent File human-liaison-pool-supervisor.md
Mode subagent
Model anthropic/claude-sonnet-4-6
Temperature 0.3
Tracking Prefix AUTO-LIAISON
Polling Interval 2 minutes

Purpose: Bridges human developers and the autonomous agent system. Monitors all human activity on Forgejo (new issues, comments, PR reviews, label changes) and responds intelligently. Has full triage authority. Must strictly follow CODE_OF_CONDUCT.md.

Subagents: ref-reader, spec-reader, ci-log-fetcher, new-issue-creator, issue-state-updater, issue-analyzer, forgejo-label-manager, automation-tracking-manager

Ten-Step Monitoring Loop (polls every 2 minutes via bash("sleep 120")):

Step Action Frequency
0 Read system announcements from other agents Every 3 cycles
1 Discover new human activity (issues, comments, reviews, labels) Every cycle
2 Handle idle detection (gap analysis, stale checks) When idle
3 Triage new human-created issues Every cycle
4 Respond to human comments on issues Every cycle
5 Respond to human PR reviews Every cycle
6 Plan implementation for newly verified issues Every cycle
7 Epic/Legendary gap analysis Every 10th cycle
8 Check stale conversations Every 15th cycle
9 Refresh specification knowledge Every 20th cycle

Feedback Incorporation Protocol: When human feedback changes the nature of a ticket, the agent must update the issue description, notify the user with a diff of the changes, and confirm the updates. This prevents feedback from being lost in comment threads.

Human Response Timeouts: 48 hours for PR feedback, 24 hours for questions, 72 hours for blocked work, 48 hours for specification approval. The agent escalates after these timeouts.

activitydiag {
  "Poll Forgejo" -> "New Human Activity?";
  "New Human Activity?" -> "New Issue?" [label = "yes"];
  "New Human Activity?" -> "Idle Detection" [label = "no"];
  "New Issue?" -> "Triage & Verify" [label = "yes"];
  "New Issue?" -> "New Comment?" [label = "no"];
  "New Comment?" -> "Respond to Comment" [label = "yes"];
  "New Comment?" -> "New PR Review?" [label = "no"];
  "New PR Review?" -> "Respond to Review" [label = "yes"];
  "New PR Review?" -> "Periodic Checks" [label = "no"];
  "Triage & Verify" -> "Periodic Checks";
  "Respond to Comment" -> "Periodic Checks";
  "Respond to Review" -> "Periodic Checks";
  "Idle Detection" -> "Periodic Checks";
  "Periodic Checks" -> "Sleep 2 min" -> "Poll Forgejo";
}

9.4 Agent Evolution Supervisor

Property Value
Agent File agent-evolution-pool-supervisor.md
Mode subagent
Model anthropic/claude-sonnet-4-6
Temperature 0.2
Tracking Prefix AUTO-EVLV
Polling Interval 30 minutes

Purpose: Self-improvement meta-agent. Monitors agent effectiveness, identifies failure patterns, and proposes modifications to agent definitions. All changes go through human-approved PRs with "needs feedback" label.

Subagents: ref-reader, session-persister, automation-tracking-manager

Two-Step Proposal Workflow:

  1. Step 1 -- Proposal Issue: When a systematic pattern is identified (e.g., agents repeatedly failing at a specific task), the Agent Evolver creates a proposal issue with the needs feedback label describing the problem, evidence, and proposed change. It does NOT immediately implement the change.

  2. Step 2 -- Implementation PR: Only when a proposal is approved (label removed, State/Verified added, or human approval comment), the Agent Evolver creates a branch, modifies the agent definition file in .opencode/agents/, commits, pushes, and creates a PR with the needs feedback label for final human review.

Seven Analysis Steps Per Cycle (30-minute interval):

  1. Gather performance data from tracking issues and PR comments
  2. Identify systematic patterns (prompt improvements, workflow fixes, config adjustments, model tier adjustments, coordination improvements, capability gaps)
  3. Filter out already-proposed or rejected patterns
  4. Create proposal issues for new patterns
  5. Check for approved proposals and implement them
  6. Monitor existing improvement PRs
  7. Post progress to tracking issue (every 3 cycles)

Change Principles: Surgical changes only, evidence-based, one pattern per PR, explain reasoning, acknowledge risks, never re-propose rejected changes.

9.5 Architecture Guard

Property Value
Agent File architecture-guard-pool-supervisor.md
Mode subagent
Model google/gemini-2.5-pro
Temperature 0.1
Tracking Prefix AUTO-GUARD
Polling Interval 10 minutes

Purpose: Aggressive codebase coherence checker. Scans for pattern drift, duplicate code, module coupling, API inconsistencies, and technical debt. Creates refactoring issues proactively. Uses Gemini 2.5 Pro for its massive context window.

Subagents: ref-reader

Seven Check Categories:

  1. Duplicate Code: Functions or blocks with >70% similarity
  2. Inconsistent Patterns: Different error handling styles, naming conventions, or API patterns across modules
  3. Module Coupling: Cross-module imports that violate defined boundaries
  4. API Surface Inconsistencies: Inconsistent parameter naming, return types, or error handling in public interfaces
  5. Technical Debt Indicators: Functions >50 lines, deep nesting (>4 levels), TODO/FIXME comments
  6. Test Quality: Tests that don't verify meaningful behavior, missing edge cases
  7. Specification Drift: Implementation that has diverged from the specification

Each finding creates a Type/Refactor issue with State/Unverified. Only scans when the master SHA has changed since the last scan.

9.6 Specification Evolution Supervisor

Property Value
Agent File spec-update-pool-supervisor.md
Mode subagent
Model anthropic/claude-sonnet-4-6
Temperature 0.2
Tracking Prefix AUTO-SPEC
Polling Interval 15 minutes

Purpose: Evolves the project specification based on implementation discoveries. Compares implementation against spec after merges, updates the spec where implementation found a better approach, and creates issues where implementation deviates incorrectly.

Subagents: ref-reader, automation-tracking-manager

Two-Step Proposal Workflow (same pattern as Agent Evolution):

  1. Step 1 -- Proposal Issue: When a spec-implementation discrepancy is found, create a proposal issue with needs feedback label describing the discrepancy and proposed spec change.
  2. Step 2 -- Spec PR: When proposal is approved, create a branch, update docs/specification.md, commit, and create a PR with needs feedback label.

Discrepancy Classification:

  • Implementation found better approach: Update the spec to match implementation.
  • Implementation deviates incorrectly: Create a bug issue to fix the implementation.

Critical Rule: Never remove specification content that has not been implemented yet. The spec is forward-looking.

Critical Bug Prevention: When updating PRs via the Forgejo API, always re-send the full PR body. The Forgejo API deletes the description if the body field is not included in update calls.

9.7 Backlog Grooming Supervisor

Property Value
Agent File backlog-grooming-pool-supervisor.md
Mode subagent
Model anthropic/claude-sonnet-4-6
Temperature 0.1
Tracking Prefix AUTO-GROOMER
Polling Interval 5 minutes

Purpose: Continuous backlog quality maintenance. Runs nineteen analysis passes on all open issues. Works entirely through the Forgejo API; no clone required.

Subagents: ref-reader, new-issue-creator, forgejo-label-manager, automation-tracking-manager

Nineteen Analysis Passes (every 5-minute cycle):

# Pass Auto-Fix?
1 Duplicate issue detection (issues only, NOT PRs) Close duplicate
2 Orphan detection (no parent Epic link) Comment
3 Stale issue detection Comment
4 Label and milestone compliance Auto-fix labels
5 Priority consistency check Comment
6 Closeable issue detection (work merged) Close
7 Definition of Done audit Comment
8 Blocked chain analysis Comment
9 Closed issue state reconciliation Auto-fix labels
10 Dependency link compliance Auto-fix links
11 Issue body compliance check Comment
12 Epic completeness analysis Create children
13 Legendary completeness analysis Create children
14 Merged-PR issue closure verification Close issue
15 Open PR dependency health Comment
16 Stale PR detection Every 3 cycles
17 Scope creep detection Every 3 cycles
18 PR-Issue label synchronization Every cycle
19 Automation tracking ticket cleanup Every 5 cycles

Announcement Cleanup Protocol (Pass 19): Tracking and announcement issues are cleaned up with priority-based age thresholds:

Priority Status Tracking Max Age Announcement Max Age
Critical 1 hour 72 hours
High 1 hour 48 hours
Medium 1 hour 24 hours
Low 1 hour 12 hours

Status tracking issues (title contains Status:) are cleaned up aggressively (1-hour age threshold) because each new cycle creates a replacement. Announcements persist longer because they represent ongoing cross-agent coordination events. Announcements marked with [PERSIST] or [KEEP_OPEN] in their body are exempt from age-based cleanup. Duplicate tracking issues (same agent prefix, same cycle number) are consolidated by keeping the newest and closing the rest.

9.8 Documentation Supervisor

Property Value
Agent File documentation-pool-supervisor.md
Mode subagent
Model anthropic/claude-sonnet-4-6
Temperature 0.3
Tracking Prefix AUTO-DOCS
Polling Interval 20 minutes

Purpose: Generates and updates project documentation at milestone boundaries. Produces README, API docs, architecture docs, changelogs, and module docs. Always extends existing documentation, never overwrites.

Subagents: ref-reader

Five Documentation Types:

  1. README.md: Overview, installation, quick start, features
  2. API Documentation (docs/api/): One file per module
  3. Architecture Documentation (docs/architecture.md): High-level system design
  4. Changelog (CHANGELOG.md): Keep a Changelog format
  5. Module Documentation (docs/modules/): Per-module deep dives

Key Rule: Must NOT modify docs/timeline.md (exclusive to the Timeline Update Supervisor). All documentation must be written for mkdocs compatibility.

9.9 Timeline Update Supervisor

Property Value
Agent File timeline-update-pool-supervisor.md
Mode subagent
Model anthropic/claude-sonnet-4-6
Temperature 0.1
Tracking Prefix AUTO-TIME
Polling Interval 30 minutes

Purpose: Keeps docs/timeline.md accurate and current. Makes surgical updates to nine sections including Gantt charts (PlantUML), status summaries, completion history, risk tables, and schedule adherence entries. Never deletes historical data.

Subagents: ref-reader, automation-tracking-manager

Nine Sections Updated:

  1. Gantt Charts (PlantUML syntax): today marker, completion percentages, color codes, update log
  2. Current Status Summary
  3. Parallel Workstreams Table
  4. What Has Been Completed (APPEND ONLY -- never modify historical entries)
  5. What Remains To Be Done
  6. Milestone Roadmap Sections
  7. Schedule Risk Summary
  8. Risk Mitigation Table (resolve risks with strikethrough, never delete)
  9. Schedule Adherence History (APPEND ONLY -- one entry per day maximum)

Day Number Calculation: (today - 2026-02-09).days + 1

9.10 Project Owner Supervisor

Property Value
Agent File project-owner-pool-supervisor.md
Mode subagent
Model anthropic/claude-sonnet-4-6
Temperature 0.3
Tracking Prefix AUTO-PROJ-OWN
Polling Interval 5 minutes

Purpose: Autonomous strategic decision-maker. Triages unverified issues, assigns MoSCoW labels (exclusive authority), makes priority decisions, assigns developers, and periodically re-evaluates priorities. Supplements human project owners.

Subagents: ref-reader, spec-reader, issue-state-updater, new-issue-creator, forgejo-label-manager, automation-tracking-manager

Seven Steps Per Cycle (5-minute interval):

  1. Analyze timeline and developer capacity (every 20th cycle)
  2. Triage unverified issues (skip needs feedback, skip if Human Liaison already triaging)
  3. Assign MoSCoW labels to verified issues missing them (exclusive authority)
  4. Assign developers to unassigned critical/blocking issues
  5. Strategic priority review (every 10th cycle): re-evaluate MoSCoW, check stale high-priority, elevate backlog items
  6. Follow up on pending questions (every 5th cycle)
  7. Refresh knowledge base (every 20th cycle)

MoSCoW Decision Framework:

  • Must Have: Core specification requirements, blocking dependencies, security fixes
  • Should Have: Usability improvements, non-blocking features, quality-of-life
  • Could Have: Nice-to-have polish, advanced features, optimizations

Developer Assignment Rule: Default to the primary automation user (HAL9000) for most issues. Strategic delegation only when there is a strong expertise match, available capacity, and it would be significantly faster without creating coordination overhead.

9.11 System Watchdog Supervisor

Property Value
Agent File system-watchdog-pool-supervisor.md
Mode subagent
Model anthropic/claude-sonnet-4-6
Temperature 0.1
Tracking Prefix AUTO-WATCHDOG
Polling Interval 5 minutes

Purpose: The system's conscience. Continuously audits quality gates, branch protection, ticket states, priority ordering, PR pipeline health, supervisor health (zombie detection via session introspection), label compliance, ticket hierarchy, test infrastructure, and automation tracking health. Dispatches one-off fix agents for immediate corrections and creates issues for systemic problems.

9.11.1 Audit Schedule

Audit Frequency Severity Level
Master CI Health Every cycle CRITICAL
Quality Gate Compliance Every cycle CRITICAL
Branch Protection Every cycle CRITICAL
Ticket State Integrity Every cycle HIGH
Priority/Milestone Ordering Every cycle HIGH
PR Pipeline Health Every cycle HIGH
Struggling PR Detection Every cycle CRITICAL
Supervisor Health (Zombie) Every cycle HIGH
Label/Dependency Compliance Every cycle MEDIUM
Ticket Hierarchy Every cycle MEDIUM
Test Infrastructure Every cycle MEDIUM
Improvement Generation Every cycle MEDIUM
Automation Tracking Health Every cycle HIGH
Session Spot-Check Every cycle HIGH
Deep Session Introspection Every 6th cycle HIGH
Closed Item Interactions Every 3rd cycle MEDIUM
System Health Monitoring Every 2nd cycle HIGH

9.11.2 Critical Audit Details

Audit 0 -- Master CI Health Monitoring (EMERGENCY priority): The highest-priority audit. If ANY test fails on master, the watchdog immediately:

  1. Investigates specific failing tests by scraping CI logs via web authentication
  2. Parses logs to identify individual failing test scenarios (Behave patterns, Robot patterns, generic pytest)
  3. Creates a Priority/CI-Blocker issue for each failing test with skip instructions
  4. Creates a follow-up Priority/High fix issue for the underlying problem This audit exists because master CI failures block all future PR merges, creating a system-wide deadlock.

Audit 5b -- Struggling PR Detection: Detects PRs where automated agents are failing repeatedly:

  • Counts bot fix attempts by analyzing comments for fix-related phrases ("fixed", "addressing", "resolved", "updated", "applied fix")
  • Tracks consecutive failure patterns across watchdog cycles
  • Detects repetitive commit patterns (same fix being attempted multiple times)
  • After 3+ failed fix attempts, creates a request for human assistance with full attempt history
  • After 5+ consecutive failures in the same watchdog cycle, flags as a "stuck in loop" pattern

Audit 6 -- Supervisor Health / Zombie Detection: Uses the OpenCode Server API to perform deep session introspection:

  • Reads the last 5 messages from each supervisor session
  • Sleep-only pattern: If last 3+ tool calls are all bash sleep with no productive actions, the agent is a zombie (likely context exhaustion)
  • Error-loop pattern: If last 3+ tool calls all returned errors, the agent is stuck
  • Identical-call loop: If the same tool+arguments appears 3+ times in the last 5 messages, the agent is in an infinite loop
  • Missing supervisors are detected by comparing running sessions against the expected set of 18

Audit 11 -- Automation Tracking Health: Monitors tracking issues for stalled agents with automated recovery:

  • Calculates expected update interval per agent type (e.g., Groomer every 5 minutes, Watchdog every 30 minutes)
  • Agents overdue by >20% trigger recovery: session termination, root cause analysis, and diagnostic issue creation

Audit 12/13 -- Session Spot-Check and Deep Introspection: The quick spot-check (every cycle) scans the 3 most recent active sessions for forbidden patterns (force_merge, direct push to master, type: ignore). The deep introspection (every 6th cycle) comprehensively analyzes ALL supervisor sessions for misbehavior, progress, conversation health, context exhaustion, and cross-agent conflicts.

9.11.3 Watchdog Dispatch Agents

When the System Watchdog detects violations, it dispatches one-off fix agents via the Async Agent Manager:

Finding Type Dispatched Agent Action
Quality gate violation quality-enforcer Repair branch protection, create CI-Blocker issues
State label mismatch state-reconciler Bulk-fix state labels across all issues
Master CI failure (creates issues directly) Priority/CI-Blocker skip issue + Priority/High fix issue
Struggling PR (adds label) Adds needs feedback label and requests human help

10. Implementation Workers (Tier 2)

10.1 Implementation Worker

Property Value
Agent File implementation-worker.md
Mode subagent
Model openai/gpt-5-codex
Temperature 0.1

10.1.1 Purpose

Dual-mode worker that handles both PR fixing and issue implementation. One instance runs per branch/PR, in parallel with other workers.

10.1.2 Mode Detection

The worker detects its mode from the prompt:

  • PR-Fix Mode (mode: pr-fix): Receives PR number, work type, issue number, branch. Fixes CI failures, handles review feedback, resolves merge conflicts.
  • Issue-Impl Mode (mode: issue-impl): Receives issue number. Implements the issue from scratch through to merged PR.

10.1.3 Issue Implementation Workflow

activitydiag {
  "Read Announcements" -> "Crash Recovery Check";
  "Crash Recovery Check" -> "Claim Issue";
  "Claim Issue" -> "Clone & Branch Setup";
  "Clone & Branch Setup" -> "Analyze Issue (parallel)" -> "Implement Subtasks (wave dispatch)";
  "Implement Subtasks (wave dispatch)" -> "Commit & Push";
  "Commit & Push" -> "Create PR";
  "Create PR" -> "Initial CI Fix";
  "Initial CI Fix" -> "PR Lifecycle Loop";
  "PR Lifecycle Loop" -> "Reviews?" -> "Handle Feedback" [label = "changes requested"];
  "Reviews?" -> "CI Passing?" [label = "approved"];
  "Handle Feedback" -> "Reviews?";
  "CI Passing?" -> "Merge PR" [label = "yes"];
  "CI Passing?" -> "Fix CI" [label = "no"];
  "Fix CI" -> "CI Passing?";
  "Merge PR" -> "Cleanup Clone";
}

10.1.4 PR-Fix Mode Workflow

When operating in PR-fix mode, the worker follows a different workflow focused on diagnosing and resolving the specific problem:

activitydiag {
  "Receive PR Assignment" -> "Clone & Checkout Branch";
  "Clone & Checkout Branch" -> "Gather Deep Context";
  "Gather Deep Context" -> "Analyze Previous Attempts";
  "Analyze Previous Attempts" -> "Stuck Pattern?";
  "Stuck Pattern?" -> "Request Human Help" [label = "yes, >3 stuck cycles"];
  "Stuck Pattern?" -> "Select Fix Strategy" [label = "no"];
  "Select Fix Strategy" -> "Execute Fix";
  "Execute Fix" -> "Run Quality Gates";
  "Run Quality Gates" -> "All Pass?";
  "All Pass?" -> "Push & Monitor" [label = "yes"];
  "All Pass?" -> "Analyze Failure" [label = "no"];
  "Analyze Failure" -> "Stuck Pattern?";
  "Push & Monitor" -> "PR Merged?" -> "Cleanup" [label = "yes"];
  "PR Merged?" -> "New Review Feedback?" [label = "no"];
  "New Review Feedback?" -> "Select Fix Strategy" [label = "yes"];
  "New Review Feedback?" -> "Sleep & Re-check" [label = "no"];
  "Sleep & Re-check" -> "PR Merged?";
}

Work types handled: review-feedback (implement reviewer suggestions, including COMMENT-only reviews), ci-fix (fix failing CI checks), merge-conflicts (resolve conflicts with master), ready-to-merge (final checks and merge using 3-tier approval detection per Section 6.17.1), awaiting-review (monitor and shepherd PRs that have no reviews yet).

Deep Context Gathering (Phase 2 of PR-fix mode): Before attempting ANY fix, the worker gathers comprehensive context:

  • Specification sections relevant to the PR via spec-reader
  • Timeline context (project phase and priorities) via ref-reader
  • Full comment history on both the PR and its linked issue
  • Full commit history with diffs to understand the implementation
  • Previous fix attempts extracted from comments (approach, outcome, timestamp)
  • CI failure patterns with error signatures (to detect repeated failures)
  • The actual code being modified (read files, understand structure)

The worker then calls analyze_previous_failures() to detect repeated approaches that have already been tried, persistent CI errors that are not changing between attempts, and ineffective strategies. This analysis drives the fix strategy selection to avoid repeating failed approaches.

Intelligent Loop Prevention (Phase 5): The worker tracks every fix attempt with a structured history including the approach taken, the error signature before and after, and the outcome. Three detection mechanisms prevent infinite loops:

  1. Stuck detection: If the same error signature appears in three or more consecutive fix attempts, the worker is stuck.
  2. Repeated approach detection: If the same fix strategy has been tried before and failed, try a different approach.
  3. Escalation threshold: After three stuck detections, the worker posts a detailed diagnostic comment documenting all attempted approaches and their outcomes, adds the needs feedback label, and exits gracefully to allow human intervention.

Merge Safety: When the work type is ready-to-merge, the worker follows this sequence:

  1. Verify approvals via the 3-tier detection (Section 6.17.1).
  2. Check if the branch needs rebasing: Fetch fresh PR data via forgejo_get_pull_request_by_index and compare merge_base against base.sha. If different, rebase the branch (git fetch + git rebase + git push --force-with-lease), then wait 2 minutes for CI before re-checking.
  3. Delegate the actual merge to safe_merge_pr() which now includes post-merge verification (Section 8.3.4).
  4. Only post a "(verified)" success comment after safe_merge_pr() returns True.
  5. If merge verification fails (branch was silently not merged), analyze the failure message for rebase-needed indicators and retry.

10.1.5 CI Artifact Mapping

When debugging CI failures, agents use this mapping to locate log artifacts:

CI Job Artifact Name Log File Path
lint ci-logs-lint build/nox-lint-output.log
typecheck ci-logs-typecheck build/nox-typecheck-output.log
security ci-logs-security build/nox-security-output.log
quality ci-logs-quality build/nox-quality-output.log
unit_tests ci-logs-unit-tests build/nox-unit-tests-output.log
integration_tests ci-logs-integration-tests build/nox-integration-tests-output.log
e2e_tests ci-logs-e2e-tests build/nox-e2e-tests-output.log
coverage ci-logs-coverage build/nox-coverage-output.log

The CI Log Fetcher agent retrieves these logs via cookie-based web authentication because the Forgejo Actions API is not available. The process is:

  1. Login: POST to https://<host>/user/login with user_name, password, and _csrf token (extracted from the login page). Store session cookies in /tmp/forgejo_cookies.txt.
  2. Navigate: GET the actions page for the repository using the session cookies.
  3. Extract run ID: Parse the HTML to find the specific CI run.
  4. Download logs: GET the log artifact using the session cookies.
  5. Cleanup: Delete the cookie file after use.

The System Watchdog uses the same cookie-based approach for its Master CI Health audit (Section 9.11.2, Audit 0), storing cookies in /tmp/watchdog_cookies.txt instead. Both agents require FORGEJO_USERNAME and FORGEJO_PASSWORD environment variables.

10.1.6 Issue Implementation: Work Claiming and Crash Recovery

Before starting work on an issue, the Implementation Worker must:

  1. Crash Recovery Check (Phase 0.5): Check for an existing clone directory, an existing PR, existing commits, or uncommitted changes from a previous interrupted run. If found, resume from the appropriate phase rather than starting over.

  2. Claim the Issue (Phase 0.5, MANDATORY): Post a [CLAIM] comment on the issue to prevent other workers from claiming it. Send heartbeat comments every 10 minutes. Release the claim with a [RELEASED] comment when done, using try/finally to guarantee release even on failure.

  3. Read Announcements (Phase 0): Check for critical announcements from other agents (watchdog quality gate violations, architecture changes, groomer scope alerts) that might affect the work.

10.1.7 Subtask Wave Dispatch

Subtasks are analyzed for dependencies and grouped into waves. Within each wave, all subtasks execute in parallel via the Subtask Loop agent. Waves execute sequentially. After each wave:

  • Conflict resolution: If multiple subtasks in the same wave modified the same files, the worker resolves conflicts.
  • Failure propagation: If a subtask fails and downstream subtasks depend on it, those are skipped.
  • Out-of-scope discovery: If implementation reveals work not covered by existing subtasks, the worker creates new subtasks in future waves or creates new issues via new-issue-creator.

10.1.8 Test Stability Requirements

The Implementation Worker enforces strict test determinism rules:

  • NEVER: time-based dependencies, random values without seeding, file system race conditions, network dependencies in tests, order-dependent tests, uncontrolled async operations
  • ALWAYS: fixed test data, mock external dependencies, isolated temp filesystems, seeded random generators, proper test isolation, synchronous operations in tests

10.1.9 Subagent Interactions

The Implementation Worker calls more subagents than any other agent in the system:

Subagent Purpose
ref-reader Load project references
ci-log-fetcher Retrieve CI logs
issue-analyzer Analyze issue metadata and subtasks
issue-state-updater Transition issue states
branch-setup Create/checkout branches
spec-reader Extract relevant specification sections
subtask-loop Implement subtasks with progressive escalation
test-fixer Fix broken existing tests
issue-note-writer Document implementation decisions
subtask-checker Update subtask checkboxes
new-issue-creator Create issues for discovered work
commit-message-formatter Format commit messages
git-committer Stage, commit, push
pr-description-writer Write PR descriptions
pr-creator Create pull requests
pr-ci-test-fixer Fix CI failures
forgejo-label-manager Manage labels
automation-tracking-manager Tracking issues

11. Progressive Escalation (Tier 3)

11.1 Tier Selector Architecture

The progressive escalation system uses four tier selector agents that serve as model-setting proxies:

Tier Agent Model Cost
tier-haiku anthropic/claude-haiku-4-5 Lowest
tier-codex openai/gpt-5-codex Low
tier-sonnet anthropic/claude-sonnet-4-6 Medium
tier-opus anthropic/claude-opus-4-6 Highest

Each tier selector receives a worker_type parameter and context, then invokes the corresponding worker agent (implementer, behave-tester, robot-tester, etc.). The worker inherits the tier selector's model. The tier selectors are pure pass-through agents: they must not modify, interpret, summarize, or filter the context.

11.2 Escalation Schedule

The Subtask Loop manages escalation according to this schedule:

Starting Tier Attempt 1 Attempt 2 Attempt 3 Attempt 4 Attempt 5+
Haiku haiku haiku codex sonnet opus (forever)
Codex codex codex sonnet opus opus (forever)
Sonnet sonnet opus opus opus opus (forever)
Opus opus opus opus opus opus (forever)

Transient errors (API timeouts, rate limits, network errors) trigger retries without incrementing the attempt counter. Only genuine failures (quality gate failures, review rejections) increment the counter.

11.3 Subtask Loop Workflow

activitydiag {
  "Evaluate Difficulty" -> "Select Starting Tier";
  "Select Starting Tier" -> "Implement via Tier Selector";
  "Implement via Tier Selector" -> "Verify Meaningful Change";
  "Verify Meaningful Change" -> "Write Tests (parallel: Behave + Robot + ASV)";
  "Write Tests (parallel: Behave + Robot + ASV)" -> "Fix Broken Tests";
  "Fix Broken Tests" -> "Quality Gates (lint, typecheck, unit, integration, coverage)";
  "Quality Gates (lint, typecheck, unit, integration, coverage)" -> "All Pass?";
  "All Pass?" -> "Implementation Review" [label = "yes"];
  "All Pass?" -> "Escalate?" [label = "no, max inner passes"];
  "Implementation Review" -> "Approved?" -> "Done" [label = "yes"];
  "Approved?" -> "Escalate?" [label = "no"];
  "Escalate?" -> "Next Tier Available?" -> "Implement via Tier Selector" [label = "yes, increment attempt"];
  "Next Tier Available?" -> "Implement via Tier Selector" [label = "no, retry at max tier"];
}

11.4 Specialized Workers

These agents have no model specified in their frontmatter; they inherit the model from their tier selector caller:

Worker Purpose
Implementer Writes code for subtasks. Never writes tests.
Behave Tester Writes BDD/Gherkin unit tests in features/.
Robot Tester Writes Robot Framework integration tests in robot/. No mocking.
Lint Fixer Runs nox -e lint and fixes all linting errors.
Typecheck Fixer Runs nox -e typecheck (Pyright). Never uses # type: ignore.
Test Fixer Distinguishes obsolete tests from genuine bugs.
Coverage Improver Writes tests to maintain >= 97% coverage.
Unit Test Runner Executes Behave tests and fixes failures.
Integration Test Runner Executes Robot tests and fixes failures.

12. Supporting Agents

12.1 PR Management Agents

Agent Purpose Model
PR Manager Unified interface for all PR operations claude-sonnet-4-6
PR Creator Creates PRs with proper metadata and dependencies claude-sonnet-4-6
PR Editor Safely edits PRs; always preserves description claude-sonnet-4-6
PR Status Analyzer Multi-dimensional PR status analysis gpt-5-codex
PR CI Test Fixer Fixes CI failures, amends commit, force-pushes claude-sonnet-4-6
PR Description Writer Generates detailed PR descriptions claude-haiku-4-5
PR Reviewer Independent code review with two-step review protocol (Section 6.17.2) claude-sonnet-4-6

12.1.1 Critical PR Management Behavioral Rules

The following rules are critical to the correct functioning of the PR management agents and have been the source of significant bugs historically:

PR Editor: Description Preservation Protocol

!!! warning "The #1 Bug Prevented"

The Forgejo API deletes the PR description if the `body` field is not included in update calls. Every single PR update -- even if it only changes a label or milestone -- must fetch the current PR, extract its description, and include it in the update payload. The PR Editor enforces this as its primary invariant: before any edit, it fetches the current PR data, prepares the update with ALL existing fields preserved, and only then applies the change.

PR Creator: Label Inheritance from Issue

When creating a PR, the PR Creator inherits comprehensive labels from the associated issue:

  • All Type/* labels (e.g., Type/Bug, Type/Feature)
  • All Priority/* labels (e.g., Priority/High)
  • All MoSCoW/* labels (e.g., MoSCoW/Must Have)
  • All Points/* labels (e.g., Points/5)
  • Adds State/In Review to the PR

Label inheritance is performed via the Forgejo Label Manager subagent. The PR Creator also creates the dependency link (PR BLOCKS issue, per Section 6.11) and transitions the issue to State/In Review via the Issue State Updater.

PR CI Test Fixer: Amend-and-Force-Push Workflow

The PR CI Test Fixer is the only agent that amends commits and force-pushes. It follows this specific protocol:

  1. Fix the code in the isolated clone
  2. Stage changes and amend the existing commit (git commit --amend)
  3. Force-push with lease (git push --force-with-lease) to BOTH origin and upstream remotes
  4. Wait for new CI checks to run
  5. Repeat until all checks pass

This agent must never create new commits (which would pollute the PR with fix-up commits). It must always amend the existing commit.

Git Committer: Dual-Remote Push

The Git Committer pushes to two remotes in sequence:

  1. git push -u origin <branch> (the fork/working remote)
  2. git push upstream <branch> (the canonical repository)

Both pushes are required. If either fails, the error is reported with full details including the remote URL, branch name, and error message.

12.1.2 PR Reviewer Detailed Specification

The PR Reviewer warrants detailed specification because of its critical two-step review protocol and flaky test detection capabilities.

Review Process:

  1. Gather Deep Context (new): Before reviewing, check previous review history, related PRs, and full linked issue context to avoid redundant feedback.
  2. Read PR metadata and diff via Forgejo API.
  3. Check CI status and fetch logs via ci-log-fetcher if failing.
  4. Load specification context via ref-reader.
  5. Review against standard criteria plus assigned focus areas.
  6. Flaky Test Detection: Analyze test patterns for non-determinism (time dependencies, unseeded randomness, race conditions, shared state, order dependence). Perform CI pattern analysis and multi-PR analysis to detect intermittent failures.
  7. Watch for Anti-Patterns: Detect repetitive fix attempts, type system workarounds (# type: ignore), test quality issues (trivial assertions), and architectural drift.
  8. Make APPROVE or REQUEST_CHANGES decision using the Two-Step Review Protocol (Section 6.17.2).

Flaky Test Red Flags: The reviewer specifically watches for patterns that cause intermittent CI failures:

  • time.sleep() or time.time() in test code without mocking
  • random.choice() / random.randint() without seed
  • Shared file system paths between tests
  • Tests that pass locally but fail in CI
  • Tests with timing-sensitive assertions

Permissions Rationale: The PR Reviewer has edit: deny -- it is strictly read-only. It posts reviews and comments but never modifies code. This ensures the reviewer provides an independent perspective without risking file corruption.

12.2 Issue Management Agents

Agent Purpose Model
Issue Finder Queries and prioritizes open issues gpt-5-nano
Issue Analyzer Extracts metadata, subtasks, DoD from issues claude-haiku-4-5
Issue Note Writer Documents design decisions as comments claude-haiku-4-5
Issue Comment Formatter Structured comment formatting gpt-5-codex
Issue State Updater Transitions issue state labels gpt-5-nano
New Issue Creator Creates issues for discovered work claude-sonnet-4-6
Subtask Checker Updates subtask checkboxes in issue body gpt-5-nano

Issue State Updater: Label Transition Protocol

The Issue State Updater performs state transitions through a 7-step process: read current state, validate preconditions, remove old state label (via REST API DELETE), apply new state label (via REST API POST), handle special cases (close issue for terminal states, remove Blocked label), synchronize PR states, and report results. Retries up to 3 times with exponential backoff (2s, 4s, 8s) on API failures. Handles HTTP 404, 401/403, 422, and 429 status codes specifically.

Issue Note Writer: Code Location Rule

The Issue Note Writer must reference code by logical location ONLY (module path, class name, method name), never by line number. Line numbers change with every commit, making them unreliable for documentation. Each comment must include the commit hash for traceability.

New Issue Creator: Milestone Scope Guard

The New Issue Creator applies a strict scope guard for milestone assignment:

  1. Critical bugs: assign to the milestone where the bug was found
  2. All other discovered issues: no milestone, Priority/Backlog
  3. Exception: only if the caller explicitly specifies a milestone AND the issue is essential
  4. Never add non-critical issues to converging milestones

12.3 Git and Repository Agents

Agent Purpose Model
Repo Isolator Clones to /tmp/ with auth and cleanup gpt-5-codex
Branch Setup Creates/checks out branches with rebase gpt-5-nano
Git Committer Stages, commits, pushes to both remotes gpt-5-nano
Git Commit Helper Safe commits with validation and rollback gpt-5-codex
CI Log Fetcher Retrieves CI logs via web authentication gpt-5-codex

12.4 Reference and Knowledge Agents

Agent Purpose Model
Ref Reader Reads and summarizes CONTRIBUTING.md, spec, timeline gemini-2.5-pro
Ref Material Loader Caches reference materials for child agents gpt-5-codex
Spec Reader Extracts issue-relevant specification sections gemini-2.5-pro
Difficulty Evaluator Recommends starting model tier for subtasks claude-haiku-4-5

Ref Material Loader: Caching Strategy

The Ref Material Loader implements a parent-child caching model to reduce redundant Ref Reader calls. When a pool supervisor loads references, it caches the result in /tmp/ref-cache/ and passes the cached content to all its workers. This reduces O(N) Ref Reader calls (one per worker) to O(1) (one per cycle).

  • Cache files are stored in /tmp/ref-cache/ with cycle-based naming
  • Cache validity: 24-hour expiry, cycle-based invalidation
  • Stale caches older than 7 days are automatically cleaned
  • Performance benefit: 80% faster for 5 workers, 90% for 10, 95% for 20

Difficulty Evaluator: Conservative Bias

The Difficulty Evaluator recommends starting model tiers based on a five-axis assessment (scope, algorithmic complexity, novelty, integration surface, ambiguity). It has an explicit conservative bias: when in doubt, it must recommend a LOWER tier, defaulting to Haiku. This is safe because the escalation system (Section 11.2) automatically promotes to higher tiers when the lower tier fails. Under-estimating difficulty costs one retry; over-estimating difficulty wastes money on every successful task.

12.5 Label and Forgejo Agents

Agent Purpose Model
Forgejo Label Manager Centralized label operations (CANNOT create) claude-sonnet-4-6
Forgejo Signature Appender Standardized bot signature formatting gpt-5-codex
Automation Tracking Manager Centralized tracking issue operations gpt-5-nano

12.6 Quality and Verification Agents

Agent Purpose Model
Implementation Reviewer Post-quality-gate functional correctness review claude-sonnet-4-6
Milestone Reviewer Holistic review after milestone completion claude-sonnet-4-6
Product Verifier End-to-end product completion verification claude-sonnet-4-6
Quality Enforcer Repairs branch protection; creates CI-Blocker issues claude-sonnet-4-6
State Reconciler Bulk-fixes state label mismatches claude-sonnet-4-6

12.7 Session Management Agents

Agent Purpose Model
Async Agent Manager Centralized async session operations gpt-5-codex
Async Agent Monitor Health checks and restart capabilities gpt-5-codex
Async Agent Cleanup Safe single-session shutdown gpt-5-codex
Async Agent Cleanup All Batch session termination gpt-5-codex
Session Persister Persists state via tracking issues gpt-5-nano
Session Cleanup One-shot cleanup of stale sessions (primary mode)

Async Agent Manager: Retry Logic

All operations use a five-attempt retry schedule with exponential backoff: 0 seconds, 5 seconds, 30 seconds, 2 minutes, 5 minutes. This handles transient OpenCode Server API failures gracefully.

Async Agent Manager: Bash Restrictions

The Async Agent Manager's bash permissions are tightly restricted to prevent misuse. Only these commands are allowed:

  • curl*localhost:4096* and curl*127.0.0.1:4096* (OpenCode Server API calls)
  • python3*, echo*, date*, jq*, grep*, sed*, awk*, cat*, rm*, sleep*

All other bash commands are denied, including any that could manipulate the filesystem, git, or external APIs.

Async Agent Cleanup All: Filter Patterns

Supports targeted cleanup with filter patterns: all (everything), tag:TAG_NAME (by tag prefix), status:STATUS (by session status), title:PATTERN (by title match). Also supports exclude_pattern for protecting specific sessions during mass cleanup. Has a dry_run mode for previewing cleanup actions.


13. Shared Modules

Shared modules in .opencode/agents/shared/ define reusable protocols and utilities that all agents must incorporate. Each module is a markdown file that agents reference for consistent behavior.

13.1 Coordination Protocols (shared/coordination_protocols.md)

Defines the work-item claiming protocol with constants (2-hour claim duration, 10-minute heartbeat interval), comment-based claims with prefixes ([CLAIM:, [HEARTBEAT:, [RELEASE:), and concurrent work detection with conflict matrices. See Section 6.12 for the full claiming protocol specification.

Conflict Matrix: Code changes conflict with other code changes and merge attempts. Merge attempts conflict with everything. Reviews conflict with nothing.

13.2 Credential Security (shared/credential_security.md)

Mandates that credentials are never logged, always accessed via environment variables, validated without exposure, and cleaned up after use. Defines validation patterns and secure configuration functions.

Required Environment Variables: FORGEJO_PAT (40 hex chars), GIT_USER_NAME, GIT_USER_EMAIL, FORGEJO_USERNAME, FORGEJO_PASSWORD (8+ chars).

Optional: CA_MAX_PARALLEL_WORKERS (default 4), OPENCODE_SERVER_PASSWORD.

Seven Security Rules: (1) No credential logging, (2) No credentials in prompts, (3) No credentials in Forgejo comments, (4) No credentials in temp files (except cookies), (5) No partial credential exposure, (6) No credential defaults, (7) Validate credentials early at startup.

13.3 Error Handling (shared/error_handling.md)

Standardizes error types (NetworkError, GitError, GitConflictError, ForgejoError, CoordinationError, AlreadyClaimedError, ConfigurationError, OperationFailedError) and recovery patterns with retry logic and exponential backoff (1s, 2s, 4s base; 60s wait for rate limits).

Key Pattern: safe_operation_with_recovery() -- wraps any operation with retry logic, cleanup on failure via a CleanupManager context manager, and specific handling per error type.

13.4 Logging (shared/logging.md)

Mandates a structured log format: [AGENT:{name}][SESSION:{id}][ACTION:{action}][LEVEL:{level}] {message}. Errors at ERROR and CRITICAL levels auto-persist to Forgejo as issue comments. Standard action names: init, setup, clone, implement, test, review, merge, dispatch, monitor, cleanup.

13.5 Performance Monitoring (shared/performance_monitoring.md)

Provides operation timing, resource monitoring (CPU, memory, I/O via psutil), health score calculation (0-1 scale based on success rates and resource usage), and system KPIs.

Key KPIs: issues_per_hour, prs_merged_per_hour, tests_written_per_hour, first_attempt_success_rate, review_approval_rate, test_coverage_trend, avg_issue_completion_time, avg_pr_fix_time, worker_utilization, system_health_score, failure_rate_trend, resource_pressure.

Adaptive Timeouts: Based on historical 99th percentile plus 50% buffer, ensuring timeouts grow with observed operation durations.

13.6 Merge Safety (shared/merge_safety.md)

Defines mandatory pre-merge verification including CI status, approval detection (with flexible keyword matching), conflict checking, post-merge verification, and the safe_merge_pr() function as the only approved merge mechanism. Direct forgejo_merge_pull_request calls without these checks are forbidden. See Section 6.18 for the merge safety protocol and Section 8.3.4 for the mandatory merge verification protocol.

Seven mandatory rules for all agents that merge:

  1. Always use safe_merge_pr(), never call forgejo_merge_pull_request directly
  2. Always call verify_merge_safety() before merging
  3. Handle both success and failure cases
  4. Never attempt to bypass safety checks
  5. Never use or accept a force_merge parameter
  6. Never post "merged successfully" without verifying merged == true via forgejo_get_pull_request_by_index
  7. Always check if the branch needs rebasing (merge_base != base.sha) before attempting merge

System Watchdog monitoring: The watchdog now monitors for "merged successfully" comments on PRs that are still open, as an additional safety net for the false-success bug.

13.7 Session State (shared/session_state.md)

Defines standardized patterns for persisting agent session state for crash recovery and work resumption. State is persisted via Forgejo (never local files), checkpointed frequently, versioned (format v1.0), and must be human-readable.

Checkpoint Format: JSON wrapped in [CHECKPOINT] comments on a tracking issue, containing version, timestamp, agent name, session ID, current phase, and phase-specific data.

Resume Patterns: Agent-specific resume logic maps checkpoint phases to restart points (e.g., clone_complete resumes at Phase 2, subtasks_done resumes at Phase 3).

13.8 Tracking Discovery Guide (shared/tracking_discovery_guide.md)

Defines how ALL agents discover, interact with, and coordinate through the automation tracking issue system. The universal discovery mechanism is: query Forgejo for issues with the Automation Tracking label, filter by agent prefix in the title, and parse the structured body.

Core Discovery Patterns:

  • discover_all_automation_activity(): Find all open issues with "Automation Tracking" label, extract active agent prefixes.
  • check_agent_activity(prefix, max_age): Check a specific agent's recent activity.
  • get_agent_status_details(prefix): Get detailed status from the most recent tracking issue.

13.9 Bug Hunter Tracking Update (shared/bug_hunter_tracking_update.md)

Defines the migration guide for converting the Bug Hunt supervisor from the old session state system to the new individual tracking issue system. Documents the tracking issue format [AUTO-BUG-POOL] Bug Detection Pool Status (Cycle N), the cleanup protocol (one issue per cycle, preserve announcements), and worker coordination via announcement issues.


14. Inter-Agent Interaction Map

The following diagram shows how all agents interact with each other through subagent calls and async launches.

@startuml
!theme plain
skinparam linetype ortho
skinparam nodesep 50
skinparam ranksep 30

package "Tier 0: Orchestrator" {
  [Product Builder] as PB
}

package "Tier 1: Pool Supervisors" {
  [Implementation Pool] as IPS
  [PR Review Pool] as PRP
  [PR Fix Pool] as PFP
  [PR Merge] as PMG
  [UAT Test Pool] as UTP
  [Bug Hunt Pool] as BHP
  [Test Infra Pool] as TIP
}

package "Tier 1: Singletons" {
  [Architecture] as ARCH
  [Epic Planning] as EPIC
  [Human Liaison] as HL
  [Agent Evolution] as AE
  [Arch Guard] as AG
  [Spec Evolution] as SE
  [Backlog Grooming] as BG
  [Documentation] as DOC
  [Timeline] as TL
  [Project Owner] as PO
  [System Watchdog] as SW
}

package "Tier 2: Workers" {
  [Impl Worker] as IW
  [PR Reviewer] as PRR
}

package "Tier 3: Specialists" {
  [Subtask Loop] as SL
  [Tier Selectors] as TS
  [Implementer] as IMPL
  [Behave Tester] as BT
  [Robot Tester] as RT
  [Lint Fixer] as LF
  [Typecheck Fixer] as TF
  [Test Fixer] as TEF
  [Coverage Improver] as CI
  [Unit Test Runner] as UTR
  [Integration Test Runner] as ITR
}

package "Shared Services" {
  [Async Agent Mgr] as AAM
  [Tracking Mgr] as ATM
  [Ref Reader] as RR
  [Label Mgr] as LM
  [Repo Isolator] as RI
  [CI Log Fetcher] as CLF
}

PB --> AAM : launches all supervisors
PB --> ATM : tracking
PB --> RR : load refs

IPS --> AAM : launches workers
IPS --> ATM : tracking
PRP --> AAM : launches reviewers
PRP --> ATM : tracking
PFP --> IW : dispatches (sync Task)
UTP --> AAM : launches workers
BHP --> AAM : launches workers
TIP --> AAM : launches workers
PMG --> ATM : tracking
PMG --> RI : rebase clones

IW --> SL : implement subtasks
IW --> ATM : tracking
IW --> CLF : fetch CI logs
IW --> RR : load refs
SL --> TS : select model tier
TS --> IMPL : implement
TS --> BT : unit tests
TS --> RT : integration tests
TS --> LF : lint
TS --> TF : typecheck
TS --> TEF : fix tests
TS --> CI : coverage
TS --> UTR : run unit tests
TS --> ITR : run integration tests

SW --> AAM : dispatch fix agents
SW --> ATM : tracking
BG --> LM : label operations
BG --> ATM : tracking
EPIC --> LM : label operations
HL --> LM : label operations
HL --> ATM : tracking
PO --> LM : label operations
PO --> ATM : tracking
PRR --> RR : load refs
PRR --> CLF : fetch CI logs
@enduml

14.1 Forgejo-Centric Coordination Flow

The following diagram shows how agents coordinate exclusively through Forgejo artifacts (issues, PRs, comments, labels) without any direct inter-agent communication:

@startuml
!theme plain
skinparam actorStyle awesome

actor "Human Developer" as Human
database "Forgejo" as FG

rectangle "Agent System" {
  [Human Liaison] as HL
  [Project Owner] as PO
  [Epic Planner] as EP
  [Impl Pool] as IP
  [Impl Worker] as IW
  [PR Review Pool] as RP
  [PR Reviewer] as RV
  [PR Merge] as PM
  [Backlog Groomer] as BG
  [System Watchdog] as SW
}

Human --> FG : creates issue
FG --> HL : polls for new activity
HL --> FG : triages, responds
FG --> PO : polls for unverified
PO --> FG : assigns MoSCoW, priority
FG --> EP : polls for empty milestones
EP --> FG : creates Epics, child issues
FG --> IP : polls for assigned issues
IP --> IW : dispatches worker (async)
IW --> FG : claims issue, creates PR
FG --> RP : polls for unreviewed PRs
RP --> RV : dispatches reviewer (async)
RV --> FG : posts review
FG --> IW : reads review, fixes
FG --> PM : polls for merge-ready PRs
PM --> FG : merges PR, closes issue
FG --> BG : polls for stale/duplicate
BG --> FG : cleans, comments, closes
FG --> SW : polls for violations
SW --> FG : creates alert issues

note right of FG
  All coordination happens through:
  - Issues (state, labels, body)
  - PRs (status, reviews, comments)
  - Comments (claims, heartbeats, notes)
  - Labels (state transitions)
  - Dependencies (blocks/blocked-by)
end note
@enduml

14.2 Tracking Ticket Coordination Flow

Agents read each other's tracking tickets to understand system state and coordinate behavior:

@startuml
!theme plain

rectangle "Tracking Issue Producers" {
  [Impl Pool\nAUTO-IMP-POOL] as IP
  [Review Pool\nAUTO-REV-POOL] as RP
  [Watchdog\nAUTO-WATCHDOG] as WD
  [Groomer\nAUTO-GROOMER] as BG
  [Liaison\nAUTO-LIAISON] as HL
  [All Others...] as OT
}

database "Forgejo Issues\n(Automation Tracking label)" as FG

rectangle "Tracking Issue Consumers" {
  [Product Builder] as PB
  [System Watchdog\n(reads ALL agents)] as WDR
  [Impl Pool\n(reads watchdog,\narch, groomer)] as IPR
  [Human Liaison\n(reads ALL agents)] as HLR
  [Backlog Groomer\n(cleanup duty)] as BGR
}

IP --> FG : status every 5 cycles
RP --> FG : status every 10 cycles
WD --> FG : health every 6 cycles
BG --> FG : grooming every cycle
HL --> FG : activity every 10 cycles
OT --> FG : per-agent schedule

FG --> PB : convergence checks
FG --> WDR : staleness detection
FG --> IPR : announcement reading
FG --> HLR : system awareness
FG --> BGR : cleanup old tickets

note bottom of FG
  Tracking issues follow format:
  [PREFIX] Type (Cycle N)
  
  Announcements follow format:
  [PREFIX] Announce: message
  
  ALL carry "Automation Tracking" label
end note
@enduml

15. Quality and Verification Agents (Detailed)

15.1 Quality Enforcer

Property Value
Agent File quality-enforcer.md
Mode subagent (one-off, dispatched by Watchdog)
Model anthropic/claude-sonnet-4-6
Subagents new-issue-creator

Purpose: Dispatched by the System Watchdog when quality gate violations are detected. Verifies and repairs Forgejo branch protection configuration and creates Priority/CI-Blocker issues for any code merged to master without passing CI. Does NOT revert commits; creates tracked issues for human review.

Actions: (1) Verify/fix branch protection rules via REST API, (2) Audit recent merges for CI compliance, (3) Create CI-Blocker issues for violations. CI-Blocker issues get absolute priority in the implementation system.

15.2 State Reconciler

Property Value
Agent File state-reconciler.md
Mode subagent (one-off, dispatched by Watchdog)
Model anthropic/claude-sonnet-4-6
Subagents forgejo-label-manager

Purpose: Bulk-fixes state label mismatches across all issues. Scans all issues and reconciles State labels against actual status.

Eight Reconciliation Rules:

  1. Closed issues must have terminal state labels (Completed or Wont Do)
  2. Open issues must NOT have terminal state labels
  3. Issues with merged PRs must be closed and marked Completed
  4. Issues with State/In Review must have an open PR
  5. Issues must have exactly ONE State label
  6. Every issue must have State, Type, and Priority labels
  7. Dependency links: child blocks parent Epic, Epic blocks Legendary, PR blocks issue
  8. Non-Epic/Legendary issues beyond Unverified must have milestones

15.3 Project Bootstrapper

Property Value
Agent File project-bootstrapper.md
Mode subagent (one-shot)
Model anthropic/claude-sonnet-4-6

Purpose: One-time project setup. Idempotent: checks if each artifact exists before creating it.

What It Creates (in order):

  1. pyproject.toml (hatch build system, Python >=3.11)
  2. noxfile.py (lint, typecheck, unit_tests, integration_tests, coverage_report sessions)
  3. Directory structure: src/<package>/, features/, features/steps/, features/mocks/, robot/, benchmarks/, docs/
  4. .forgejo/workflows/ci.yml (CI pipeline)
  5. CONTRIBUTING.md (development standards)
  6. Forgejo labels (all labels from Section 6.9 with exact color codes)
  7. Forgejo milestones (M0 Project Setup, M1 Core Foundation, etc.)
  8. Branch protection for master (status checks required, 1 approval, dismiss stale, block on rejected, push disabled)

Critical: Commits all files BEFORE applying branch protection (otherwise the commits would be blocked).

15.4 Product Verifier

Property Value
Agent File product-verifier.md
Mode subagent
Model anthropic/claude-sonnet-4-6
Subagents ref-reader

Purpose: End-to-end product completion verification. Returns COMPLETE or INCOMPLETE.

Ten-Point Verification Checklist:

  1. All milestones complete (every issue closed per milestone)
  2. No open issues with State/Verified, In Progress, or Paused
  3. No open/unmerged pull requests
  4. Full test suite passes (nox all sessions)
  5. Coverage >= 97% (nox -s coverage_report)
  6. Every specification requirement has test coverage
  7. Documentation complete (README, API docs, architecture docs)
  8. No TODO/FIXME/HACK/XXX in code, no debug code
  9. No Blocked label issues remain
  10. No stale feature branches

15.5 Implementation Reviewer

Property Value
Agent File implementation-reviewer.md
Mode subagent (read-only)
Model anthropic/claude-sonnet-4-6

Purpose: Final gate before a subtask is considered complete. Invoked AFTER all quality gates pass. Verifies functional correctness (does the code actually do what the subtask requires?) rather than code quality (which lint/typecheck/tests already verified).

Decision: Returns APPROVE (with confidence level) or REJECT (with specific concerns, file references, and suggested fixes). Does NOT reject for style issues (that is the linter's job). Must be specific when rejecting: file, function, line range.


16. Escalation State Persistence

The Subtask Loop persists its escalation state as HTML comments within PR comments, enabling recovery after crashes:

<!-- ESCALATION-STATE: START
{
  "subtask": "description",
  "current_tier": "codex",
  "attempt": 3,
  "history": [
    {"tier": "haiku", "attempt": 1, "result": "quality_gate_failure"},
    {"tier": "haiku", "attempt": 2, "result": "review_rejection"},
    {"tier": "codex", "attempt": 3, "result": "in_progress"}
  ]
}
ESCALATION-STATE: END -->

On startup, the Subtask Loop checks for an existing PR and parses escalation state from PR comments. If found, it resumes from the correct tier and attempt number rather than restarting from scratch.


17. Deprecated Agents

The following agents have been deprecated and replaced by the tier selector architecture:

  • implementer-haiku.md, implementer-codex.md, implementer-sonnet.md, implementer-opus.md
  • behave-tester-haiku.md, behave-tester-codex.md, behave-tester-sonnet.md, behave-tester-opus.md
  • robot-tester-haiku.md, robot-tester-codex.md, robot-tester-sonnet.md, robot-tester-opus.md
  • coverage-checker.md, quality-gate-escalator.md, subtask-loop-v2.md

These files contain only a deprecation notice pointing to the tier selector architecture.


18. Configuration

18.1 Model Configuration (config/models.yaml)

Defines four cost tiers (haiku, codex, sonnet, opus) with agent-specific model assignments and escalation paths.

18.2 Resource Configuration (config/resources.yaml)

Key operational constants. The config file is the canonical reference; values listed here are for quick lookup.

Timeouts:

Parameter Value Context
Agent heartbeat 600s (10 min) Time between heartbeat signals
Work claim duration 2 hours Maximum time a claim is valid (Section 6.12)
Bash command default 120s (2 min) Default timeout for bash tool calls
Bash sleep multiplier 1.5x Sleep timeout = sleep_duration × 1.5
Forgejo API 30,000ms (30s) API call timeout
Git operations 300,000ms (5 min) Clone, push, fetch timeout
Test execution 900,000ms (15 min) Nox session timeout

Human response timeouts:

Parameter Value
PR needs feedback 48 hours
Question on issue 24 hours
Blocked on human 72 hours
Architecture approval 48 hours
Verification request 24 hours

Retry policies:

Error Type Max Attempts Strategy
Network errors 3 Exponential backoff (1s, 2s, 4s; max 60s)
Git conflicts 2 Rebase and retry (cleanup on failure)
Test failures 3 Escalate model tier
Rate limits 5 Fixed 60s delay between attempts

Pressure thresholds:

Metric Warning Critical
Worker utilization 90% 95%
Failure rate 20% 80%
Queue depth 80% of max 100% of max

Queue limits: Maximum queue depth = workers × 3. Priority queue holds 10 high-priority items ready for immediate dispatch.

Monitoring intervals: Health signal every 10 min, worker status check every 1 min, session validation every 5 min, resource cleanup every 5 min.

Cleanup: Temp directories use prefix /tmp/cleveragents-, expire after 24 hours, cleaned automatically on agent exit.


19. Operational Model

19.1 System Startup

The system is started by invoking the Product Builder as a primary agent in OpenCode. The Product Builder is the only entry point. No other agent should be launched directly by an operator.

Pre-requisites before startup:

  1. OpenCode Server running at localhost:4096
  2. Forgejo instance accessible with valid FORGEJO_PAT
  3. All required environment variables set (see Section 19.4)
  4. Git authentication configured (GIT_USER_NAME, GIT_USER_EMAIL)
  5. Repository exists on Forgejo with appropriate permissions for the bot account

Startup command: Invoke product-builder as a primary agent with a product description prompt.

19.2 System Shutdown

There is no graceful shutdown command built into the Product Builder (by design -- it is meant to run until the product is complete). To shut down the system:

  1. Preferred: Use the session-cleanup primary agent, which queries all active sessions and terminates them. It detects automated sessions by searching for the [AUTO- prefix substring in session titles.
  2. Alternative: Use async-agent-cleanup-all as a subagent with filter: all to terminate every active session.
  3. Manual: Query the OpenCode Server API directly (GET localhost:4096/api/session) and terminate sessions individually.

Workers in progress will lose uncommitted work when their sessions are terminated. Committed-and-pushed work is safe. Claimed issues will have stale claims that expire after 2 hours.

19.3 Crash Recovery Model

The system is designed for crash recovery at every level:

Level Crash Scenario Recovery Mechanism
Product Builder Orchestrator process dies Re-invoke Product Builder; it detects existing sessions via OpenCode API (Phase C.0), adopts them, and resumes monitoring
Supervisor A supervisor session dies Product Builder detects it within 60 seconds and re-launches with the same parameters
Worker A worker session dies Supervisor detects dead worker, slot becomes available, work re-dispatched; new worker checks for existing PR/branch (crash recovery check)
Subtask Loop Subtask loop dies mid-escalation HTML comment escalation state (Section 14) in PR comments preserves tier and attempt number; new invocation resumes from correct state
Git push failure Network interruption during push Retry with exponential backoff; clone is preserved until successful push
Forgejo API failure Forgejo temporarily unavailable All API calls retry with exponential backoff per shared error handling module

State preservation hierarchy (most durable to least):

  1. Forgejo issues/PRs/comments -- survives any crash, persisted on the Forgejo server
  2. Git branches/commits -- survives any crash once pushed to remote
  3. Tracking issues -- survives any crash, provides status and cycle state
  4. Clone directories in /tmp/ -- survives worker crash but not machine reboot
  5. In-memory agent state -- lost on any crash (must be recoverable from levels 1-4)

19.4 Environment Variables Reference

Variable Required Format Purpose
FORGEJO_PAT Yes 40 hex chars ([a-f0-9]{40}) Forgejo personal access token for API authentication
GIT_USER_NAME Yes Any string Git commit author name (typically CleverAgents Bot)
GIT_USER_EMAIL Yes Email format Git commit author email (typically bot@cleveragents.ai)
FORGEJO_USERNAME Yes Alphanumeric Forgejo web login username for CI log scraping
FORGEJO_PASSWORD Yes 8+ chars Forgejo web login password for CI log scraping
CA_MAX_PARALLEL_WORKERS No Integer (default 4) Controls parallelism (see Section 1.3)
OPENCODE_SERVER_PASSWORD No Any string Authentication for OpenCode Server API

Security rules: See Section 13.2 for the seven mandatory security rules governing credential handling.

19.5 Security Model

All automated agents operate under a single Forgejo bot account (HAL9000). This account requires:

  • Repository write access (push to branches, create PRs, post comments)
  • Organization label read access (list organization-level labels)
  • Issue and PR management permissions (create, edit, close, merge)
  • Branch protection bypass is NOT granted (the bot account must comply with branch protection rules)

The OpenCode Server API at localhost:4096 is the control plane. Only the Async Agent Manager is permitted to make direct HTTP calls to this API. All other agents must invoke the Async Agent Manager as a subagent.

Credential isolation: No agent ever receives another agent's credentials. All agents read their own credentials from environment variables at startup. The Credential Security module (Section 13.2) mandates validation without exposure.


20. Design Decisions and Rationale

This section documents intentional design choices that might otherwise appear to be inconsistencies.

20.1 Two-Tier Claim Timeout

The Work Item Claiming Protocol (Section 6.12) specifies a 2-hour stale claim threshold. Individual workers use a shorter 30-minute operational target for completing their work. These are complementary, not contradictory: the 30-minute target is how long a worker aims to hold a claim, while the 2-hour value is how long other workers must wait before overriding an apparently-abandoned claim. This two-tier approach prevents premature claim stealing while encouraging workers to release claims promptly.

20.2 Configuration Files as Aspirational Reference

The configuration files config/models.yaml and config/resources.yaml serve as aspirational reference documents for cost-tier planning. The authoritative model assignment for each agent is in its frontmatter model: field; the config files provide a bird's-eye view of intended tier allocation. The config files should be kept synchronized with frontmatter, but when they diverge, frontmatter takes precedence at runtime.


21. Additional Agent Behavioral Specifications

21.1 PR Fix Pool Supervisor: Synchronous Dispatch

Unlike other pool supervisors which dispatch workers via the Async Agent Manager, the PR Fix Pool Supervisor dispatches workers synchronously using the Task tool. This is by design: the PR Fix supervisor performs intelligent pre-analysis (common cause grouping, root cause identification) before dispatching, and needs to coordinate the results of multiple workers against the same PR. The Task tool's blocking semantics enable this coordination.

Subagents: implementation-worker, ref-reader, ci-log-fetcher, issue-note-writer

Worker Prioritization: When the number of required fixes exceeds the worker limit, priority is: root cause fixes first, then critical path fixes, then simpler fixes.

Stuck Detection Threshold: If more than five previous fix attempts are recorded and failures have not changed, the supervisor requests human help and adds the needs feedback label.

Default Worker Count: max(1, CA_MAX_PARALLEL_WORKERS // 4) (quarter allocation, minimum 1).

21.2 PR Merge Pool Supervisor: Complete Subagent List

Subagents: ref-reader, pr-status-analyzer, automation-tracking-manager, repo-isolator, git-commit-helper

Important: edit: deny -- the PR Merge supervisor does NOT have file edit permissions. Rebase operations are performed exclusively via bash git commands within an isolated clone (created by repo-isolator), not via the Edit tool.

Branch Deletion Policy: delete_branch_after_merge is set to False (not True as the merge safety default suggests). The rationale is to let humans decide when to delete branches.

Rebase Protocol: When a PR has no merge conflicts but is behind master, the supervisor: (1) clones via repo-isolator, (2) fetches latest, (3) rebases, (4) force-pushes with lease, (5) cleans up clone, (6) posts comment.

21.3 UAT Test Pool Supervisor: Complete Subagent List

Subagents: ref-reader, async-agent-manager, spec-reader, new-issue-creator, pr-description-writer, git-committer, pr-creator, automation-tracking-manager

Documentation Generation: Successful test runs generate showcase documentation in categorized directories (cli-tools, api-clients, data-processing, testing-tools). Duplicate detection uses 0.7 cosine similarity threshold. Candidates require a minimum of 3 commands to qualify. Documentation is submitted as PRs.

21.4 Implementer: Domain Model Verification Rule

!!! danger "Critical Rule"

Before writing code that references any field, method, or attribute on a domain model class, the Implementer MUST read the actual class definition to confirm the member exists. Never assume a field exists based solely on the issue description. If the field does not exist, CREATE it -- do not reference a non-existent field.

The Implementer also must NOT write tests (that is the Behave Tester's and Robot Tester's job) and must NOT run nox or quality checks (that is the Subtask Loop's responsibility). Return values must reference code by module path, class name, and method name -- never by line number.

21.5 Subtask Loop: Async Test Writer Launching

The Subtask Loop launches three test writers in parallel via the Async Agent Manager:

  • Behave Tester with session tag AUTO-SUBTASK-BEHAVE-{attempt}
  • Robot Tester with session tag AUTO-SUBTASK-ROBOT-{attempt}
  • ASV Benchmarker with session tag AUTO-SUBTASK-ASV-{attempt}

A monitoring loop checks every 10 seconds (bash("sleep 10", timeout=15000)) for up to 60 cycles (10-minute timeout). Failed writers are restarted.

Per-Gate Independent Tier Escalation: Each quality gate (lint, typecheck, unit tests, integration tests, coverage) has its own independent tier that starts at Haiku and escalates independently. Quality gate sessions use tags like AUTO-SUBTASK-{GATE_NAME}-A{attempt}-P{inner_pass}. The monitoring loop runs every 10 seconds with a 20-minute timeout (120 cycles).

Inner Pass Limit: Each tier gets 5 inner passes before escalation occurs.

Meaningful Change Verification: Before quality gates run, the subtask loop verifies the implementer produced meaningful changes: fewer than 3 functional lines (excluding comments, whitespace, and empty lines) causes rejection without running quality gates. The working directory is reset with git checkout -- . and escalation is triggered.

21.6 Plan Agent: Behavioral Specification

The Plan agent (plan.md, mode all) is available in both primary and subagent modes. It replaces the default planning agent and has broad permissions (task: "*": allow, webfetch: allow, edit: deny).

Mandatory Pre-Planning Steps: Before creating any plan, the agent must read CONTRIBUTING.md, project documentation (README, specification, ADRs), and analyze the project structure.

Required Plan Structure (six sections):

  1. Context and Analysis: Current state understanding, requirements interpretation
  2. Implementation Strategy: Approach, key design decisions, CONTRIBUTING.md compliance
  3. Detailed Steps: What to change, where, how, which tests, which CONTRIBUTING.md section applies
  4. Testing Plan: Unit (BDD), integration (Robot), performance (ASV), coverage targets
  5. Risk Analysis: Breaking changes, performance impacts, security concerns, migration needs
  6. Task Breakdown: Prerequisites, implementation order, testing sequence, documentation, deployment

Clone Isolation for Analysis: When analyzing code on different branches, the Plan agent clones to /tmp/ for read-only analysis. Direct /app access is permitted for reading documentation only.

Red Flags: The plan must flag violations of CONTRIBUTING.md, introduction of new tools/frameworks, changes to established patterns, missing testing strategy, or lack of rollback plan.

21.7 Context Self-Management Pattern

Long-running agents (all supervisors and workers) must actively manage their context window to prevent exhaustion. The pattern is:

  • Every N cycles (varies by agent: 10-50), discard all accumulated tool outputs.
  • Retain only: persistent state variables (active worker maps, completed lists, cycle counts, fail counts, queue depths).
  • Never retain: raw Forgejo API responses, full file contents, CI log contents, PR diffs.

Agents that have been observed to exhaust context include the Backlog Groomer (every 20 cycles), Human Liaison (every 20 cycles), Implementation Pool Supervisor (every 50 iterations), and Agent Evolution Supervisor (every 10 cycles).

21.8 Bug Hunt: Clone Failure Handling and Finding Validation

Hostname Warning: The Bug Hunt agent must derive the Forgejo hostname from environment variables or API responses. It must never assume the hostname is git.<org-name>.com. TLS/SSL failures, DNS resolution errors, and clone failures are infrastructure problems, NOT product bugs. The agent must never file issues about its own infrastructure failures.

Finding Validation (five rules before filing any bug issue):

  1. Must have actual code evidence (file path, function name, specific code pattern)
  2. Must verify environment assumptions (check actual Python version, dependency versions)
  3. Must verify the finding is actionable (not a design choice or documented limitation)
  4. Must verify against the actual codebase (not outdated cached code)
  5. Severity must match evidence (Critical requires data loss/security/crash proof)

Severity Assessment:

Severity Criteria
Critical Data loss, security vulnerability, application crash
High Incorrect behavior, resource leaks, performance degradation
Medium Edge cases, minor spec deviations, non-critical error handling
Low Code quality, potential future problems, style inconsistencies

21.9 Issue Finder: Blocking Category Detection

The Issue Finder classifies issues into three blocking categories:

Category Meaning Action
ready No blockers, or blockers are all completed Include in queue
blocked_by_self Blocked by an issue assigned to the same user (HAL9000) Include in queue (will unblock itself)
blocked_by_other Blocked by an issue assigned to a different user Skip (cannot unblock)

This distinction prevents the Implementation Pool from dispatching workers on issues that are blocked by human-assigned work.

21.10 Forgejo Label Manager: Five Operations

The Forgejo Label Manager provides five discrete operations:

Operation Purpose
Label Validation Check if a label name exists at the organization level
Label Application Apply labels to an issue or PR by name (handles name-to-ID mapping)
Label Reading Read current labels on an issue or PR
Label Inference Infer appropriate labels from issue title, body, and commit message content
Label Compliance Checking Verify an issue has required labels (State, Type, Priority, Points if applicable)

The label inference capability uses keyword matching against the issue content to suggest appropriate Type, Priority, and MoSCoW labels.

21.11 Subtask Checker: Fuzzy Matching

The Subtask Checker matches subtask descriptions by content similarity, not exact string match. The provided description from the caller may be paraphrased relative to the original subtask text in the issue body. The checker must find the closest-matching subtask and update its checkbox. It must only modify checkbox states ([ ] to [x]) and must NOT change any other part of the issue body.

21.12 Forgejo Signature Appender: Three Format Variants

The Forgejo Signature Appender supports three signature formats:

Format Structure Use Case
standard (default) --- separator + bold attribution + supervisor/agent line Most content
minimal Bold attribution only (no separator, no supervisor line) Inline comments, short notes
extended --- separator + bold attribution + supervisor/agent + timestamp + closing --- Formal reports, tracking issues

The appender includes a clean_existing_signatures() function that strips any existing bot signatures before appending a new one, preventing signature duplication from repeated updates.

21.13 Issue Comment Formatter: Five Comment Types

The Issue Comment Formatter supports five structured comment types, each with a distinct visual template:

Type Visual Indicators Use Case
progress Progress bars, checklist, completion percentage Status updates
error Red alert icons, error details block, stack traces Error reports
success Green checkmarks, summary, next steps Completion notices
status Dashboard layout, metrics table, health indicators Periodic status
analysis Collapsible sections, data tables, trend indicators Deep analysis

Features include collapsible sections, read-time estimates, auto-linking to commits/files/issues, and markdown injection prevention.

21.14 Product Builder: Specification PR Monitoring

The Product Builder monitors specification PRs created by the Architecture Supervisor. If a spec PR becomes stale (no activity for 24+ hours), the Product Builder rebases it. If a human merges a spec PR, the Product Builder detects this and updates its internal state. If a spec PR is closed (rejected), the Product Builder creates a follow-up issue. Reminder comments are posted after 24 hours of inactivity.

21.15 Product Builder: Non-Return Guarantee

The Product Builder must NEVER return prematurely. An explicit list of things that are NOT reasons to stop includes: "You 'feel done'", "The monitoring loop feels repetitive", "Context is getting large", "No immediate progress is visible", "A few supervisors have restarted", and "Some issues appear stuck". The only valid exit condition is the Product Verifier returning COMPLETE.

21.16 Final Reporter: Output Format

The Final Reporter is a read-only agent invoked by the Product Builder at the end of a session. It produces a structured markdown report with the following sections:

  1. Summary: Total issues completed/skipped, total PRs created, overall status
  2. Per-Branch Detail: For each branch: issue number, PR number/URL, quality check table (lint, typecheck, unit tests, integration tests, coverage with pass/fail and notes), PR description summary, issues encountered
  3. Model Usage and Efficiency Table: Per-issue breakdown of evaluator recommendation, starting tier, final tier, attempt count, escalation count, and cost estimate
  4. Problems Encountered: Aggregated list of failures, skips, and stuck issues
  5. Recommendations: Suggested follow-up actions

Permissions: edit: deny, task: deny — the Final Reporter is strictly read-only. It reads from Forgejo (issues, PRs, comments) and git history but cannot modify anything.

21.17 Milestone Reviewer: Holistic Review Protocol

The Milestone Reviewer runs after all issues in a milestone are merged. It reviews the integrated codebase (not individual PRs) looking for problems that per-issue reviews cannot catch.

Eight Review Areas:

  1. Integration gaps: Do the modules that were built separately actually work together?
  2. API consistency: Are naming conventions, parameter ordering, error handling, and return types consistent across the public API surface?
  3. Specification coverage: Does every specification requirement have a corresponding implementation and test?
  4. Test quality: Are there integration test gaps between modules? Are the tests meaningful?
  5. Error handling coherence: Does the error handling strategy flow consistently from module boundaries to the top level?
  6. Performance concerns: Are there O(n²) patterns, unbounded queries, or resource leaks introduced across the milestone?
  7. Documentation completeness: Are all new public APIs documented?
  8. Technical debt: Were any TODO/FIXME/HACK items introduced?

Output: Posts a comprehensive review comment on the milestone issue. Creates Type/Bug or Type/Refactor issues for any problems found.

Subagents: ref-reader

Permissions: edit: deny — the reviewer clones the repo to its own /tmp/ directory for analysis and runs nox to execute the full test suite, but it never pushes changes.

21.18 Commit Message Formatter: Three-Part Format

The Commit Message Formatter constructs git commit messages following a strict three-part structure:

<exact Commit Message from issue Metadata table>

<Implementation description: what was done, key design decisions,
 technical approaches, modules affected>

ISSUES CLOSED: #<issue-number>

Rules:

  1. The first line MUST be the exact commit message from the issue's Metadata section (Conventional Changelog format, e.g., feat(module): description)
  2. A blank line MUST separate the first line from the body
  3. The body describes what was implemented and why
  4. The footer MUST include ISSUES CLOSED: #N for the linked issue

Permissions: edit: deny, bash: deny — this is a pure formatting agent that reads from Forgejo (to get issue metadata) and returns a formatted string. It cannot execute any commands.

21.19 PR Status Analyzer: Multi-Dimensional Analysis

The PR Status Analyzer provides deep PR health assessment across six dimensions, returning structured JSON:

Dimension What It Checks
ci_cd Check pass/fail statuses, log URLs, failure categorization
merge_conflicts Conflict detection, affected files, resolution complexity
reviews Approval status, pending reviews, blocking reviews, reviewer list
tests Test pass/fail counts, flaky test detection, coverage delta
blocking_issues Dependency analysis, upstream blockers, label blockers
build Build status, artifact availability, deployment readiness

Three analysis depths: quick (CI and conflicts only), standard (all six dimensions), comprehensive (all six plus log fetching and delta comparison against a baseline).

Subagents: ci-log-fetcher

21.20 Async Agent Monitor: Four Operations

The Async Agent Monitor supports four discrete operations:

Operation Purpose Key Parameters
monitor Continuous health monitoring of a session tag or session_id, health_timeout_minutes (default 10), auto_restart
health_check One-shot health assessment Returns healthy, unhealthy, or dead with last activity timestamp
get_messages Retrieve recent messages from a session include_messages, pagination support
restart Terminate and re-launch a session restart_params (agent_name, prompt_text, display_name), preserves the same tag

Health detection: A session is unhealthy if it has had no messages for health_timeout_minutes (default 10 minutes). A session is dead if the OpenCode Server reports it as completed or errored.

Auto-restart: When auto_restart: true, the monitor automatically restarts unhealthy agents using the same tag, enabling seamless recovery. The new session inherits the tag so that the parent agent can find it.

Subagents: async-agent-manager

21.21 Git Commit Helper: Safe Commit with Rollback

The Git Commit Helper wraps git commit operations with validation, conflict resolution, and rollback capabilities:

Pre-commit validation:

  1. Verify the working directory is a git repository
  2. Verify the target branch is checked out
  3. Stage specified files (or all changes if files: all)
  4. Validate that staged changes are non-empty (unless allow_empty: true)
  5. Run pre-commit hooks if pre_commit_checks: true

Commit creation:

  • Formats the message using Conventional Changelog if commit_type is provided
  • Adds Co-authored-by: <name> <email> trailer if co_authored_by is specified
  • Signs the commit if sign_commit: true and signing is configured

Rollback on failure: If rollback_on_failure: true (default) and any post-commit operation fails (e.g., push), the helper automatically rolls back the commit with git reset --soft HEAD~1, preserving the staged changes for retry.

Output: Returns structured JSON with commit_sha, commit_message, files_changed, and stats (insertions, deletions).

21.22 PR Reviewer: Total Bash Lockdown

The PR Reviewer agent has bash: "*": deny — a total bash lockdown that is more restrictive than most agents. Combined with edit: deny, this makes the PR Reviewer one of the most constrained agents in the system. It can only:

  • Read Forgejo data via MCP tools (PRs, issues, comments, reviews, diffs)
  • Invoke two subagents: ref-reader (for specification context) and ci-log-fetcher (for CI failure analysis)
  • Post reviews and comments via Forgejo MCP tools

It cannot run any bash commands, edit any files, or invoke any other subagents. This extreme lockdown is intentional: the reviewer must provide an independent assessment without the ability to modify code or run tests. Its perspective must be purely analytical.

21.23 Branch Setup: Rebase-Only Policy

The Branch Setup agent creates or checks out branches with a strict rebase-only policy:

Workflow:

  1. Checkout and pull the base branch (default: master, but supports any base for dependent branch stacking)
  2. Check if the target branch exists on the remote
  3. If exists: fetch, checkout, and rebase onto the base branch
  4. If not: create new branch from the base branch
  5. Verify the current branch

Critical rules:

  • Never merge, always rebase — no merge commits are permitted
  • Rebase conflicts are NOT auto-resolved — if a rebase has conflicts, the agent reports the conflict details and aborts the rebase. The caller must handle conflicts.
  • Dependent branch support: By accepting a base_branch parameter (not just master), the agent supports stacking branches for dependent issues.

Permissions: edit: deny — the agent only runs git commands, never modifies files directly.


Appendix A: Complete Agent Registry

# Agent Mode Model Tracking Prefix Type
1 product-builder primary claude-sonnet-4-6 AUTO-PROD-BLDR Orchestrator
2 implementation-pool-supervisor all (inherited) AUTO-IMP-POOL Pool Supervisor
3 pr-review-pool-supervisor subagent claude-sonnet-4-6 AUTO-REV-POOL Pool Supervisor
4 pr-merge-pool-supervisor subagent claude-sonnet-4-6 AUTO-MERGE Singleton Supervisor
5 pr-fix-pool-supervisor subagent gpt-5-codex -- Pool Supervisor
6 uat-test-pool-supervisor subagent claude-sonnet-4-6 AUTO-UAT-POOL Pool Supervisor
7 bug-hunt-pool-supervisor subagent gemini-2.5-pro AUTO-BUG-POOL Pool Supervisor
8 test-infra-pool-supervisor subagent gemini-2.5-pro AUTO-INF-POOL Pool Supervisor
9 architecture-pool-supervisor subagent claude-sonnet-4-6 AUTO-ARCH Singleton Supervisor
10 epic-planning-pool-supervisor subagent claude-sonnet-4-6 AUTO-EPIC Singleton Supervisor
11 human-liaison-pool-supervisor subagent claude-sonnet-4-6 AUTO-LIAISON Singleton Supervisor
12 agent-evolution-pool-supervisor subagent claude-sonnet-4-6 AUTO-EVLV Singleton Supervisor
13 architecture-guard-pool-supervisor subagent gemini-2.5-pro AUTO-GUARD Singleton Supervisor
14 spec-update-pool-supervisor subagent claude-sonnet-4-6 AUTO-SPEC Singleton Supervisor
15 backlog-grooming-pool-supervisor subagent claude-sonnet-4-6 AUTO-GROOMER Singleton Supervisor
16 documentation-pool-supervisor subagent claude-sonnet-4-6 AUTO-DOCS Singleton Supervisor
17 timeline-update-pool-supervisor subagent claude-sonnet-4-6 AUTO-TIME Singleton Supervisor
18 project-owner-pool-supervisor subagent claude-sonnet-4-6 AUTO-PROJ-OWN Singleton Supervisor
19 system-watchdog-pool-supervisor subagent claude-sonnet-4-6 AUTO-WDOG Singleton Supervisor
20 implementation-worker subagent gpt-5-codex AUTO-IMP-WRK Worker
21 pr-reviewer subagent claude-sonnet-4-6 -- Worker
22 subtask-loop subagent gpt-5-codex -- Worker
23 implementer subagent (inherited) -- Specialist
24 behave-tester subagent (inherited) -- Specialist
25 robot-tester subagent (inherited) -- Specialist
26 lint-fixer subagent (inherited) -- Specialist
27 typecheck-fixer subagent (inherited) -- Specialist
28 test-fixer subagent (inherited) -- Specialist
29 coverage-improver subagent (inherited) -- Specialist
30 unit-test-runner subagent (inherited) -- Specialist
31 integration-test-runner subagent (inherited) -- Specialist
32 tier-haiku subagent claude-haiku-4-5 -- Tier Selector
33 tier-codex subagent gpt-5-codex -- Tier Selector
34 tier-sonnet subagent claude-sonnet-4-6 -- Tier Selector
35 tier-opus subagent claude-opus-4-6 -- Tier Selector
36 async-agent-manager subagent gpt-5-codex -- Infrastructure
37 async-agent-cleanup subagent gpt-5-codex -- Infrastructure
38 async-agent-cleanup-all subagent gpt-5-codex -- Infrastructure
39 async-agent-monitor subagent gpt-5-codex -- Infrastructure
40 automation-tracking-manager subagent gpt-5-nano -- Infrastructure
41 session-persister subagent gpt-5-nano AUTO-SESSION Infrastructure
42 repo-isolator subagent gpt-5-codex -- Infrastructure
43 git-committer subagent gpt-5-nano -- Infrastructure
44 git-commit-helper subagent gpt-5-codex -- Infrastructure
45 branch-setup subagent gpt-5-nano -- Infrastructure
46 ci-log-fetcher subagent gpt-5-codex -- Infrastructure
47 ref-reader subagent gemini-2.5-pro -- Knowledge
48 ref-material-loader subagent gpt-5-codex -- Knowledge
49 spec-reader subagent gemini-2.5-pro -- Knowledge
50 difficulty-evaluator subagent claude-haiku-4-5 -- Knowledge
51 pr-manager all claude-sonnet-4-6 -- PR Management
52 pr-creator subagent claude-sonnet-4-6 -- PR Management
53 pr-editor subagent claude-sonnet-4-6 -- PR Management
54 pr-status-analyzer subagent gpt-5-codex -- PR Management
55 pr-ci-test-fixer subagent claude-sonnet-4-6 -- PR Management
56 pr-description-writer subagent claude-haiku-4-5 -- PR Management
57 issue-finder subagent gpt-5-nano -- Issue Management
58 issue-analyzer subagent claude-haiku-4-5 -- Issue Management
59 issue-note-writer subagent claude-haiku-4-5 -- Issue Management
60 issue-comment-formatter subagent gpt-5-codex -- Issue Management
61 issue-state-updater subagent gpt-5-nano -- Issue Management
62 new-issue-creator subagent claude-sonnet-4-6 -- Issue Management
63 subtask-checker subagent gpt-5-nano -- Issue Management
64 forgejo-label-manager subagent claude-sonnet-4-6 -- Forgejo
65 forgejo-signature-appender subagent gpt-5-codex -- Forgejo
66 implementation-reviewer subagent claude-sonnet-4-6 -- Quality
67 milestone-reviewer subagent claude-sonnet-4-6 -- Quality
68 product-verifier subagent claude-sonnet-4-6 -- Quality
69 quality-enforcer subagent claude-sonnet-4-6 -- Quality
70 state-reconciler subagent claude-sonnet-4-6 -- Quality
71 project-bootstrapper subagent claude-sonnet-4-6 -- Bootstrap
72 final-reporter subagent claude-sonnet-4-6 -- Reporting
73 commit-message-formatter subagent gpt-5-nano -- Utility
74 plan all (not specified) -- Planning
75 session-cleanup primary (not specified) -- Maintenance
76 asv-benchmarker subagent claude-sonnet-4-6 -- Specialist
77 build primary (not specified) -- Primary Agent
78 build-opencode primary claude-sonnet-4-6 -- Primary Agent
79 fix-pr primary claude-sonnet-4-6 -- Primary Agent

!!! note "Non-Autonomous Agents"

Agent 76 (ASV Benchmarker) is a **hidden subagent** called by the Subtask Loop during the testing phase, not a user-facing tool. Agents 77-79 are **primary agents** invoked directly by human users (not part of the autonomous supervisor hierarchy):

- **ASV Benchmarker** (76): Writes Airspeed Velocity performance benchmarks in `benchmarks/`. Hidden subagent (`mode: subagent`, `hidden: true`).
- **Build** (77): General-purpose development agent replacing the default build agent. Reads CONTRIBUTING.md before any changes.
- **Build OpenCode** (78): Specialized agent for editing `.opencode/` agent definition files. The one exception to clone isolation (works on `/app/.opencode/` directly).
- **Fix PR** (79): Primary agent for manual PR fixing invoked by users. Orchestrates subagents for comprehensive PR resolution.

Appendix B: Revision History

!!! note "Section Number References"

Section references in revision entries v1.0.0 through v1.14.0 use section numbers from the time they were written. Sections were renumbered in v1.15.0 when Sections 2 (Agent Definition Format) and 3 (Glossary) were inserted, shifting all subsequent sections by +2. The mapping is: old Section N → new Section N+2 for N ≥ 3.
Date Version Changes
2026-04-10 1.0.0 Initial specification capturing all 75+ active agents
2026-04-10 1.1.0 Second pass: Added TDD Tags system, complete label taxonomy, state transition diagram, dependency direction rules, work item claiming protocol, standard issue/PR body formats, priority ordering rules, merge safety protocol, CI artifact mapping, detailed singleton supervisor workflows with subagent lists, Human Liaison 10-step loop with activity diagram, Agent Evolution two-step proposal workflow, Spec Update two-step proposal workflow, Architecture Guard 7 check categories, Backlog Grooming 19 analysis passes enumerated, announcement cleanup protocol, Implementation Worker PR-fix mode activity diagram, escalation state persistence, Forgejo coordination flow diagram, tracking ticket coordination diagram, detailed Quality Enforcer/State Reconciler/Bootstrapper/Verifier/Reviewer specifications
2026-04-10 1.2.0 Third pass incorporating recent git changes: 3-Tier Approval Detection system (4.17.1), Two-Step Review Protocol (4.17.2), Approval Count Policy (4.17.3), Label Delegation Enforcement (4.19), expanded PR Reviewer with flaky test detection, expanded Implementation Worker with Deep Context Gathering and Loop Prevention, expanded System Watchdog audits (7.11.2, 7.11.3)
2026-04-10 1.3.0 Fourth pass: Fixed 6.3 PR Merge stale 2-tier approval; added PR management critical behavioral rules (10.1.1); added Ref Material Loader caching (10.4); added Difficulty Evaluator bias (10.4); added Async Agent Manager/Cleanup details (10.7); added Issue management agent details (10.2)
2026-04-10 1.4.0 Fifth pass: Fixed announcement cleanup thresholds; added Sections 17 (Known Discrepancies) and 18 (15 behavioral specifications)
2026-04-10 1.5.0 Sixth pass (accuracy verification): Verified all Appendix A frontmatter values; fixed both diagrams (added missing Tier 3 agents, distinguished IW modes, added 10 missing dispatch links); documented supervisor count discrepancy (17.5→17.6)
2026-04-10 1.6.0 Seventh pass: PR Merge dual categorization note; fixed Singleton count to 12; added claim timeout discrepancy (18.5)
2026-04-10 1.7.0 Eighth pass: Added Section 17 "Operational Model" (startup, shutdown, crash recovery, env vars, security); added spec to mkdocs.yml nav; renumbered sections 18-19; verified Kroki/markdown syntax
2026-04-10 1.8.0 Ninth pass: Script-verified all 79 Appendix A models and temperatures (zero mismatches); documented session tag vs tracking prefix dual-naming scheme (Section 5.5.1)
2026-04-10 1.9.0 Tenth pass: Added 7 behavioral specs (19.16-19.22) for under-documented agents
2026-04-10 1.10.0 Eleventh pass: Added Sections 4.5 (visibility), 4.6 (edit permissions), 4.7 (internet access); renumbered 4.8-4.19; updated 13 cross-references
2026-04-10 1.11.0 Twelfth pass: Fixed PR Merge edit permission error (19.2); verified all 19 cross-references; numeric consistency audit clean
2026-04-10 1.12.0 Thirteenth pass: Added Section 6.9.1 Special Label Lifecycles for all 5 special labels; fixed Type/Refactoring→Type/Refactor
2026-04-10 1.13.0 Fourteenth pass: Expanded Section 18.2 with complete resource configuration tables; added 2 discrepancies (18.5, 18.6)
2026-04-10 1.14.0 Fifteenth pass: Merge verification protocol, pre-merge rebase, PR-first enforcement, nox routing, cookie-based CI auth
2026-04-10 1.15.0 Eighteenth pass: Added Section 2 (Agent Definition Format) and Section 3 (Glossary); renumbered all sections 3→5 through 19→21
2026-04-10 1.16.0 Nineteenth pass (spec vs implementation alignment): Replaced Section 20 "Known Discrepancies" with Section 20 "Design Decisions and Rationale" — removed 8 bug reports that described unintended behavior, retained 2 intentional design choices (two-tier claim timeout, config files as aspirational reference); fixed 8 bugs in agent definition files: config/models.yaml (updated all 16 stale agent names, fixed codex model ID to openai/gpt-5-codex, fixed sonnet model ID to anthropic/claude-sonnet-4-6); config/resources.yaml (updated all 16 stale agent names, fixed session naming pattern to [{tag}] {display_name}); epic-planning-pool-supervisor.md (fixed State/Needs VerificationState/Unverified); forgejo-label-manager.md (fixed Signed-off:Signed-off, added missing Automation Tracking, needs feedback, Priority/CI-Blocker labels); shared/merge_safety.md (fixed status_check_contexts from CI / CI to status-check); session-cleanup.md (fixed [CA-AUTO] prefix to [AUTO-); product-builder.md (removed duplicate pr-merge-pool-supervisor launch entry)
2026-04-10 1.17.0 Twentieth pass (post-commit review): Added Section 6.20 (Forgejo API Pagination Requirement), Section 6.21 (PR Ownership Detection), expanded Section 8.1.2 with three mandatory PR dispatch rules and updated work scoring table (added COMMENT review category at 85, changed awaiting-review from 40→60, removed stale-check category), added Section 21.22 (PR Reviewer Total Bash Lockdown), fixed Appendix A note to correctly identify ASV Benchmarker as subagent not primary; fixed 6 bugs in agent definition files: product-builder.md (fixed stale implementation-orchestrator reference in error handling text), async-agent-manager.md (updated entire valid_agents validation list from 15+ stale names to current *-pool-supervisor names), async-agent-monitor.md (fixed 2 stale implementation-orchestrator references in examples), shared/logging.md (fixed 2 stale pr-self-reviewer references to pr-reviewer), agent-evolution-pool-supervisor.md (fixed stale continuous-pr-reviewer reference to pr-review-pool-supervisor), shared/tracking_discovery_guide.md (fixed stale implementation-orchestrator reference in coordination example)
2026-04-10 1.18.0 Twenty-first pass (deep functional audit): Fixed Appendix A build-opencode model from (not specified) to claude-sonnet-4-6; fixed 6 functional bugs in agent definition files: implementation-pool-supervisor.md (fixed task permission timeline-updatertimeline-update-pool-supervisor, fixed 2 stale task invocation references in timeline update section), test-infra-pool-supervisor.md (fixed worker launch agent_name: test-infra-improvertest-infra-pool-supervisor — workers were failing validation), uat-test-pool-supervisor.md (fixed worker launch agent_name: uat-testeruat-test-pool-supervisor — workers were failing validation), human-liaison-pool-supervisor.md (fixed stale task invocation instruction to use Forgejo issue creation instead of direct agent invocation, fixed backtick-quoted project-ownerproject-owner-pool-supervisor), async-agent-manager.md (updated documentation agent name list to match current names)
2026-04-10 1.19.0 Twenty-second pass (cross-reference audit and config cleanup): Fixed 3 broken cross-references (Section 20.4 → inline text, Section 13.2 → Section 11.2 for escalation, removed stale stale-check work type from Section 10.1 worker types); fixed 3 config file bugs: models.yaml (removed deprecated quality-gate-escalator entry, added runtime model comments for ref-reader and spec-reader), resources.yaml (added missing pr-fix-pool-supervisor at 0.25 allocation and pr-merge-pool-supervisor as singleton); verified all 21 top-level sections sequential, all 23 Section 21 subsections sequential, Appendix A count matches 79 active agents (94 files minus 15 deprecated)
2026-04-10 1.20.0 Twenty-third pass (permission block audit): Fixed 3 agent definition bugs: implementation-worker.md (moved pr-creator and pr-ci-test-fixer from forgejo: permission block to task: block — they were in the wrong section, preventing the IW from invoking them as subagents; also added missing hidden: true flag), pr-ci-test-fixer.md (fixed task permission coverage-checkercoverage-improver — coverage-checker is deprecated); verified all 79 agents' task permissions against spec subagent claims, all hidden flags correct, no other permission block misplacements
2026-04-10 1.21.0 Twenty-fourth pass (label deny and permission consistency audit): Expanded Section 6.19 from Automation-Tracking-Manager-specific to universal label application delegation rule documenting all 77 agents with deny + 2 intentional exceptions (forgejo-label-manager, issue-state-updater); fixed 6 agent definition bugs: pr-editor.md, pr-manager.md, pr-merge-pool-supervisor.md, async-agent-manager.md (all 4 missing forgejo_add_issue_labels: deny — could bypass label delegation), forgejo-signature-appender.md (missing deny AND broken YAML permission: {} creating disconnected forgejo block); verified 41 edit:deny agents match spec claim exactly, 3 webfetch:allow agents match spec claim exactly
2026-04-10 1.22.0 Twenty-fifth pass (directory layout, bash permissions, subsystem verification): Added Section 2.4 (Directory Layout) documenting .opencode/ structure including agents/, shared/, config/, scripts/, deprecated stubs; fixed 1 agent definition bug: forgejo-signature-appender.md (missing bash: "*": deny and edit: deny — the only active agent without any bash restriction, could run arbitrary commands despite being a text-formatting-only agent); verified 3-Tier Approval Detection (Section 6.17) matches pr-merge-pool-supervisor implementation; verified Mandatory Merge Verification Protocol (Section 8.3.4) matches shared/merge_safety.md; confirmed zero remaining stale names, stale labels, or stale session prefixes across all agent files
2026-04-10 1.23.0 Twenty-sixth pass (deep automation tracking audit): Major rewrite of Section 5.2 (Status Issues) with one-at-a-time invariant, close-ALL-then-create protocol, and explicit "even from previous sessions" language; new Section 5.3.1 (Announcement Issue Lifecycle) with mandatory self-review every 3 cycles; new Section 5.3.2 (Tracking Issue Consumption Protocol) with per-agent triage table, read depth levels, and priority-based filtering; fixed 4 agent definitions: automation-tracking-manager.md (strengthened CREATE_TRACKING_ISSUE to specify close-ALL-then-create invariant), backlog-grooming-pool-supervisor.md (added READ_ANNOUNCEMENTS from watchdog/liaison/owner + REVIEW_OWN_ANNOUNCEMENTS every 3 cycles), pr-review-pool-supervisor.md (added READ_ANNOUNCEMENTS for critical watchdog/liaison + REVIEW_OWN_ANNOUNCEMENTS), agent-evolution-pool-supervisor.md (added READ_ANNOUNCEMENTS for critical watchdog + REVIEW_OWN_ANNOUNCEMENTS with 24h stale threshold); updated shared/tracking_discovery_guide.md with mandatory announcement review and consumption protocols
2026-04-10 1.28.0 Thirty-first pass (body template field enforcement): Added **Estimated Cycle Interval** field to the actual tracking body templates in all 14 agents that had inline body strings without it (agent-evolution, architecture-guard, architecture, documentation, pr-review, test-infra, timeline-update, uat-test, backlog-grooming ×2, human-liaison, system-watchdog, product-builder, implementation-pool); fixed 2 non-standard body formats (project-owner-pool-supervisor had non-standard [HEALTH] header → standardized to # Project Owner Status, bug-hunt-pool-supervisor had body starting at ## Summary without header → added standard header); added tracking body requirement note to pr-merge-pool-supervisor; all 18 status-creating agents now have Estimated Cycle Interval in their actual body templates
2026-04-10 1.27.0 Thirtieth pass (tracking reference ordering and interval fields): Fixed tracking operations reference ordering in ALL 17 supervisor/orchestrator agents — moved READ_TRACKING_STATE before CREATE_TRACKING_ISSUE with startup note, rolling average interval calculation, and Estimated Cycle Interval requirement; added Estimated Cycle Interval field to IPS tracking body template; all 17 agents now include rolling average default values based on their sleep intervals
2026-04-10 1.26.0 Twenty-ninth pass (cycle interval, dual cleanup, cycle continuity): Added Section 5.3.4 (Estimated Cycle Interval rolling average with 90/10 weighting), Section 5.3.5 (Dual Status Issue Cleanup — agent-side + groomer-side), Section 5.3.6 (Cycle Number Continuity Across Sessions); updated Section 5.6 body template to include mandatory Estimated Cycle Interval field; fixed 3 agent definitions: system-watchdog-pool-supervisor.md (replaced hardcoded interval lookup table with parsing from status issue body, changed staleness threshold from 1.2x to 2x per spec), backlog-grooming-pool-supervisor.md (added Pass 20: Automation Tracking Status Issue Deduplication for redundant one-at-a-time enforcement), automation-tracking-manager.md (added estimated_cycle_interval to READ_TRACKING_STATE return schema); updated shared/tracking_discovery_guide.md with rolling average calculation pattern
2026-04-10 1.25.0 Twenty-eighth pass (startup state recovery): Added Section 5.3.3 (Startup State Recovery Protocol) with mandatory read-then-delete-then-create sequence, agent-specific recovery table, and offline duration behavior rules; enhanced ATM READ_TRACKING_STATE operation to return full comments array, creation timestamp, and offline duration; fixed startup sequence in 2 key agents: implementation-pool-supervisor.md (added state recovery as mandatory first action before PR analysis, with branch/PR target extraction and resume-before-new-work logic), product-builder.md (replaced manual curl state detection with ATM READ_TRACKING_STATE); updated shared/tracking_discovery_guide.md with mandatory startup recovery protocol
2026-04-10 1.24.0 Twenty-seventh pass (tracking protocol complete rollout): Fixed 12 agent definition bugs: 5 supervisors missing automation-tracking-manager: allow task permission despite invoking it in their prompt (architecture-guard, bug-hunt, documentation, epic-planning, test-infra — tracking operations were silently denied); 5 remaining announcement-creating supervisors now have REVIEW_OWN_ANNOUNCEMENTS (architecture-pool, spec-update, uat-test, bug-hunt, product-builder); all 18 supervisors + product-builder now READ_ANNOUNCEMENTS per consumption table (6 added: architecture-guard, documentation, epic-planning, project-owner, timeline-update, test-infra); pr-fix-pool-supervisor added pre-dispatch announcement check + ATM permission; product-builder fixed stale [AUTO-SYS-WATCH] prefix → [AUTO-WATCHDOG] and converted to READ_ANNOUNCEMENTS; all 19 orchestrator/supervisor agents now have complete tracking protocol (create, read, review cycle)