Files
cleveragents-core/docs/development/agent-system-specification.md
HAL9000 f808abff86 chore(ci): fix pre-commit hook failures
Fix JSON syntax errors in .devcontainer/devcontainer.json (removed
invalid JS-style // comments) and .devcontainer/opencode.json (removed
90+ trailing commas). Apply auto-fixes for end-of-file and trailing
whitespace issues across 100+ files. Fix SIM105 ruff violations in
benchmarks/core_circuit_breaker_bench.py (use contextlib.suppress).

Note: The security fix from issue #7478 (validate_path startswith bypass)
was already delivered to master in commit e18ac5f2. This PR as currently
structured is non-atomic (35 commits across 10+ issues) and needs
significant restructure before merge. This commit only addresses the
CI/pre-commit failures.

ISSUES CLOSED: #7478
2026-06-14 09:51:14 -04:00

532 KiB
Raw Permalink 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.

  6. Defense-in-Depth Redundancy: Critical system responsibilities are covered by two, three, or even four independent agents. No single agent's failure creates a gap in system functionality. The complete responsibility matrix with redundancy analysis is documented in Section 22.

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 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"];
    "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"];

    "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 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" -> "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";

  "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) UAT Test, Bug Hunt, Test Infra Discovery agents; capping prevents scope explosion
Single (1) 1 11 singleton supervisors (Architecture through Watchdog, excluding PR Merge) Strategic work requiring single-threaded coherence; one async worker at a time
Blocking (0 async) 0 PR Merge Pool Calls pr-merge-worker as a blocking subagent via the Task tool; no async worker sessions (see Section 8.3)

!!! note "Worker Dispatch Model"

Almost every supervisor in the system dispatches workers as async sessions via the Async Agent Manager. Workers are short-lived — they perform a discrete task (implement an issue, review a PR, scan a module, update a document) and then exit. The supervisor's job is to identify work, dispatch workers, and keep its pool full by launching new workers as old ones complete. This separation ensures crash isolation (a failed worker doesn't take down the supervisor), fresh context per task, and independent health monitoring by both the supervisor and the Product Builder.

**Exception — PR Merge Pool**: The PR Merge Pool Supervisor calls `pr-merge-worker` as a **blocking subagent** (via the Task tool) rather than dispatching it as an async session. The supervisor blocks until the worker finishes, then continues its cycle. This means there are no `[AUTO-PRMRG-<N>]` async sessions. The Product Builder and System Watchdog must skip worker health checks for this supervisor — its health is determined solely by whether the supervisor session itself (`[AUTO-PRMRG-SUP]`) is active. When the supervisor is busy calling its worker, it appears as a normal busy session.

Capacity examples (concurrent async worker sessions, not counting the 18 supervisor sessions themselves):

N Implementation PR Review UAT Bug Hunt Test Infra Single-worker (×11) PR Merge (blocking) Total Async Workers
4 4 2 1 1 1 11 0 20
8 8 4 2 2 2 11 0 29
16 16 8 4 4 4 11 0 47

Total concurrent sessions = 18 supervisors + async worker count from the table above. For N=4: 18 + 20 = 38 sessions. (PR Merge worker runs inside the supervisor's session, not as a separate session.)


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.3.1 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 (95 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: 95 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 primary Forgejo bot account used by most automated agents for implementation, PR creation, issue management, and merges. A separate reviewer bot account handles PR reviews (Section 6.17). 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-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-GROOM | grooming-pool-supervisor | 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-ONEOFF | (various) | One-off dispatched agents | | AUTO-IMP-ISSUE-<N> | implementation-worker | Implementation worker (issue #N) | | AUTO-IMP-PR-<N> | implementation-worker | Implementation worker (PR #N fix) | | AUTO-REV-<N> | pr-reviewer | PR reviewer worker | | AUTO-UAT-<N> | uat-test-worker | UAT test worker | | AUTO-BUG-<N> | bug-hunt-worker | Bug hunt worker | | AUTO-INF-<N> | test-infra-worker | Test infra worker | | AUTO-PRMRG-<N> | pr-merge-worker | PR merge/rebase worker (Removed — pr-merge-worker is now called as a blocking subagent, not an async session. See Section 8.3.) | | AUTO-ARCH-<N> | architecture-worker | Architecture spec worker | | AUTO-EPIC-<N> | epic-planning-worker | Epic planning worker | | AUTO-HUMAN-<N> | human-liaison-worker | Human liaison worker | | AUTO-EVLV-<N> | agent-evolution-worker | Agent evolution worker | | AUTO-GUARD-<N> | architecture-guard-worker | Architecture guard worker | | AUTO-SPEC-<N> | spec-update-worker | Spec update worker | | AUTO-GROOM-<N> | grooming-worker | Grooming worker | | AUTO-DOCS-<N> | documentation-worker | Documentation worker | | AUTO-TIME-<N> | timeline-update-worker | Timeline update worker | | AUTO-OWNR-<N> | project-owner-worker | Project owner worker | | AUTO-WDOG-<N> | system-watchdog-worker | System watchdog 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 operates at two cadences: a fast cycle (every sixty seconds) for health checking and an hourly cycle for status reporting.

4.3.1 Fast Cycle (every 60 seconds)

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

  2. Check each supervisor by searching for its session tag via the Async Agent Manager. Verify the session exists and is in a busy state. Any supervisor whose session has completed, errored, or disappeared is immediately re-launched.

  3. Answer questions. If a supervisor's session is waiting for input (it asked a question), read the messages to understand the question and provide an answer so it can continue.

4.3.2 Deep Inspection (every 5 fast cycles, ~5 minutes)

Every fifth fast cycle, perform deeper checks on each supervisor and its workers:

  1. Supervisor inspection: Read the last several messages from each supervisor's session, including the agent's internal thinking. Evaluate whether the supervisor is making progress and behaving correctly. Look for repeated errors, no work activity for fifteen or more minutes, looping behavior, or the agent doing work outside its responsibilities. If the supervisor appears stuck or misbehaving, stop it and launch a fresh one.

  2. Worker health check: For each pool supervisor, search for sessions matching the supervisor's worker tag pattern (see Section 4.2.1). Count active workers and compare against the expected count for that supervisor's tier. If a pool supervisor has been running for more than five minutes but has zero workers, investigate by reading the supervisor's messages. Check individual worker sessions for problems (errored, stuck, completed but not cleaned up). Exception — PR Merge Pool (AUTO-PRMRG-SUP): This supervisor calls pr-merge-worker as a blocking subagent (not async). There are no [AUTO-PRMRG-<N>] async worker sessions to search for. Skip the worker health check for this supervisor entirely — its health is determined solely by whether the supervisor session itself is active.

4.3.3 Hourly Status Cycle (~60 fast cycles)

Approximately once per hour, perform these additional steps:

  1. Completion verification: Invoke the Product Verifier to assess product completeness — milestone status, open issues and PRs, test suite results, quality gate compliance.

  2. Convergence check: Based on the verifier's results, determine whether the product is approaching or has reached completion (all milestones done, all issues closed, all PRs merged, all quality gates passing).

  3. Create status tracking ticket: Create a new automation tracking issue via the Automation Tracking Manager with comprehensive status including all eighteen supervisor statuses, worker counts per pool, completion results, convergence assessment, and corrective actions taken.

activitydiag {
  "Launch 18 Supervisors" -> "Sleep 60s";
  "Sleep 60s" -> "Check Each Supervisor (by tag)";
  "Check Each Supervisor (by tag)" -> "Any Dead or Waiting?";
  "Any Dead or Waiting?" -> "Re-launch Dead / Answer Questions" [label = "yes"];
  "Any Dead or Waiting?" -> "Deep Inspection Due?" [label = "no"];
  "Re-launch Dead / Answer Questions" -> "Deep Inspection Due?";
  "Deep Inspection Due?" -> "Inspect Supervisors + Workers" [label = "every 5 cycles"];
  "Deep Inspection Due?" -> "Hourly Cycle Due?" [label = "not yet"];
  "Inspect Supervisors + Workers" -> "Hourly Cycle Due?";
  "Hourly Cycle Due?" -> "Run Completion Verification" [label = "every ~60 cycles"];
  "Hourly Cycle Due?" -> "Sleep 60s" [label = "not yet"];
  "Run Completion Verification" -> "Create Status Tracking Ticket";
  "Create Status Tracking Ticket" -> "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.

This calculation is centralized in the Automation Tracking Manager (per the Subagent Specialization Principle, Section 6.0). Agents do NOT calculate the interval themselves. Instead, they pass sleep_interval_default to CREATE_TRACKING_ISSUE and the ATM handles the rest:

task automation-tracking-manager "CREATE_TRACKING_ISSUE" \
  --agent-prefix "AUTO-WATCHDOG" \
  --tracking-type "System Health Report" \
  --body "$tracking_body" \
  --sleep-interval-default 5 \   # Agent's sleep duration in minutes
  --repo-owner "$owner" \
  --repo-name "$repo"
# ATM automatically calculates and injects the Estimated Cycle Interval

ATM internal calculation (rolling average with 90/10 weighting):

# If no previous tracking issue exists:
estimated_interval = sleep_interval_default

# If previous tracking issue found:
old_interval = parse "Estimated Cycle Interval" from previous issue body
actual_interval = (now - previous_issue.created_at) in minutes
estimated_interval = round(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 eleven 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
CYCLE_ANNOUNCEMENT_REVIEW Combined per-cycle: read others' announcements + review and close own stale announcements

5.5 Agent Prefix Registry

Prefix Agent
AUTO-SESSION Session Persister
AUTO-WATCHDOG System Watchdog
AUTO-GROOMER Grooming Supervisor
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-SUP 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-SUP
Test Infrastructure Pool AUTO-INF-SUP AUTO-INF-POOL
Human Liaison AUTO-HUMAN AUTO-LIAISON
Grooming AUTO-GROOM AUTO-GROOMER
Project Owner AUTO-OWNR AUTO-PROJ-OWN
System Watchdog AUTO-WDOG AUTO-WATCHDOG
PR Merge AUTO-PRMRG-SUP AUTO-MERGE

For the remaining seven supervisors (Architecture, Epic Planning, Agent Evolution, Architecture Guard, Spec Update, Documentation, Timeline), 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).

  • Worker-level session tags (e.g., AUTO-IMP-ISSUE-<N>, AUTO-IMP-PR-<N>, AUTO-REV-<N>, AUTO-UAT-<N>, AUTO-BUG-<N>, AUTO-INF-<N>, and all other AUTO-*-<N> worker patterns) have no tracking prefix counterpart except AUTO-IMP-WRK. Implementation workers use AUTO-IMP-ISSUE-<N> when implementing a new issue and AUTO-IMP-PR-<N> when fixing an existing PR. All other workers follow the pattern AUTO-{SUPERVISOR_PREFIX}-<N>. Exception: AUTO-PRMRG-<N> no longer exists as a session tag — pr-merge-worker is called as a blocking subagent by the PR Merge Pool Supervisor (see Section 8.3).

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.0 Subagent Specialization Principle

!!! info "Architectural Rule: Centralize, Don't Duplicate"

The system MUST use specialized subagents with restrictive permissions wherever possible. Functionality that multiple agents need MUST be centralized in a single subagent rather than duplicated across agent definitions. When identical logic appears in more than two agents, it is a code smell that should be refactored into a subagent.

Examples of correct centralization:

  • Label operations → Forgejo Label Manager (not duplicated in each agent)
  • Tracking issue lifecycle → Automation Tracking Manager (not duplicated in each agent)
  • Cycle interval calculation → ATM's CREATE_TRACKING_ISSUE with sleep_interval_default (not duplicated in each agent)
  • Announcement review cycle → ATM's CYCLE_ANNOUNCEMENT_REVIEW operation (not duplicated in each agent)
  • Merge verification → Shared Merge Safety module (not duplicated in each merging agent)

Why this matters: Duplicated logic drifts. When a bug is fixed in one copy, the other copies remain broken. Centralized subagents ensure fixes propagate everywhere simultaneously.

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.

Workers, by contrast, must never sleep or loop indefinitely. A worker performs a discrete task (implement an issue, review a PR, scan a module, write a document section) and then exits. The supervisor is responsible for launching new workers to keep its pool full.

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 110 agent definition files (95 active + 15 deprecated stubs), only 10 are user-facing (visible in the OpenCode agent selection UI). The remaining active agents 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
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 (42 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

The Product Builder loads all project reference materials (CONTRIBUTING.md, docs/specification.md, open announcements, and per-supervisor tracking state) during its startup sequence (Section 7.6, Step 4) and synthesizes a customized briefing for each supervisor. This briefing is included in each supervisor's launch prompt.

Supervisors do not invoke the Ref Reader subagent themselves. Instead, they rely on the briefing received from the Product Builder and pass relevant portions of it to their workers. This eliminates redundant reference loading across supervisors and ensures consistent interpretation of project standards.

Workers receive the relevant rules and guidelines from their supervisor's prompt, so they also do not need to read reference materials independently.

6.9 Credential Flow: Top-Down Through Prompts

Only the Product Builder reads environment variables directly (via echo $VAR). All other agents — supervisors, workers, and subagents — receive credentials exclusively through their prompts, passed down the agent hierarchy:

  1. Product Builder reads environment variables (FORGEJO_PAT, GIT_USER_NAME, GIT_USER_EMAIL, FORGEJO_USERNAME, FORGEJO_PASSWORD, FORGEJO_REVIEWER_PAT, FORGEJO_REVIEWER_USERNAME, FORGEJO_REVIEWER_PASSWORD, CA_MAX_PARALLEL_WORKERS) and includes the relevant subset in each supervisor's launch prompt.

  2. Supervisors receive credentials from the Product Builder's prompt and pass the relevant subset to each worker they dispatch. For example, the PR Review supervisor passes the reviewer credentials (not the primary credentials) to its workers.

  3. Workers receive credentials from their supervisor's prompt and use them directly. They never read environment variables.

No supervisor or worker has the "echo $*": allow bash permission. This ensures credentials are controlled at the top level and distributed on an as-needed basis. If a credential changes, only the Product Builder's startup needs to be re-run — all downstream agents receive the updated values through the prompt chain.

6.10 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 at max escalation tier Implementation Pool Supervisor, System Watchdog Human developer (after needs feedback label and comment)
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.11 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.12 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.13 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.14 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.15 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.16 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.17 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.18 Dual-Account Architecture and Approval Detection

!!! success "Solved: The Shared Bot Account Problem"

The system uses **two separate Forgejo bot accounts**: a **primary account** (`FORGEJO_USERNAME` / `FORGEJO_PAT` / `FORGEJO_PASSWORD`) for implementation, PR creation, issue management, and merges; and a **reviewer account** (`FORGEJO_REVIEWER_USERNAME` / `FORGEJO_REVIEWER_PAT` / `FORGEJO_REVIEWER_PASSWORD`) exclusively for PR reviews. Since the reviewer is a different Forgejo user than the PR author, formal `APPROVED` reviews work natively.

Environment Variables:

Variable Purpose Used By
FORGEJO_PAT Primary bot API token All agents except PR Reviewer
FORGEJO_USERNAME Primary bot identity All agents (PR creation, issues, ownership detection)
FORGEJO_REVIEWER_PAT Reviewer bot API token PR Reviewer (curl for write ops)
FORGEJO_REVIEWER_USERNAME Reviewer bot identity PR Reviewer (attribution)
FORGEJO_REVIEWER_PASSWORD Reviewer bot web login PR Reviewer's ci-log-fetcher calls

Separation of concerns:

  • The primary account creates PRs, manages issues, pushes code, applies labels, and merges PRs.
  • The reviewer account ONLY posts reviews and review-related comments. It does not create PRs, issues, or push code.
  • The PR Review Pool Supervisor receives both sets of credentials from the Product Builder and passes all three reviewer credentials (PAT, USERNAME, PASSWORD) to each PR Reviewer instance it dispatches.

6.17.0 MCP Token Limitation and the curl Workaround

!!! warning "Critical Implementation Constraint"

The Forgejo MCP tools (e.g., `forgejo_create_pull_review`, `forgejo_create_issue_comment`) authenticate using a single token configured at the MCP server level. **There is no way to override the token on a per-call basis.** This means all MCP tool calls authenticate as the primary bot account, regardless of which agent invokes them.

Consequence for the PR Reviewer: The PR Reviewer cannot use forgejo_create_pull_review or forgejo_create_issue_comment MCP tools — those would create reviews as the primary bot (the PR author), which Forgejo would reject as self-approval. Instead:

  • READ operations (get PR details, list reviews, get diff, list comments): Use Forgejo MCP tools normally. Reads don't care which account authenticates.
  • WRITE operations (post formal review, post backup comment): Use curl with the FORGEJO_REVIEWER_PAT header. This is the ONLY way to authenticate as the reviewer account.

The PR Reviewer's permission block enforces this split:

  • bash: "curl *": allow — enables curl-based API calls
  • forgejo_create_pull_review: deny — blocks the MCP tool (would use wrong token)
  • forgejo_create_issue_comment: deny — blocks the MCP tool (would use wrong token)
Operation Tool Authentication
Get PR details forgejo_get_pull_request_by_index (MCP) Primary bot (fine for reads)
List reviews forgejo_list_pull_reviews (MCP) Primary bot (fine for reads)
Post formal review curl with FORGEJO_REVIEWER_PAT Reviewer bot ✓
Post backup comment curl with FORGEJO_REVIEWER_PAT Reviewer bot ✓
Fetch CI logs ci-log-fetcher with reviewer credential overrides Reviewer bot ✓

6.17.1 Three-Tier Approval Detection

Every agent that checks for approval must inspect three sources, in order of preference:

Tier Source Mechanism Priority
1 Formal Reviews Reviews with state == "APPROVED" from FORGEJO_REVIEWER_USERNAME Primary path — works natively because reviewer ≠ author
2 Review Bodies Reviews with state in ("COMMENT", "PENDING") whose body contains approval keywords Fallback for edge cases
3 Issue Comments Issue comments containing approval keywords Durable backup 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.

6.17.2 Dual-Account Review Protocol

The PR Reviewer agent operates under the reviewer bot account and implements a dual-account protocol:

  1. Step 1 -- Post a formal review via curl with FORGEJO_REVIEWER_PAT to the Forgejo pulls reviews API. This authenticates as the reviewer account (not the PR author), so Forgejo accepts the formal APPROVED state. This is the primary approval signal. (Note: the MCP tool forgejo_create_pull_review cannot be used because it authenticates as the primary bot — see Section 6.17.0.)

  2. Step 2 -- Post a backup issue comment via curl with FORGEJO_REVIEWER_PAT to the Forgejo issues comments API. This provides a durable backup visible regardless of Forgejo review UI state.

Why both steps? The formal review (Step 1) is the standard Forgejo mechanism. The issue comment (Step 2) ensures the decision is always visible and parseable, even if Forgejo review APIs behave unexpectedly.

activitydiag {
  "Review PR (read via MCP)" -> "Decision: APPROVE or REQUEST CHANGES";
  "Decision: APPROVE or REQUEST CHANGES" -> "Step 1: Post Formal Review\n(curl with FORGEJO_REVIEWER_PAT)";
  "Step 1: Post Formal Review\n(curl with FORGEJO_REVIEWER_PAT)" -> "Step 2: Post Backup Comment\n(curl with FORGEJO_REVIEWER_PAT)";
  "Step 2: Post Backup Comment\n(curl with FORGEJO_REVIEWER_PAT)" -> "Review Complete";
}

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.

The system uses dual bot accounts: PRs are created by FORGEJO_USERNAME and reviewed by FORGEJO_REVIEWER_USERNAME. Formal APPROVED reviews are the primary approval mechanism.

6.19 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.20 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.21 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.22 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 acts as a process supervisor (analogous to systemd), not a worker. Its responsibilities are:

  1. Clean up stale sessions from previous runs
  2. Assess project state and bootstrap if needed
  3. Launch all supervisors via the Async Agent Manager
  4. Monitor their health continuously, keeping them running and answering their questions
  5. Verify product completion periodically and report status

The Product Builder never stops running until the user explicitly tells it to stop. If the product is verified complete, it reports this in its status tracking ticket but continues monitoring.

7.3 What the Product Builder Must Never Do

  • Implement issues itself
  • Edit code directly
  • Create or merge pull requests
  • Review code
  • Use the Task tool for launching supervisors (must use Async Agent Manager)
  • Make direct HTTP calls to the OpenCode Server (must use Async Agent Manager)
  • Tell supervisors what to do or pass data between them (supervisors self-coordinate through Forgejo)

7.4 Permissions Rationale

Permission Setting Rationale
edit deny Never edits files directly
webfetch deny No internet access needed
bash.* deny (with exceptions) Only echo, sleep, jq, and git remote allowed
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 for supervisor briefings
task.product-verifier allow Verify product completion
task.automation-tracking-manager allow Manage tracking issues and read announcements
forgejo.* deny All Forgejo interactions delegated to subagents

7.5 Execution Flow

activitydiag {
  "Gather Required Info" -> "Clean Up Old Sessions";
  "Clean Up Old Sessions" -> "Assess Project State";
  "Assess Project State" -> "Bootstrap Needed?";
  "Bootstrap Needed?" -> "Bootstrap" [label = "yes"];
  "Bootstrap Needed?" -> "Load Refs & Prepare Briefings" [label = "no"];
  "Bootstrap" -> "Load Refs & Prepare Briefings";
  "Load Refs & Prepare Briefings" -> "Initial Completion Check";
  "Initial Completion Check" -> "Launch All Supervisors";
  "Launch All Supervisors" -> "Verify All Running";
  "Verify All Running" -> "Create Initial Status Ticket";
  "Create Initial Status Ticket" -> "Monitoring Loop (see Section 4.3)";
}

7.6 Startup Sequence

Step 1: Clean Up Old Sessions

On every new session, the Product Builder finds and stops all sessions whose title starts with [AUTO-, then deletes them. This ensures a clean slate. Supervisors recover their own state from Forgejo tracking issues (via the Startup State Recovery Protocol, Section 5.3.3), so nothing is lost.

!!! note "No Session Adoption"

Previous versions of the Product Builder adopted existing sessions from prior runs. The current design always starts fresh because: (a) all persistent state lives on Forgejo, (b) supervisors implement their own crash recovery via tracking issues, and (c) a clean slate avoids stale session problems.

Step 2: Assess Project State

The Product Builder checks whether the project needs bootstrapping by verifying that pyproject.toml, noxfile.py, .forgejo/workflows/ (CI pipeline), and CONTRIBUTING.md all exist. The Product Verifier (Step 5) provides a thorough assessment of Forgejo state.

Step 3: Bootstrap If Needed

If any files from Step 2 are missing, the Product Builder invokes the Project Bootstrapper subagent to set up project structure, CI, labels, milestones, and branch protection. This step is skipped entirely if all infrastructure exists.

Step 4: Load Reference Materials and Prepare Supervisor Briefings

The Product Builder loads all project reference materials via the Ref Reader subagent (CONTRIBUTING.md, docs/specification.md) and retrieves open announcements and per-supervisor tracking state via the Automation Tracking Manager. It then synthesizes a customized briefing for each supervisor, extracting the portions of the reference material relevant to that supervisor's role. These briefings are included in each supervisor's launch prompt (Step 6). See Section 6.8 for details.

Step 5: Initial Completion Check

The Product Builder invokes the Product Verifier to get a baseline assessment of product completeness (milestones, issues, PRs, tests, quality gates). This is informational and recorded in the initial status ticket.

Step 6: Launch All Supervisors

Each supervisor is launched via the Async Agent Manager with its agent name, session tag, display name, and a prompt containing all configuration parameters (repository info, credentials, worker count, and the customized briefing from Step 4). Worker counts are computed from CA_MAX_PARALLEL_WORKERS using the tiered allocation formula (Section 1.3) and passed to each supervisor as a runtime parameter.

The PR Review Pool Supervisor receives the reviewer credentials (FORGEJO_REVIEWER_PAT, FORGEJO_REVIEWER_USERNAME, FORGEJO_REVIEWER_PASSWORD) instead of the primary bot credentials (Section 6.17).

Step 7: Verify All Supervisors Running

Immediately after launching, the Product Builder verifies each supervisor is alive by searching for its session tag and checking it is in a busy state. Any failed launches are retried.

Step 8: Create Initial Status Ticket

An initial status tracking ticket is created via the Automation Tracking Manager with comprehensive status: session start time, product vision, all supervisor statuses, completion check results, and worker allocation values.

7.7 Subagent Interactions

blockdiag {
  "Product Builder" -> "async-agent-manager" [label = "launch/monitor supervisors"];
  "Product Builder" -> "project-bootstrapper" [label = "one-shot: bootstrap"];
  "Product Builder" -> "product-verifier" [label = "hourly: completion check"];
  "Product Builder" -> "ref-reader" [label = "one-shot: load context"];
  "Product Builder" -> "automation-tracking-manager" [label = "hourly: status tickets"];
}

7.8 Worker Tag Patterns

Pool supervisors launch workers whose session tags follow predictable patterns. The Product Builder uses these patterns to find and count workers independently of the supervisor:

Supervisor Tag Worker Tag Pattern Examples
[AUTO-IMP-SUP] [AUTO-IMP-ISSUE-<N>] or [AUTO-IMP-PR-<N>] [AUTO-IMP-ISSUE-42], [AUTO-IMP-PR-15]
[AUTO-REV-SUP] [AUTO-REV-<N>] [AUTO-REV-1]
[AUTO-UAT-SUP] [AUTO-UAT-<N>] [AUTO-UAT-1]
[AUTO-BUG-SUP] [AUTO-BUG-<N>] [AUTO-BUG-1]
[AUTO-INF-SUP] [AUTO-INF-<N>] [AUTO-INF-1]

Implementation workers use [AUTO-IMP-ISSUE-<N>] when implementing a new issue (where N is the issue number) and [AUTO-IMP-PR-<N>] when fixing an existing PR (where N is the PR number). This naming prevents collisions and makes it easy to identify what each worker is doing.

7.9 Product Builder Responsibilities

Responsibility Role Redundancy Layer Section
R-01: Supervisor Liveness Primary: 60-second health checks, immediate re-launch of dead supervisors; deep inspection every 5 cycles including message reading and question answering; worker health monitoring via tag patterns Layer 1 + Layer 2 22.1
R-04: Issue Implementation Orchestrates by launching Implementation Pool Supervisor Dispatch chain 22.4
R-12: Merge Safety Invokes Project Bootstrapper for initial branch protection setup Setup chain 22.12
R-20: Automation Tracking Creates hourly tracking issues with comprehensive status; reads supervisor status for convergence Layer 2 (self-cleanup) 22.20
R-67: Product Verification Invokes Product Verifier hourly for completion check Dispatch 22.67
R-80: Non-Return Guarantee Never stops unless user explicitly requests it; product completion is reported but does not trigger exit Self-constraint 22.80
R-81: Worker Allocation Computes N/N÷2/N÷4/1 allocation and passes to each supervisor as a runtime parameter Configuration 22.81
R-121: Bootstrap Skip Skips bootstrap if pyproject.toml + noxfile.py + CI + CONTRIBUTING.md all exist Phase gate 22.121
R-122: prompt_async Supervisors via prompt_async (fire-and-forget); Task tool FORBIDDEN (would block forever) Architectural 22.122
R-123: 18 Mandatory Post-launch verification: ALL 18 must have active sessions; re-launch any missing Verification 22.123
R-124: Convergence Hourly convergence check via Product Verifier; reports status in tracking ticket Lifecycle gate 22.124
R-125: Never Edits FORBIDDEN: implement, edit code, create PR, merge PR, review PR, fix CI — always re-launch supervisor Prohibition 22.125
R-126: No Duplicates One instance per supervisor type; checks for existing session before launch Layer 1 (prevention) 22.126
R-21: Crash Recovery Clean-slate startup (stops all [AUTO-*] sessions, launches fresh); supervisors recover their own state from Forgejo tracking issues Product Builder + Supervisor levels 22.21

7.9 Universal Supervisor Responsibilities (All 18 Supervisors)

!!! info "Shared Baseline"

The following responsibilities apply to **every one of the 18 supervisors** (7 pool + 11 singleton). Individual supervisor tables in Sections 8 and 9 list only their **unique** responsibilities on top of this shared baseline. The Product Builder (Section 7.9) shares most of these but has its own variants.
Responsibility What Every Supervisor Must Do Section
R-141: Startup Sequence Execute 4-step startup: READ_TRACKING_STATE → parse recovered state → CREATE_TRACKING_ISSUE → begin main loop 22.141
R-142: State Recovery Read most recent tracking issue BEFORE creating new one; parse previous cycle's work items, health indicators 22.142
R-20: Tracking Coordination Create status tracking issues via ATM every N cycles; update with current state 22.20
R-143: Dual Cleanup Close ALL own old status issues before creating new one (via ATM's close-all protocol) 22.143
R-133: Announcement Consumption Read announcements from relevant agents at appropriate priority depth per the consumption table 22.133
R-43: Announcement Lifecycle Review own announcements every 3 cycles; close resolved ones 22.43
R-44: Context Self-Management Periodically discard accumulated tool outputs; retain only persistent state 22.44
R-113: Resource Cleanup Guarantee resource release (claims, clones, temps) via try/finally 22.113
R-114: Credential Validation Validate all required credentials at startup before any work 22.114
R-63: Bot Signature Append standardized bot signature to ALL Forgejo content 22.63
R-41: Worker Dispatch Pool supervisors only: maintain sliding window of N workers; fill slots immediately from priority queue 22.41
R-78: Structured Logging Use [AGENT:][SESSION:][ACTION:][LEVEL:] format for all logs 22.78
R-79: Performance Monitoring Track operation durations, success rates, resource usage; adaptive timeouts 22.79
R-77: Push Conflict Recovery Cloning agents only: rebase-and-retry on push rejection; reclone after 5 failures 22.77
R-127: No Label Creation Never create labels; delegate to Forgejo Label Manager 22.127
R-134: No Internet No webfetch access; work from local files, Forgejo API, and OpenCode API only 22.134

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.1.7 Implementation Pool Supervisor Responsibilities

In addition to the universal supervisor responsibilities:

Responsibility Role Redundancy Layer Section
R-49: PR Ownership & Scoring Classifies PRs by pr.user.login; scores by work type (95/90/85/80/60) + age bonus Single 22.49
R-98: Dispatch Ordering 7-level priority: CI-Blocker → Critical bugs → lowest milestone → In Progress → Priority → MoSCoW → unblock score Single 22.98
R-04: Issue Implementation Primary dispatcher: finds verified issues, manages sliding window of N workers, enforces PR-first priority gate Dispatch 22.4
R-50: Worker Adoption Scans for existing worker sessions on startup; validates status; adopts into tracking Layer 1 22.50
R-51: Pagination & Truncation Paginates ALL PR pages; reads truncated output files; logs verification counts Most affected 22.51
R-07: PR Fixing PR-first priority gate guarantees every bot PR has an active worker before any new issues Layer 1 22.7
R-08: PR Merging Dispatches workers with ready-to-merge work type for approved PRs Layer 2 (backup) 22.8
R-20: Automation Tracking Creates tracking issues; reads announcements from watchdog, architecture, groomer Layer 2 (self-cleanup) 22.20
R-21: Crash Recovery Adopts existing worker sessions; parses previous tracking for active PRs/issues Worker level 22.21

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.2.4 PR Review Pool Supervisor Responsibilities

In addition to the universal supervisor responsibilities:

Responsibility Role Redundancy Layer Section
R-05: Code Review Primary dispatcher: polls for unreviewed PRs, dispatches N/2 parallel PR Reviewer instances with rotating focus areas Layer 1 22.5
R-52: Dual-Account Auth Passes all 3 reviewer credentials (PAT, username, password) to each dispatched PR Reviewer instance Credential distribution 22.52
R-53: Anti-Pattern Detection Assigns rotating focus areas (10 categories) to each reviewer instance, ensuring diverse detection Layer 1 (rotation) 22.53
R-101: Flaky Test Detection Reviewers check for 16 specific non-deterministic test patterns; REQUEST_CHANGES immediately on match Layer 1 (per-PR) 22.101
R-135: File Organization Checks files in correct directories per CONTRIBUTING.md Layer 2 (review) 22.135
R-136: No type:ignore Scans diff for type: ignore; requests changes if found Layer 2 (review) 22.136
R-137: 500-Line Limit Checks file sizes in diff; requests changes for files exceeding 500 lines Layer 2 (review) 22.137
R-138: Framework Selection Rejects xUnit-style tests; verifies correct framework per test level Layer 2 (review) 22.138
R-140: Commit Format Checks Conventional Changelog format in PR commits Layer 2 (review) 22.140
R-20: Automation Tracking Creates tracking issues; reads critical announcements from watchdog/liaison Layer 2 (self-cleanup) 22.20

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. Unlike other supervisors, the PR Merge Pool calls pr-merge-worker as a blocking subagent (via the Task tool) rather than dispatching it as an async session. The supervisor blocks until the worker finishes, then continues its cycle. This means there are no [AUTO-PRMRG-<N>] async sessions — the Product Builder and System Watchdog must skip worker health checks for this supervisor.

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)

Both bot accounts are recognized as valid approvers. See Section 6.17 for the dual-account architecture.

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 calls pr-merge-worker as a blocking subagent via the Task tool. The worker handles the rebase operation based on whether conflicts exist:

Condition Action
Behind, no conflicts Worker creates an isolated clone via repo-isolator, rebases via git rebase, force-pushes with lease via git-commit-helper, cleans up the clone, waits for CI to pass, then attempts a fast-forward merge if the PR is mergeable.
Behind, with conflicts Worker resolves conflicts by reviewing recent git history, or posts comment requesting manual rebase if unresolvable.
Up-to-date Supervisor proceeds directly to merge (no worker needed).

Blocking call semantics: The supervisor blocks while the worker runs — including during the worker's CI polling wait. Only after the worker finishes does the supervisor continue to the next PR. This is intentional since only one rebase operation happens at a time.

Critical rule: After a successful rebase, the worker waits for CI to complete before attempting merge. The worker polls every 60 seconds for CI completion and only merges with fast-forward if CI passes and the PR is mergeable.

Supervisor subagents: automation-tracking-manager, repo-isolator, git-commit-helper, pr-merge-worker (blocking)

Worker subagents (used by pr-merge-worker): repo-isolator, git-commit-helper

8.3.6 PR Merge Pool Supervisor Responsibilities

In addition to the universal supervisor responsibilities:

Responsibility Role Redundancy Layer Section
R-99: 7 Merge Criteria ALL seven criteria verified before every merge: approval, CI, conflicts, staleness, needs-feedback, blocked, issue state Protocol 22.99
R-100: Blocking Detection REQUEST_CHANGES only blocks if more recent than latest approval from any of the 3 tiers Protocol 22.100
R-54: 3-Tier Approval check_pr_approval() implements 3-tier detection: formal reviews → review bodies → issue comments Consumer 22.54
R-08: PR Merging Primary merger: polls every 5 minutes for merge-ready PRs, verifies 7 merge criteria, handles pre-merge rebase Layer 1 22.8
R-55: Post-Merge Verification After every merge: forgejo_get_pull_request_by_index to confirm merged == true AND state == "closed" Layer 1 (inline) 22.55
R-30: Branch Management Pre-merge staleness check (merge_base vs base.sha); automatic rebase for behind-but-no-conflict PRs Layer 2 22.30
R-12: Merge Safety Implements safe_merge_pr() with all 7 mandatory rules Layer 2 (enforcement) 22.12
R-139: 97% Coverage CI coverage check at merge gate; failing coverage blocks merge Layer 2 (merge gate) 22.139
R-28: Issue Closure After verified merge: updates linked issues to State/Completed Layer 1b (immediate) 22.28
R-20: Automation Tracking Creates tracking issues; reads critical announcements from watchdog Layer 2 (self-cleanup) 22.20

8.4 PR Fix Pool Supervisor (Removed)

!!! note "Absorbed into Implementation Pool Supervisor"

The PR Fix Pool Supervisor has been removed. Its responsibilities are now handled by the **Implementation Pool Supervisor** (Section 8.1), which has PR-first priority and dispatches `implementation-worker` agents for both new issues and PR fixes. PR fix behavior is covered by the implementation pool's progressive escalation model (four model tiers with human escalation at the top). Workers use the `ci-log-fetcher` subagent directly to understand CI failures.

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 Supervisor-Worker Separation

The supervisor discovers testable feature areas and dispatches uat-test-worker agents, each assigned one feature area. Workers clone the repo, test their assigned feature, file bugs for failures, and exit. The supervisor keeps the pool full by launching new workers as old ones complete.

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.5.4 UAT Test Pool Supervisor Responsibilities

In addition to the universal supervisor responsibilities:

Responsibility Role Redundancy Layer Section
R-16: Bug Detection Tests feature areas against specification; files bug issues for gaps and spec deviations Layer 2 (spec compliance) 22.16
R-66: Finding Validation Checks open PRs for keywords matching feature area before filing bugs Layer (UAT gate) 22.66
R-86: Open PR Awareness Skips bug filing if open PR already addresses the gap Layer 1 22.86
R-88: Feature Retest Maps changed files to feature areas; invalidates tested_areas set to force retest Single 22.88
R-17: Documentation Generates showcase documentation from successful end-to-end test runs Supplementary 22.17
R-19: Scope Management Milestone Scope Guard: only critical bugs to active milestone, non-critical to backlog Layer 3b (prevention at testing) 22.19
R-15: Backlog Hygiene Worker coordination via Forgejo comments to avoid duplicate testing Layer 2c (self-dedup) 22.15

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-SUP
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.6.4 Bug Hunt Pool Supervisor Responsibilities

In addition to the universal supervisor responsibilities:

Responsibility Role Redundancy Layer Section
R-16: Bug Detection Primary proactive detector: nine analysis passes per module (error handling, concurrency, security, boundaries, resources, types, spec alignment, consistency, data flow) Layer 1 (code analysis) 22.16
R-66: Finding Validation 5-check gate: code evidence, environment verification, actionability, codebase freshness, severity match Layer (Bug Hunt gate) 22.66
R-70: TDD Awareness Includes TDD Note in every bug report for subsequent test-first workflow Layer 1 (filing) 22.70
R-86: Open PR Awareness Validates finding is not already being addressed by open PR Layer 2 22.86
R-14: Codebase Coherence Pass 8 (code consistency) and Pass 9 (data flow) identify inconsistent patterns across modules Layer 2 (per-module analysis) 22.14
R-15: Backlog Hygiene Finding validation: five rules before filing any bug issue to prevent duplicates and false positives Layer 2b (self-dedup) 22.15

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.

8.7.4 Test Infrastructure Pool Supervisor Responsibilities

In addition to the universal supervisor responsibilities:

Responsibility Role Redundancy Layer Section
R-06: Quality Gate Enforcement Proposes improvements to CI pipeline and test infrastructure; never disables existing checks Improvement (indirect) 22.6
R-71: Never-Disable-Checks Hard constraint: never disable coverage, type checking, linting, security. Never reduce below 97%. Never remove CI steps. Layer 1 (self-constraint) 22.71
R-138: Framework Selection Verifies all three test levels exist per module; never weakens framework requirements Layer 3 (infrastructure) 22.138
R-66: Finding Validation Five mandatory dedup checks with ### Duplicate Check section in every issue body Layer (Test Infra gate) 22.66
R-15: Backlog Hygiene Strongest self-dedup of any agent — historical 48+ duplicates motivate 5-step protocol Layer 2 (self-dedup) 22.15

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. When creating a PR for a major spec change, the agent assigns it to the current active milestone using forgejo_update_pull_request (querying available milestones via forgejo_list_repo_milestones); if no active milestone can be determined, milestone assignment is skipped gracefully.

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

9.1.1 Architecture Supervisor Responsibilities

In addition to the universal supervisor responsibilities:

Responsibility Role Redundancy Layer Section
R-13: Specification Governance Primary spec writer: writes/extends docs/specification.md, defines module boundaries, interfaces, data models, patterns Layer 1 (spec → code) 22.13
R-73: Spec Classification Classifies changes: initial → direct commit; major → PR with needs feedback; minor → direct commit Layer 1 (classification) 22.73
R-03: Work Planning Provides the specification that drives epic/issue decomposition Layer 1 (specification) 22.3
R-18: Human Escalation Creates needs feedback PRs for major architectural changes requiring human approval Layer 4 (proposal escalation) 22.18

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.2.1 Epic Planning Supervisor Responsibilities

In addition to the universal supervisor responsibilities:

Responsibility Role Redundancy Layer Section
R-03: Work Planning Primary decomposer: breaks milestones into Epics and Issues with dependency chains; four phases per cycle Layer 2 (decomposition) 22.3
R-11: Dependency Integrity Creates issue→epic→legendary links with correct direction (child BLOCKS parent); fixes orphaned issues/epics; validates ALL dependency directions Layer 1 (creation + enforcement) 22.11
R-69: Orphan Remediation Phase 1: scans ALL open issues/epics for missing parents; finds or creates suitable parents; fixes reversed directions Layer 1 (enforcement) 22.69
R-68: Epic/Legendary Closure Phase 2: evaluates closure candidates where all children completed; closes with acceptance criteria check Layer 1 (evaluation) 22.68
R-40: Spec-First Enforcement Phase 3: identifies features requiring spec changes, creates ADR→Spec→Implementation dependency chains Layer 1 (planning gate) 22.40
R-38: Body & DoD Compliance Creates issues with CONTRIBUTING.md-compliant body format (Metadata, Subtasks, DoD) Layer 1 (at creation) 22.38
R-37: Milestone Assignment Milestone Scope Guard: skips converging milestones; new work goes to backlog Layer 2 (planning-level guard) 22.37
R-19: Scope Management Milestone Scope Guard: prevents new issue creation in converging milestones Layer 2 (prevention at planning) 22.19

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.

9.3.1 Human Liaison Supervisor Responsibilities

In addition to the universal supervisor responsibilities:

Responsibility Role Redundancy Layer Section
R-105: 10-Step Loop Precise 10-step cycle: poll (4 sub-polls), idle detect, triage, respond comments, respond reviews, plan, gap analysis, stale check, refresh, context mgmt Single 22.105
R-106: Closed Issue Response 4 patterns: answer questions, refuse reopening, create new bug for related reports, acknowledge feedback Single 22.106
R-18: Human Communication Primary bridge: handles all human activity, Feedback Incorporation Protocol Layer 1 (primary bridge) 22.18
R-46: Feedback Incorporation Exclusive owner: updates descriptions when discussion changes ticket nature, posts diff for user, confirms completion Layer 1 (single) 22.46
R-47: Timeout Management Tracks 5 timeout types (48h/24h/72h/48h/24h), creates provisional decisions, escalates Layer 1 (tracking) 22.47
R-48: Developer Assignment Tags developers in comments based on expertise areas when guidance is needed Layer 2 (tagging) 22.48
R-02: Issue Triage Triages human-created issues with full triage authority; fastest polling interval (2 min) Layer 2 (human issues) 22.2
R-36: Story Points Estimates story points during triage (XS 1pt through XXL 13pt) Layer 1 (triage-time) 22.36
R-03: Work Planning Plans implementation for verified issues; Epic/Legendary gap analysis every 10th cycle Layer 4 (human requests) 22.3
R-40: Spec-First Enforcement For features requiring spec changes: creates spec issue, tracks spec PR, creates impl issues after merge Layer 3 (feedback channel) 22.40
R-22: Self-Improvement Channels human feedback about agent behavior into the improvement pipeline Layer 3 (human feedback) 22.22
R-09: Label Correctness Sets labels on issues it creates via Forgejo Label Manager Layer 2 (initial assignment) 22.9
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.4.1 Agent Evolution Supervisor Responsibilities

In addition to the universal supervisor responsibilities:

Responsibility Role Redundancy Layer Section
R-22: Self-Improvement Primary evolution agent: seven analysis steps, two-step proposal workflow (proposal issue → implementation PR after human approval) Layer 1 (proactive analysis) 22.22
R-85: Pattern Detection Eight detection categories: task-type failures, merge failures, early exits, context exhaustion, high escalation rate, duplicate work, capability gaps, subtask failures. Six improvement types. Layer 1 (detection) 22.85
R-57: Clone Isolation Creates clone to modify .opencode/agents/ files; pushes agent definition changes via PR Protocol user 22.57
R-135: File Organization Only modifies files in .opencode/agents/ — never modifies source code Self-constraint 22.135
R-18: Human Escalation Creates needs feedback proposals for agent definition changes Layer 4 (proposal escalation) 22.18

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.5.1 Architecture Guard Responsibilities

In addition to the universal supervisor responsibilities:

Responsibility Role Redundancy Layer Section
R-14: Codebase Coherence Primary coherence scanner: seven check categories (duplicate code, inconsistent patterns, module coupling, API inconsistencies, technical debt, test quality, specification drift) Layer 1 (proactive scanning) 22.14
R-74: SHA-Based Idle Detection Compares master SHA with last known; skips scanning when unchanged; only scans on new code Single 22.74
R-13: Specification Governance Check 7: detects specification drift — implementation diverged from spec Layer 3 (drift detection) 22.13
R-16: Bug Detection Check 6: test quality (tests not verifying meaningful behavior), Check 5: technical debt indicators Layer 4 (architecture-level) 22.16

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. Also monitors all specification PRs for human feedback (approval, rejection, staleness) as the domain expert for the specification lifecycle.

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.

Spec PR Monitoring (human-in-the-loop): The Specification Evolution Supervisor monitors all open specification PRs (those with the needs feedback label) for human activity:

  • Merged by human: Note the approval, update internal state to reflect the new spec baseline.
  • Rejected by human (closed without merge): Note the rejection, do not re-propose the same change.
  • Gone stale (master has advanced): Rebase the spec branch onto master and force-push.
  • Waiting >24 hours: Post a reminder comment requesting human review.

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.6.1 Specification Evolution Supervisor Responsibilities

In addition to the universal supervisor responsibilities:

Responsibility Role Redundancy Layer Section
R-13: Specification Governance Backward alignment: compares implementation against spec after merges; updates spec where implementation found better approach; creates bug issues for incorrect deviations Layer 2 (code → spec) 22.13
R-73: Two-Step Proposal Proposal issue first with needs feedback; implementation PR only after human approval; tracks rejected proposals Layer 2 (proposal workflow) 22.73
R-74: SHA-Based Idle Compares master SHA; proactive deep scan every 5th idle cycle (~75 min) Single 22.74
R-92: Proactive Scan Module-by-module spec-vs-code comparison; classifies discrepancies; generates ≥1 proposal per scan Single 22.92
R-65: Spec PR Lifecycle Primary spec PR monitor: tracks all spec PRs for human feedback (merged, rejected, stale); rebases when master advances; posts reminders after 24h; preserves needs feedback label Layer 1 (monitoring + self-rebase) 22.65
R-59: PR Description Re-sends full body on every PR update to prevent Forgejo API description deletion Layer 2 22.59
R-18: Human Escalation Creates needs feedback proposals for spec changes Layer 4 (proposal escalation) 22.18

9.7 Grooming Supervisor

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

Purpose: Continuous quality maintenance for ALL open issues and pull requests. Dispatches workers to perform a full 10-point quality analysis on individual items. Prioritizes PRs with unaddressed review feedback. Works entirely through the Forgejo API; no clone required.

Subagents: async-agent-manager, automation-tracking-manager

Worker model: Each worker takes a single issue or PR number, reads all comments and reviews, performs 10 quality checks, applies fixes, and posts a [GROOMED] marker comment. For PRs, the worker also syncs labels (Priority, Type, MoSCoW, milestone) from the linked issue to the PR.

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.7.1 Grooming Supervisor Responsibilities

In addition to the universal supervisor responsibilities:

!!! info "Most Cross-Referenced Agent"

The Backlog Groomer participates in more responsibilities than any other single agent. Its 19 analysis passes provide redundancy checks across nearly every system responsibility.
Responsibility Role Redundancy Layer Section
R-09: Label Correctness Pass 4: auto-fixes missing State/Type/Priority labels; Pass 19: PR-issue label synchronization Layer 3 (verification & auto-fix) 22.9
R-35: PR-Issue Label Sync Pass 19: copies missing Priority/MoSCoW/Points labels from issue to PR, removes stale labels, syncs milestones Layer 2 (ongoing sync) 22.35
R-10: Issue State Management Pass 9: reconciles closed issue states; Pass 4: detects wrong-state issues; Pass 6: detects closeable issues; Pass 14: closes issues whose PRs merged Layer 2 (reconciliation) 22.10
R-36: Story Points Pass 4: estimates points for unlabeled issues (0-2 subtasks→Points/2, 3-5→Points/3, 6-8→Points/5, 9+→Points/8) Layer 2 (compliance fill) 22.36
R-37: Milestone Assignment Pass 4: assigns milestone to Verified+ issues without one Layer 3 (compliance fill) 22.37
R-11: Dependency Integrity Pass 2: orphan detection; Pass 10: auto-fixes missing dependency links; Pass 16: fixes wrong-direction dependencies Layer 2 (verification & auto-fix) 22.11
R-02: Issue Triage Pass 4: fills missing labels with safe defaults (State/Unverified, Priority/Backlog) Layer 3 (gap filler) 22.2
R-03: Work Planning Passes 12-13: detects incomplete epics/legendaries, creates missing child issues Layer 3 (gap detection) 22.3
R-24: Work Claiming Pass 3: detects stale In Progress issues (>48h no activity), implying abandoned claims Layer 2 (stale detection) 22.24
R-15: Backlog Hygiene Primary hygiene agent: Pass 1 (duplicates), Pass 2 (orphans), Pass 3 (stale), Pass 8 (blocked chains), Pass 11 (body compliance), Pass 17 (stale PRs) Layer 1 (comprehensive) 22.15
R-38: Body & DoD Compliance Pass 11: checks for Metadata/Subtasks/DoD sections; Pass 7: audits DoD checklist accuracy Layer 2 (verification) 22.38
R-39: Blocked Chains Pass 8: detects circular dependencies, orphaned blockers, impossible chains Layer 1 (analysis) 22.39
R-102: Post-Merge Closure Pass 15: removes satisfied dependency links (merged PRs, closed issues) via DELETE API before closing issues Layer 2 (dependency cleanup) 22.102
R-103: Wrong-Direction Fix Pass 16: detects issue-blocks-PR (deadlock); DELETE wrong + POST correct direction (PR blocks issue) Layer 1 (detection & fix) 22.103
R-104: Priority Consistency Pass 5: High blocked by Low, current milestone low while next has high Layer 1 (detection) 22.104
R-28: Issue Closure Pass 14: closes issues whose PRs merged; Pass 6: closes issues with completed DoD; removes stale dependency links Layer 2 (catch-up) 22.28
R-19: Scope Management Pass 18: scope creep detection via creation-vs-closure rate monitoring Layer 1 (detection) 22.19
R-20: Automation Tracking Pass 19: cleans stale tracking tickets; Pass 20: deduplicates status issues Layer 3 (redundant cleanup) 22.20
R-130: Issue Body Format Pass 11: verifies Metadata, Subtasks, DoD sections; posts comment listing missing sections Layer 2 (verification) 22.130
R-128: State Transitions Pass 4/9: detects issues in impossible states; corrects to valid transitions Layer 2 22.128
R-129: Priority Ordering Pass 5: detects priority inconsistencies within and across milestones Layer (detection) 22.129
R-42: Tracking Cleanup Pass 19/20: age-based cleanup (Critical=72h, High=48h, Medium=24h, Low=12h), deduplication (keeps newest per prefix) Layer 3 (cross-agent cleanup) 22.42
R-43: Announcements Pass 19: auto-closure inquiry, 24h grace period, respects PERSIST/KEEP_OPEN markers Layer 3 (stale cleanup) 22.43
R-68: Epic/Legendary Closure Passes 12-13: detects parents with all children closed; creates missing children or flags for closure Layer 2 (detection) 22.68
R-69: Orphan Remediation Pass 2: flags orphan issues not linked to any parent Epic Layer 2 (detection) 22.69
R-72: Stale PR Detection Pass 17: detects PRs with no milestone, duplicates, targeting completed issues, >72h no reviews Layer 1 (detection) 22.72

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.8.1 Documentation Supervisor Responsibilities

In addition to the universal supervisor responsibilities:

Responsibility Role Redundancy Layer Section
R-17: Documentation Exclusive documentation owner: generates/updates README, API docs, architecture docs, changelog, module docs. Always extends, never overwrites. Single (exclusive domain) 22.17
R-89: Doc Generation Five doc types: README, API (from docstrings), Architecture (from spec), Changelog (Keep a Changelog), Module docs. mkdocs-compatible. Single 22.89
R-57: Clone Isolation Creates isolated clone for doc generation (edit:allow agent); pushes and cleans up Protocol user 22.57
R-61: Reference Loading Loads spec and project state via ref-reader before generating docs Protocol user 22.61

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.9.1 Timeline Update Supervisor Responsibilities

In addition to the universal supervisor responsibilities:

Responsibility Role Redundancy Layer Section
R-17: Documentation Exclusive timeline owner: docs/timeline.md only. Nine sections including Gantt charts, status, completion history, risk tables. Single (exclusive domain) 22.17
R-82: Surgical Edit Append-only history, one entry per day, strikethrough for resolved risks, conservative data policy, PlantUML Gantt color codes Single (exclusive protocol) 22.82
R-57: Clone Isolation Creates isolated clone for timeline edits; pushes via PR workflow Protocol user 22.57

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.10.1 Project Owner Supervisor Responsibilities

In addition to the universal supervisor responsibilities:

Responsibility Role Redundancy Layer Section
R-02: Issue Triage Primary triager: assigns MoSCoW labels (exclusive authority), sets priorities, verifies issues, transitions states Layer 1 (strategic triage) 22.2
R-107: MoSCoW Framework 11-signal framework: Must (MUST/required/blocks/demo), Should (SHOULD/quality/perf), Could (MAY/polish/refactor) Single (exclusive) 22.107
R-108: Priority Re-eval Every 10 cycles: MoSCoW drift, milestone health (>50% open + >50% time), scope health (creation/closure rates) Single 22.108
R-109: Assignment Gate 4-condition gate: expertise >0.7, capacity, velocity >1.3×, no blocking risks. 5 blocking scenarios. Golden Rule. Single 22.109
R-48: Developer Assignment Primary assigner: git history analysis, expertise mapping, strategic delegation Layer 1 (discovery & assignment) 22.48
R-47: Timeout Management Follows up on developer questions after 48h, triages independently after 96h Layer 2 (follow-up) 22.47
R-18: Human Communication Tags developers with questions, assigns developers to issues based on expertise, follows up on pending questions Layer 2 (strategic questions) 22.18
R-19: Scope Management Strategic priority review every 10th cycle: MoSCoW re-evaluation, milestone health check, scope health check Governance 22.19
R-09: Label Correctness Assigns MoSCoW, priority, and type labels via Forgejo Label Manager Layer 2 (initial assignment) 22.9

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

9.11.4 System Watchdog Supervisor Responsibilities

In addition to the universal supervisor responsibilities:

!!! info "System Conscience"

The System Watchdog participates as a redundancy layer in more responsibilities than any other agent except the Backlog Groomer. Its role is always as an **auditor and detector** — it finds problems and dispatches fixers, but never fixes things directly (except creating issues).
Responsibility Role Redundancy Layer Section
R-01: Supervisor Liveness Audit 6: zombie detection via session introspection (sleep-only, error-loop, identical-call patterns); Audit 11: staleness detection via tracking issue age Layer 3 (behavioral analysis) 22.1
R-32: Master CI Emergency Audit 0 (EMERGENCY): detects master CI failures, parses logs for specific failing tests, creates CI-Blocker issues Layer 1 (detection & triage) 22.32
R-06: Quality Gate Enforcement Audit 1: quality gate compliance; Audit 2: branch protection verification Layer 3 (post-merge audit) 22.6
R-33: Flaky Test Detection Audit 9: monitors CI execution times, detects recurring failures on same tests across PRs Layer 2 (infrastructure detection) 22.33
R-07: PR Fixing Audit 5b: detects struggling PRs with 3+ fix attempts; requests human help Layer 3 (struggling detection) 22.7
R-55: Post-Merge Verification Monitors for "merged successfully" comments on still-open PRs (false-merge detection) Layer 3 (audit) 22.55
R-08: PR Merging Audit 5: tracks PR aging, review coverage, merge throughput Layer (health monitoring) 22.8
R-09: Label Correctness Audit 7: verifies all issues have required labels and dependency links Layer 4 (audit) 22.9
R-39: Blocked Chains Audit 7/8: detects orphan issues and hierarchy violations in dependency graph Layer 3 (audit) 22.39
R-10: Issue State Management Audit 3: checks closed issues with wrong state, In Review without PR, multiple State labels Layer 3 (audit) 22.10
R-11: Dependency Integrity Audit 8: verifies Epic→Legendary hierarchy intact, minimum children, orphan detection Layer 3 (audit) 22.11
R-12: Merge Safety Audit 2: verifies branch protection configuration; dispatches Quality Enforcer for violations Layer 3 (audit) 22.12
R-02: Issue Triage Audit 4: verifies priority/milestone ordering is correct Layer 3b (audit) 22.2
R-18: Human Escalation Audit 5b: independently requests human assistance for struggling PRs Layer 3b (independent escalation) 22.18
R-20: Automation Tracking Audit 11: monitors tracking health, detects stalled agents, triggers recovery Layer 4 (health monitoring) 22.20
R-45: Cycle Interval Audit 11: parses estimated interval from tracking issues, detects frozen agents when age > 2× interval Layer 2 (consumption) 22.45
R-44: Context Management Audit 6: detects context-exhausted zombies via sleep-only pattern in session messages Layer 2 (external detection) 22.44
R-22: Self-Improvement Deep session introspection detects misbehavior patterns; creates needs-feedback issues for systemic problems Layer 2 (problem detection) 22.22
R-23: Security Audit 12/13: session spot-checks for forbidden patterns (force_merge, type: ignore, direct master push) Layer 3 (behavioral audit) 22.23
R-71: Never-Disable-Checks Audits for coverage reduction, CI step removal, type: ignore additions Layer 3 (audit) 22.71
R-136: No type:ignore Audit 12/13: session spot-checks for type: ignore in tool outputs Layer 3 (audit) 22.136
R-139: 97% Coverage Audit 1: verifies master commits have passing coverage Layer 3 (audit) 22.139
R-72: Stale PR Detection Audit 5: detects PRs >24h without reviews, approved >6h without merge, CI failing >2h Layer 2 (pipeline) 22.72
R-90: Alert Dispatch Dispatches Quality Enforcer, State Reconciler; re-launches offending supervisors; creates needs-feedback issues Single (dispatcher) 22.90

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

10.1.10 Implementation Worker Responsibilities

Responsibility Role Redundancy Layer Section
R-04: Issue Implementation Primary executor: claims issue, creates clone, implements subtasks via wave dispatch, creates PR, shepherds to merge Execution 22.4
R-93: Wave Dispatch Builds dependency graph, dispatches parallel waves, detects post-wave conflicts, auto-resolves or re-runs sequentially Single 22.93
R-24: Work Claiming Posts [CLAIM]/[HEARTBEAT]/[RELEASE] comments; checks for existing claims; try/finally release guarantee Layer 1 (claiming) 22.24
R-25: Test Writing Removes @tdd_expected_fail from passing TDD tests after bug fixes; delegates test creation to testers Layer 2 (TDD cleanup) 22.25
R-07: PR Fixing In pr-fix mode: fixes CI, handles review feedback, resolves merge conflicts Worker level 22.7
R-94: Deep Context 7-step context gathering: spec, timeline, comments, commits, previous fixes, CI logs, actual code Single 22.94
R-95: Loop Prevention Hash-based duplicate detection, CI error signature comparison, stuck_counter escalation after 3 Layer 1 (self-detect) 22.95
R-96: PR Lifecycle Max 10 review cycles at 5-min intervals; checks merge/conflict/review/CI each cycle Single 22.96
R-97: Feedback Routing Parses feedback via regex into code/test/docs/style; routes to specialist subagent Single 22.97
R-27: CI Log Retrieval Invokes ci-log-fetcher subagent for CI failure diagnosis Layer 3 (consumer) 22.27
R-54: 3-Tier Approval has_required_approvals() checks formal reviews, review bodies, issue comments for approval keywords Consumer 22.54
R-08: PR Merging In ready-to-merge mode: verifies approvals, rebases if needed, delegates to safe_merge_pr() Layer 2 (backup merger) 22.8
R-55: Post-Merge Verification After merge: verifies merged == true via API; only posts "(verified)" comment after confirmation Layer 1 (inline) 22.55
R-28: Issue Closure After verified merge: transitions issue to State/Completed, posts final comment, deletes clone Layer 1 (immediate) 22.28
R-57: Clone Isolation Creates clone at /tmp/cleveragents-<branch>, configures auth/remotes, deletes on exit Protocol user 22.57
R-30: Branch Management Pre-commit rebase onto master; pre-merge rebase if behind; auto-resolves simple conflicts Layer 3 (worker rebase) 22.30
R-34: Test Stability Enforces strict determinism rules: no timing deps, no unseeded random, no shared filesystem, no network deps Layer 1 (rules) 22.34
R-18: Human Escalation After 3 stuck detections: posts diagnostic comment, adds needs feedback label, exits gracefully Layer 3 (self-escalation) 22.18
R-21: Crash Recovery Phase 0.5 crash recovery: checks for existing clone, PR, commits, uncommitted changes; resumes from appropriate phase Worker level 22.21
R-70: TDD Workflow Searches for @tdd_issue_N tests; removes @tdd_expected_fail after bug fix Layer 2 (TDD execution) 22.70
R-84: Checkpoint Persistence Posts [CHECKPOINT] comments with phase state JSON for crash recovery Single (per worker) 22.84
R-135: File Organization Delegates to specialist testers that know their target directories Layer 1 (implementation) 22.135
R-137: 500-Line Limit "Maximum 500 lines per file" — must split files growing beyond this Layer 1 (implementation) 22.137
R-141: Startup Sequence Not a supervisor but follows the issue-impl startup sequence: announcements → crash recovery → claiming Protocol 22.141
R-09: Label Correctness Sets labels on issues/PRs it creates via Forgejo Label Manager delegation Layer 2 (initial assignment) 22.9

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.

11.3.1 Subtask Loop Responsibilities

Responsibility Role Section
R-31: Progressive Escalation Orchestrator: manages haiku→codex→sonnet→opus schedule; persists state as HTML comments 22.31
R-56: Meaningful Change Rejects <3 functional lines; prevents trivial implementations from passing gates 22.56
R-110: Per-Gate Tier Tracking Independent {gate: tier} map; 5 inner passes; selective re-run; individual gate escalation 22.110
R-111: Opus Diagnostics Posts diagnostic comments every 3 attempts after attempt 4 at opus tier 22.111
R-25: Test Writing Launches Behave + Robot + ASV testers in parallel; monitors with 10s polling 22.25
R-06: Quality Gates Runs lint, typecheck, unit, integration, coverage gates before PR creation 22.6
R-62: Correctness Verification Invokes Implementation Reviewer after quality gates pass 22.62
R-56b: Transient Errors Retries transient errors (timeout, 429) without incrementing attempt counter 22.56b
R-144: Tier Pass-Through Invokes tier selectors that must forward context unmodified 22.144

11.4.1 Specialized Worker Responsibilities

Worker Responsibilities Sections
Implementer R-04 (code writing), R-135 (correct directories), R-137 (500-line limit), R-64 (nox routing) 22.4, 22.135, 22.137, 22.64
Behave Tester R-25 (BDD tests), R-138 (Behave framework), R-34 (determinism), R-70 (TDD tags) 22.25, 22.138, 22.34, 22.70
Robot Tester R-25 (integration tests), R-138 (Robot framework, no mocking), R-34 (determinism) 22.25, 22.138, 22.34
Lint Fixer R-06 (lint gate), R-64 (nox -e lint) 22.6, 22.64
Typecheck Fixer R-06 (typecheck gate), R-136 (no type: ignore), R-64 (nox -e typecheck) 22.6, 22.136, 22.64
Coverage Improver R-139 (≥97% threshold), R-06 (coverage gate) 22.139, 22.6
Test Fixer R-06 (test fixing), R-34 (distinguishes obsolete from genuine bugs) 22.6, 22.34
Unit/Integration Test Runner R-06 (test execution), R-64 (nox -e unit_tests/integration_tests) 22.6, 22.64

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 dual-account 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 dual-account review protocol (Section 6.17.2) 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 Dual-Account Review Protocol (Section 6.17.2): post formal review via curl with FORGEJO_REVIEWER_PAT, then post backup issue comment via curl.

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 and bash: "*": deny with "curl *": allow. It reads PR data via Forgejo MCP tools (which authenticate as the primary bot — fine for reads) and posts reviews/comments via curl with FORGEJO_REVIEWER_PAT (which authenticates as the reviewer bot — required for formal APPROVED reviews). The MCP write tools forgejo_create_pull_review and forgejo_create_issue_comment are explicitly denied because they would authenticate as the wrong account (see Section 6.17.0).

12.1.3 PR Management Agent Responsibilities

Agent Responsibilities Sections
PR Creator R-26 (label inheritance, dependency link, state transition), R-35 (initial label sync), R-131 (body format), R-127 (via Label Manager delegation) 22.26, 22.35, 22.131, 22.127
PR CI Test Fixer R-91 (amend-only, force-push-with-lease), R-27 (CI log consumption), R-06 (post-PR quality fixes), R-59 (body preservation on amend) 22.91, 22.27, 22.6, 22.59
PR Editor R-59 (primary enforcer: fetch-before-edit for body preservation), R-127 (labels via Label Manager only) 22.59, 22.127
PR Reviewer R-05, R-52, R-53, R-101, R-135, R-136, R-137, R-138, R-140 22.5, 22.52, 22.53, 22.101, 22.13522.140
PR Status Analyzer R-118 (5-dimension analysis) 22.118

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.2.1 Issue Management Agent Responsibilities

Agent Responsibilities Sections
Issue State Updater R-10 (state transitions), R-60 (precondition validation, blocker checks, PR sync), R-128 (valid transition matrix), R-127 (one of two agents permitted to call forgejo_add_issue_labels) 22.10, 22.60, 22.128, 22.127
New Issue Creator R-37 (milestone scope guard), R-130 (Metadata/Subtasks/DoD format), R-38 (body compliance at creation), R-11 (child-blocks-parent Epic link), R-127 (labels via Label Manager) 22.37, 22.130, 22.38, 22.11, 22.127
Issue Analyzer R-115 (structured data extraction: metadata, subtasks, DoD, comments, deps) 22.115
Issue Note Writer R-117 (logical code references, never line numbers, mandatory 7-section format) 22.117
Subtask Checker R-116 (fuzzy-match checkbox toggle, body preservation) 22.116
Issue Comment Formatter R-83 (5 comment types: progress/error/success/analysis/status) 22.83

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.3.1 Git and Repository Agent Responsibilities

Agent Responsibilities Sections
Repo Isolator R-57 (clone creation in /tmp/isolated-*, auth URL construction, safety validation — refuses /, /tmp, /app deletion, retry cleanup 3×), R-114 (PAT validation before clone) 22.57, 22.114
Branch Setup R-30 (create or checkout with rebase-only policy, dependent branch stacking via base_branch, local-then-remote branch existence check, conflict abort-and-report) 22.30
Git Committer R-29 (stage all, commit, dual-remote push: origin then upstream, both required, error reporting with full context) 22.29
Git Commit Helper R-29 (pre-commit validation, optional hooks, Co-authored-by trailers, rollback via git reset --soft HEAD~1 on failure, structured JSON return) 22.29
CI Log Fetcher R-27 (cookie-based web auth: POST /user/login with CSRF, navigate to actions page, extract run ID from HTML, download logs, 8 CI job-to-artifact mappings, cookie cleanup) 22.27

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.4.1 Reference and Knowledge Agent Responsibilities

Agent Responsibilities Sections
Ref Reader R-61 (reads and summarizes CONTRIBUTING.md + docs/specification.md + docs/timeline.md; output is the foundation for all worker context) 22.61
Ref Material Loader R-61 (cycle-based caching in /tmp/ref-cache/, 24h expiry, 7-day stale cleanup, O(N)→O(1) optimization for worker pools) 22.61
Spec Reader R-61 (issue-relevant extraction: filters full spec to applicable modules, interfaces, data models, cross-cutting concerns) 22.61
Difficulty Evaluator R-119 (5-axis assessment: scope, complexity, novelty, integration, ambiguity → simple/moderate/complex/very_complex; conservative bias → default lower tier) 22.119

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.5.1 Label and Forgejo Agent Responsibilities

Agent Responsibilities Sections
Forgejo Label Manager R-09 (label application), R-58 (name→ID resolution, conflict detection, MoSCoW exclusivity), R-127 (cannot create labels — only apply existing) 22.9, 22.58, 22.127
Forgejo Signature Appender R-63 (3 format types, signature dedup on updates, format validation) 22.63
Automation Tracking Manager R-20 (11 tracking operations), R-42 (close-all protocol), R-45 (rolling average calculation), R-143 (primary close-all-then-create), R-132 (centralized tracking logic) 22.20, 22.42, 22.45, 22.143, 22.132

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.6.1 Quality and Verification Agent Responsibilities

Agent Responsibilities Sections
Implementation Reviewer R-62 (requirement-by-requirement cross-reference; "would-fail" test reasoning; rejects for functional gaps, not style) 22.62
Milestone Reviewer R-120 (8-area cross-issue review; PASS/PASS WITH ISSUES/FAIL assessment; creates issues for gaps) 22.120
Product Verifier R-67 (10-point checklist: milestones, issues, PRs, tests, coverage, spec, docs, code quality, blockers, branches) 22.67
Quality Enforcer R-12 (branch protection repair), R-32 (Priority/CI-Blocker issue creation), R-90 (dispatched by Watchdog for violations) 22.12, 22.32, 22.90
State Reconciler R-10 (8 reconciliation rules for bulk fixes), R-09 (bulk label correction), R-11 (dependency direction fixes) 22.10, 22.9, 22.11

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)

12.7.1 Session Management Agent Responsibilities

Agent Responsibilities Sections
Async Agent Manager R-75 ([TAG] display-name convention, 24+ prefixes, duplicate prevention), R-122 (exclusive localhost:4096 access), R-56b (5-attempt exponential backoff) 22.75, 22.122, 22.56b
Async Agent Monitor R-76 (unhealthy detection: no messages 10 min; auto-restart with same tag) 22.76

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-SUP] 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 (primary bot account)
FORGEJO_REVIEWER_PAT Yes 40 hex chars ([a-f0-9]{40}) Forgejo personal access token for the reviewer bot account (used by PR Reviewer only)
FORGEJO_REVIEWER_USERNAME Yes Alphanumeric Forgejo username for the reviewer bot account (must be different from FORGEJO_USERNAME to allow formal PR approval)
FORGEJO_REVIEWER_PASSWORD Yes 8+ chars Forgejo password for the reviewer bot account (web UI access for CI log scraping via ci-log-fetcher)
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

The system uses two Forgejo bot accounts (Section 6.17):

  1. Primary account (HAL9000) — used by all agents except the PR Reviewer:

    • 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 (must comply with branch protection rules)
  2. Reviewer account — used exclusively by the PR Reviewer for review operations:

    • Pull request review access (post formal APPROVED / REQUEST_CHANGES reviews)
    • Issue comment access (post backup review comments)
    • Web UI access (for CI log scraping via ci-log-fetcher)
    • No write access to branches, issues, or labels (review-only)

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: The primary and reviewer credentials are separate environment variable sets. The PR Review Pool Supervisor receives both sets and passes reviewer credentials to PR Reviewer instances via prompt parameters. 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: pr-merge-worker (blocking), automation-tracking-manager, repo-isolator, git-commit-helper

Worker dispatch model: Unlike all other supervisors, the PR Merge Pool Supervisor calls pr-merge-worker as a blocking subagent via the Task tool. It does NOT use async-agent-manager to dispatch workers. The supervisor blocks until the worker finishes, then continues its cycle. There are no [AUTO-PRMRG-<N>] async sessions. The async-agent-manager is not in the supervisor's task permissions.

Important: edit: deny -- the PR Merge supervisor does NOT have file edit permissions. Rebase operations are delegated to the pr-merge-worker subagent, which creates an isolated clone via repo-isolator and performs git operations within it.

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 calls pr-merge-worker which: (1) creates an isolated clone via repo-isolator, (2) rebases onto the base branch, (3) resolves conflicts by reviewing recent git history, (4) force-pushes with lease via git-commit-helper, (5) cleans up the clone, (6) polls for CI completion, (7) merges with fast-forward if the PR is mergeable.

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: Restricted Bash with curl for Reviewer Authentication

The PR Reviewer agent has bash: "*": deny with a selective exception for curl *: allow. Combined with edit: deny, this makes the PR Reviewer highly constrained — it can only:

  • Read Forgejo data via MCP tools (PRs, issues, comments, reviews, diffs) — these authenticate as the primary bot, which is fine for reads
  • Write reviews and comments via curl with FORGEJO_REVIEWER_PAT — this authenticates as the reviewer bot, enabling formal APPROVED reviews
  • Invoke two subagents: ref-reader (for specification context) and ci-log-fetcher (for CI failure analysis, with reviewer credential overrides)

It cannot edit any files, run arbitrary bash commands, or invoke any other subagents. The curl exception exists solely to enable reviewer-authenticated API calls (see Section 6.17.0 for the MCP token limitation). The Forgejo MCP write tools (forgejo_create_pull_review, forgejo_create_issue_comment) are explicitly denied in its permissions to prevent accidentally using the wrong account.

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.


22. Division of Responsibilities and Redundancy Model

!!! abstract "Purpose of This Section"

This section provides an exhaustive, responsibility-first view of the entire agent system. For each system responsibility, it identifies every agent that participates, describes that agent's specific role, and highlights the **redundancy layers** that ensure no single agent's failure creates a gap. The system is designed with **defense-in-depth**: critical responsibilities are covered by two, three, or even four independent agents, each approaching the responsibility from a different angle. Where an agent is mentioned under a responsibility, a cross-reference link to that agent's main specification section is provided. Conversely, each agent's specification section contains a back-reference table listing all responsibilities it participates in (see Sections [7.8](#78-product-builder-responsibilities), [8.1.7](#817-implementation-pool-supervisor-responsibilities), etc.).

!!! tip "How to Read This Section"

**By responsibility**: Start with the [Responsibility Index](#220-responsibility-index-categorized) to find a specific responsibility (R-01 through R-144). Each entry links to a detail section with a goal statement, redundancy depth, agent role table, and sub-responsibilities.

**By agent**: Go to the agent's specification section (Sections 712) and look for its "Responsibilities" subsection. Each entry links back to the corresponding R-item detail. Every supervisor also inherits 13 [universal responsibilities](#79-universal-supervisor-responsibilities-all-18-supervisors).

**By category**: Browse the 8 categories (AH) in the index. Each category is subdivided into 28 sub-categories grouping related responsibilities.

**By redundancy**: See Section [22.145](#22145-redundancy-analysis-summary) for the redundancy depth distribution, highest-redundancy responsibilities, most cross-referenced agents, and the five named redundancy patterns.

**Scale**: 144 named responsibilities, 8 categories, 29 sub-categories, 30 agent back-reference tables covering ~50 agents.

22.0 Responsibility Index (Categorized)

Category A — Development Lifecycle

The complete code pipeline from planning through merge — 50 responsibilities covering how work is planned, claimed, implemented, tested, reviewed, fixed, merged, and closed. This is the largest category because it encompasses the core value-delivery chain.

A.1 — Planning and Work Setup

ID Responsibility Redundancy Primary Agent(s)
R-03 Work Planning and Decomposition Double Epic Planner, Architecture Supervisor
R-68 Epic and Legendary Closure Evaluation Double Epic Planner, Backlog Groomer
R-69 Orphaned Issue and Epic Remediation Triple Epic Planner, Backlog Groomer, Watchdog
R-24 Work Item Claiming and Coordination Double Implementation Worker, Backlog Groomer
R-49 PR Ownership Detection and Work Scoring Single Implementation Pool
R-98 Issue Dispatch Priority Ordering Rules Single Implementation Pool
R-119 Difficulty Evaluator 5-Criteria Assessment Single Difficulty Evaluator

A.2 — Implementation and Testing

ID Responsibility Redundancy Primary Agent(s)
R-04 Issue Implementation Single (crash recovery) Implementation Pool, Implementation Worker
R-93 Subtask Wave Dispatch and Parallel Conflict Resolution Single Implementation Worker
R-56 Meaningful Change Verification Single Subtask Loop
R-31 Progressive Model Escalation Single Subtask Loop, Tier Selectors
R-25 Test Writing and TDD Lifecycle Double Behave Tester, Robot Tester, Implementation Worker

A.3 — Quality Gates

ID Responsibility Redundancy Primary Agent(s)
R-06 Quality Gate Enforcement Triple Subtask Loop, PR CI Test Fixer, System Watchdog
R-110 Per-Gate Independent Tier Tracking Single Subtask Loop
R-111 Periodic Diagnostics at Opus Tier Single Subtask Loop
R-91 Amend-Only Commit Protocol for CI Fixes Single PR CI Test Fixer

A.4 — PR Creation and Review

ID Responsibility Redundancy Primary Agent(s)
R-26 PR Creation and Metadata Inheritance Double PR Creator, Backlog Groomer
R-05 Code Review and Quality Assessment Double PR Review Pool, PR Reviewer
R-52 Dual-Account Review Authentication Single PR Reviewer
R-53 Anti-Pattern and Code Smell Detection Triple PR Reviewer, Architecture Guard, Bug Hunt Pool
R-97 Review Feedback Type-Based Routing Single Implementation Worker
R-112 PR Concurrent Work Conflict Matrix Single (shared protocol) All PR-modifying agents

A.5 — PR Fixing and CI Remediation

ID Responsibility Redundancy Primary Agent(s)
R-07 PR Fixing and CI Remediation Single Implementation Pool (PR-first priority with progressive escalation)
R-27 CI Log Retrieval and Diagnosis Single (shared tool) CI Log Fetcher, System Watchdog
R-94 Deep Context Gathering Before PR Fixes Single Implementation Worker
R-95 Fix Attempt Loop Prevention and Stuck Detection Single Implementation Worker
R-96 PR Lifecycle Monitoring Loop Single Implementation Worker

A.6 — Merging and Post-Merge

ID Responsibility Redundancy Primary Agent(s)
R-54 Three-Tier Approval Detection Single (shared protocol) PR Merge Pool, Implementation Worker
R-99 PR Merge Seven Criteria Checklist Single PR Merge Pool
R-100 Blocking Review Temporal Detection Single PR Merge Pool, Implementation Worker
R-08 PR Merging and Post-Merge Verification Double PR Merge Pool, Implementation Worker
R-55 Post-Merge State Verification Triple PR Merge Pool, Implementation Worker, System Watchdog
R-28 Issue Closure and Post-Merge Cleanup Triple Implementation Worker, Backlog Groomer, PR Merge Pool
R-102 Merged PR Issue Closure with Dependency Cleanup Triple Backlog Groomer, Implementation Worker, PR Merge Pool

A.7 — Git Operations

ID Responsibility Redundancy Primary Agent(s)
R-29 Commit Formatting and Git Operations Single (delegation) Git Committer, Commit Message Formatter
R-30 Branch Management and Rebase Double Branch Setup, PR Merge Pool
R-59 PR Description Preservation Double PR Editor, Spec Evolution
R-77 Push Conflict Recovery Protocol Single (shared) All pushing agents

A.8 — Lifecycle Events

ID Responsibility Redundancy Primary Agent(s)
R-65 Specification PR Monitoring and Lifecycle Double Product Builder, Spec Evolution
R-66 Finding Validation Gate Before Issue Filing Triple Bug Hunt, Test Infra, UAT
R-67 Product Completion Verification Single Product Verifier
R-93 Subtask Wave Dispatch and Parallel Conflict Resolution Single Implementation Worker
R-94 Deep Context Gathering Before PR Fixes Single Implementation Worker
R-95 Fix Attempt Loop Prevention and Stuck Detection Single Implementation Worker
R-96 PR Lifecycle Monitoring Loop Single Implementation Worker
R-97 Review Feedback Type-Based Routing Single Implementation Worker
R-98 Issue Dispatch Priority Ordering Rules Single Implementation Pool
R-112 PR Concurrent Work Conflict Matrix Single (shared protocol) All PR-modifying agents
R-91 Amend-Only Commit Protocol for CI Fixes Single PR CI Test Fixer

Category B — Quality Assurance and Bug Detection

Ensuring code quality through CI health monitoring, testing standards, correctness verification, and proactive bug detection. The deepest redundancy in the system (quadruple depth) exists here because quality failures cascade into every other category.

B.1 — CI and Build Health

ID Responsibility Redundancy Primary Agent(s)
R-32 Master CI Health Emergency Response Double System Watchdog, Quality Enforcer
R-12 Merge Safety and Branch Protection Triple PR Merge Pool, System Watchdog, Quality Enforcer
R-71 Never-Disable-Checks Safety Constraint Triple Test Infra Pool, PR Reviewer, System Watchdog

B.2 — Testing Quality and Stability

ID Responsibility Redundancy Primary Agent(s)
R-33 Flaky Test Detection and Prevention Double PR Reviewer, System Watchdog
R-34 Test Stability Enforcement Triple Implementation Worker, PR Reviewer, Subtask Loop
R-101 Flaky Test 16-Pattern Detection Checklist Single PR Reviewer
R-70 TDD Workflow Awareness in Bug Reports Double Bug Hunt Pool, Implementation Worker

B.3 — Code Quality and Correctness

ID Responsibility Redundancy Primary Agent(s)
R-62 Implementation Correctness Verification Double Implementation Reviewer, Milestone Reviewer
R-120 Milestone Reviewer Holistic Integration Review Single (post-milestone) Milestone Reviewer
R-53 Anti-Pattern and Code Smell Detection Triple PR Reviewer, Architecture Guard, Bug Hunt Pool
R-14 Codebase Coherence and Technical Debt Triple Architecture Guard, Bug Hunt Pool, PR Reviewer

B.4 — Proactive Bug Detection

ID Responsibility Redundancy Primary Agent(s)
R-16 Bug Detection and Proactive Quality Assurance Quadruple Bug Hunt Pool, UAT Test Pool, PR Reviewer, Architecture Guard
R-66 Finding Validation Gate Before Issue Filing Triple Bug Hunt, Test Infra, UAT
R-86 Open PR Awareness Before Bug Filing Double UAT Test Pool, Bug Hunt Pool

Category C — Ticket Hygiene and Metadata Management

Maintaining the integrity of Forgejo's issue and PR metadata — labels, state transitions, dependency links, milestones, body format, and backlog cleanliness. The Backlog Groomer (24 responsibilities) and System Watchdog (24 responsibilities) provide overlapping coverage here, creating the system's strongest redundancy zone.

C.1 — Labels and Metadata

ID Responsibility Redundancy Primary Agent(s)
R-09 Label and Metadata Correctness Quadruple Forgejo Label Manager, Backlog Groomer
R-58 Label-Name-to-ID Resolution and Conflict Prevention Single (centralized) Forgejo Label Manager
R-35 PR-Issue Label Synchronization Double Backlog Groomer, PR Creator
R-36 Story Point Estimation Double Backlog Groomer, Human Liaison
R-127 Label Creation Prohibition Enforcement Triple Permission blocks, Bash URL blocking, Label Manager delegation

C.2 — Issue State and Lifecycle

ID Responsibility Redundancy Primary Agent(s)
R-10 Issue State Lifecycle Management Quadruple Issue State Updater, Backlog Groomer
R-60 State Transition Precondition Enforcement Double Issue State Updater, Backlog Groomer
R-128 Valid State Transition Matrix Enforcement Single (enforced by updater) Issue State Updater

C.3 — Dependencies and Hierarchy

ID Responsibility Redundancy Primary Agent(s)
R-11 Dependency and Hierarchy Integrity Triple Epic Planner, Backlog Groomer, System Watchdog
R-103 Wrong-Direction Dependency Auto-Fix Double Backlog Groomer, Epic Planner
R-104 Priority Consistency Cross-Check Double Backlog Groomer, System Watchdog

C.4 — Milestones and Scope

ID Responsibility Redundancy Primary Agent(s)
R-37 Milestone Assignment and Scope Guard Triple New Issue Creator, Epic Planner, UAT Test Pool
R-129 Priority Ordering Rules for Milestone Work Double Implementation Pool, System Watchdog

C.5 — Issue and PR Body Format

ID Responsibility Redundancy Primary Agent(s)
R-38 Issue Body and Definition of Done Compliance Double Backlog Groomer, New Issue Creator
R-130 Standard Issue Body Format Enforcement Double New Issue Creator, Backlog Groomer
R-131 Standard PR Body Format Enforcement Double PR Creator, PR Description Writer
R-115 Issue Analyzer Structured Data Extraction Single (subagent) Issue Analyzer
R-116 Subtask Checker Fuzzy Match Checkbox Toggle Single (subagent) Subtask Checker
R-117 Issue Note Writer Logical Reference Protocol Single (subagent) Issue Note Writer
R-118 PR Status Analyzer 5-Dimension Framework Single (subagent) PR Status Analyzer

C.6 — Backlog Hygiene

ID Responsibility Redundancy Primary Agent(s)
R-15 Backlog Hygiene and Duplicate Detection Double Backlog Groomer, Test Infrastructure Pool
R-72 Stale PR Detection and Remediation Double Backlog Groomer, System Watchdog
R-39 Blocked Chain Analysis and Resolution Double Backlog Groomer, System Watchdog

Category D — Architecture and Specification Governance

Keeping the specification current with implementation discoveries and preventing architectural drift. The spec flows in both directions: Architecture Supervisor writes spec forward (design → code), Spec Evolution corrects it backward (code → design), and Architecture Guard detects divergence.

D.1 — Specification Lifecycle

ID Responsibility Redundancy Primary Agent(s)
R-13 Specification and Architecture Governance Double Architecture Supervisor, Spec Evolution
R-40 Specification-First Development Enforcement Double Epic Planner, Architecture Supervisor
R-73 Spec Change Classification and Two-Step Proposal Double Architecture Supervisor, Spec Evolution
R-92 Proactive Specification Scan Protocol Single Spec Evolution

D.2 — Codebase Scanning

ID Responsibility Redundancy Primary Agent(s)
R-74 SHA-Based Idle Detection for Scanners Single Architecture Guard, Spec Evolution
R-132 Subagent Specialization Principle Universal All agents

Category E — Operational Health and Coordination

The system's "plumbing" — keeping supervisors alive, workers dispatched, sessions healthy, tracking issues coordinated, errors retried, clones isolated, credentials validated, and logs structured. These responsibilities are invisible when working but catastrophic when broken.

E.1 — Supervisor and Worker Management

ID Responsibility Redundancy Primary Agent(s)
R-01 Supervisor Liveness and Health Monitoring Triple Product Builder, System Watchdog
R-50 Worker Session Adoption and Lifecycle Single per pool Pool Supervisors
R-41 Worker Dispatch and Sliding Window Management Single per pool Pool Supervisors
R-81 Tiered Worker Allocation Formula Single Product Builder
R-76 Async Session Health Detection Double Async Agent Monitor, Product Builder
R-75 Session Naming and Tag Convention Single (centralized) Async Agent Manager
R-122 prompt_async Mandatory for Supervisor Launch Single (architectural) Product Builder
R-123 All 18 Supervisors Mandatory Verification Single Product Builder
R-126 No Duplicate Supervisor Instances Double Product Builder, System Watchdog

E.2 — Automation Tracking and Coordination

ID Responsibility Redundancy Primary Agent(s)
R-20 Automation Tracking and Inter-Agent Coordination Triple Automation Tracking Manager, Backlog Groomer, System Watchdog
R-42 Tracking Issue Cleanup and Deduplication Triple Automation Tracking Manager, Backlog Groomer, Each Supervisor
R-43 Announcement Lifecycle Management Double Each Supervisor, Backlog Groomer
R-133 Announcement Consumption Priority Protocol Universal All supervisors (per consumption table)
R-45 Estimated Cycle Interval Maintenance Double Automation Tracking Manager, System Watchdog

E.3 — Crash Recovery and State Persistence

ID Responsibility Redundancy Primary Agent(s)
R-21 Crash Recovery and State Persistence Multi-level Every agent (per level)
R-84 Checkpoint and State Persistence via Forgejo Comments Single (per worker) Implementation Worker
R-44 Context Window Self-Management Single (per agent) Long-running agents
R-124 Convergence Check Algorithm Single Product Builder
R-80 Non-Return Guarantee Enforcement Single Product Builder
R-125 Product Builder Never Edits or Merges Directly Single (prohibition) Product Builder

E.4 — Universal Agent Protocols

ID Responsibility Redundancy Primary Agent(s)
R-51 Forgejo API Pagination and Truncation Recovery Universal All Forgejo-querying agents
R-57 Clone Isolation and Safety Single (protocol) Repo Isolator, All cloning agents
R-56b Transient Error Classification and Retry Single (shared module) All agents via Error Handling module
R-113 Guaranteed Resource Cleanup via CleanupManager Universal All resource-acquiring agents
R-114 Startup Credential Validation Gate Universal All agents at startup
R-63 Bot Signature Standardization Single (centralized) Forgejo Signature Appender
R-78 Structured Logging Protocol Single (shared module) All agents
R-79 Performance Monitoring and Health Scoring Single (shared module) All agents
R-61 Reference Material Caching and Distribution Single (optimization) Ref Material Loader
R-134 Internet Access Restriction Universal All autonomous agents (denied)

E.5 — Content Formatting Standards

ID Responsibility Redundancy Primary Agent(s)
R-83 Issue Comment Type Formatting Standards Single (centralized) Issue Comment Formatter
R-82 Timeline Surgical Edit and Append-Only Protocol Single Timeline Supervisor
R-77 Push Conflict Recovery Protocol Single (shared) All pushing agents

Category F — Human Interaction and Escalation

The bridge between autonomous agents and human developers. Covers issue triage, MoSCoW prioritization, developer assignment, comment response, feedback incorporation, timeout management, and escalation. The Human Liaison (14 responsibilities) is the fastest-polling agent (2-minute cycle) to minimize human wait time.

F.1 — Issue Triage and Prioritization

ID Responsibility Redundancy Primary Agent(s)
R-02 Issue Triage, Verification, and Priority Management Triple Project Owner, Human Liaison
R-107 MoSCoW Decision Framework Single (exclusive) Project Owner
R-108 Strategic Priority Re-evaluation Single Project Owner
R-48 Developer Expertise Discovery and Assignment Double Project Owner, Human Liaison
R-109 Developer Assignment Decision Gate Single Project Owner

F.2 — Human Communication and Monitoring

ID Responsibility Redundancy Primary Agent(s)
R-18 Human Communication and Escalation Double Human Liaison, System Watchdog
R-105 Human Liaison 10-Step Monitoring Loop Single Human Liaison
R-106 Closed Issue Comment Response Patterns Single Human Liaison
R-46 Feedback Incorporation Protocol Single Human Liaison
R-47 Human Response Timeout Management Double Human Liaison, Project Owner
R-48 Developer Expertise Discovery and Assignment Double Project Owner, Human Liaison

Category G — Strategic Governance and Self-Improvement

Long-term system health — scope creep prevention, agent self-improvement, documentation maintenance, and security enforcement. These responsibilities operate on longer timescales (every 10+ cycles) than the development lifecycle categories.

G.1 — Scope and Milestone Governance

ID Responsibility Redundancy Primary Agent(s)
R-19 Scope Management and Milestone Control Triple Backlog Groomer, Epic Planner, New Issue Creator
R-87 Five-State Project Classification Single Product Builder
R-88 UAT Feature Area Retest on Code Changes Single UAT Test Pool
R-67 Product Completion Verification Single Product Verifier

G.2 — Self-Improvement and Evolution

ID Responsibility Redundancy Primary Agent(s)
R-22 Self-Improvement and Agent Evolution Double Agent Evolution, System Watchdog
R-85 Agent Improvement Pattern Detection Double Agent Evolution, System Watchdog
R-90 Watchdog Alert Response and Dispatch Single System Watchdog

G.3 — Documentation and Reporting

ID Responsibility Redundancy Primary Agent(s)
R-17 Documentation and Timeline Maintenance Single (exclusive domains) Documentation Supervisor, Timeline Supervisor
R-89 Documentation Generation by Type Single Documentation Supervisor

G.4 — Security

ID Responsibility Redundancy Primary Agent(s)
R-23 Security and Credential Management Double Shared Credential Security module, System Watchdog
R-134 Internet Access Restriction Universal All autonomous agents (denied)

Category H — Project Standards and CONTRIBUTING.md Compliance

The non-negotiable project conventions that every code-writing, test-writing, and PR-creating agent must follow. These are enforced at implementation time (workers), review time (PR Reviewer), and audit time (System Watchdog), creating triple redundancy on every standard.

H.1 — Code Standards

ID Responsibility Redundancy Primary Agent(s)
R-64 Nox Routing Enforcement Universal All code-executing agents
R-135 File Organization Enforcement Triple Implementation Worker, PR Reviewer, Backlog Groomer
R-136 Static Typing and type: ignore Prohibition Triple Typecheck Fixer, PR Reviewer, System Watchdog
R-137 Maximum File Size Enforcement (500 Lines) Double Implementation Worker, PR Reviewer

H.2 — Testing Standards

ID Responsibility Redundancy Primary Agent(s)
R-138 Testing Framework Selection Rules Triple Behave Tester, Robot Tester, PR Reviewer
R-139 Coverage Threshold Enforcement (97%) Triple Coverage Improver, PR Merge Pool, System Watchdog

H.3 — Commit and PR Standards

ID Responsibility Redundancy Primary Agent(s)
R-140 Conventional Changelog Commit Format Double Commit Message Formatter, PR Reviewer
R-131 Standard PR Body Format Enforcement Double PR Creator, PR Reviewer

H.4 — Startup and Lifecycle Protocols

ID Responsibility Redundancy Primary Agent(s)
R-141 Supervisor Mandatory Startup Sequence Universal All 18 supervisors
R-142 Startup State Recovery Before Tracking Creation Universal All 18 supervisors
R-143 Dual Status Issue Cleanup (Defense-in-Depth) Double Each supervisor, Backlog Groomer
R-144 Tier Selector Pure Pass-Through Constraint Single (architectural) Four tier selectors

Category A — Development Lifecycle

22.1 R-01: Supervisor Liveness and Health Monitoring

Goal: Ensure all 18 supervisors remain alive and productive at all times. A dead or zombied supervisor creates a gap in system functionality that can cascade into stalled work.

Redundancy Depth: Triple

Layer Agent Role Detection Method Response
1 (Primary) Product Builder 60-second monitoring loop queries session status via Async Agent Manager; immediately re-launches any dead supervisor (Section 4.3) Session no longer appears in OpenCode Server API response Re-launch with same parameters within 60 seconds
2 (Deep Inspection) Product Builder Every 5 heartbeats (~5 minutes), reads last 100 messages from each pool supervisor to verify active worker dispatching (Section 7.6) No worker activity patterns in last 15 minutes Announces zombie warning, may force-restart
3 (Behavioral Analysis) System Watchdog Audit 6 reads last 5 messages from each supervisor session and analyzes tool call patterns to detect zombies, error loops, and identical-call loops (Section 9.11.2) Sleep-only pattern (3+ consecutive sleep calls with no productive actions), error-loop pattern (3+ consecutive errors), identical-call loop (same tool+args 3+ times) Creates diagnostic issue, may dispatch restart
3b (Staleness) System Watchdog Audit 11 monitors tracking issue age against the agent's self-reported estimated cycle interval; triggers recovery when overdue by >2× (Section 9.11.2) Tracking issue age exceeds 2× estimated cycle interval Session termination, root cause analysis, diagnostic issue creation

Why triple redundancy? Layer 1 catches hard crashes (session disappears). Layer 2 catches soft failures (session alive but supervisor not dispatching workers — "zombie" state caused by context exhaustion). Layer 3 catches behavioral failures (session alive, supervisor appears active, but stuck in a non-productive loop). Each layer catches a distinct failure mode invisible to the other layers.


22.2 R-02: Issue Triage, Verification, and Priority Management

Goal: Every new issue must be triaged (verified or rejected), assigned appropriate priority and MoSCoW labels, and placed in the correct milestone. No issue should remain in State/Unverified indefinitely.

Redundancy Depth: Triple

Layer Agent Role Scope Notes
1 (Strategic Triage) Project Owner Primary triager. Polls every 5 minutes for State/Unverified issues. Assigns MoSCoW labels (exclusive authority — no other agent may assign MoSCoW). Sets priority labels. Transitions to State/Verified or State/Wont Do. Assigns developers. (Section 9.10) All unverified issues (skips needs feedback, skips issues being triaged by Human Liaison) MoSCoW decision framework: Must Have = spec requirements + blockers + security; Should Have = usability + non-blocking; Could Have = polish + advanced
2 (Human-Created Issues) Human Liaison Triages human-created issues with full triage authority. Polls every 2 minutes. Verifies, sets priority, plans implementation. Responds to human comments and PR reviews. (Section 9.3) Human-originated activity only (new issues, comments, reviews, label changes) Has the fastest polling interval (2 min) to minimize human wait time
3 (Gap Filler) Backlog Groomer Pass 4 auto-fixes missing labels: adds State/Unverified if no state label, adds Priority/Backlog if no priority, infers Type/* from title/body. (Section 9.7) All open issues with missing required labels Safety net — catches issues that slip through triage
3b (Audit) System Watchdog Audit 4 verifies priority/milestone ordering is correct; flags issues worked on out of order. (Section 9.11.2) All in-progress issues across milestones Catches systemic priority violations

Redundancy pattern: The Project Owner performs strategic triage; the Human Liaison provides fast-response triage for human activity; the Backlog Groomer fills any gaps with safe defaults; the Watchdog audits the result.


22.3 R-03: Work Planning and Decomposition

Goal: Transform high-level milestones and product vision into a structured hierarchy of Legendary → Epic → Issue with correct dependency chains, subtasks, and definitions of done.

Redundancy Depth: Double

Layer Agent Role Trigger Notes
1 (Specification) Architecture Supervisor Writes and extends docs/specification.md. Defines module boundaries, interfaces, data models, and patterns. Major changes go through PRs with needs feedback label. (Section 9.1) New milestones without spec coverage, spec ambiguities, human requests "Most consequential agent — bad architecture cascades everywhere"
2 (Decomposition) Epic Planner Decomposes architecture into Forgejo Epics and Issues with proper dependency chains (child BLOCKS parent). Four phases: hierarchy enforcement, closure evaluation, specification compliance, traditional planning. (Section 9.2) Milestones without issues, epics without children, human requests Enforces Legendary→Epic→Issue hierarchy
3 (Gap Detection) Backlog Groomer Passes 12-13 detect incomplete epics and legendaries; creates missing child issues when gaps are identified. (Section 9.7) Epics with zero or incomplete children, legendaries with missing child epics Redundant check on Epic Planner's completeness
4 (Human Requests) Human Liaison Step 7 (every 10th cycle): Epic/Legendary gap analysis. Also decomposes human-created issues into implementation plans. (Section 9.3) Human-created issues needing decomposition, periodic gap analysis Handles the human-originated subset of planning

Redundancy pattern: Architecture provides the what (specification), Epic Planner provides the how (decomposition), Backlog Groomer catches what the Planner missed (gap detection), Human Liaison handles human-originated planning requests.


22.24 R-24: Work Item Claiming and Coordination

Goal: Prevent two workers from implementing the same issue simultaneously. Ensure claimed issues have active heartbeats and stale claims are detected.

Redundancy Depth: Double

Layer Agent Role Specific Actions
1 (Claiming) Implementation Worker Posts [CLAIM: agent=<name>, session=<id>, timestamp=<ISO>] comment before starting work. Sends [HEARTBEAT:] comments every 10 minutes. Posts [RELEASE: reason=completed|failed|timeout] on exit, guaranteed via try/finally. Checks existing claims before claiming — aborts if issue already claimed within 30 minutes. (Section 6.12) Claim posting, heartbeat maintenance, release guarantee, stale claim detection
2 (Stale Detection) Backlog Groomer Pass 3: detects State/In Progress issues with no comments for >48 hours, implying stale or abandoned claims. Posts staleness comment. (Section 9.7) Stale claim detection via activity monitoring

Sub-responsibilities: Generating unique claim IDs (MD5 hash), parsing existing claims for freshness, wrapping all work in try/finally for release guarantee, conflict matrix evaluation (code changes conflict with other code changes, merges conflict with everything, reviews conflict with nothing).


22.49 R-49: PR Ownership Detection and Work Scoring

Goal: Correctly classify every open PR as bot-owned (needs automated shepherding) or human-created (leave for human workflows), then score bot PRs by work urgency to prioritize the dispatch queue.

Redundancy Depth: Single

Layer Agent Role Specific Actions
1 (Detection) Implementation Pool Ownership check: pr.user.login == FORGEJO_USERNAME. FORBIDDEN checks: PR body content, PR labels, branch name patterns. Historical bug: 26+ PRs were misclassified as "external" because ownership was checked via body content. (Section 6.21) Login identity comparison only
2 (Scoring) Implementation Pool Work scoring algorithm: ready-to-merge=95, review-feedback (REQUEST_CHANGES)=90, review-feedback (COMMENT)=85, ci-fix=85, merge-conflicts=80, awaiting-review=60, orphan PRs=100. Age bonus: min(age_days * 2, 10). (Section 8.1.2) Numerical priority scoring per PR

Sub-responsibilities: Extracting linked issue numbers from PR body (Closes #N, Fixes #N, closes #N, fixes #N, Close #N, Fix #N), fetching review state per PR, CI-Blocker priority override (score=infinity, bypasses PR-first gate).


22.4 R-04: Issue Implementation

Goal: Transform verified issues into merged code on master through an automated pipeline of implementation, testing, quality gates, PR creation, review, and merge.

Redundancy Depth: Single chain (with crash recovery at every level)

Stage Agent Role Notes
Dispatch Implementation Pool Finds verified issues, dispatches workers via Async Agent Manager, manages sliding window of N workers. Enforces PR-first priority gate. (Section 8.1) Only agent that dispatches implementation workers
Execution Implementation Worker Dual-mode worker. In issue-impl mode: claims issue, creates clone, implements subtasks, creates PR, shepherds to merge. In pr-fix mode: fixes CI, handles review feedback, resolves conflicts. (Section 10.1) One instance per branch/PR; owns work to merge
Subtask Orchestration Subtask Loop Manages progressive escalation for each subtask. Evaluates difficulty, selects starting tier, loops through implement→test→quality gates→review until passing. (Section 11.3) Escalates haiku→codex→sonnet→opus on failure
Code Writing Implementer Writes code for subtasks. Never writes tests. Verifies domain model fields exist before referencing them. (Section 11.4, 21.4) Inherits model from tier selector
Unit Testing Behave Tester Writes BDD/Gherkin unit tests in features/. (Section 11.4) Inherits model from tier selector
Integration Testing Robot Tester Writes Robot Framework integration tests in robot/. No mocking. (Section 11.4) Inherits model from tier selector
Performance Testing ASV Benchmarker Writes Airspeed Velocity benchmarks in benchmarks/. (Section 11.4) Launched in parallel with unit/integration testers

Why only single depth? Implementation is inherently sequential — you cannot have two agents implementing the same issue simultaneously. Redundancy comes instead from crash recovery: the Implementation Worker checks for existing PRs/branches (Section 10.1.6), the Subtask Loop preserves escalation state in HTML comments (Section 16), and the Pool Supervisor re-dispatches workers for failed slots.

Sub-responsibilities: Subtask dependency analysis and wave grouping, parallel wave dispatch, post-wave conflict detection (git status --porcelain), auto-resolution of merge conflicts between parallel subtasks, sequential re-run of conflicting subtasks, out-of-scope work detection and new issue creation, subtask checkbox updates via Subtask Checker, implementation notes via Issue Note Writer.


22.25 R-25: Test Writing and TDD Lifecycle

Goal: Every implementation change has corresponding unit tests (Behave/BDD), integration tests (Robot Framework), and optionally performance benchmarks (ASV). Bug fixes follow the TDD lifecycle with @tdd_expected_fail tags.

Redundancy Depth: Double

Layer Agent Role Specific Actions
1 (Test Creation) Behave Tester Writes BDD/Gherkin unit tests in features/. Tags bug-fix tests with @tdd_issue, @tdd_issue_<N>, @tdd_expected_fail. (Section 11.4) Creates .feature files with Given/When/Then scenarios
1b (Integration) Robot Tester Writes Robot Framework integration tests in robot/. No mocking allowed. Tags with tdd_issue_<N> for bug fixes. (Section 11.4) Creates .robot files with keyword-driven tests
1c (Performance) ASV Benchmarker Writes Airspeed Velocity benchmarks in benchmarks/ for performance-sensitive code. (Section 11.4) Creates benchmark classes with time_* and mem_* methods
2 (TDD Tag Cleanup) Implementation Worker After bug fix: searches features/ and robot/ for @tdd_issue_N tests, removes @tdd_expected_fail tags (indicating bug is fixed), keeps permanent @tdd_issue and @tdd_issue_N tags. (Section 6.13) Tag removal from passing TDD tests
2b (TDD Verification) PR Reviewer For bug-fix PRs: verifies all @tdd_issue_N tests had @tdd_expected_fail removed. (Section 12.1.2) Verifies TDD tag correctness in reviews
3 (Parallel Launch) Subtask Loop Launches Behave, Robot, and ASV testers simultaneously via async-agent-manager. Monitors with 10-second polling (10-minute timeout). Restarts failed writers. (Section 21.5) Parallel test writer orchestration

Sub-responsibilities: Test determinism enforcement (no time.sleep(), no unseeded randomness, no shared filesystem, no network dependencies), test isolation, proper mock placement in features/mocks/, Coverage Improver writes additional tests when coverage drops below 97%.


22.56 R-56: Meaningful Change Verification

Goal: Prevent empty or trivial implementation attempts from consuming expensive quality gate runs. Reject attempts with fewer than 3 functional lines of code.

Redundancy Depth: Single

Layer Agent Role Specific Actions
1 Subtask Loop After implementer returns: runs git diff --stat and git diff. Counts functional lines (excluding comments, whitespace, empty lines, import-only additions). If <3 functional lines: resets working directory with git checkout -- ., increments attempt counter, triggers tier escalation. (Section 21.5) Diff analysis, functional line counting, attempt rejection

Why this matters: Without this check, a model that produces only comments or import statements would pass to quality gates, which would pass (no code to fail), and the subtask would be "completed" with no actual implementation.


22.26 R-26: PR Creation and Metadata Inheritance

Goal: Every PR is created with correct metadata: closing keywords, inherited labels from the linked issue, milestone, dependency links (PR BLOCKS issue), and proper state transitions.

Redundancy Depth: Double

Layer Agent Role Specific Actions
1 (Creation) PR Creator Creates PR via Forgejo API. Inherits ALL labels from issue (Type/, Priority/, MoSCoW/, Points/). Adds State/In Review. Creates dependency link (PR BLOCKS issue). Transitions issue to State/In Review via Issue State Updater. Post-creation compliance verification: re-reads PR and issue to verify all metadata correct. (Section 12.1) PR creation, label inheritance, dependency linking, state transition, compliance verification
2 (Sync Verification) Backlog Groomer Pass 19: detects PRs missing labels that exist on the linked issue. Auto-fixes by copying Priority/, MoSCoW/, Points/ labels. Updates milestone to match. (Section 9.7) Post-creation label synchronization

Sub-responsibilities: PR description generation via PR Description Writer (Summary, Changes, Design Decisions, Testing, Modules Affected, Related Issues, Checklist), Forgejo Label Manager delegation for label application, PR body preservation on subsequent updates (Forgejo API deletes body if not re-sent).


22.5 R-05: Code Review and Quality Assessment

Goal: Every PR receives at least one independent code review before merge, assessing code quality, specification alignment, security, and correctness.

Redundancy Depth: Double

Layer Agent Role Focus Notes
1 (Code Quality) PR Review PoolPR Reviewer Dispatches N/2 parallel reviewers. Each reviewer reads diff, checks CI, loads spec context, reviews against rotating focus areas (10 categories). Posts formal APPROVED/REQUEST_CHANGES review via dual-account protocol. (Sections 8.2, 12.1.2) Architecture alignment, error handling, test quality, security, performance, code patterns, specification compliance, and more Uses FORGEJO_REVIEWER_PAT for formal reviews (different account from PR author)
2 (Functional Correctness) Implementation Reviewer Post-quality-gate review invoked by the Subtask Loop AFTER lint, typecheck, unit tests, integration tests, and coverage all pass. Verifies the code actually fulfills the subtask requirements. (Section 15.5) Does the code do what the subtask requires? (Not style — that is the linter's job) Returns APPROVE or REJECT with specific file/function references
3 (Flaky Test Detection) PR Reviewer Specifically watches for non-deterministic test patterns: time.sleep(), random.choice() without seed, shared filesystem paths, timing-sensitive assertions. Performs CI pattern analysis across multiple PRs. (Section 12.1.2) Tests that pass locally but fail in CI, or fail intermittently Catches a class of issues that quality gates miss

Redundancy pattern: Layer 1 reviews the PR as a whole (quality, patterns, architecture); Layer 2 reviews each subtask individually (functional correctness); Layer 3 adds specialized detection for a specific class of hard-to-catch issues (flaky tests).


22.52 R-52: Dual-Account Review Authentication

Goal: PR reviews must be posted as a different Forgejo user than the PR author to enable formal APPROVED state. The MCP tools cannot override their server-level authentication token, so the reviewer must use curl for all write operations.

Redundancy Depth: Single (architectural constraint)

Layer Agent Role Specific Actions
1 (READ ops) PR Reviewer Uses Forgejo MCP tools (forgejo_get_pull_request_by_index, forgejo_list_pull_reviews, etc.) authenticated as primary bot — fine for reads. (Section 6.17.0) MCP tools for all reads
2 (WRITE ops) PR Reviewer Uses curl with FORGEJO_REVIEWER_PAT header for: (1) formal review via POST to pulls/reviews API, (2) backup issue comment via POST to issues/comments API. MCP write tools (forgejo_create_pull_review, forgejo_create_issue_comment) are explicitly DENIED. (Section 6.17.2) curl-based writes as reviewer account

Sub-responsibilities: Credential passing from PR Review Pool (all 3 reviewer credentials: PAT, username, password), backup comment posting after every formal review, ci-log-fetcher invocation with reviewer credential overrides.


22.53 R-53: Anti-Pattern and Code Smell Detection

Goal: Detect recurring anti-patterns that indicate systemic problems rather than individual code issues: repetitive fix attempts, type system workarounds, test quality issues, and architectural drift.

Redundancy Depth: Triple

Layer Agent Role Specific Patterns Detected
1 (Per-PR) PR Reviewer Watches for: repetitive fix attempts (same fix tried multiple times indicating misunderstanding), type system workarounds (excessive cast(), Any, complex generics), test quality issues (testing implementation details, mocked-to-pass, brittle assertions), architectural drift (new patterns without spec update, boundary violations "just this once"). (Section 12.1.2) Implementation-level anti-patterns
2 (Codebase-wide) Architecture Guard Seven checks including: inconsistent patterns (different error handling styles across modules), module coupling violations (cross-module imports violating boundaries), technical debt indicators (>50 line functions, >4 nesting levels, TODO/FIXME). (Section 9.5) Structural anti-patterns
3 (Per-module) Bug Hunt Pool Pass 8 (code consistency): identifies inconsistent patterns within and across modules. Pass 6 (type safety): detects type system abuse. (Section 8.6.2) Module-level anti-patterns

22.6 R-06: Quality Gate Enforcement

Goal: No code reaches master without passing ALL quality checks: lint, typecheck, unit tests, integration tests, and ≥97% coverage. Quality gates must be enforced at PR creation time, CI pipeline time, and post-merge audit time.

Redundancy Depth: Triple

Layer Agent Role When Notes
1 (Pre-PR) Subtask LoopLint Fixer, Typecheck Fixer, Unit Test Runner, Integration Test Runner, Coverage Improver Runs all five quality gates BEFORE creating a PR. Each gate has its own independent tier that starts at Haiku and escalates independently. 5 inner passes per tier before escalation. (Section 11.3) Before PR creation Catches issues before they enter the CI pipeline
2 (Post-PR CI) PR CI Test Fixer The ONLY agent that amends commits and force-pushes. Fixes CI failures after PR creation by running quality gates in the clone, amending the commit, and force-pushing. Loops until all checks pass. (Section 12.1) After PR creation, when CI fails Handles issues that the pre-PR gates missed (environment differences, test isolation)
3 (Post-Merge Audit) System Watchdog Audit 0: monitors master CI health (EMERGENCY priority). Audit 1: verifies recent master commits have passing CI. Audit 2: verifies branch protection is active. (Section 9.11.2) Continuously, every 5 minutes Catches cases where code reached master despite quality gates
3b (Enforcement Repair) Quality Enforcer Dispatched by Watchdog when quality gate violations are detected. Repairs branch protection rules. Creates Priority/CI-Blocker issues for code merged without CI. (Section 15.1) On Watchdog dispatch Nuclear option — creates blocking issues when gates are bypassed

Redundancy pattern: Layer 1 prevents bad code from entering a PR. Layer 2 fixes issues that CI catches after PR creation. Layer 3 audits that the entire pipeline is working and repairs it when it is not. Each layer operates at a different point in the code's journey to master.


22.7 R-07: PR Fixing and CI Remediation

Goal: Ensure every PR with failing CI or review feedback gets an active worker to fix it. No PR should remain in a failing state indefinitely.

Redundancy Depth: Double

Layer Agent Role Strategy Notes
1 (PR-First Gate) Implementation Pool Enforces absolute PR-first priority: NO new issues dispatched until every bot-created PR has an active worker. Analyzes all open PRs, scores them by work type, and dispatches workers in pr-fix mode. (Section 8.1.2) Worker re-assignment: existing workers shift to PR fixing Guarantees every PR gets attention before new work starts
2 (Progressive Escalation) Implementation Pool Four-tier model escalation (haiku → codex → sonnet → opus) with same-problem detection. Workers use ci-log-fetcher for failure analysis. Human escalation via needs feedback label after exhausting all tiers. (Section 8.1) Cost-optimized fixing with guaranteed human fallback Escalation state tracked via PR/issue comments
3 (Struggling Detection) System Watchdog Audit 5b detects PRs with 3+ failed fix attempts; requests human assistance after threshold. Audit 5 tracks PR aging and review coverage. (Section 9.11.2) Escalation to humans when automation is stuck Safety net for cases where automated fixing loops

Redundancy pattern: The Implementation Pool guarantees every PR gets a worker (throughput). The PR Fix Pool adds intelligence (root cause analysis). The Watchdog adds escalation (human assistance when both automated approaches fail).


22.8 R-08: PR Merging and Post-Merge Verification

Goal: Approved PRs with passing CI are merged promptly, and every merge is verified to have actually succeeded (guarding against Forgejo's silent merge failures).

Redundancy Depth: Double

Layer Agent Role Mechanism Notes
1 (Dedicated Merger) PR Merge Pool Singleton that continuously polls for merge-ready PRs every 5 minutes. Verifies all 7 merge criteria (Section 8.3.2). Handles pre-merge rebase. Uses safe_merge_pr() with mandatory post-merge verification. (Section 8.3) Polls PRs → verifies criteria → rebases if needed → merges → verifies Primary merge path for all PRs
2 (Worker Merge) Implementation Worker In ready-to-merge work type: verifies approvals via 3-tier detection, rebases if needed, delegates to safe_merge_pr(). (Section 10.1.4) Triggered by Implementation Pool when PR is scored as "ready to merge" Backup merge path — catches PRs faster than the 5-minute poll cycle
3 (Merge Verification) Shared Merge Safety module safe_merge_pr() function mandates: (1) call merge API, (2) immediately call forgejo_get_pull_request_by_index, (3) verify merged == true AND state == "closed". Never post success without verification. (Section 6.18, 8.3.4) Post-merge API verification Prevents the false "merged successfully" bug (Forgejo silently fails when branch is behind)
4 (False-Merge Monitoring) System Watchdog Monitors for "merged successfully" comments on PRs that are still open. (Section 13.6) Cross-checks comment text against PR state Catches any case where merge verification itself was bypassed

Redundancy pattern: Two independent agents can merge PRs (Merge Pool and Worker). The merge safety module enforces verification in both paths. The Watchdog provides a final audit layer for false-merge detection.


22.54 R-54: Three-Tier Approval Detection

Goal: Reliably detect PR approval from any source — formal reviews, review body keywords, or issue comments — with proper handling of blocking reviews that may have been superseded by later approvals.

Redundancy Depth: Single (shared protocol, multiple consumers)

Tier Source Mechanism Priority
1 Formal Reviews Reviews with state == "APPROVED" from FORGEJO_REVIEWER_USERNAME Primary path
2 Review Bodies Reviews with state in ("COMMENT", "PENDING") whose body contains approval keywords Fallback
3 Issue Comments Comments containing approval keywords (case-insensitive) Durable backup

Consumers: PR Merge Pool (check_pr_approval()), Implementation Worker (has_required_approvals()), Shared Merge Safety (check_flexible_approval()).

Sub-responsibilities: Approval keyword matching against specific set (lgtm, approved, decision: approved, ready to merge, looks good, ship it, merge it, good to go, plus emoji , 👍). Blocking review recency check: REQUEST_CHANGES only blocks if more recent than latest approval from ANY tier.


22.55 R-55: Post-Merge State Verification

Goal: After every merge API call, verify via a second API call that the merge actually succeeded. The forgejo_merge_pull_request tool returns success even when merges silently fail (e.g., branch behind base). Never post "merged" without verification.

Redundancy Depth: Triple

Layer Agent Role Specific Actions
1 (Inline) PR Merge Pool, Implementation Worker After forgejo_merge_pull_request: immediately call forgejo_get_pull_request_by_index, check merged == true AND state == "closed". On failure: attempt rebase and retry. (Section 8.3.4) Post-merge API verification
2 (Shared) Shared Merge Safety safe_merge_pr() includes mandatory verification step. Rule 6: "Never post 'merged successfully' without verifying merged == true". (Section 13.6) Protocol-level enforcement
3 (Audit) System Watchdog Monitors for "merged successfully" comments on PRs that are still open — the telltale sign of a false merge. (Section 13.6) Cross-check comment text against PR state

22.59 R-59: PR Description Preservation

Goal: When editing a PR (changing labels, milestone, dependencies, or any other field), the full PR description must be re-sent in the API call. The Forgejo API silently deletes the description if the body field is omitted from update calls.

Redundancy Depth: Double

Layer Agent Role Specific Actions
1 (Editor) PR Editor Primary invariant: before ANY edit, fetches current PR data, extracts body, includes it in every update payload. Even for label-only or milestone-only changes. (Section 12.1.1) Fetch-before-edit protocol
2 (Spec Evolution) Spec Evolution Explicitly warned about this bug: "When updating PRs via the Forgejo API, always re-send the full PR body." (Section 9.6) Duplicate enforcement in spec-related PRs

Historical context: This was documented as "The #1 Bug Prevented" in PR management. Multiple PR descriptions were silently deleted before this protocol was established.


22.27 R-27: CI Log Retrieval and Diagnosis

Goal: When CI fails, agents must retrieve detailed logs to diagnose the specific failure. Since the Forgejo Actions API is unavailable, this requires cookie-based web authentication.

Redundancy Depth: Single (shared tool)

Layer Agent Role Specific Actions
1 (Retrieval Tool) CI Log Fetcher Cookie-based web authentication: POSTs to /user/login with _csrf token, stores cookies in /tmp/forgejo_cookies.txt. Navigates to actions page, extracts run ID from HTML, downloads job logs. Maps CI jobs to artifact names (lint→ci-logs-lint, typecheck→ci-logs-typecheck, etc.). Cleans up cookie file after use. (Section 10.1.5) Web login, CSRF extraction, run ID parsing, log download, cookie cleanup
2 (Consumer: Watchdog) System Watchdog Audit 0: uses same cookie-based approach (stores in /tmp/watchdog_cookies.txt) to investigate master CI failures. Parses Behave failure patterns (FAILED...features/*.feature...line N), Robot patterns (FAIL...robot/*.robot), and generic test failure patterns. (Section 9.11.2) Log parsing for specific failing test identification
3 (Consumer: Workers) Implementation Worker, PR CI Test Fixer, PR Reviewer All invoke ci-log-fetcher as subagent to retrieve CI logs for their respective purposes (fixing, reviewing, diagnosing). (Sections 10.1, 12.1) CI log consumption for diagnosis and fixing

Sub-responsibilities: CSRF token extraction from login page HTML, session cookie management, CI job-to-artifact name mapping (8 mappings), log file path resolution, HTML parsing for workflow run IDs.


22.28 R-28: Issue Closure and Post-Merge Cleanup

Goal: After a PR is merged, the linked issue must be closed, state transitioned to State/Completed, stale dependency links removed, and the issue properly finalized.

Redundancy Depth: Triple

Layer Agent Role Specific Actions
1 (Immediate) Implementation Worker After successful merge verification: transitions issue to State/Completed via Issue State Updater, posts final comment with statistics, deletes clone directory. (Section 10.1) State transition, final comment, cleanup
1b (Immediate) PR Merge Pool After verified merge: updates linked issues to State/Completed. (Section 8.3) State transition after merge
2 (Catch-up) Backlog Groomer Pass 14: for PRs merged in last 24 hours, checks if linked issues are still open. Removes satisfied dependency links (merged PRs, closed issues). Closes issues and transitions to State/Completed. Posts diagnostic comment for issues with remaining blockers. Pass 6: detects closeable issues (DoD complete, branch merged). (Section 9.7) Stale dependency removal, issue closure catch-up
3 (Reconciliation) State Reconciler Rule 3: issues with merged PRs must be closed and marked State/Completed. (Section 15.2) Bulk state correction

Sub-responsibilities: Dependency link removal via REST API DELETE, clone directory deletion, bot signature on final comments.


22.29 R-29: Commit Formatting and Git Operations

Goal: All commits follow Conventional Changelog format, are pushed to both origin and upstream remotes, and use proper author attribution.

Redundancy Depth: Single (delegation chain)

Layer Agent Role Specific Actions
1 (Formatting) Commit Message Formatter Constructs three-part commit message: exact commit message from issue Metadata, implementation description body, ISSUES CLOSED: #N footer. Read-only agent (edit:deny, bash:deny). (Section 21.18) Message formatting from issue metadata
2 (Execution) Git Committer Stages all changes, commits with formatted message, pushes to BOTH remotes in sequence: git push -u origin <branch> then git push upstream <branch>. Both pushes required. Reports errors with full details. (Section 12.1) Staging, committing, dual-remote pushing
2b (Safe Commit) Git Commit Helper Pre-commit validation (verify repo, branch, staged changes). Optional pre-commit hooks. Co-authored-by trailers. Rollback on failure (git reset --soft HEAD~1). Returns structured JSON with sha, message, files, stats. (Section 21.21) Validated commit with rollback capability
3 (Amend-only) PR CI Test Fixer The ONLY agent that amends commits. git commit --amend --no-edit followed by git push --force-with-lease to both remotes. Never creates new commits on existing PRs. (Section 12.1) Commit amendment, force-push with lease

22.30 R-30: Branch Management and Rebase

Goal: Feature branches are always created from and kept current with master via rebase (never merge). Rebase conflicts are detected and handled appropriately.

Redundancy Depth: Double

Layer Agent Role Specific Actions
1 (Branch Setup) Branch Setup Creates or checks out branches with strict rebase-only policy. Supports dependent branch stacking via base_branch parameter. If branch exists: fetches, checkouts, rebases onto base. If not: creates from base. Rebase conflicts are NOT auto-resolved — aborts and reports. (Section 21.23) Branch creation, checkout, rebase-only enforcement
2 (Pre-merge Rebase) PR Merge Pool Pre-merge staleness check: compares merge_base vs base.sha. If behind: calls pr-merge-worker as a blocking subagent which clones via repo-isolator, rebases, force-pushes with lease, waits for CI, and attempts fast-forward merge. With conflicts: worker resolves by reviewing git history or posts comment. (Section 8.3.5) Pre-merge rebase via blocking worker, conflict detection
3 (Worker Rebase) Implementation Worker Before committing: rebases branch onto latest master (stash, fetch, rebase, pop). Resolves simple conflicts automatically (imports, whitespace, version numbers). Falls back to no-rebase if auto-resolution fails. Before merge: compares merge_base vs base.sha, rebases if behind, waits 120s for CI. (Section 10.1) Pre-commit rebase, pre-merge rebase

22.31 R-31: Progressive Model Escalation

Goal: Start with the cheapest viable model (Haiku) and automatically escalate through Codex, Sonnet, Opus as failures accumulate, optimizing cost while ensuring complex tasks succeed.

Redundancy Depth: Single

Layer Agent Role Specific Actions
1 (Orchestration) Subtask Loop Manages escalation schedule: haiku(2x)→codex→sonnet→opus(forever). Distinguishes transient errors (retries without incrementing) from genuine failures (increments attempt counter). Each quality gate has independent tier escalation. 5 inner passes per tier before escalation. Persists state as HTML comments in PR. (Section 11.2, 11.3) Escalation scheduling, transient error detection, state persistence
2 (Tier Selection) Tier Selectors (tier-haiku, tier-codex, tier-sonnet, tier-opus) Pure pass-through agents that set the model via their frontmatter and invoke the specified worker. Must not modify, interpret, or filter context. (Section 11.1) Model selection, context forwarding
3 (Difficulty Pre-assessment) Difficulty Evaluator Five-axis assessment (scope, complexity, novelty, integration, ambiguity). Conservative bias: when in doubt, recommends LOWER tier. (Section 12.4) Starting tier recommendation

Sub-responsibilities: Meaningful change verification (rejects <3 functional lines), per-gate independent tier tracking, escalation state persistence as <!-- ESCALATION-STATE: --> HTML comments, diagnostic comments every 3 attempts at opus tier.


Category B — Quality Assurance and Bug Detection

22.62 R-62: Implementation Correctness Verification

Goal: After all quality gates pass (lint, typecheck, tests, coverage), verify the code actually fulfills the subtask requirements — not just that it compiles and passes tests. Detect tests that pass trivially or test the wrong thing.

Redundancy Depth: Double

Layer Agent Role Specific Actions
1 (Per-Subtask) Implementation Reviewer Invoked AFTER quality gates pass. Enumerates each requirement from subtask description, verifies code fulfilling each requirement exists AND tests verifying each requirement exist. Rejects with specific file/function references and suggested fixes. Does NOT reject for style (linter's job). (Section 15.5) Requirement-by-requirement cross-reference
2 (Per-Milestone) Milestone Reviewer After all issues in a milestone are merged: reviews integrated codebase across 8 areas (integration gaps, API consistency, spec coverage, test quality, error handling coherence, performance, documentation, tech debt). Creates issues for problems found. (Section 21.17) Cross-issue integration verification

Sub-responsibilities: "Would-fail" reasoning (would this test actually fail if the implementation were broken?), detecting tests that pass trivially (assert True, empty mocks), verifying domain model fields exist before referencing (Implementer rule from Section 21.4).


22.32 R-32: Master CI Health Emergency Response

Goal: Master branch must NEVER have failing tests. Any master CI failure blocks all future PR merges, creating a system-wide deadlock. This responsibility has EMERGENCY priority — higher than any other audit.

Redundancy Depth: Double

Layer Agent Role Specific Actions
1 (Detection & Triage) System Watchdog Audit 0 (CRITICAL): checks latest master commit CI status. For each failing check: logs into Forgejo web UI, retrieves workflow run logs, parses for specific failing test scenarios (Behave patterns, Robot patterns, generic patterns). Creates Priority/CI-Blocker issue for each identified failing test with skip instructions. Creates Priority/High follow-up fix issue for the underlying problem. (Section 9.11.2) Failure detection, log parsing, CI-Blocker issue creation
2 (Enforcement Repair) Quality Enforcer Dispatched by Watchdog. Creates Priority/CI-Blocker issues for code merged without CI. Verifies/repairs branch protection rules via REST API. (Section 15.1) CI-Blocker issue creation, branch protection repair
3 (Priority Override) Implementation Pool Priority/CI-Blocker issues bypass the PR-first priority gate — the only exception. Dispatches workers immediately regardless of pending PR queue. (Section 8.1.2) Priority override for CI blockers

22.9 R-09: Label and Metadata Correctness

Goal: Every issue and PR has the correct labels (State, Type, Priority, MoSCoW, Points), milestone assignment, and PR-issue label synchronization. Label application must use the centralized Label Manager to prevent label-ID errors.

Redundancy Depth: Quadruple

Layer Agent Role When Notes
1 (Application) Forgejo Label Manager Centralized label operations. Handles name-to-organization-ID mapping. Five operations: validation, application, reading, inference, compliance checking. (Section 12.5) Every label operation by every agent The ONLY agent (besides Issue State Updater) permitted to call forgejo_add_issue_labels
2 (Initial Assignment) Every issue-creating agent: Epic Planner, New Issue Creator, Project Owner, Human Liaison, Bug Hunt Pool, UAT Test Pool, Test Infra Pool, Architecture Guard, System Watchdog Sets initial labels when creating issues, via Label Manager delegation. (Section 6.19) At issue creation time Responsible for getting labels right the first time
3 (Verification & Auto-Fix) Backlog Groomer Pass 4: auto-fixes missing State, Type, Priority labels. Pass 5: checks priority consistency. Pass 19: synchronizes PR labels with issue labels (Priority, MoSCoW, Points, State, milestone). (Section 9.7) Every 5-minute grooming cycle Catches and fixes any gaps left by Layer 2
4 (Audit) System Watchdog Audit 7: verifies all issues have required labels and dependency links. (Section 9.11.2) Every 5-minute watchdog cycle Detects systemic labeling failures
4b (Bulk Fix) State Reconciler Dispatched by Watchdog for mass label correction. Rule 6: every issue must have State, Type, and Priority labels. (Section 15.2) On Watchdog dispatch Nuclear option for systemic label drift

Redundancy pattern: Label Manager ensures correct application (mechanism). Creating agents set initial labels (first pass). Groomer verifies and fixes (second pass). Watchdog audits (third pass). Reconciler bulk-fixes (emergency fourth pass). This quadruple redundancy exists because incorrect labels cause cascading failures: wrong priority → wrong work order → milestone delays.


22.10 R-10: Issue State Lifecycle Management

Goal: Every issue's State/* label accurately reflects its actual status at all times. Closed issues have terminal state labels. Issues with merged PRs are closed. Issues in State/In Review have open PRs.

Redundancy Depth: Quadruple

Layer Agent Role Mechanism Notes
1 (Transitions) Issue State Updater Performs state transitions through 7-step process: read, validate, remove old, apply new, handle special cases, synchronize PRs, report. Retries 3× with exponential backoff. (Section 12.2) Direct label manipulation via REST API (one of two agents permitted to do so) The canonical state transition engine
2 (Reconciliation) Backlog Groomer Pass 9: reconciles closed issue states (closed but wrong state label → auto-fix to State/Completed). Pass 4: detects State/In Review with no PR. Pass 6: detects closeable issues. Pass 14: closes issues whose PRs have been merged. (Section 9.7) Scans all issues and cross-references with PR state Catches issues where state transitions were missed or incomplete
3 (Audit) System Watchdog Audit 3: checks closed issues with wrong state labels, In Review without PR, multiple State labels on same issue. (Section 9.11.2) Cross-references issue state against Forgejo actual status Detects systemic state integrity violations
4 (Bulk Fix) State Reconciler Eight reconciliation rules including: closed issues must have terminal labels, open issues must NOT have terminal labels, issues with merged PRs must be closed. (Section 15.2) Dispatched by Watchdog for mass correction Handles large-scale state drift after system disruptions

Redundancy pattern: Identical to label correctness (R-09). The Updater transitions (real-time), the Groomer reconciles (periodic), the Watchdog audits (periodic), the Reconciler bulk-fixes (on-demand). Four independent checks on the same invariant.


22.11 R-11: Dependency and Hierarchy Integrity

Goal: All dependency links follow correct directions (child BLOCKS parent Epic, Epic BLOCKS Legendary, PR BLOCKS issue). Every non-Epic/Legendary issue has a parent Epic. Every Epic has a parent Legendary.

Redundancy Depth: Triple

Layer Agent Role Links Created/Verified Notes
1 (Creation) Epic Planner — issue→epic→legendary links; PR Creator — PR→issue links Create dependency links with correct direction at creation time. (Sections 9.2, 12.1) Epic Planner: child BLOCKS parent; PR Creator: PR BLOCKS issue Responsible for getting direction right the first time
2 (Verification & Auto-Fix) Backlog Groomer Pass 2: detects orphan issues (no parent Epic). Pass 10: auto-fixes missing dependency links by parsing issue body for "Parent Epic: #N". Pass 16: fixes wrong-direction dependencies (issue blocking PR → PR blocking issue) that create merge deadlocks. (Section 9.7) All dependency types: issue→epic, epic→legendary, PR→issue Most active dependency fixer — catches and corrects wrong directions
3 (Audit) System Watchdog Audit 8: verifies Epic→Legendary hierarchy intact, Epics have minimum children, no orphaned epics. Audit 7: verifies orphan issues and dependency links. (Section 9.11.2) Hierarchy completeness and correctness Detects systemic hierarchy violations
3b (Bulk Fix) State Reconciler Rule 7: fixes dependency link directions (child blocks parent Epic, Epic blocks Legendary, PR blocks issue). (Section 15.2) All dependency directions Dispatched by Watchdog for mass correction

Redundancy pattern: Creators set links (real-time). Groomer verifies and auto-fixes, including the critical wrong-direction fix that prevents merge deadlocks. Watchdog audits hierarchy completeness. Reconciler handles bulk corrections.


22.12 R-12: Merge Safety and Branch Protection

Goal: No code reaches master without passing CI. All merges use the safe_merge_pr() protocol with post-merge verification. Branch protection rules cannot be silently disabled.

Redundancy Depth: Triple

Layer Agent Role What It Protects Notes
1 (Setup) Project Bootstrapper Configures branch protection for master: status checks required, 1 approval, dismiss stale reviews, block on rejected, push disabled. (Section 15.3) Initial configuration One-time setup; must be correct because it is the foundation
2 (Enforcement) Shared Merge Safety module safe_merge_pr() enforces 7 mandatory rules: never call merge API directly, verify safety first, handle success/failure, no force_merge, no false success messages, check rebase needed. (Section 13.6) Every merge attempt Used by PR Merge Pool and Implementation Worker
3 (Audit) System Watchdog Audit 1: verifies recent master commits have passing CI. Audit 2: verifies branch protection is active and correctly configured (status checks enabled, status-check context present, ≥1 required approval). (Section 9.11.2) Continuous verification that protection is intact Catches silent disablement or misconfiguration
4 (Repair) Quality Enforcer Dispatched by Watchdog. Repairs branch protection rules via REST API. Creates Priority/CI-Blocker issues for code merged without CI (absolute highest priority). (Section 15.1) Recovery from violations Does NOT revert commits — creates tracked issues for human review

Redundancy pattern: Bootstrapper sets up protection (once). Merge Safety module enforces it per-merge (continuous). Watchdog audits that it has not been tampered with (periodic). Quality Enforcer repairs it when violations are detected (on-demand).


22.13 R-13: Specification and Architecture Governance

Goal: The project specification (docs/specification.md) accurately reflects the intended architecture, stays current with implementation discoveries, and drives implementation decisions.

Redundancy Depth: Double

Layer Agent Role Direction Notes
1 (Spec → Code) Architecture Supervisor Writes and extends specification. Defines module boundaries, interfaces, data models. Monitors for new milestones without spec coverage, spec ambiguities, and human requests. Major changes go through PRs with needs feedback label. (Section 9.1) Specification drives implementation (forward-looking) "Most consequential agent — bad architecture cascades everywhere"
2 (Code → Spec) Spec Evolution Compares implementation against spec after merges. Updates spec where implementation found a better approach. Creates bug issues where implementation deviates incorrectly. Two-step proposal workflow with needs feedback. (Section 9.6) Implementation corrects specification (backward-looking) Critical rule: never removes unimplemented spec content
3 (Drift Detection) Architecture Guard Check 7: detects specification drift — implementation that has diverged from the specification. Creates Type/Refactor issues. (Section 9.5) Detects divergence in either direction Uses Gemini 2.5 Pro's massive context window for full-codebase analysis
4 (Milestone Review) Milestone Reviewer Area 3: verifies every specification requirement has corresponding implementation and test. (Section 21.17) Post-milestone verification Holistic check across the entire milestone's work

Redundancy pattern: Architecture writes spec forward (creation). Spec Evolution corrects it backward (alignment). Architecture Guard detects drift (continuous monitoring). Milestone Reviewer verifies coverage (periodic).


22.40 R-40: Specification-First Development Enforcement

Goal: Features that require architectural decisions or API changes must go through a spec-change → ADR → implementation pipeline. No implementation of unspecified architecture.

Redundancy Depth: Double

Layer Agent Role Specific Actions
1 (Planning Gate) Epic Planner Phase 3 (Specification-First Compliance): identifies features requiring spec changes (keywords: architecture, design, interface, API, protocol, schema, model, integration). Creates ADR issue, spec update issue (depends on ADR), makes feature depend on spec update. Posts specification-first comment. (Section 9.2) ADR→Spec→Implementation dependency chain creation
2 (Governance) Architecture Supervisor Major architectural changes go through PRs with needs feedback label. Minor clarifications committed directly. (Section 9.1) Human-approval workflow for major changes
3 (Feedback Channel) Human Liaison For features requiring spec changes: creates spec change issue, notes spec-updater will handle it, tracks spec PR, creates implementation issues when spec PR merges. (Section 9.3) Human-side spec change tracking

22.14 R-14: Codebase Coherence and Technical Debt

Goal: The codebase maintains consistent patterns, avoids duplication, respects module boundaries, and accumulates minimal technical debt.

Redundancy Depth: Triple

Layer Agent Role Analysis Type Notes
1 (Proactive Scanning) Architecture Guard Seven check categories: duplicate code (>70% similarity), inconsistent patterns, module coupling violations, API surface inconsistencies, technical debt indicators (>50 line functions, >4 nesting levels, TODO/FIXME), test quality, specification drift. Creates Type/Refactor issues. (Section 9.5) Codebase-wide, triggered by master SHA changes Uses Gemini 2.5 Pro for massive context analysis
2 (Per-Module Analysis) Bug Hunt Pool Pass 8: code consistency analysis. Pass 9: data flow analysis. Identifies inconsistent patterns across modules. (Section 8.6.2) Module-by-module, nine-pass deep analysis Different perspective — code analysis rather than architecture review
3 (Per-PR Review) PR Reviewer Focus areas 1 (architecture alignment), 4 (API consistency), 7 (code maintainability). Detects architectural drift and pattern violations per-PR. (Section 12.1.2) Per-PR, with rotating focus areas Catches issues at the point of introduction

Redundancy pattern: Guard scans the whole codebase periodically (breadth). Bug Hunt analyzes each module deeply (depth). PR Reviewer catches issues as they are introduced (prevention). Three different angles on the same coherence goal.


22.33 R-33: Flaky Test Detection and Prevention

Goal: Identify and eliminate non-deterministic tests that pass sometimes and fail others, which erode CI reliability and cause false positives.

Redundancy Depth: Double

Layer Agent Role Specific Actions
1 (Per-PR Detection) PR Reviewer Code review red flags: time.sleep() or datetime.now() in test code without mocking, random.choice()/random.randint() without seed, shared filesystem paths between tests, tests that pass locally but fail in CI, timing-sensitive assertions. CI pattern analysis: intermittent failures, timeout errors. Multi-PR analysis: same tests failing across multiple PRs = master branch issue. Immediately requests changes for non-deterministic patterns. (Section 12.1.2) Pattern detection in PR diffs, CI cross-analysis
2 (Infrastructure Detection) System Watchdog Audit 9: monitors CI execution times (flags >30 minutes), detects recurring failures on same tests across different PRs. (Section 9.11.2) Cross-PR failure pattern analysis
2b (Infrastructure Analysis) Test Infrastructure Pool Area 4: dedicated flaky test analysis pass across the full test suite. (Section 8.7.2) Systematic flaky test identification

22.34 R-34: Test Stability Enforcement

Goal: All tests must be deterministic — no random behavior, timing dependencies, or external calls. Violations must be caught before they reach master.

Redundancy Depth: Triple

Layer Agent Role Specific Actions
1 (Worker Rules) Implementation Worker Enforces strict test determinism rules: NEVER time-based dependencies, random values without seeding, filesystem races, network dependencies, order-dependent tests, uncontrolled async. ALWAYS: fixed test data, mock external deps, isolated temp filesystems, seeded random, proper isolation, synchronous operations. (Section 10.1.8) Rule enforcement during implementation
2 (Review) PR Reviewer Detects all six non-deterministic patterns in PR diffs and requests changes. (Section 12.1.2) Pattern detection in code review
3 (Quality Gate) Subtask Loop Unit Test Runner and Integration Test Runner detect and fix flaky tests during quality gate execution. Test Fixer distinguishes tests that fail due to intentional behavior changes (update/remove) from tests exposing genuine bugs (fix code). (Section 11.3) Runtime failure detection and classification

22.15 R-15: Backlog Hygiene and Duplicate Detection

Goal: The issue backlog is clean, free of duplicates, properly linked, and contains no stale or abandoned issues.

Redundancy Depth: Double

Layer Agent Role Scope Notes
1 (Comprehensive Grooming) Backlog Groomer 19 analysis passes every 5 minutes: duplicate detection (issues only, NOT PRs), orphan detection, stale detection, label compliance, closeable issues, blocked chain analysis, body compliance, scope creep, PR health, and more. (Section 9.7) All open issues and PRs The primary hygiene agent — most comprehensive
2 (Self-Dedup) Test Infrastructure Pool Five mandatory dedup checks before filing any issue: keyword search, cross-area search, closed issues search, dedup proof in issue body, uncertainty avoidance. (Section 8.7.3) Its own issue creation only Documented as "#1 problem with this agent" — historical 48+ duplicates
2b (Self-Dedup) Bug Hunt Pool Finding validation: must have actual code evidence, verify environment assumptions, verify actionable, verify against actual codebase, severity must match evidence. (Section 21.8) Its own issue creation only Prevents filing issues about infrastructure failures
2c (Self-Dedup) UAT Test Pool Worker coordination through Forgejo comments to avoid duplicate testing. (Section 8.5) Its own testing scope only Prevents duplicate test-driven issues

Redundancy pattern: Backlog Groomer provides comprehensive cross-agent hygiene. Issue-creating agents (Test Infra, Bug Hunt, UAT) each implement self-dedup to prevent duplicates at the source. The combination of source prevention and downstream detection creates double coverage.


22.58 R-58: Label-Name-to-ID Resolution and Conflict Prevention

Goal: Labels exist at the Forgejo organization level with numeric IDs. Agents must never reference labels by name in API calls — they must resolve names to org-level IDs first. Multiple labels in the same pattern group (e.g., two State/ labels) must be prevented.

Redundancy Depth: Single (centralized)

Layer Agent Role Specific Actions
1 (Resolution) Forgejo Label Manager Queries GET /orgs/{org}/labels to build name→ID mapping. Resolves label names to IDs before application. Detects and rejects requests for non-existent labels. Detects pattern conflicts (e.g., trying to add State/Verified when State/In Progress already exists) and removes the old one first. Enforces MoSCoW exclusivity (project owner only). (Section 21.10) Name→ID mapping, conflict detection, pattern enforcement

Sub-responsibilities: Label inference from content (title/body keyword analysis), label compliance checking per lifecycle stage (State + Type + Priority required, Points required for Verified+), providing helpful alternatives when requested labels don't exist.


22.35 R-35: PR-Issue Label Synchronization

Goal: PRs must mirror all relevant labels from their linked issue (Priority, MoSCoW, Points, State, Type) and milestones must match. Stale labels removed from the issue must also be removed from the PR.

Redundancy Depth: Double

Layer Agent Role Specific Actions
1 (At Creation) PR Creator Inherits ALL Type/, Priority/, MoSCoW/, Points/ labels from issue to PR. Adds State/In Review. Copies milestone. (Section 12.1) Initial label inheritance
2 (Ongoing Sync) Backlog Groomer Pass 19 (every cycle): compares ALL labels between PR and issue. Adds missing Priority/, MoSCoW/, Points/ labels. Updates State/ labels to match issue. Removes stale labels that no longer exist on issue. Updates milestone. Posts explanatory comment. (Section 9.7) Continuous synchronization with drift correction

22.36 R-36: Story Point Estimation

Goal: Every issue in State/Verified or later (except Epics and Legendaries) has a Points/* label estimating effort.

Redundancy Depth: Double

Layer Agent Role Specific Actions
1 (Triage-time) Human Liaison Estimates story points during triage: XS (1pt), S (2pt), M (3pt), L (5pt), XL (8pt), XXL (13pt). Applies Points/ label via Forgejo Label Manager. (Section 9.3) Estimation during human issue triage
2 (Compliance Fill) Backlog Groomer Pass 4: detects Verified+ issues without Points/ label. Estimates from subtask count and description complexity (0-2→Points/2, 3-5→Points/3, 6-8→Points/5, 9+→Points/8, epic-level→Points/13). Posts comment explaining estimation. (Section 9.7) Automated estimation for unlabeled issues

22.37 R-37: Milestone Assignment and Scope Guard

Goal: Non-Epic, non-Legendary issues beyond State/Unverified have milestones. New non-critical issues never inflate active milestone scope.

Redundancy Depth: Triple

Layer Agent Role Specific Actions
1 (At Creation) New Issue Creator Strict scope guard: critical bugs → source milestone; all others → no milestone, Priority/Backlog. Exception only for caller-specified essential milestones. NEVER adds non-critical to converging milestones. (Section 12.2) Milestone assignment with scope guard
2 (Planning) Epic Planner Milestone Scope Guard: will not create new issues in converging milestones (closed > open). New discovered work goes to backlog. (Section 9.2) Planning-level scope guard
3 (Compliance) Backlog Groomer Pass 4: assigns milestone to non-Epic/non-Legendary issues in Verified+ without one. (Section 9.7) Missing milestone fill
3b (Testing) UAT Test Pool Milestone Scope Guard: only critical bugs assigned to active milestone. (Section 8.5.3) Testing-level scope guard

22.60 R-60: State Transition Precondition Enforcement

Goal: State transitions must follow strict preconditions: transitioning FROM State/Paused requires the blocking issue to be closed; transitioning TO State/In Review requires an open PR; terminal states close the issue. No shortcuts.

Redundancy Depth: Double

Layer Agent Role Specific Actions
1 (Enforcement) Issue State Updater Step 2 (validate preconditions): checks blocking issue is closed before Paused→In Progress. Step 5 (special cases): closes issue for terminal states, removes Blocked label. Step 6: synchronizes PR state labels (finds PRs referencing this issue, removes old State/, adds new State/). Retries 3× with exponential backoff. (Section 12.2) Precondition validation, terminal state closure, PR sync
2 (Cross-check) Backlog Groomer Pass 4: detects State/In Review with no open PR (transitions to Completed if merged, or In Progress if never created). Pass 9: fixes closed issues with non-terminal labels. (Section 9.7) State/reality cross-check

Sub-responsibilities: Atomic multi-state label cleanup (DELETE all existing State/* labels before adding new one, preventing accumulation), PR label synchronization (when issue state changes, matching PRs get updated labels), HTTP error handling (404 = label doesn't exist, 422 = already applied, 429 = rate limit).


22.38 R-38: Issue Body and Definition of Done Compliance

Goal: Every issue body contains the required sections per CONTRIBUTING.md: Metadata (Branch, Commit Message, Parent Epic), Subtasks (at least one checkbox), and Definition of Done.

Redundancy Depth: Double

Layer Agent Role Specific Actions
1 (At Creation) New Issue Creator, Epic Planner Create issues with CONTRIBUTING.md-compliant body format (Metadata, Subtasks, DoD). Standard DoD includes: all subtasks completed, unit tests (≥97% coverage), integration tests, quality gates pass, PR created and approved, PR merged. (Section 6.14) Compliant issue creation
2 (Verification) Backlog Groomer Pass 11: checks for ## Metadata, ## Subtasks (with checkbox), ## Definition of Done headings. Posts comment listing missing sections. Pass 7: audits DoD checklist for premature/missing check-offs. (Section 9.7) Post-creation compliance verification

22.39 R-39: Blocked Chain Analysis and Resolution

Goal: Detect and resolve circular dependencies, orphaned blockers (blocked by closed issue), and impossible chains (blocked by later milestone issue). No issue should be permanently stuck due to dependency problems.

Redundancy Depth: Double

Layer Agent Role Specific Actions
1 (Analysis) Backlog Groomer Pass 8: analyzes full dependency graph. Detects circular dependencies (A→B→C→A). Detects orphaned blockers (blocked by #N but #N is closed). Detects impossible chains (blocked by issue in later milestone). Posts comment explaining the problem and suggesting resolution. (Section 9.7) Dependency graph analysis, problem detection
2 (State Enforcement) Issue State Updater When transitioning from State/Paused: validates that the blocking issue is actually resolved before allowing transition. Prevents premature unblocking. (Section 12.2) Transition precondition enforcement
3 (Audit) System Watchdog Audit 7/8: detects orphan issues and hierarchy violations. (Section 9.11.2) Hierarchy and dependency auditing

Category D — Architecture and Specification Governance

22.16 R-16: Bug Detection and Proactive Quality Assurance

Goal: Find bugs before users do. Detect bugs through code analysis, specification comparison, acceptance testing, and code review.

Redundancy Depth: Quadruple

Layer Agent Role Detection Method Notes
1 (Code Analysis) Bug Hunt Pool Nine analysis passes per module: error handling, concurrency, security, boundary conditions, resource management, type safety, specification alignment, code consistency, data flow. (Section 8.6) Static code analysis against spec Uses Gemini 2.5 Pro for cross-module analysis
2 (Spec Compliance) UAT Test Pool Tests feature areas against the specification. Files bug issues for gaps and spec deviations. Captures successful workflows as documentation. (Section 8.5) Dynamic testing against spec Finds issues Bug Hunt cannot (runtime behavior)
3 (Per-PR Detection) PR Reviewer Focus areas 2 (error handling/edge cases), 5 (security), 6 (performance), 10 (behavior correctness). Flaky test detection. (Section 12.1.2) Code review of changes Catches bugs at the point of introduction
4 (Architecture-Level) Architecture Guard Check 6: test quality (tests that do not verify meaningful behavior, missing edge cases). Check 5: technical debt indicators. (Section 9.5) Codebase-wide structural analysis Catches classes of bugs caused by architectural issues

Redundancy pattern: Bug Hunt finds code-level bugs proactively. UAT finds spec-deviation bugs through testing. PR Reviewer catches bugs at introduction. Architecture Guard finds bugs caused by structural issues. Four completely independent detection methods.


22.17 R-17: Documentation and Timeline Maintenance

Goal: Project documentation (README, API docs, architecture docs, changelog, module docs) and timeline (docs/timeline.md) stay current with the project state.

Redundancy Depth: Single (exclusive domains)

Domain Agent Role Territory Notes
Documentation Documentation Supervisor Generates and updates five documentation types: README, API docs, architecture docs, changelog, module docs. Always extends, never overwrites. (Section 9.8) All files EXCEPT docs/timeline.md Must NOT modify timeline (exclusive to Timeline Supervisor)
Timeline Timeline Supervisor Keeps docs/timeline.md accurate. Makes surgical updates to nine sections including Gantt charts, status summaries, completion history, risk tables. (Section 9.9) docs/timeline.md exclusively Never deletes historical data; append-only for history sections
Showcase Docs UAT Test Pool Generates showcase documentation from successful end-to-end test runs demonstrating real-world usage patterns. (Section 21.3) Categorized showcase directories Supplementary documentation from testing

Redundancy pattern: None — these are exclusive domains by design. The Documentation Supervisor and Timeline Supervisor have non-overlapping territories enforced by explicit rules. This prevents conflicting edits to the same files.


22.18 R-18: Human Communication and Escalation

Goal: Human developers receive timely, professional responses. Automated issues that require human decisions are escalated promptly. Human feedback is incorporated systematically.

Redundancy Depth: Double

Layer Agent Role Trigger Notes
1 (Primary Bridge) Human Liaison 10-step monitoring loop every 2 minutes. Handles all human activity: new issues, comments, PR reviews, label changes. Full triage authority. Feedback Incorporation Protocol updates descriptions and notifies users. (Section 9.3) All human activity on Forgejo Fastest response time (2-minute poll). Timeouts: 48h PR feedback, 24h questions, 72h blocked work
2 (Strategic Questions) Project Owner Tags developers with questions in Forgejo comments. Assigns developers to issues based on expertise. Follows up on pending questions every 5th cycle. (Section 9.10) Unassigned critical/blocking issues, strategic questions Complements Liaison with strategic focus
3 (Automated Escalation) Implementation Worker After 3 stuck detections: posts diagnostic comment, adds needs feedback label, exits gracefully. (Section 10.1.4) Repeated implementation failures on the same error Self-escalation when automation is stuck
3b (Independent Escalation) System Watchdog Audit 5b: independently detects struggling PRs (3+ fix attempts), requests human assistance. (Section 9.11.2) PR-level repeated failures detected from outside Catches cases where the worker itself did not escalate
4 (Proposal Escalation) Agent Evolution, Spec Evolution, Architecture Supervisor Create needs feedback proposals for major changes requiring human approval. (Sections 9.4, 9.6, 9.1) Significant architectural/agent/spec changes Human-approved workflow for high-impact changes

Redundancy pattern: The Implementation Worker self-escalates when stuck (self-awareness). The Watchdog independently detects the same condition from outside (external awareness). This double escalation ensures no struggling PR goes unnoticed even if the worker itself fails to escalate.


22.46 R-46: Feedback Incorporation Protocol

Goal: When human feedback changes the nature of a ticket (scope, requirements, approach), the change must be captured in the issue/PR description — not buried in a comment thread. Users must be notified of description changes with a diff.

Redundancy Depth: Single

Layer Agent Role Specific Actions
1 (Protocol Execution) Human Liaison When discussion conclusions change ticket nature: (1) updates issue/PR description to reflect new understanding (source of truth), (2) posts comment tagging user with diff between old and new description, (3) confirms change is complete and ready for implementation. Applies to ALL scenarios where discussion changes agreed-upon details — scope changes, requirement changes, approach changes, priority changes, acceptance criteria changes. (Section 9.3) Description updates, user notification with diff, confirmation

Why single depth? Only the Human Liaison communicates with humans. This is an exclusive domain. However, the Updated description persists on Forgejo and is read by all subsequent agents (Implementation Worker, PR Reviewer, etc.), so the effect propagates through the system.


22.47 R-47: Human Response Timeout Management

Goal: Automated work must not stall indefinitely waiting for human responses. Escalation actions must occur after defined timeout periods.

Redundancy Depth: Double

Layer Agent Role Specific Actions
1 (Timeout Tracking) Human Liaison Tracks five timeout types: needs_feedback_pr (48h), question_on_issue (24h), blocked_on_human (72h), spec_approval (48h), verification_requested (24h). On timeout: creates provisional ADR (PR feedback), proceeds with documented assumption (question), creates announcement (approval), removes State/Blocked (unblocking). Posts timeout action comments. (Section 9.3) Timeout tracking, escalation actions, provisional decisions
2 (Question Follow-up) Project Owner Tracks developer questions asked. Posts follow-up after 48 hours of no response. Triages independently based on available info after 96 hours. (Section 9.10) Question timeout follow-up

22.48 R-48: Developer Expertise Discovery and Assignment

Goal: Issues are assigned to the most appropriate developer based on expertise, capacity, and velocity. The system discovers expertise automatically from git history and Forgejo assignments.

Redundancy Depth: Double

Layer Agent Role Specific Actions
1 (Discovery & Assignment) Project Owner Creates temporary shallow clone (depth=200). Analyzes git log for contributors and their primary files/modules. Checks Forgejo for recent assignees and PR authors. Builds developer_expertise map. Assigns developers considering: expertise match (>0.7), capacity, velocity boost (>1.3x), coordination overhead. Golden Rule: if ANY doubt, defaults to HAL9000. (Section 9.10) Git history analysis, expertise mapping, strategic assignment
2 (Expertise Tagging) Human Liaison Tags specific developers in comments based on their expertise areas when guidance is needed. Cross-references known developer specializations. (Section 9.3) Developer tagging for expertise-specific questions

Category G — Strategic Governance and Self-Improvement

22.19 R-19: Scope Management and Milestone Control

Goal: Milestones converge toward completion. New issues do not inflate scope uncontrollably. Non-critical discovered work goes to backlog, not active milestones.

Redundancy Depth: Triple

Layer Agent Role Mechanism Notes
1 (Detection) Backlog Groomer Pass 18: scope creep detection. Calculates convergence ratio, 24h creation/closure rates. Alerts when creation rate > 2× closure rate. (Section 9.7) Creation-vs-closure rate monitoring Creates Priority/High announcement issues for scope alerts
2 (Prevention at Planning) Epic Planner Milestone Scope Guard: does not create new issues in converging milestones. New discovered work goes to backlog. (Section 9.2) Prevents new issue creation in converging milestones Applied at the planning level
3 (Prevention at Creation) New Issue Creator Strict scope guard: critical bugs → current milestone; all other discovered issues → no milestone, Priority/Backlog. (Section 12.2) Milestone assignment rules at creation time Applied at the issue creation level
3b (Prevention at Testing) UAT Test Pool Milestone Scope Guard: only critical bugs assigned to active milestone. Non-critical issues go to backlog with no milestone. (Section 8.5.3) Applied when filing test-discovered bugs Prevents test-driven scope explosion

Redundancy pattern: Groomer detects scope creep (monitoring). Planner, Creator, and UAT all independently apply scope guards (prevention). Three independent prevention mechanisms plus one detection mechanism.


22.20 R-20: Automation Tracking and Inter-Agent Coordination

Goal: All agents coordinate through a consistent tracking issue system. Status issues follow the one-at-a-time invariant. Stale tracking issues are cleaned up. Announcements propagate to relevant consumers.

Redundancy Depth: Triple

Layer Agent Role Mechanism Notes
1 (Operations) Automation Tracking Manager Centralized tracking operations: 11 operations including create, update, close, read, announce, review. Enforces close-ALL-then-create for the one-at-a-time invariant. Manages cycle numbers, interval calculation. (Section 5.4) Central API for all tracking operations No agent creates tracking issues directly
2 (Self-Cleanup) Every supervisor Each supervisor closes its own old status issues via CREATE_TRACKING_ISSUE (which calls close-all first). Reviews own announcements every 3 cycles. (Sections 5.2.1, 5.3.1) Agent-side cleanup Primary cleanup mechanism
3 (Redundant Cleanup) Backlog Groomer Pass 19: cleans up stale tracking tickets with priority-based age thresholds. Pass 20: deduplicates status issues (keeps newest, closes rest) when same prefix has multiple open. (Section 9.7) Age-based and duplicate-based cleanup Safety net for agent-side cleanup failures
4 (Health Monitoring) System Watchdog Audit 11: monitors tracking issue age against expected interval. Triggers recovery for stalled agents. (Section 9.11.2) Staleness detection Detects agents that stopped updating

Redundancy pattern: Tracking Manager provides the mechanism. Each agent cleans up after itself (self-maintenance). Groomer catches failures in self-cleanup (cross-agent cleanup). Watchdog detects frozen agents (health monitoring). Three independent mechanisms maintain tracking hygiene.


22.21 R-21: Crash Recovery and State Persistence

Goal: The system survives crashes at every level — from individual workers to the Product Builder itself — without losing significant work.

Redundancy Depth: Multi-level (every level has its own recovery mechanism)

Level Agent Recovery Mechanism State Source Notes
Product Builder crash Product Builder Re-invoke → detects existing sessions via OpenCode API (Phase C.0) → adopts running supervisors → resumes monitoring. (Section 7.6) OpenCode Server session list Human must re-invoke, but existing sessions survive
Supervisor crash Product Builder Detects dead supervisor within 60 seconds → re-launches with same parameters. Startup State Recovery Protocol: reads most recent tracking issue before creating new one. (Sections 4.3, 5.3.3) Forgejo tracking issues New session recovers state from previous session's tracking issue
Worker crash Pool Supervisors Detect dead worker → slot becomes available → re-dispatches. New worker checks for existing PR/branch. (Section 10.1.6) Git branches, existing PRs, Forgejo comments Work-in-progress preserved if committed/pushed
Subtask Loop crash Subtask Loop Reads escalation state from HTML comments in PR comments. Resumes from correct tier and attempt number. (Section 16) PR comment HTML Embedded state survives session death
Git push failure Shared Error Handling Retry with exponential backoff. Clone preserved until successful push. (Section 13.3) Clone directory in /tmp/ Clone survives worker crash but not machine reboot
Forgejo API failure Shared Error Handling All API calls retry with exponential backoff (1s, 2s, 4s base; 60s for rate limits). (Section 13.3) Retry state in memory Handles transient unavailability

Design principle: The system uses a durability hierarchy: Forgejo issues/PRs/comments (most durable, survives any crash) → Git branches/commits (survives any crash once pushed) → Tracking issues (survives any crash) → Clone directories (survives worker crash, not reboot) → In-memory state (lost on crash, must be recoverable from higher levels).


22.50 R-50: Worker Session Adoption and Lifecycle

Goal: When a pool supervisor restarts, it must discover and adopt existing worker sessions from its previous incarnation rather than launching duplicates. Dead worker sessions must be detected, cleaned up, and their slots recycled.

Redundancy Depth: Single per pool

Layer Agent Role Specific Actions
1 (Adoption) All pool supervisors On startup: scan all active OpenCode sessions for matching title patterns (e.g., [AUTO-IMP] worker-issue-impl: issue-N). For each match: verify session is still active via /session/status API. Adopt active sessions into tracking dictionaries. Skip launch for adopted workers. (Section 8.1.4) Session scanning, status verification, dictionary adoption
2 (Lifecycle) All supervisors Periodically search for worker sessions by tag pattern. Monitor worker health (stuck, errored, completed). Launch new workers to keep the pool full as old ones complete. Terminate excess workers when count exceeds the allocated worker count. (Section 8.1) Status polling, dead worker cleanup, pool maintenance

22.51 R-51: Forgejo API Pagination and Truncation Recovery

Goal: The Forgejo REST API returns at most 50 items per page. Every list query must paginate through ALL pages. When tool output is truncated, the saved file must be read before proceeding. Failing to paginate causes silent data loss.

Redundancy Depth: Universal (mandatory for all Forgejo-querying agents)

Layer Agent Role Specific Actions
1 (All agents) Every agent querying Forgejo lists Loop pattern: page=1; while page_items: if len(page_items) < 50: break; page += 1. Log total count after pagination. (Section 6.20) Mandatory pagination loop
2 (Truncation) Implementation Pool (most affected) When tool response shows ...N bytes truncated... Full output saved to: /path, reads the saved file via jq or Read before proceeding. NEVER treats truncated output as complete data. (Section 8.1.2) Truncated output file recovery

Most affected agents: Implementation Pool (must analyze every open PR) and Backlog Groomer (scans all open issues). Missing items has severe consequences in both cases.


22.57 R-57: Clone Isolation and Safety

Goal: Every agent that touches the filesystem creates its own isolated clone in /tmp/. No agent ever modifies /app. Clone directories are created with authentication, used for work, pushed to remote, and deleted on exit. Safety validations prevent catastrophic directory deletion.

Redundancy Depth: Single (protocol)

Layer Agent Role Specific Actions
1 (Creation) Repo Isolator Creates unique directory /tmp/isolated-{agent}-{id}-{timestamp}/. Constructs authenticated clone URL (PAT embedded in HTTPS URL, never logged). Configures git identity. Returns clone path. (Section 6.2) Clone creation, auth setup
2 (Safety) Repo Isolator Refuses to delete protected directories (/, /tmp, /app). Only deletes directories matching /tmp/isolated-* pattern. Retries rm -rf up to 3× with verification. (Section 12.3) Deletion safety, retry with verification
3 (Branch Verification) Repo Isolator Checks refs/heads/{branch} then refs/remotes/origin/{branch} as fallback. Separate paths for checkout vs. create-and-checkout. (Section 12.3) Branch existence verification

22.56b R-56b: Transient Error Classification and Retry

Goal: Distinguish infrastructure failures (timeouts, rate limits, network errors) from genuine implementation failures (quality gate failures, review rejections). Transient errors get retries without penalty; genuine failures trigger escalation.

Redundancy Depth: Single (shared module)

Error Type Examples Retry Strategy
NetworkError Timeout, connection refused, DNS failure 3 retries, exponential backoff (1s, 2s, 4s)
ForgejoError (429) Rate limit exceeded 5 retries, fixed 60s delay
ForgejoError (5xx) Server error 3 retries, exponential backoff
GitError Push rejected, fetch failed 3 retries, exponential backoff
GitConflictError Rebase conflict 2 retries with rebase strategy, cleanup on failure
CoordinationError Already claimed, stale claim Abort immediately
ConfigurationError Missing env var, invalid credential Abort immediately

Key distinction in Subtask Loop: Transient errors (timeout, rate limit, "context canceled") get 3 retries WITHOUT incrementing the attempt counter. Only genuine failures (quality gate failure, review rejection) increment and potentially escalate to a higher model tier.


22.41 R-41: Worker Dispatch and Sliding Window Management

Goal: Each pool supervisor maintains a sliding window of N parallel workers, immediately filling vacant slots from a priority queue. No worker slot should be idle when work is available.

Redundancy Depth: Single per pool

Pool Agent Workers Allocation Dispatch Method
Implementation Implementation Pool implementation-worker N (full) Async (via Async Agent Manager)
PR Review PR Review Pool pr-reviewer N/2 (half) Async (via Async Agent Manager)
PR Fix Implementation Pool implementation-worker (PR-first priority) Shared with issue workers (N) Async (via Async Agent Manager)
UAT Test UAT Test Pool uat-test-worker N/4 (quarter) Async (via Async Agent Manager)
Bug Hunt Bug Hunt Pool bug-hunt-worker N/4 (quarter) Async (via Async Agent Manager)
Test Infra Test Infra Pool test-infra-worker N/4 (quarter) Async (via Async Agent Manager)

Sub-responsibilities: Session naming with tags ([AUTO-IMP] worker-issue-impl: issue-{N}), worker session adoption on startup, dead worker detection and slot recycling, excess worker termination, worker count enforcement.


22.42 R-42: Tracking Issue Cleanup and Deduplication

Goal: At most one open status tracking issue per agent prefix at any time. Stale tracking issues and announcements are cleaned up. No tracking issue accumulation.

Redundancy Depth: Triple

Layer Agent Role Specific Actions
1 (Self-Cleanup) Automation Tracking Manager CREATE_TRACKING_ISSUE closes ALL open status issues with same prefix before creating new one. Searches with state: "open" and labels: "Automation Tracking" with no pagination limits. Posts "Superseded by Cycle N" comment before closing. (Section 5.2.1) Close-all-then-create protocol
2 (Per-Agent) Every supervisor Invokes ATM's CREATE_TRACKING_ISSUE which handles cleanup internally. Reviews own announcements every 3 cycles via REVIEW_OWN_ANNOUNCEMENTS. (Section 5.3.1) Agent-side announcement review
3 (Cross-Agent) Backlog Groomer Pass 19: cleans stale tracking tickets with priority-based age thresholds (Critical=72h, High=48h, Medium=24h, Low=12h for announcements; 1h for status). Pass 20: deduplicates status issues — keeps newest per prefix, closes rest. Checks for [PERSIST]/[KEEP_OPEN] markers before closing. (Section 9.7) Age-based cleanup, deduplication, persistence markers

22.43 R-43: Announcement Lifecycle Management

Goal: Important cross-agent events (quality gate violations, scope alerts, capacity warnings) are communicated via persistent announcement issues that survive cycle boundaries. Announcements are closed when their condition resolves. Stale announcements are cleaned.

Redundancy Depth: Double

Layer Agent Role Specific Actions
1 (Creation & Self-Review) Every announcement-creating supervisor Creates announcements via ATM CREATE_ANNOUNCEMENT_ISSUE with [PREFIX] Announce: <message> title, priority label, and detailed body. Reviews own announcements via REVIEW_OWN_ANNOUNCEMENTS every 3 cycles. Closes resolved announcements. (Section 5.3) Creation, self-review, self-closure
2 (Consumption) Consumer agents per consumption protocol System Watchdog reads ALL agents' announcements (Medium+). Product Builder reads ALL (Medium+). Human Liaison reads ALL (High+). Implementation Pool reads Watchdog/Liaison/Groomer (High+). Other supervisors read Watchdog (Critical only). Read depth varies: title-only, summary, or full body+comments. (Section 5.3.2) Priority-filtered reading at appropriate depth
3 (Stale Cleanup) Backlog Groomer Pass 19: applies age thresholds per priority. Posts auto-closure inquiry comments on borderline announcements. Closes after 24h no response. Respects [PERSIST]/[KEEP_OPEN] markers. (Section 9.7) Age-based cleanup with grace period

22.44 R-44: Context Window Self-Management

Goal: Long-running agents must actively manage their context window to prevent exhaustion, which causes zombie behavior (agent alive but non-productive).

Redundancy Depth: Single (per agent, with external detection)

Layer Agent Role Specific Actions
1 (Self-Management) Every long-running agent Discards accumulated tool outputs every N cycles. Retains only persistent state (worker maps, completed lists, cycle counts, fail counts, queue depths). NEVER retains raw API responses, file contents, CI logs, PR diffs. (Section 21.7) Periodic context pruning
2 (External Detection) System Watchdog Audit 6: detects zombied agents via sleep-only pattern (context exhausted, agent only sleeping). (Section 9.11.2) Zombie detection for context-exhausted agents

Agent-specific intervals: Backlog Groomer (every 20 cycles), Human Liaison (every 20 cycles), Implementation Pool (every 50 iterations), Agent Evolution (every 10 cycles).


22.61 R-61: Reference Material Caching and Distribution

Goal: Reduce redundant ref-reader calls by caching reference materials at the pool supervisor level and distributing pre-analyzed content to all child workers.

Redundancy Depth: Single (optimization)

Layer Agent Role Specific Actions
1 (Caching) Ref Material Loader Stores ref-reader output in /tmp/ref-cache/ with cycle-based naming. Cache validity: 24-hour expiry. Stale caches >7 days automatically cleaned. Performance: 80% faster for 5 workers, 90% for 10, 95% for 20. (Section 12.4) Cycle-based caching, expiry management
2 (Extraction) Spec Reader Given an issue title and description, reads full specification and filters to only relevant sections: applicable modules, interface contracts, data models, cross-cutting concerns. (Section 12.4) Issue-relevant specification extraction
3 (Distribution) Pool supervisors Load references once per cycle via Ref Reader or cached Ref Material Loader, then pass the content to every worker launched in that cycle. (Section 6.8) Parent-to-child content distribution

22.63 R-63: Bot Signature Standardization

Goal: Every piece of content that any agent creates on Forgejo (issue bodies, comments, PR descriptions, review comments) must end with a standardized bot signature block for attribution, filtering, and tracing.

Redundancy Depth: Single (centralized)

Layer Agent Role Specific Actions
1 (Formatting) Forgejo Signature Appender Three signature formats: standard (separator + attribution + supervisor/agent), minimal (attribution only), extended (separator + attribution + supervisor + timestamp + closing). Includes clean_existing_signatures() to prevent duplication on updates. (Section 5.7, 21.12) Signature formatting, dedup on update
2 (Enforcement) Every agent creating Forgejo content Must append signature to ALL content: issue bodies, comments, PR descriptions, review comments, tracking issues. (Section 5.7) Universal signature requirement

Signature template: ---\n**Automated by CleverAgents Bot**\nSupervisor: <Name> | Agent: <filename>


22.64 R-64: Nox Routing Enforcement

Goal: ALL build, test, lint, and typecheck commands must be routed through nox sessions. No agent may install software directly (pip install, npm install) or run quality tools directly (ruff, pyright, behave).

Redundancy Depth: Universal (all code-executing agents)

Command Nox Session Used By
Linting nox -e lint Lint Fixer
Type checking nox -e typecheck Typecheck Fixer
Unit tests nox -e unit_tests Unit Test Runner
Integration tests nox -e integration_tests Integration Test Runner
Coverage nox -s coverage_report Coverage Improver
Security nox -e security Quality gates
Quality nox -e quality Quality gates

Enforcement: CONTRIBUTING.md compliance (Section 6.4). PR Reviewer checks for direct tool invocations. System Watchdog session spot-checks for forbidden commands.


22.45 R-45: Estimated Cycle Interval Maintenance

Goal: Every status tracking issue includes a rolling-average cycle interval that enables the Watchdog to detect frozen agents accurately without false positives.

Redundancy Depth: Double

Layer Agent Role Specific Actions
1 (Calculation) Automation Tracking Manager Calculates rolling average internally when sleep_interval_default is passed to CREATE_TRACKING_ISSUE. Formula: round(old_interval * 0.90 + actual_interval * 0.10). Injects **Estimated Cycle Interval**: Nmin into the tracking body automatically. (Section 5.3.4) Rolling average calculation, body injection
2 (Consumption) System Watchdog Audit 11: parses Estimated Cycle Interval from each tracking issue body. If issue age exceeds 2× estimated interval, the agent is likely frozen. The 2× threshold accounts for natural variance. (Section 9.11.2) Staleness detection using the interval

Category F — Human Interaction and Escalation

22.22 R-22: Self-Improvement and Agent Evolution

Goal: The agent system identifies its own weaknesses and proposes improvements to agent definitions, with human approval before any changes are applied.

Redundancy Depth: Double

Layer Agent Role Detection Source Notes
1 (Proactive Analysis) Agent Evolution Seven analysis steps per cycle: gather performance data, identify patterns (prompt improvements, workflow fixes, config adjustments, model tier adjustments, coordination improvements, capability gaps), filter already-proposed patterns, create proposal issues, implement approved proposals, monitor improvement PRs. (Section 9.4) Tracking issues, PR comments, failure patterns Two-step workflow: proposal issue first, implementation PR only after approval
2 (Problem Detection) System Watchdog Deep session introspection detects misbehavior patterns (forbidden API flags, policy violations, stuck agents, infinite loops). Creates needs-feedback issues for systemic problems requiring agent definition changes. (Section 9.11.2) Session message analysis Provides evidence that triggers Agent Evolution proposals
3 (Human Feedback) Human Liaison Incorporates human feedback about agent behavior. Feedback Incorporation Protocol ensures changes to ticket nature are captured. (Section 9.3) Human comments and reviews Channels human observations into the improvement pipeline

Redundancy pattern: Agent Evolution proactively analyzes failure patterns (analytical). Watchdog independently detects behavioral problems (observational). Human Liaison channels human feedback (experiential). All three feed into the same improvement pipeline with mandatory human approval.


22.23 R-23: Security and Credential Management

Goal: Credentials are never exposed in logs, comments, or temporary files. Dual bot accounts maintain proper separation. No agent exceeds its security scope.

Redundancy Depth: Double

Layer Agent Role Enforcement Notes
1 (Protocol) Shared Credential Security module Seven mandatory rules: no credential logging, no credentials in prompts, no credentials in Forgejo comments, no credentials in temp files (except cookies), no partial exposure, no defaults, validate early. (Section 13.2) Built into every agent's startup Defines the security invariants
2 (Permission Enforcement) Every agent's permission block Bash URL blocking prevents label creation API access. Task permissions restrict subagent access. Edit permissions prevent unauthorized file modification. (Section 2.3) OpenCode permission system Structural enforcement — agents literally cannot call forbidden tools
3 (Behavioral Audit) System Watchdog Audit 12/13: session spot-checks for forbidden patterns (force_merge, direct push to master, type: ignore). Deep introspection analyzes ALL supervisor sessions for misbehavior. (Section 9.11.2) Active monitoring of agent behavior Catches violations that structural enforcement misses
4 (Account Separation) Dual-Account Architecture Primary bot account (HAL9000) for implementation; separate reviewer account for PR reviews. MCP tools cannot override authentication per-call, so reviewer uses curl with FORGEJO_REVIEWER_PAT. (Section 6.17) Separate Forgejo accounts Enables formal APPROVED reviews on bot-created PRs

Redundancy pattern: Credential Security defines rules (policy). Permission blocks enforce structurally (prevention). Watchdog audits behavior (detection). Dual accounts maintain separation (isolation).


Additional Responsibilities: Category A — Development Lifecycle

22.65 R-65: Specification PR Monitoring and Lifecycle

Goal: Specification PRs created by the Architecture Supervisor must be tracked through human review, rebased when stale, and their outcomes (merge/reject) propagated to dependent work.

Redundancy Depth: Double

Layer Agent Role Specific Actions
1 (Monitoring) Product Builder Tracks pending spec PRs; checks periodically; if merged → reloads spec via ref-reader; if stale (>24h no activity) → rebases; if closed without merge → notes as rejected and creates follow-up issue; posts reminder comments. (Section 21.14) Staleness detection, rebase, outcome propagation
2 (Rebase) Spec Evolution Keeps own spec PRs up to date via rebase when master advances; force-pushes, preserves needs feedback label, posts rebase comment. (Section 9.6) Self-rebase of spec PRs

22.66 R-66: Finding Validation Gate Before Issue Filing

Goal: Agents that file issues (Bug Hunt, Test Infra, UAT) must validate every finding through a multi-check gate to prevent false positives, duplicate issues, and noise in the backlog.

Redundancy Depth: Triple (each filing agent has own gate)

Agent Validation Gate Specific Checks
Bug Hunt Pool 5-check gate: (1) actual code evidence (file/function/line), (2) verify environment assumptions, (3) actionable finding, (4) verified against actual codebase, (5) severity matches evidence. Never files infrastructure failures as product bugs. (Section 21.8) Evidence, environment, actionability, freshness, severity
Test Infra Pool 5-step dedup: (1) keyword search 2-3 nouns, (2) cross-area search, (3) include closed issues, (4) ### Duplicate Check section in every issue body, (5) if uncertain, don't file. (Section 8.7.3) Keyword, cross-area, closed, proof, uncertainty
UAT Test Pool Open PR awareness: checks if an open PR already addresses the gap; if so, doesn't file. Worker coordination via comments to avoid duplicate testing. (Section 8.5) PR awareness, worker coordination

22.67 R-67: Product Completion Verification

Goal: The autonomous system must know when the product is DONE. A single binary decision (COMPLETE or INCOMPLETE) based on a rigorous 10-point checklist. This is the ONLY mechanism that can cause the Product Builder to exit its monitoring loop.

Redundancy Depth: Single (invoked by Product Builder)

# Verification Point Check Method Failure Creates
1 All milestones complete Query Forgejo API for open milestones List of incomplete milestones
2 No open issues (verified/in-progress/paused) Query by State labels List of unfinished issues
3 No open/unmerged PRs Query open PRs List of orphaned PRs
4 Full nox test suite passes Run nox all sessions in isolated clone Failing test details
5 Coverage ≥97% nox -s coverage_report Coverage gap details
6 Every spec requirement has test coverage Cross-reference spec vs test suite Uncovered requirements
7 Documentation complete Check README, API docs, architecture docs Missing doc list
8 No TODO/FIXME/HACK/XXX markers Grep codebase Marker locations
9 No Blocked label issues Query Forgejo Blocked issue list
10 No stale feature branches Query branches not merged to master Stale branch list

Decision: ALL 10 pass → COMPLETE (Product Builder exits to Phase D). ANY fail → INCOMPLETE with specific gap list and actionable remediations (Product Builder continues Phase C).


22.68 R-68: Epic and Legendary Closure Evaluation

Goal: When all child issues of an Epic are closed (or all child Epics of a Legendary are closed), evaluate whether the parent should be closed based on acceptance criteria fulfillment.

Redundancy Depth: Double

Layer Agent Role Specific Actions
1 (Evaluation) Epic Planner Phase 2: finds open Epics where all children closed (minimum 2 children required). Evaluates acceptance criteria. Closes with completion comment. Same for Legendaries with all child Epics closed. (Section 9.2) Acceptance criteria evaluation, closure
2 (Detection) Backlog Groomer Pass 12-13: detects Epics/Legendaries where all children closed but parent still open. Creates missing children or flags for closure. (Section 9.7) Gap detection and remediation

22.69 R-69: Orphaned Issue and Epic Remediation

Goal: Every issue must have a parent Epic and every Epic must have a parent Legendary. Orphans must be automatically linked to appropriate parents.

Redundancy Depth: Triple

Layer Agent Role Specific Actions
1 (Enforcement) Epic Planner Phase 1: scans ALL open non-Epic/non-Legendary issues for missing parent dependency. Finds suitable existing Epic (scope similarity) or creates new one. Creates blocks link. Same for orphan Epics → Legendary. Validates ALL dependency directions and fixes reversed ones. (Section 9.2) Orphan detection, parent assignment, direction fixing
2 (Detection) Backlog Groomer Pass 2: flags orphan issues with no parent Epic. (Section 9.7) Orphan flagging
3 (Audit) System Watchdog Audit 7/8: verifies orphan counts and hierarchy integrity. (Section 9.11.2) Hierarchy auditing

Additional Responsibilities: Category B — Quality Assurance

22.70 R-70: TDD Workflow Awareness in Bug Reports

Goal: Every bug report must include a TDD note explaining that after verification, a Type/Testing issue will be created with @tdd_issue, @tdd_issue_<N>, and @tdd_expected_fail tags to prove the bug exists before fixing it.

Redundancy Depth: Double

Layer Agent Role Specific Actions
1 (Bug Filing) Bug Hunt Pool Includes TDD Note in every bug report body. (Section 8.6) TDD note in bug body
2 (TDD Execution) Implementation Worker Before implementing bug fix: searches features/ and robot/ for existing @tdd_issue_N tests. After fix: removes @tdd_expected_fail from all matching tests. (Section 6.13) Tag search and cleanup

22.71 R-71: Never-Disable-Checks Safety Constraint

Goal: No agent may ever disable, weaken, or reduce any quality check. Coverage thresholds, type checking, linting, security scanning, and test frameworks must never be downgraded.

Redundancy Depth: Triple

Layer Agent Role Specific Prohibitions
1 (Self-constraint) Test Infrastructure Pool Hard constraint in system prompt: "Never disable coverage thresholds, type checking, linting, security scanning. Never reduce coverage below 97%. Never remove CI steps. Never bypass nox." (Section 8.7) Self-prohibition
2 (Review) PR Reviewer Reviews for: removal of test cases, lowered coverage thresholds, added # type: ignore, weakened CI pipeline. (Section 12.1.2) Detection in review
3 (Audit) System Watchdog Session spot-checks for type: ignore, coverage reduction commands, CI step removal. (Section 9.11.2) Behavioral audit

Additional Responsibilities: Category C — Ticket Hygiene

22.72 R-72: Stale PR Detection and Remediation

Goal: PRs that have gone stale (no milestone, duplicated, targeting completed issues, or open >72h with no review activity) must be detected and flagged.

Redundancy Depth: Double

Layer Agent Role Specific Checks
1 (Detection) Backlog Groomer Pass 17 (every 3 cycles): detects PRs with no milestone, duplicate PRs (same branch or same linked issue), PRs targeting completed/wont-do issues, PRs open >72h with no review activity. (Section 9.7) Four staleness patterns
2 (Pipeline) System Watchdog Audit 5: detects PRs open >24h with no reviews, approved PRs not merged >6h, PRs with CI failing >2h. (Section 9.11.2) Three pipeline health checks

Additional Responsibilities: Category D — Architecture

22.73 R-73: Spec Change Classification and Two-Step Proposal

Goal: Specification changes must be classified by impact (initial/major/minor) and major changes must go through a two-step human-approved workflow: proposal issue first, implementation PR only after approval.

Redundancy Depth: Double

Layer Agent Role Specific Actions
1 (Architecture) Architecture Supervisor Classifies changes: Initial (no prior spec) → commit directly. Major (new modules, changed interfaces) → create branch spec/architecture-<desc>, PR with needs feedback. Minor (typos, formatting) → commit directly. (Section 9.1) Classification + needs-feedback PR
2 (Spec Evolution) Spec Evolution Two-step workflow: Step 1: create PROPOSAL ISSUE with needs feedback, Type/Task, State/Unverified. Step 2: only after approval (label removed, State/Verified added, or approval comment), create branch and PR. Tracks rejected proposals in rejected_proposals set. (Section 9.6) Proposal → Approval → PR pipeline

22.74 R-74: SHA-Based Idle Detection for Scanners

Goal: Agents that scan the codebase (Architecture Guard, Spec Evolution) should not waste cycles re-scanning unchanged code. Skip scanning when master SHA is unchanged since last scan.

Redundancy Depth: Single (per agent)

Agent Mechanism Idle Behavior
Architecture Guard Compares current master SHA with last_known_sha. If unchanged, increments idle counter and sleeps without scanning. Only scans when new code appears. (Section 9.5) Sleep on unchanged SHA
Spec Evolution Compares master SHA; proactive deep scan every 5th idle cycle (~75 min) even without new merges. (Section 9.6) Sleep + periodic deep scan

Additional Responsibilities: Category E — Operational Health

22.75 R-75: Session Naming and Tag Convention

Goal: Every async session must follow the [TAG] display-name naming convention with registered tag prefixes. This enables session discovery, health monitoring, and crash recovery.

Redundancy Depth: Single (centralized)

Layer Agent Role Specific Actions
1 (Naming) Async Agent Manager Creates sessions with [TAG] display-name format. 24+ registered tag prefixes. Validates agent names against whitelist (overridable with force=true). Checks for existing sessions with same tag before launch. (Section 4.2.1) Naming enforcement, duplicate prevention
2 (Discovery) All pool supervisors, Product Builder Search for sessions by tag pattern to discover workers, adopt orphan sessions, and detect duplicates. (Section 4.2) Tag-based session discovery

22.76 R-76: Async Session Health Detection

Goal: Detect unhealthy, stuck, or dead async sessions promptly so they can be restarted without losing significant work.

Redundancy Depth: Double

Layer Agent Role Specific Actions
1 (Monitor) Async Agent Monitor Four operations: monitor (continuous), health_check (one-shot), get_messages (retrieve), restart (terminate + re-launch). Unhealthy = no messages for 10 minutes. Dead = OpenCode reports completed/errored. Auto-restart with same tag. (Section 21.20) Health detection, auto-restart
2 (Product Builder) Product Builder 60-second monitoring loop detects dead supervisor sessions; deep inspection every 5 heartbeats reads last 100 messages to detect zombies. (Section 4.3) Session liveness polling

22.77 R-77: Push Conflict Recovery Protocol

Goal: When git push is rejected (typically because another agent pushed to the same branch), recover automatically via rebase-and-retry rather than failing the operation.

Redundancy Depth: Single (shared protocol)

Step Action Fallback
1 git push --force-with-lease If rejected → Step 2
2 git pull --rebase origin <branch> then git push If rebase conflicts → Step 3
3 Resolve conflicts (prefer own changes for trivial, abort for complex) If 5 consecutive failures → Step 4
4 Delete clone entirely, reclone fresh, cherry-pick changes, retry Report failure if still failing

Consumers: Implementation Worker, PR CI Test Fixer, PR Merge Pool, Spec Evolution.


22.78 R-78: Structured Logging Protocol

Goal: All agents must use a standardized log format that enables automated analysis, cross-agent correlation, and critical error persistence.

Redundancy Depth: Single (shared module)

Component Format Purpose
Standard log [AGENT:{name}][SESSION:{id}][ACTION:{action}][LEVEL:{level}] {message} Human-readable
Structured log [STRUCTURED] + JSON payload (timestamp, agent, session, action, level, data) Machine-parseable
Auto-persistence ERROR and CRITICAL level → automatically posted as Forgejo comment Crash-survivable
Standard actions init, setup, clone, implement, test, review, merge, dispatch, monitor, cleanup Consistent naming

22.79 R-79: Performance Monitoring and Health Scoring

Goal: Track operation durations, success rates, resource usage, and system KPIs to enable adaptive timeouts and health assessment.

Redundancy Depth: Single (shared module)

Metric Category Specific Metrics Usage
Operation tracking Duration, status (success/failure/timeout), nested stack, min/max/avg Adaptive timeout = max_observed × 1.5
Resource monitoring CPU%, memory RSS MB, disk I/O (via psutil snapshots) Resource exhaustion detection
Health score Weighted average: success rates + resource scores, penalized 0.8× if >10 in-progress ops Zombie/stuck detection
System KPIs Throughput (issues/hour, PRs merged/hour), Quality (first-attempt success rate), Efficiency (avg completion time, worker utilization) System-level health

22.80 R-80: Non-Return Guarantee Enforcement

Goal: The Product Builder must NEVER return prematurely. Fourteen specific scenarios are explicitly identified as NOT valid exit conditions.

Redundancy Depth: Single (Product Builder self-constraint)

Category NOT Valid Exit Conditions
Subjective "I feel done", "The monitoring loop feels repetitive", "Context is getting large"
Transient "No immediate progress is visible", "A few supervisors have restarted", "Some issues appear stuck"
Perceived completion "Most milestones look done", "I've been running for hours", "The system seems stable"

Only 3 valid exit conditions: (1) Product Verifier returns COMPLETE, (2) User explicitly says stop, (3) Unrecoverable error (HTTP 401/403 indicating revoked credentials).


22.81 R-81: Tiered Worker Allocation Formula

Goal: Worker counts are derived from CA_MAX_PARALLEL_WORKERS (N) using a tiered formula that maximizes implementation throughput while capping discovery/fix agents.

Redundancy Depth: Single (Product Builder configuration)

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

22.82 R-82: Timeline Surgical Edit and Append-Only Protocol

Goal: Timeline updates must be surgical (change only what changed), append-only for historical sections, and follow strict formatting rules including PlantUML Gantt chart color codes.

Redundancy Depth: Single (exclusive domain)

Rule Enforcement Rationale
Append-only history NEVER modify existing schedule adherence entries; only append new Historical integrity
One entry per day If already updated today, update existing entry Prevent duplicates
Risk resolution Mark with strikethrough: ~~Risk~~ RESOLVED — reason Preserve risk visibility
Gantt colors PaleGreen=100%, LightSkyBlue=in-progress, #E8E8E8=not-started, Gold=milestones Visual consistency
Conservative data If unsure whether data changed, leave unchanged Accuracy over freshness

22.83 R-83: Issue Comment Type Formatting Standards

Goal: Issue comments from automated agents must follow one of five structured templates with consistent visual formatting, collapsible sections, and security-sanitized content.

Redundancy Depth: Single (centralized)

Comment Type Visual Indicators Use Case
progress Progress bars (█░), circular (X/Y - N%), emoji checklists () Status updates
error Red alert icons, error detail blocks, stack traces Error reports
success Green checkmarks, deliverable summaries, file tables Completion notices
analysis Collapsible <details> sections, severity tables, metrics Deep analysis
status Dashboard layout, active operations table, health indicators Periodic status

Sub-responsibilities: Git-style diff block generation, read-time estimates, auto-linking to commits/files/issues, markdown injection prevention (input sanitization), content filtering to remove sensitive info from code blocks, comment quality scoring (readability, density, visual appeal, actionability).


22.84 R-84: Checkpoint and State Persistence via Forgejo Comments

Goal: Workers must persist their phase state to Forgejo comments (not local files) so that crash recovery can determine what was completed. Checkpoints use versioned JSON format embedded in [CHECKPOINT] comments.

Redundancy Depth: Single (per worker)

Component Format Purpose
Checkpoint comment [CHECKPOINT] prefix + metadata lines + JSON code fence Phase state persistence
Version field "version": "1.0" in JSON Future migration support
Phase resume map clone_complete → phase_2, all_subtasks_complete → phase_3, commit_complete → phase_4, pr_created → phase_4_monitoring Crash recovery routing
Anti-pattern NEVER write /tmp/checkpoint.json; NEVER include file contents Forgejo-only persistence

22.85 R-85: Agent Improvement Pattern Detection

Goal: The Agent Evolution supervisor must detect specific categories of agent failure patterns and propose targeted improvements — not generic suggestions but evidence-based fixes.

Redundancy Depth: Double

Layer Agent Role Eight Pattern Categories
1 (Detection) Agent Evolution Scans tracking issues, PR comments, and failure patterns for: (1) consistent task-type failures, (2) merge failures from unchecked CI, (3) early reviewer exits, (4) context exhaustion, (5) >50% model escalation rate, (6) duplicate work, (7) missing capability gaps, (8) repeated subtask-type failures. (Section 9.4) Eight evidence-based pattern categories
2 (Trigger) System Watchdog Deep session introspection detects misbehavior (forbidden flags, policy violations, stuck loops, identical-call patterns) and creates needs-feedback issues. (Section 9.11.2) Behavioral problem detection

Six improvement types: (1) Prompt improvements, (2) Workflow fixes, (3) Config adjustments (temperature, thresholds), (4) Permission updates, (5) Architecture changes (split/merge agents), (6) Model tier adjustments. One pattern per PR. Surgical changes only.


22.86 R-86: Open PR Awareness Before Bug Filing

Goal: Before filing a bug issue for a feature gap, agents must check if an open PR already addresses the gap. Filing a bug for work already in-progress creates noise.

Redundancy Depth: Double

Layer Agent Role Specific Actions
1 (UAT) UAT Test Pool Before filing bug: search open PRs for keywords matching the feature area. If a PR exists (especially if approved/in-review), skip filing. (Section 8.5) PR keyword search before filing
2 (Bug Hunt) Bug Hunt Pool Finding validation rule 3: verify finding is actionable and not already being addressed. (Section 21.8) Actionability verification

22.87 R-87: Five-State Project Classification

Goal: On startup, the Product Builder must classify the project's current state to determine which phases to execute, avoiding redundant work.

Redundancy Depth: Single (Product Builder)

State Detection Criteria Action
Fresh No spec, no code, no issues Execute Phase A (bootstrap), B (spec), C (planning + implementation)
Bootstrapped Structure exists but no spec Execute Phase B (spec), C (planning + implementation)
Designed Spec exists, few/no issues Execute Phase C starting with planning
In Progress Spec + issues, some completed Execute Phase C starting with resume (adopt existing sessions)
Near Complete Most milestones done Execute Phase D (verification)

22.88 R-88: UAT Feature Area Retest on Code Changes

Goal: When master advances, UAT workers must identify which previously-tested feature areas are affected by the changes and retest them, rather than testing stale code.

Redundancy Depth: Single

Step Action Details
1 Detect master advance Compare current master SHA against last-tested SHA
2 Identify changed files git diff --name-only <old_sha>..<new_sha>
3 Map files to feature areas src/cleveragents/api/ → api-clients, src/cleveragents/cli/ → cli-tools, etc.
4 Invalidate tested areas Remove affected areas from tested_areas set
5 Dispatch retests Dispatch workers for invalidated areas before testing new areas

Space management: If clone grows beyond 2GB, delete and reclone fresh. Clean up generated artifacts after each test cycle.


22.89 R-89: Documentation Generation by Type

Goal: Project documentation is generated across five distinct types, each with its own source, format, and output location.

Redundancy Depth: Single (exclusive domain)

Doc Type Source Output Location Generation Method
README Project state, spec, milestones README.md Extend, never overwrite
API docs Code docstrings, type hints docs/api/ Extracted from source
Architecture Specification docs/architecture.md Derived from spec
Changelog Git history, PR descriptions CHANGELOG.md Keep a Changelog format
Module docs Per-module implementation docs/modules/ Auto-generated per module

Constraint: All documentation must be mkdocs-compatible. Must NOT modify docs/timeline.md.


22.90 R-90: Watchdog Alert Response and Dispatch

Goal: The System Watchdog must not only detect problems but dispatch appropriate one-off fix agents for immediate corrections.

Redundancy Depth: Single (Watchdog as dispatcher)

Finding Type Dispatched Agent Action Taken
Quality gate violation Quality Enforcer Repair branch protection, create CI-Blocker issues
State label mismatch (bulk) 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 (3+ attempts) (adds label) Adds needs feedback label, requests human help
Forbidden API patterns (re-launches) Terminates and re-launches offending supervisor session
Stuck in error loop (re-launches) Terminates with fresh context
No recent Forgejo activity (re-launches) Immediate session re-launch

22.91 R-91: Amend-Only Commit Protocol for CI Fixes

Goal: When fixing CI failures on existing PRs, the PR CI Test Fixer must amend the existing commit rather than creating new commits. This keeps the commit history clean and avoids "fix fix fix" commit chains.

Redundancy Depth: Single (PR CI Test Fixer exclusive)

Step Action Details
1 Identify failing CI jobs Maps 8 CI job names to artifact paths
2 Fetch CI logs Via ci-log-fetcher subagent
3 Apply fix Dispatches appropriate fixer subagent
4 Amend commit git add -A && git commit --amend --no-edit (NEVER new commits)
5 Force push git push --force-with-lease to BOTH origin and upstream
6 Verify Wait for CI checks; loop back to step 1 if still failing
7 Stuck detection After 5 attempts with same error signature, report "Stuck — need human help"

Additional Responsibilities: Category A — Development Lifecycle (Algorithmic Details)

22.93 R-93: Subtask Wave Dispatch and Parallel Conflict Resolution

Goal: Maximize implementation throughput by dispatching independent subtasks in parallel waves, with automated detection and resolution of merge conflicts between parallel outputs.

Redundancy Depth: Single

Phase Agent Specific Actions
Dependency Analysis Implementation Worker Classify each subtask by files/modules it will touch (inferred from description + spec). Build directed dependency graph. Topological sort into waves: Wave 1 = zero-dependency subtasks, Wave N = depends only on Wave N-1. Prefer parallel dispatch when dependency is uncertain.
Parallel Dispatch Implementation Worker Launch ALL subtasks in wave simultaneously via Subtask Loop. Send heartbeat before each wave. Provide enriched context (spec, issue comments, completed subtasks, wave info).
Conflict Detection Implementation Worker After wave completes: git status --porcelain + git diff --name-only --diff-filter=U. Any unmerged paths indicate conflicts between parallel subtask outputs.
Auto-Resolution Implementation Worker Prefer spec-aligned implementation. Only auto-resolve files with ≤3 conflict markers. If auto-resolution fails: git reset --hard HEAD, re-run ALL conflicting subtasks sequentially with individual commits between each.
Downstream Blocking Implementation Worker When a subtask fails: check keyword overlap and file references against future-wave subtasks. Mark blocked subtasks. Remove empty waves. Re-evaluate remaining wave plan.
Out-of-Scope Discovery Implementation Worker Small related work → add as subtask to future wave. Separate concern → create new issue via new-issue-creator with parent Epic, labels, milestone from current context.

22.94 R-94: Deep Context Gathering Before PR Fixes

Goal: Before attempting any PR fix, gather comprehensive context from 7 distinct sources to avoid repeating previous failed approaches and understand the full picture.

Redundancy Depth: Single

Step Source What Is Gathered
1 Spec Reader Specification sections relevant to the PR's module
2 docs/timeline.md Project phase and current priorities
3 PR + Issue comments FULL history (paginate to 100), filtered for reviewer feedback, fix attempts, design decisions
4 PR commit history ALL commits with SHAs, messages, timestamps, files changed, diff summaries
5 Previous fix analysis Normalize fix descriptions, count duplicates, flag approaches tried >1 time as "repeated — try different"
6 CI logs (for ci-fix) Per-failing-job logs via ci-log-fetcher; extract error signatures for dedup
7 Actual code files First 10 PR files, first 5000 chars each, for context

22.95 R-95: Fix Attempt Loop Prevention and Stuck Detection

Goal: Prevent the implementation worker from endlessly retrying the same failed fix approach. Detect stuck loops via hash-based duplicate detection and escalate to humans after 3 stuck detections.

Redundancy Depth: Double

Layer Agent Specific Actions
1 (Self-detection) Implementation Worker Per-PR attempt_history dict tracking timestamp, work_type, ci_status, has_new_reviews. is_stuck_in_loop(): if last 3 attempts have same work_type AND all ci_status=="failure" → stuck. Hash review feedback; if same hash seen before → switch to alternative approach. Compare CI error signatures between attempts; identical → increment stuck_counter; different → reset to 0.
2 (External) System Watchdog Audit 5b: independently detects PRs with 3+ failed fix attempts by scanning bot comments.

Escalation: After stuck_counter >= 3: post detailed comment (last 5 attempts, failure patterns, approaches tried), add needs feedback label, exit with "Stuck in fix loop."


22.96 R-96: PR Lifecycle Monitoring Loop

Goal: After PR creation, continuously monitor the PR through review cycles until merge or human escalation, with structured wait intervals.

Redundancy Depth: Single

Phase Wait Check Action on Trigger
Review cycle 5 min New reviews? Route to type-specific handler (R-97)
Merge check 5 min merged == true? Exit with success
Conflict check 5 min mergeable == false? Attempt rebase with stash protocol
CI check 5 min CI failing? Invoke fix_ci_failures()
Max cycles 10 cycles reached? Add needs feedback label, exit

22.97 R-97: Review Feedback Type-Based Routing

Goal: Parse review feedback into categories (code/test/docs/style) using regex patterns and route each to the appropriate specialist subagent.

Redundancy Depth: Single

Type Regex Patterns Routed To
code "please change/modify/update/fix X in Y.py", "function should X", "consider refactoring" Implementer
test "please add tests for X", "missing test coverage", "test should verify" Behave Tester or Robot Tester (keyword-based)
docs "please update documentation", "readme should", "add docstring" Direct markdown edit
style "formatting issue", "fix linting errors", "style violation" Lint Fixer
(unmatched) Implementer (general code improvement)

Post-routing: After all changes applied, run quality gates, fix failures, amend commit, force-push with lease, post acknowledgment comment listing addressed feedback.


22.98 R-98: Issue Dispatch Priority Ordering Rules

Goal: The Implementation Pool must dispatch workers in strict priority order to ensure critical work is done first and lower milestones complete before higher ones.

Redundancy Depth: Single

Priority Rule Rationale
1 (Highest) Priority/CI-Blocker issues Fixes broken CI that blocks ALL PRs
2 Type/Bug + Priority/Critical across ALL milestones Critical bugs anywhere
3 Lowest milestone number first Complete milestones in order
4 State/In Progress before State/Verified Resume work before starting new
5 Higher Priority label first (Critical > High > Medium > Low) Urgency within milestone
6 Higher MoSCoW ranking (Must > Should > Could) Strategic importance
7 Issues that unblock the most other issues Dependency graph optimization

Additional Responsibilities: Category B — Quality Assurance (Algorithmic Details)

22.99 R-99: PR Merge Seven Criteria Checklist

Goal: Before any merge attempt, ALL seven criteria must be verified. No partial checks. No assumptions.

Redundancy Depth: Single (protocol)

# Criterion Check Method Failure Action
1 Approving review exists 3-tier detection (R-54) Skip PR
2 All CI checks pass No failing, no pending Skip PR
3 No merge conflicts mergeable != false Post conflict comment
4 Branch up-to-date merge_base == base.sha Auto-rebase (R-30)
5 Not labeled "Needs Feedback" Label check Skip PR
6 Not labeled "Blocked" Label check Skip PR
7 Linked issue in correct state State/In Review Skip PR

22.100 R-100: Blocking Review Temporal Detection

Goal: A REQUEST_CHANGES review only blocks merge if it is MORE RECENT than the latest approval signal from any source. Older blocking reviews that have been superseded by approvals do not prevent merge.

Redundancy Depth: Single (shared protocol)

Step Action
1 Find latest REQUEST_CHANGES review timestamp
2 Find latest approval timestamp from ANY of: formal APPROVED review, review body containing approval keywords, issue comment containing approval keywords
3 If request_changes_timestamp > latest_approval_timestampblocking (merge prevented)
4 If latest_approval_timestamp > request_changes_timestampsuperseded (merge allowed)
5 If no REQUEST_CHANGES reviews exist → not blocking

22.101 R-101: Flaky Test 16-Pattern Detection Checklist

Goal: During code review, systematically check for 16 specific patterns that indicate non-deterministic tests. REQUEST_CHANGES immediately for any match.

Redundancy Depth: Single

Category Specific Red Flags
Unit Test time.sleep() in test code, datetime.now() without mock, random.choice()/random.randint() without seed, uuid.uuid4() in assertions, external HTTP calls without mock, threading without synchronization primitives, writes to shared filesystem paths
Integration Test Sleep-based timing instead of condition waits, shared /tmp paths between tests, random port generation without retry, hardcoded timeouts
CI Pattern Same test fails in some PRs but passes in others, timeout errors on specific tests, test order dependency (passes alone, fails in suite), different results on rerun
Cross-PR Same test failing across multiple unrelated PRs = master branch flaky test (escalate to system monitoring)

Additional Responsibilities: Category C — Ticket Hygiene (Algorithmic Details)

22.102 R-102: Merged PR Issue Closure with Dependency Cleanup

Goal: After a PR merges, clean up ALL satisfied dependency links on the linked issue before closing it. This prevents "blocked by already-merged PR" situations from keeping issues open.

Redundancy Depth: Triple

Layer Agent Specific Actions
1 (Immediate) Implementation Worker and PR Merge Pool After verified merge: transition issue to State/Completed, close issue.
2 (Dependency Cleanup) Backlog Groomer Pass 15: for each PR merged in last 24h, extract linked issues. For each still-open issue: fetch ALL dependency links. Check each: merged PR → satisfied (DELETE), closed issue → satisfied (DELETE), open blocker → unsatisfied (keep). After removing satisfied links, attempt closure. If remaining blockers exist, post diagnostic comment.
3 (Reconciliation) State Reconciler Rule 3: issues with merged PRs must be closed. Bulk-fixes any that slipped through.

22.103 R-103: Wrong-Direction Dependency Auto-Fix

Goal: Detect and fix dependencies pointing in the wrong direction. The most critical case: an issue blocking its own PR creates a merge deadlock (PR can't merge because the issue it would close is "blocking" it).

Redundancy Depth: Double

Layer Agent Specific Actions
1 (Detection & Fix) Backlog Groomer Pass 16: detects issue-blocks-PR (wrong, creates deadlock). Fixes by: DELETE wrong-direction link → POST correct direction (PR blocks issue). Also: removes satisfied dependencies on open PRs (closed/merged blockers), creates missing PR→issue links from Closes #N in PR body.
2 (Enforcement) Epic Planner Phase 1: validates ALL dependency directions. Detects issue-depends-on-epic (wrong, should be reversed) and epic-depends-on-legendary (wrong). Fixes by removing incorrect and creating correct. Posts correction comment on BOTH child and parent.

22.104 R-104: Priority Consistency Cross-Check

Goal: Detect situations where high-priority work is blocked by low-priority work, or where milestone ordering is inconsistent with priority labels.

Redundancy Depth: Double

Layer Agent Specific Actions
1 (Detection) Backlog Groomer Pass 5: flags Priority/High issues blocked by Priority/Low issues. Flags current-milestone low-priority issues while next-milestone has high-priority.
2 (Audit) System Watchdog Audit 4: verifies implementation work follows priority/milestone ordering. Detects work on later milestones while critical bugs exist in earlier ones.

Additional Responsibilities: Category E — Operational Health (Algorithmic Details)

22.110 R-110: Per-Gate Independent Tier Tracking

Goal: Each quality gate (lint, typecheck, unit_tests, integration_tests, coverage) maintains its own independent model tier, starting at Haiku. Failed gates escalate individually while passing gates stay cheap.

Redundancy Depth: Single

Component Details
Data structure quality_gate_tiers = {coverage: "haiku", lint: "haiku", typecheck: "haiku", unit_tests: "haiku", integration_tests: "haiku"}
Inner passes 5 stabilization passes per tier level. First pass: ALL gates in parallel. Subsequent passes: only re-run gates that (a) failed, or (b) passed but fixer modified files they depend on.
Escalation After 5 inner passes: escalate ONLY failing gates (haiku→codex→sonnet→opus). Passing gates stay at their tier.
Session tags AUTO-SUBTASK-{GATE}-A{attempt}-P{pass} for identification and crash recovery.
Cost optimization A simple lint fix stays at Haiku ($0.001) while a complex type error escalates to Opus ($0.15), independently.

22.111 R-111: Periodic Diagnostics at Opus Tier

Goal: When the system has been trying to implement a subtask at the highest tier (Opus) for many attempts, post detailed diagnostic comments to help humans understand what's stuck.

Redundancy Depth: Single

Trigger Content Posted
tier == opus AND attempt >= 4 AND (attempt - 4) % 3 == 0 Invokes issue-note-writer with: total attempts so far, which quality gates are still failing and with what errors, approaches already tried, current implementation state, suggested manual intervention points.

Additional Responsibilities: Category F — Human Interaction (Algorithmic Details)

22.105 R-105: Human Liaison 10-Step Monitoring Loop

Goal: The Human Liaison executes a precise 10-step monitoring loop every 2 minutes, ensuring all human activity is detected and responded to within one cycle.

Redundancy Depth: Single

Step Action Frequency
1 Poll for new human issues (State/Unverified, created by non-bot) Every cycle
1a Poll for new comments on open issues (filter out bot/claim/checkpoint) Every cycle
1b Poll for new PR reviews from humans Every cycle
1c Poll for label changes by humans Every cycle
1d Poll for newly verified issues needing planning Every cycle
2 Idle detection (if no new activity, fill with gap analysis + stale checks) Every cycle
3 Triage new issues (full triage authority) When detected
4 Respond to comments (Feedback Incorporation Protocol when needed) When detected
5 Respond to PR reviews (guidance for struggling PRs) When detected
6 Plan verified issues (ensure metadata, subtasks, DoD, parent Epic) When detected
7 Epic/Legendary gap analysis Every 10 cycles
8 Stale conversation check (4 patterns) Every 15 cycles
9 Refresh spec knowledge via ref-reader Every 20 cycles
10 Context self-management (discard tool outputs) Every 20 cycles

22.106 R-106: Closed Issue Comment Response Patterns

Goal: When humans comment on closed issues, respond appropriately without re-triaging. Four specific response patterns based on comment type.

Redundancy Depth: Single

Comment Type Response Pattern
Question Answer helpfully from context. Do NOT re-triage, modify labels, or change state.
Reopen request Refuse per CONTRIBUTING.md. Offer to create new issue instead.
Related bug report Create new Type/Bug issue via new-issue-creator, link to same parent Epic.
General feedback Acknowledge briefly. No action on closed item.

22.107 R-107: MoSCoW Decision Framework

Goal: The Project Owner applies MoSCoW labels using an 11-signal decision framework. MoSCoW assignment is exclusive to the Project Owner — no other agent may assign these labels.

Redundancy Depth: Single (exclusive authority)

Label Decision Signals
Must Have Spec says "MUST"/"required"; blocks other Must Have items; core milestone demo functionality; security fix; data integrity
Should Have Spec says "SHOULD"/"recommended"; quality improvement; performance optimization; usability improvement; non-blocking for demo
Could Have Spec says "MAY"/"optional"; polish/UX; advanced features; refactoring with no behavior change; documentation improvements

22.108 R-108: Strategic Priority Re-evaluation

Goal: Priorities are not static. The Project Owner periodically re-evaluates MoSCoW labels and milestone health as the project evolves.

Redundancy Depth: Single

Check Frequency Specific Actions
MoSCoW drift Every 10 cycles Could Have blocking Must Have → elevate to Should Have. Must Have superseded → demote. Milestone behind → defer Could Haves. Post comment on every changed issue.
Milestone health Every 10 cycles If >50% Must Haves still open AND milestone >50% through time window → post warning.
Scope health Every 10 cycles If creation_rate > closure_rate × 2 → post [SCOPE ALERT]. If total issues grew >10% since last cycle → flag for human review.
Stale high-priority Every 5 cycles State/Verified + Priority/Critical/High + >48h no activity → tag assigned developer with reminder.
Backlog review Every 5 cycles Backlog items >1 week old → evaluate for elevation or State/Wont Do.

22.109 R-109: Developer Assignment Decision Gate

Goal: Only delegate issues to specific developers when ALL four conditions are met. The system defaults to the primary bot account (HAL9000) to minimize coordination overhead.

Redundancy Depth: Single

Gate Condition Threshold
1 Expertise match > 0.7 similarity score from git history analysis
2 Capacity available Developer has < N active issues
3 Velocity impact > 1.3× faster than HAL9000 estimate
4 No blocking risks NOT: dependency conflicts, merge conflicts, critical path blocking, frequent coordination needs, shared components

Golden Rule: "If ANY doubt about coordination, defaults to HAL9000."

Five blocking scenarios that override all conditions: (1) Issue has dependencies on HAL9000's active work, (2) Issue touches files with active merge conflicts, (3) Issue is on the critical path for milestone, (4) Issue requires frequent coordination with other in-progress work, (5) Issue modifies shared components with active changes.


Additional Responsibilities: Category A continued

22.92 R-92: Proactive Specification Scan Protocol

Goal: Even without new merged PRs, the Spec Evolution supervisor must periodically perform deep module-by-module comparison of specification vs implementation to catch drift.

Redundancy Depth: Single

Layer Agent Role Specific Actions
1 Spec Evolution Every 5th idle cycle (~75 min): full module-by-module spec-vs-code comparison. Classifies discrepancies as "implementation-better" (update spec) or "implementation-deviates" (create fix issue). Must generate ≥1 proposal per scan if any discrepancy exists. If 0 proposals for 3 scans → deeper analysis. (Section 9.6) Periodic deep scan, discrepancy classification, proposal generation

Additional Responsibilities: Cross-Cutting Protocols

22.112 R-112: PR Concurrent Work Conflict Matrix

Goal: Before modifying a PR, agents must check for other agents concurrently working on the same PR and either wait or coordinate based on a defined conflict matrix.

Redundancy Depth: Single (shared protocol)

Work Type Conflicts With Resolution
code-change code-change, merge-attempt Wait 5 min, retry
merge-attempt code-change, merge-attempt, test-fix Wait 5 min, retry
test-fix code-change, merge-attempt, test-fix Wait 5 min, retry
review (nothing) Proceed immediately

15-minute stale override: If the conflicting agent has been working >15 minutes, proceed anyway (they may be stuck).


22.113 R-113: Guaranteed Resource Cleanup via CleanupManager

Goal: All acquired resources (claims, clones, temp files, cookies) must be released even when exceptions occur. Cleanup failures must not suppress the original exception.

Redundancy Depth: Universal

Resource Type Cleanup Action Guaranteed By
Work claims Post [RELEASE:<id>] comment try/finally
Clone directories rm -rf /tmp/isolated-* (with safety checks) try/finally
Temp files os.unlink() try/finally
Cookie files rm /tmp/*_cookies.txt try/finally

22.114 R-114: Startup Credential Validation Gate

Goal: Every agent must validate all required credentials exist and match expected formats at startup, BEFORE performing any work. Missing or malformed credentials halt execution immediately.

Redundancy Depth: Universal

Credential Format Regex Required By
FORGEJO_PAT ^[a-f0-9]{40}$ All agents
GIT_USER_EMAIL ^[^@]+@[^@]+\.[^@]+$ All cloning agents
GIT_USER_NAME Non-empty string All cloning agents
FORGEJO_USERNAME ^[a-zA-Z0-9_-]+$ CI log fetching agents
FORGEJO_PASSWORD ^.{8,}$ CI log fetching agents
FORGEJO_REVIEWER_PAT ^[a-f0-9]{40}$ PR Review Pool, PR Reviewer

Validation reports format: "FORGEJO_PAT: ✓ Set" or "FORGEJO_PAT: ✗ Missing" — never shows actual values.


Additional Responsibilities: Specialized Subagent Responsibilities

22.115 R-115: Issue Analyzer Structured Data Extraction

Goal: Extract and return structured data from a Forgejo issue — metadata, subtask states, DoD items, comment summaries, and dependency graph — so calling agents don't need to parse issue bodies themselves.

Redundancy Depth: Single (subagent)

Output Field Extraction Method
Metadata Parse ## Metadata section: Branch, Commit Message, milestone, type, priority, MoSCoW, assignee, parent Epic
Subtasks Parse ## Subtasks section: preserve order, extract checkbox state ([x] vs [ ]), strip formatting
Definition of Done Parse ## Definition of Done section: list of criteria
Comment summaries Read ALL comments (paginated), extract who/when/key-info, filter bot noise
Dependency graph Query Forgejo dependency API: blocking and blocked-by with current issue state
Missing sections Report explicitly rather than guessing

22.116 R-116: Subtask Checker Fuzzy Match Checkbox Toggle

Goal: Match completed subtask descriptions (which may be paraphrased) to the closest subtask in the issue body and toggle its checkbox, without modifying any other content.

Redundancy Depth: Single (subagent)

Rule Enforcement
Matching is content-similarity, NOT exact string match Handles paraphrased descriptions
ONLY modify [ ][x] Never uncheck, never change text
Preserve ALL other formatting, whitespace, content Issue body is not reformatted
Skip already-checked subtasks Idempotent operation
Report unmatched descriptions Caller can investigate

22.117 R-117: Issue Note Writer Logical Reference Protocol

Goal: Implementation notes posted to issues must reference code by logical location (module path, class, method), NEVER by line number, and must include the git commit hash for traceability.

Redundancy Depth: Single (subagent)

Mandatory Section Content
Implementation summary What was done and why
Design decisions Chosen approach + rejected alternatives
Discoveries/assumptions Found during implementation
Code locations Module.class.method format (NEVER file:line)
Workarounds/deviations From original plan, with justification
Test results Before/after coverage numbers
Risk mitigations Applied or needed

22.118 R-118: PR Status Analyzer 5-Dimension Framework

Goal: Provide deep PR health assessment across five dimensions with structured output including blocking issues and fix recommendations.

Redundancy Depth: Single (subagent)

Dimension What It Checks Depth Levels
Basic info Open/draft/closed, title, linked issue All levels
Merge conflicts Conflict detection, complexity rating (trivial/moderate/complex) Standard+
CI/CD status Check categorization, optional log fetching via ci-log-fetcher Standard+
Review status Approval state against requirements Standard+
Branch status Ahead/behind counts vs base Standard+

Three depth levels: quick (basic + CI only), standard (all 5 dimensions), comprehensive (all 5 + log fetching + delta comparison).


22.119 R-119: Difficulty Evaluator 5-Criteria Assessment

Goal: Before implementation, assess subtask difficulty across five axes to recommend the cheapest viable starting model tier, saving cost on simple tasks while ensuring complex tasks get adequate reasoning power.

Redundancy Depth: Single (pre-gate)

Criterion Simple Moderate Complex Very Complex
Scope 1-2 files 3-5 files 5-10 files 10+ files
Algorithmic CRUD, simple logic Moderate algorithms Complex algorithms, types Concurrency, distributed
Novelty Extending patterns New within patterns New architecture Novel approach
Integration Internal only 1-2 interfaces Multiple interfaces System-wide
Ambiguity Clear requirements Some interpretation Significant gaps Major unknowns

Conservative bias: When uncertain → recommend LOWER tier. very_complex should be RARE. Escalation handles under-estimation automatically; over-estimation wastes money with no recovery.


22.120 R-120: Milestone Reviewer Holistic Integration Review

Goal: After all issues in a milestone are merged, review the INTEGRATED codebase for cross-issue problems that per-PR reviews cannot catch.

Redundancy Depth: Single (post-milestone)

Review Area What It Catches
Integration gaps Missing glue code between components from different issues
API consistency Naming, parameter ordering, error handling inconsistencies across public API
Specification coverage Spec requirements without corresponding implementation or tests
Test quality Integration test gaps between modules; trivial/meaningless tests
Error handling coherence Inconsistent error propagation from module boundaries to top level
Performance O(n²) patterns, unbounded queries, resource leaks introduced across milestone
Documentation Undocumented new public APIs
Technical debt TODO/FIXME/HACK introduced; dead code; orphaned files

Assessment: PASS (all clean), PASS WITH ISSUES (tests pass but minor gaps → issues created), FAIL (tests fail, critical integration gaps, significant spec unmet).


Additional Responsibilities: Product Builder Lifecycle Gates

22.121 R-121: Phase A Bootstrap Skip Condition

Goal: Skip the bootstrap phase entirely when the project already has its foundational structure, avoiding redundant work.

Redundancy Depth: Single

Detection All FOUR must exist Action if Missing
pyproject.toml Build configuration Invoke project-bootstrapper
noxfile.py Task runner config Invoke project-bootstrapper
.forgejo/workflows/ CI pipeline Invoke project-bootstrapper
CONTRIBUTING.md Development standards Invoke project-bootstrapper

If all four exist → skip Phase A entirely, proceed to Phase C.


22.122 R-122: prompt_async Mandatory for Supervisor Launch

Goal: Supervisors must be launched via prompt_async (fire-and-forget), NEVER via the Task tool. The Task tool blocks the caller until the subagent completes, and since supervisors run indefinitely, this would block the Product Builder forever.

Redundancy Depth: Single (architectural constraint)

Method Behavior Use For
prompt_async (via Async Agent Manager) Returns 204 immediately Supervisors (run indefinitely)
Task tool Blocks until subagent returns One-shot subagents (return results)

22.123 R-123: All 18 Supervisors Mandatory Verification

Goal: After launching supervisors, verify ALL 18 have active session IDs. Partial launch is a CRITICAL ERROR — any missing supervisor creates a gap in system functionality.

Redundancy Depth: Single

Verification Step Action on Failure
Read /tmp/supervisor-sessions.env Recreate file
Count session entries ≥ 18 Immediately re-launch missing types
Verify each session ID active via API Re-launch dead sessions
Log tiered worker counts per pool Alert if allocation incorrect

22.124 R-124: Convergence Check Algorithm

Goal: Determine when the product is potentially complete and invoke the Product Verifier. This is the gate between "keep building" and "verify completion."

Redundancy Depth: Single

Step Check Outcome
1 (every 10 heartbeats) Query Forgejo for open issues in target milestones If open_issues > 0 → continue
2 Query Forgejo for open PRs If open_prs > 0 → continue
3 Check for pending spec PRs If pending_spec_prs > 0 → continue
4 ALL zeros Invoke Product Verifier (one-shot via Task tool)
5a Verifier returns COMPLETE Proceed to Phase D (final report + exit)
5b Verifier returns INCOMPLETE Verifier creates issues for gaps; supervisors discover them; continue Phase C

22.125 R-125: Product Builder Never Edits or Merges Directly

Goal: The Product Builder is a process supervisor (like systemd), not a worker. Even when everything is down, it must not do the work itself — it must re-launch the appropriate supervisor instead.

Redundancy Depth: Single (behavioral prohibition)

Forbidden Action Required Alternative
Implement an issue Re-launch Implementation Pool
Edit code directly Delegate to Implementation Worker
Create a PR Delegate to PR Creator via worker
Merge a PR Re-launch PR Merge Pool
Review a PR Re-launch PR Review Pool
Fix CI Re-launch PR Fix Pool

22.126 R-126: No Duplicate Supervisor Instances

Goal: Each supervisor type gets exactly ONE instance. Launching duplicates causes work duplication, coordination failures, and tracking issue conflicts.

Redundancy Depth: Double

Layer Agent Mechanism
1 (Prevention) Product Builder Tracks active sessions by type. Checks for existing session with matching tag before launch. Skips launch for already-running types.
2 (Detection) System Watchdog Audit 6: checks that ALL 16 expected supervisors are running and reports missing/duplicate ones.

Additional Responsibilities: Section 6 Universal Constraints

22.127 R-127: Label Creation Prohibition Enforcement

Goal: No agent may ever create new labels. All labels exist at the Forgejo organization level and were pre-configured during project bootstrapping. This is enforced through three independent mechanisms.

Redundancy Depth: Triple

Layer Mechanism Scope
1 (Permission Denial) Every agent's permission block explicitly denies forgejo_create_label, forgejo_create_org_label, forgejo_create_repo_label 79 agent definitions
2 (Bash URL Blocking) Every agent's bash permissions deny *api/v1/orgs/*/labels* and *api/v1/repos/*/labels* patterns All bash-enabled agents
3 (Delegation) Agents that need to apply labels must delegate to Forgejo Label Manager, which itself cannot create labels but can apply existing ones All label-applying agents

22.128 R-128: Valid State Transition Matrix Enforcement

Goal: Issue state transitions must follow the defined state machine. Invalid transitions (e.g., directly from State/Unverified to State/In Review without going through State/Verified and State/In Progress) are prevented.

Redundancy Depth: Double

From State Valid Transitions To
State/Unverified State/Verified, State/Wont Do
State/Verified State/In Progress
State/In Progress State/Paused (requires Blocked label), State/In Review (requires open PR)
State/Paused State/In Progress (requires blocker resolved)
State/In Review State/Completed (requires PR merged)
Any State/Wont Do, State/Completed (maintainer decision)
Layer Agent Enforcement
1 Issue State Updater Validates preconditions before each transition. Rejects invalid transitions.
2 Backlog Groomer Pass 4/9: detects issues in impossible states and corrects them.

22.129 R-129: Priority Ordering Rules for Milestone Work

Goal: Implementation work must follow strict priority ordering: lower milestones complete before higher ones, and within a milestone, critical work comes first. No agent should work on Milestone 3 while Milestone 1 has open critical bugs.

Redundancy Depth: Double

Layer Agent Enforcement
1 (Dispatch) Implementation Pool Issue dispatch ordering (R-98): CI-Blocker → Critical bugs across all milestones → lowest milestone → In Progress → Priority → MoSCoW → unblock score.
2 (Audit) System Watchdog Audit 4: verifies work follows priority/milestone ordering; detects later-milestone work while critical bugs exist in earlier milestones.

22.130 R-130: Standard Issue Body Format Enforcement

Goal: Every issue must follow the CONTRIBUTING.md body format with three mandatory sections: ## Metadata (Branch, Commit Message, Parent Epic), ## Subtasks (at least one - [ ] checkbox), and ## Definition of Done.

Redundancy Depth: Double

Layer Agent Enforcement
1 (At Creation) New Issue Creator, Epic Planner Creates issues with compliant body format. Standard DoD includes: all subtasks complete, unit tests ≥97%, integration tests, quality gates pass, PR created and approved, PR merged.
2 (Verification) Backlog Groomer Pass 11: checks for ## Metadata, ## Subtasks, ## Definition of Done headings. Posts comment listing missing sections.

22.131 R-131: Standard PR Body Format Enforcement

Goal: Every PR must follow the standard format with Summary, Changes, Design Decisions, Testing, Modules Affected, Related Issues sections, plus closing keywords (Closes #N) and a compliance checklist.

Redundancy Depth: Double

Layer Agent Enforcement
1 (At Creation) PR Description Writer Generates PR body with standard sections. Includes closing keywords for linked issues.
2 (Review) PR Reviewer Checks CONTRIBUTING.md compliance including PR metadata (closing keywords, type label, milestone, title format).

22.132 R-132: Subagent Specialization Principle

Goal: Functionality needed by multiple agents MUST be centralized in a single subagent. Duplicated logic across agent definitions is a code smell requiring refactoring.

Redundancy Depth: Universal (architectural principle)

Centralized Function Subagent Why Not Duplicated
Label operations Forgejo Label Manager Name-to-ID mapping, conflict detection
Tracking issue lifecycle Automation Tracking Manager Close-all protocol, cycle numbering
Cycle interval calculation ATM's CREATE_TRACKING_ISSUE Rolling average formula
Announcement review cycle ATM's CYCLE_ANNOUNCEMENT_REVIEW Combined read + review + close
Merge verification Shared Merge Safety 7-rule protocol

22.133 R-133: Announcement Consumption Priority Protocol

Goal: Each agent reads announcements from specific other agents at specific minimum priority levels and depths, preventing low-priority noise from disrupting high-priority work while ensuring critical events are seen.

Redundancy Depth: Universal

Consumer Reads From Min Priority Read Depth
System Watchdog All agents All Full (body + comments)
Product Builder All agents Medium+ Full
Human Liaison All agents High+ Full
Implementation Pool Watchdog, Liaison, Groomer High+ Summary only
PR Review Pool Watchdog, Liaison Critical only Summary only
PR Merge Pool Watchdog Critical only Summary only (pauses merging if critical)
All other supervisors Watchdog Critical only Title + priority label only

22.134 R-134: Internet Access Restriction

Goal: No autonomous agent may access the internet. Only three user-facing primary agents (build, build-opencode, plan) have webfetch: allow. All autonomous agents work entirely from local files, the Forgejo API, and the OpenCode Server API.

Redundancy Depth: Single (permission enforcement)

Agent Category Internet Access Rationale
User-facing (3 agents) webfetch: allow Human-invoked, may need external docs
All autonomous (76+ agents) webfetch: deny (or not granted) Security: autonomous agents must never fetch external resources, download dependencies, or access external services

Category H — Project Standards and CONTRIBUTING.md Compliance

22.135 R-135: File Organization Enforcement

Goal: All source code, tests, and documentation must follow the project's directory structure. No agent may place files in incorrect locations.

Redundancy Depth: Triple

Location Contents Rule
src/cleveragents/ All production source code Modules here, nowhere else
features/ Unit tests (Behave/BDD/Gherkin) One .feature per capability
features/mocks/ Mock implementations All mocks here, never inline
features/steps/ Step definitions Step implementations
robot/ Integration tests (Robot Framework) No mocking allowed
benchmarks/ Performance benchmarks (ASV) Airspeed Velocity format
docs/ Documentation (mkdocs) Spec, API, architecture, timeline
.opencode/agents/ Agent definitions only Agent Evolution exclusive
Layer Agent Enforcement
1 (Implementation) Implementation Worker Delegates to specialist testers that know their target directories
2 (Review) PR Reviewer Checks files are in correct directories per CONTRIBUTING.md
3 (Hygiene) Backlog Groomer Pass 11: checks issue body metadata for correct branch/path references

22.136 R-136: Static Typing and type: ignore Prohibition

Goal: All Python code must be fully statically typed. The # type: ignore comment is absolutely prohibited — Pyright must pass without suppression.

Redundancy Depth: Triple

Layer Agent Enforcement
1 (Fixing) Typecheck Fixer Runs nox -e typecheck (Pyright) and fixes errors. Explicit instruction: "Never uses # type: ignore." Must resolve the actual type error.
2 (Review) PR Reviewer CONTRIBUTING.md compliance check: scans diff for type: ignore strings, requests changes if found.
3 (Audit) System Watchdog Audit 12/13: session spot-checks for type: ignore in tool outputs; flags as policy violation.

22.137 R-137: Maximum File Size Enforcement (500 Lines)

Goal: No source file may exceed 500 lines. Files approaching this limit must be refactored into smaller modules.

Redundancy Depth: Double

Layer Agent Enforcement
1 (Implementation) Implementation Worker Rule in system prompt: "Maximum 500 lines per file." Workers must split files that grow beyond this limit.
2 (Review) PR Reviewer Checks file sizes in PR diff; requests changes for files exceeding 500 lines.

22.138 R-138: Testing Framework Selection Rules

Goal: The correct testing framework must be used for each test level. Using the wrong framework (e.g., xUnit for unit tests, or mocking in integration tests) is a violation.

Redundancy Depth: Triple

Test Level Required Framework Key Rules
Unit tests Behave (BDD/Gherkin) Given/When/Then scenarios in features/. Never xUnit (pytest, unittest). Mocks in features/mocks/.
Integration tests Robot Framework Keyword-driven in robot/. NO mocking allowed — tests must use real component interactions.
Performance ASV (Airspeed Velocity) Benchmarks in benchmarks/. time_* and mem_* methods.
Layer Agent Enforcement
1 (Creation) Behave Tester, Robot Tester, ASV Benchmarker Each tester writes in its designated framework only
2 (Review) PR Reviewer Checks that new tests use correct framework; rejects xUnit-style tests
3 (Infrastructure) Test Infrastructure Pool Verifies all three test levels exist per module; never weakens framework requirements

22.139 R-139: Coverage Threshold Enforcement (97%)

Goal: Test coverage must be ≥97% at all times. No merge, no PR approval, and no milestone completion can proceed below this threshold.

Redundancy Depth: Triple

Layer Agent Enforcement Point
1 (Pre-PR) Coverage Improver Writes additional tests until coverage ≥97% before PR creation
2 (Merge Gate) PR Merge Pool CI check includes coverage; failing coverage blocks merge
3 (Audit) System Watchdog Audit 1: verifies recent master commits have passing coverage

22.140 R-140: Conventional Changelog Commit Format

Goal: Every commit message must follow Conventional Changelog format enforced by Commitizen: type(scope): description where type is feat/fix/refactor/test/docs/chore/ci/style/perf.

Redundancy Depth: Double

Layer Agent Enforcement
1 (Formatting) Commit Message Formatter Constructs three-part message: exact type(scope): description from issue Metadata, implementation body, ISSUES CLOSED: #N footer
2 (Review) PR Reviewer Checks commit message format in PR; requests changes for non-conventional messages

22.141 R-141: Supervisor Mandatory Startup Sequence

Goal: Every supervisor must execute a strict 4-step startup sequence. Deviating from this order causes data loss (reading state after creating a new tracking issue reads the empty new issue instead of the previous session's state).

Redundancy Depth: Universal

Step Action Why This Order
1 READ_TRACKING_STATE (recover from previous session) MUST be first — CREATE_TRACKING_ISSUE closes all old issues, destroying recoverable state
2 Parse recovered state (extract work items, health indicators, cycle number) Uses data from Step 1
3 CREATE_TRACKING_ISSUE (closes all old status issues, creates new one) Safe to close old issues because state was already recovered
4 Begin main processing loop using recovered state to inform first cycle Longer offline = more aggressive first-cycle scanning

22.142 R-142: Startup State Recovery Before Tracking Creation

Goal: When a supervisor starts or restarts, it must read its most recent tracking issue to recover state BEFORE creating a new one. Creating first destroys the recoverable state.

Redundancy Depth: Universal

Agent Category Recovery Behavior
Implementation Pool Parse worker table for PR/issue numbers. Check each on Forgejo. Resume in-progress work before scanning for new.
PR Review Pool Parse recently-reviewed PR list. Check if those PRs still need 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 active sessions to detect which need re-launch.
All others Parse cycle number and summary. Longer offline = more aggressive scanning.

22.143 R-143: Dual Status Issue Cleanup (Defense-in-Depth)

Goal: At most one open status tracking issue per agent prefix at any time. Two independent cleanup mechanisms ensure this invariant even under crash conditions.

Redundancy Depth: Double

Layer Agent Mechanism When
1 (Primary: agent-side) Every supervisor via CREATE_TRACKING_ISSUE Closes ALL open status issues with same prefix before creating new one. Searches with state: "open", no pagination limits. Posts "Superseded by Cycle N." Every cycle
2 (Safety net: groomer-side) Backlog Groomer Pass 20: finds prefixes with >1 open status issue, closes all but newest. Catches: race conditions (two agents launched simultaneously), crash between create and close, Forgejo API returning success but not actually closing. Every grooming cycle

22.144 R-144: Tier Selector Pure Pass-Through Constraint

Goal: The four tier selector agents (tier-haiku, tier-codex, tier-sonnet, tier-opus) must act as pure pass-through proxies that only set the model via their frontmatter. They must NOT modify, interpret, filter, summarize, or add to the context they receive.

Redundancy Depth: Single (architectural)

Tier Agent Model Set Constraint
tier-haiku anthropic/claude-haiku Must invoke requested worker_type with UNMODIFIED context
tier-codex openai/gpt-5-codex Must invoke requested worker_type with UNMODIFIED context
tier-sonnet anthropic/claude-sonnet-4-6 Must invoke requested worker_type with UNMODIFIED context
tier-opus anthropic/claude-opus-4-6 Must invoke requested worker_type with UNMODIFIED context

Why this matters: If a tier selector summarizes context, the worker receives degraded information. If it adds instructions, it overrides the worker's own specialized prompt. The tier selector's ONLY job is model selection.


22.145 Redundancy Analysis Summary

!!! info "How Deep Is the Defense?"

This section provides a statistical overview of the redundancy model across all 144 responsibilities. The system's reliability comes not from any single agent being perfect, but from multiple independent agents checking the same invariants from different perspectives.

Redundancy Depth Distribution

Depth Count Percentage Meaning
Quadruple 3 2% Four independent agents check the same invariant (R-09 Label Correctness, R-10 State Lifecycle, R-16 Bug Detection)
Triple 22 15% Three independent checks (e.g., R-01 Supervisor Liveness: PB session check + PB deep inspection + Watchdog behavioral analysis)
Double 40 28% Two independent checks (e.g., R-05 Code Review: PR Reviewer quality + Implementation Reviewer correctness)
Single 55 38% One agent responsible but with crash recovery or protocol enforcement
Universal 14 10% Applies to all agents via shared modules or permission blocks (e.g., R-64 Nox Routing, R-113 Cleanup Manager, R-114 Credential Validation)
Multi-level 1 <1% Different recovery mechanism at each system level (R-21 Crash Recovery)
Single (exclusive) 9 6% Deliberately single-owner to prevent conflicting edits (e.g., R-17 Documentation/Timeline exclusive domains, R-107 MoSCoW exclusive authority)

Highest-Redundancy Responsibilities

These responsibilities have the deepest defense-in-depth, reflecting their criticality:

Responsibility Depth Agents Involved Why Critical
R-09 Quadruple Label Manager → Creating agents → Groomer → Watchdog → Reconciler Wrong labels cascade: wrong priority → wrong work order → milestone delays
R-10 Quadruple State Updater → Groomer → Watchdog → Reconciler Wrong state prevents work from progressing through the pipeline
R-16 Quadruple Bug Hunt (code) → UAT (spec) → Reviewer (per-PR) → Guard (structure) Undetected bugs reach production
R-01 Triple PB session check → PB deep inspection → Watchdog behavioral analysis Dead supervisor = entire capability gap
R-06 Triple Pre-PR gates → Post-PR CI fixer → Post-merge Watchdog audit Bad code on master breaks everything
R-12 Triple Bootstrapper sets → Merge Safety enforces → Watchdog audits → Enforcer repairs Bypassed protection = unreviewed code on master

Most Cross-Referenced Agents

These agents participate in the most responsibilities, making them the system's most critical components:

Agent Responsibility Count Role Pattern
Backlog Groomer 24 The universal safety net — verifies and auto-fixes work done by every other agent
System Watchdog 24 The universal auditor — detects violations across every system invariant
Implementation Worker 30 The universal executor — touches every phase of the implementation pipeline
PR Reviewer 12 The quality gatekeeper — checks code, tests, patterns, flaky tests, compliance
Product Builder 12 The orchestrator — manages supervisor lifecycle, convergence, and spec PRs
PR Merge Pool 12 The merge authority — verifies 7 criteria, 3-tier approval, post-merge state
Epic Planner 8 The planner — decomposes work, enforces hierarchy, manages closure
Project Owner 12 The strategist — MoSCoW, developer assignment, priority re-evaluation

Redundancy Pattern Taxonomy

The system uses five distinct redundancy patterns:

Pattern Description Example
Create → Verify → Audit → Bulk-Fix Agent creates, second verifies, third audits, fourth bulk-fixes Labels: Creator → Groomer → Watchdog → Reconciler
Self-detect → External-detect Agent detects its own problems, independent agent detects the same from outside Worker stuck detection → Watchdog struggling PR detection
Pre-action → Post-action → Post-merge Gate before, gate after, audit after merge Quality gates: Subtask Loop → CI Fixer → Watchdog
Primary → Backup → Safety net Main path, fallback path, emergency recovery Merge: Merge Pool → Worker merge → Watchdog false-merge monitor
Exclusive domain Deliberately single-owner to prevent conflicts Documentation vs Timeline: separate agents, non-overlapping files

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 (removed — absorbed into implementation-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-SUP 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-13 2.13.0 Fourteenth pass (PR Merge blocking subagent migration): Changed pr-merge-pool-supervisor from async worker dispatch to blocking subagent model — it now calls pr-merge-worker via the Task tool and blocks until it finishes, instead of dispatching it as an async session via async-agent-manager. Updated 8 spec sections: Section 1.3 (added Blocking tier to worker allocation table, updated capacity examples to show ×11 singleton workers instead of ×12, adjusted session totals); Section 4.2.1 (struck through AUTO-PRMRG-<N> entry in session tag table since no async worker sessions exist); Section 4.3.2 (added PR Merge exception to worker health check); Section 5.5.1 (added exception note for AUTO-PRMRG-<N>); Section 8.3.1 (documented blocking subagent model in purpose); Section 8.3.5 (rewrote pre-merge rebase protocol to describe worker-based rebase with CI polling); Section 21.2 (updated subagent list: replaced async-agent-manager with pr-merge-worker, documented dispatch model difference); Section 22.30 R-30 (updated rebase layer 2 to reflect blocking worker). Updated 6 agent definition files in prior commits: pr-merge-pool-supervisor.md (replaced async-agent-manager: allow with pr-merge-worker: allow in task permissions, rewrote all dispatch language to blocking subagent), pr-merge-worker.md (updated description and intro), agent-type-info.md (updated PR Merge Pool entry and worker table), agent-prefix-info.md (changed worker tag pattern to "none", added exception paragraph), product-builder.md (added worker health check exception for PR Merge), system-watchdog-pool-supervisor.md (added supervisor health exception for PR Merge).
2026-04-12 2.12.0 Thirteenth pass: Reader experience and navigation improvements. Added 6th foundational principle to Section 1.1 ("Defense-in-Depth Redundancy") with cross-reference to Section 22. Added "How to Read This Section" tip box at top of Section 22 with 5 navigation paths (by responsibility, by agent, by category, by redundancy, by scale). Added introductory paragraphs to all 8 categories explaining scope, scale, and significance: A (50 responsibilities, core value chain), B (deepest redundancy — quadruple), C (Groomer + Watchdog strongest redundancy zone), D (bidirectional spec flow), E (invisible plumbing), F (2-minute human response), G (long-timescale governance), H (triple enforcement of standards).
2026-04-12 2.11.0 Twelfth pass: Consistency and quality audit. Fixed 3 R-items (R-41, R-77, R-79) missing from agent back-reference tables by adding them to the Universal Supervisor Responsibilities table (Section 7.9). Expanded 2 thin R-item detail sections: R-67 (Product Completion) expanded from 12 to 20 lines with full 10-point verification table showing check methods and failure outputs; R-88 (UAT Feature Retest) expanded from 12 to 17 lines with 5-step file→area mapping process. Verified: all 144 R-items have detail sections, all 144 are in category index tables, all referenced agents have back-reference tables. Zero broken cross-references.
2026-04-12 2.10.0 Eleventh pass: Added Section 7.9 (Universal Supervisor Responsibilities) — a shared baseline table of 13 responsibilities that ALL 18 supervisors inherit (R-141 Startup Sequence, R-142 State Recovery, R-20 Tracking, R-143 Dual Cleanup, R-133 Announcement Consumption, R-43 Announcement Lifecycle, R-44 Context Management, R-113 Resource Cleanup, R-114 Credential Validation, R-63 Bot Signature, R-78 Logging, R-127 No Label Creation, R-134 No Internet). Added "In addition to universal supervisor responsibilities" cross-reference notes to all 18 supervisor responsibility tables (Sections 8.1.7, 8.2.4, 8.3.6, 8.4.3, 8.5.4, 8.6.4, 8.7.4, 9.1.1, 9.2.1, 9.3.1, 9.4.1, 9.5.1, 9.6.1, 9.7.1, 9.8.1, 9.9.1, 9.10.1, 9.11.4). Expanded 4 thin agent tables: PR Fix Pool (+R-27, R-112), Documentation (+R-57, R-61), Timeline (+R-57), Agent Evolution (+R-57, R-135). Each supervisor's effective responsibility count is now its specific entries PLUS 13 universal = true total.
2026-04-12 2.9.0 Tenth pass: Final completeness pass. Added back-reference tables for the last 2 uncovered agent sections: 12.3.1 (Git and Repository Agents — Repo Isolator, Branch Setup, Git Committer, Git Commit Helper, CI Log Fetcher) and 12.4.1 (Reference and Knowledge Agents — Ref Reader, Ref Material Loader, Spec Reader, Difficulty Evaluator). Added Section 22.145 (Redundancy Analysis Summary) with: redundancy depth distribution table (Quadruple 2%, Triple 15%, Double 28%, Single 38%, Universal 10%), highest-redundancy responsibilities table (R-09/R-10/R-16 at quadruple depth), most cross-referenced agents table (Groomer 24, Watchdog 24, Worker 30), and redundancy pattern taxonomy (5 named patterns: Create→Verify→Audit→BulkFix, Self-detect→External-detect, Pre→Post→PostMerge, Primary→Backup→SafetyNet, ExclusiveDomain). Total agent back-reference tables: 29 (covering all agent sections in the specification). Final total: 144 responsibilities, 8 categories, 29 sub-categories, 29 agent tables.
2026-04-12 2.8.0 Ninth pass: Completed bidirectional cross-references by adding responsibility back-reference tables to 12 supporting agent sections that previously had none. Added tables at: 11.3.1 (Subtask Loop — 9 responsibilities), 11.4.1 (Specialized Workers — 9 workers × 2-4 responsibilities each), 12.1.3 (PR Management Agents — 5 agents with full responsibility mapping), 12.2.1 (Issue Management Agents — 6 agents), 12.5.1 (Label and Forgejo Agents — 3 agents including ATM with 5 responsibilities), 12.6.1 (Quality and Verification Agents — 5 agents), 12.7.1 (Session Management Agents — 2 agents). Total agent back-reference tables: 32 (up from 20). All 144 responsibilities now have bidirectional links: R-item → agent section AND agent section → R-item.
2026-04-12 2.7.0 Eighth pass: Added Category H (Project Standards and CONTRIBUTING.md Compliance) with 4 sub-categories (H.1 Code Standards, H.2 Testing Standards, H.3 Commit/PR Standards, H.4 Startup/Lifecycle Protocols). Added 10 new responsibilities: R-135 (File Organization — triple enforcement), R-136 (Static Typing & type:ignore Prohibition — triple enforcement), R-137 (Max 500-Line File Size — double enforcement), R-138 (Testing Framework Selection — BDD/Robot/ASV — triple enforcement), R-139 (97% Coverage Threshold — triple enforcement), R-140 (Conventional Changelog Commit Format), R-141 (Supervisor Mandatory Startup Sequence — 4-step protocol), R-142 (Startup State Recovery Before Tracking Creation — per-supervisor recovery behavior), R-143 (Dual Status Issue Cleanup — defense-in-depth), R-144 (Tier Selector Pure Pass-Through Constraint). Updated 6 agent back-reference tables (PR Review Pool +6, Implementation Worker +3, System Watchdog +2, PR Merge Pool +1, Test Infra +1). Final total: 144 responsibilities across 8 categories with 29 sub-categories.
2026-04-12 2.6.0 Seventh pass: Major organizational restructuring — added sub-category headers within all 7 categories (A.1-A.8 Planning/Implementation/Quality Gates/PR Creation/Fixing/Merging/Git/Lifecycle, B.1-B.4 CI Health/Testing/Code Quality/Bug Detection, C.1-C.6 Labels/States/Dependencies/Milestones/Format/Hygiene, D.1-D.2 Spec Lifecycle/Scanning, E.1-E.5 Supervisors/Tracking/Recovery/Protocols/Formatting, F.1-F.2 Triage/Communication, G.1-G.4 Scope/Evolution/Docs/Security). Added 8 new Section 6 universal constraint responsibilities: R-127 (Label Creation Prohibition — triple enforcement), R-128 (Valid State Transition Matrix), R-129 (Priority Ordering Rules), R-130 (Standard Issue Body Format), R-131 (Standard PR Body Format), R-132 (Subagent Specialization Principle), R-133 (Announcement Consumption Priority Protocol — per-agent triage table), R-134 (Internet Access Restriction). Updated Backlog Groomer back-references (+3). Final total: 134 responsibilities (R-01 through R-134, with R-56b), 7 categories with 25 sub-categories.
2026-04-11 2.5.0 Sixth pass: Added 15 final responsibilities (R-112 through R-126) from three gap areas. Cross-cutting protocols: R-112 (PR Concurrent Work Conflict Matrix), R-113 (Guaranteed Resource Cleanup via CleanupManager), R-114 (Startup Credential Validation Gate). Specialized subagent responsibilities: R-115 (Issue Analyzer Structured Data Extraction), R-116 (Subtask Checker Fuzzy Match Checkbox Toggle), R-117 (Issue Note Writer Logical Reference Protocol), R-118 (PR Status Analyzer 5-Dimension Framework), R-119 (Difficulty Evaluator 5-Criteria Assessment), R-120 (Milestone Reviewer Holistic Integration Review). Product Builder lifecycle gates: R-121 (Phase A Bootstrap Skip Condition), R-122 (prompt_async Mandatory for Supervisors), R-123 (All 18 Supervisors Mandatory Verification), R-124 (Convergence Check Algorithm), R-125 (PB Never Edits/Merges Directly), R-126 (No Duplicate Supervisor Instances). Updated Product Builder back-references (+7 entries). Final total: 126 responsibilities across 7 categories.
2026-04-11 2.4.0 Fifth pass: Added 19 algorithmic-detail responsibilities (R-93 through R-111): R-93 (Subtask Wave Dispatch & Parallel Conflict Resolution), R-94 (Deep Context Gathering Before PR Fixes — 7-step protocol), R-95 (Fix Attempt Loop Prevention — hash-based duplicate detection + stuck_counter), R-96 (PR Lifecycle Monitoring Loop — 10 cycles × 5 min), R-97 (Review Feedback Type-Based Routing — regex to code/test/docs/style), R-98 (Issue Dispatch 7-Level Priority Ordering), R-99 (PR Merge 7 Criteria Checklist), R-100 (Blocking Review Temporal Detection), R-101 (Flaky Test 16-Pattern Detection Checklist), R-102 (Merged PR Issue Closure with Dependency Cleanup), R-103 (Wrong-Direction Dependency Auto-Fix), R-104 (Priority Consistency Cross-Check), R-105 (Human Liaison 10-Step Monitoring Loop), R-106 (Closed Issue Comment 4 Response Patterns), R-107 (MoSCoW 11-Signal Decision Framework), R-108 (Strategic Priority Re-evaluation), R-109 (Developer Assignment 4-Condition Decision Gate), R-110 (Per-Gate Independent Tier Tracking), R-111 (Periodic Diagnostics at Opus Tier). Updated 9 agent back-reference tables. Total: 111 responsibilities across 7 categories.
2026-04-11 2.3.0 Fourth pass: Added 28 more granular responsibilities (R-65 through R-92): R-65 (Spec PR Monitoring), R-66 (Finding Validation Gate — triple redundancy across Bug Hunt/Test Infra/UAT), R-67 (Product Completion 10-Point Checklist), R-68 (Epic/Legendary Closure Evaluation), R-69 (Orphaned Issue Remediation), R-70 (TDD Workflow Awareness), R-71 (Never-Disable-Checks Constraint), R-72 (Stale PR Detection), R-73 (Spec Change Classification & Two-Step Proposal), R-74 (SHA-Based Idle Detection), R-75 (Session Naming & Tag Convention), R-76 (Async Session Health Detection), R-77 (Push Conflict Recovery), R-78 (Structured Logging Protocol), R-79 (Performance Monitoring & Health Scoring), R-80 (Non-Return Guarantee), R-81 (Tiered Worker Allocation Formula), R-82 (Timeline Surgical Edit & Append-Only), R-83 (Issue Comment Formatting Standards), R-84 (Checkpoint & State Persistence), R-85 (Agent Improvement Pattern Detection), R-86 (Open PR Awareness Before Bug Filing), R-87 (Five-State Project Classification), R-88 (UAT Feature Area Retest), R-89 (Documentation Generation by Type), R-90 (Watchdog Alert Response & Dispatch), R-91 (Amend-Only Commit Protocol), R-92 (Proactive Spec Scan). Updated 14 agent back-reference tables. Total: 92 responsibilities across 7 categories.
2026-04-11 2.2.0 Third pass: Added 16 more micro-responsibilities (R-49 through R-64): R-49 (PR Ownership Detection & Work Scoring), R-50 (Worker Session Adoption & Lifecycle), R-51 (Forgejo API Pagination & Truncation Recovery), R-52 (Dual-Account Review Authentication), R-53 (Anti-Pattern & Code Smell Detection), R-54 (Three-Tier Approval Detection), R-55 (Post-Merge State Verification), R-56 (Meaningful Change Verification), R-56b (Transient Error Classification & Retry), R-57 (Clone Isolation & Safety), R-58 (Label-Name-to-ID Resolution), R-59 (PR Description Preservation), R-60 (State Transition Precondition Enforcement), R-61 (Reference Material Caching), R-62 (Implementation Correctness Verification), R-63 (Bot Signature Standardization), R-64 (Nox Routing Enforcement). Updated 6 agent back-reference tables (IPS +3, PR Review Pool +2, PR Merge Pool +4, Implementation Worker +3, System Watchdog +2, Backlog Groomer already comprehensive). Total: 64 responsibilities across 7 categories.
2026-04-11 2.1.0 Second pass: Restructured Section 22 into 7 categories (A: Development Lifecycle, B: Quality Assurance, C: Ticket Hygiene, D: Architecture, E: Operational Health, F: Human Interaction, G: Strategic Governance). Expanded from 23 to 48 responsibilities — added 25 new granular responsibilities: R-24 (Work Claiming), R-25 (Test Writing & TDD), R-26 (PR Creation & Metadata Inheritance), R-27 (CI Log Retrieval), R-28 (Issue Closure & Post-Merge Cleanup), R-29 (Commit Formatting & Git Ops), R-30 (Branch Management & Rebase), R-31 (Progressive Model Escalation), R-32 (Master CI Emergency), R-33 (Flaky Test Detection), R-34 (Test Stability), R-35 (PR-Issue Label Sync), R-36 (Story Point Estimation), R-37 (Milestone Assignment & Scope Guard), R-38 (Issue Body & DoD Compliance), R-39 (Blocked Chain Analysis), R-40 (Spec-First Development), R-41 (Worker Dispatch & Sliding Window), R-42 (Tracking Issue Cleanup & Dedup), R-43 (Announcement Lifecycle), R-44 (Context Window Self-Management), R-45 (Cycle Interval Maintenance), R-46 (Feedback Incorporation Protocol), R-47 (Human Response Timeout Management), R-48 (Developer Expertise & Assignment). Expanded all 20 agent back-reference tables with new responsibilities.
2026-04-11 2.0.0 Added Section 22: Division of Responsibilities and Redundancy Model — initial pass with 23 system responsibilities, redundancy depth classification, per-agent role tables, cross-references; added 20 Responsibilities subsections to agent sections
2026-04-10 1.36.0 Final pass (structural integrity audit): Fixed duplicate section number (two §2.4 headings → renamed first to §2.3.1); verified all section cross-references valid (only historical reference to 20.4 in revision history); verified Appendix A model/mode data matches actual frontmatter for 10 sample agents; verified mkdocs.yml navigation entry; comprehensive stale-name sweep clean across all 79 active agents + 9 shared modules + spec body; final statistics: 3,593 lines, 21 sections, 128 subsections, 56 sub-subsections, 14 diagrams, 79 Appendix A entries
2026-04-10 1.35.0 Thirty-eighth pass (spec-wide dual-account coherence): Fixed 5 stale references in spec body: Glossary HAL9000 definition updated for dual-account, Section 6.17.2 "two-step" → "dual-account", Section 12.1.2 PR Reviewer table and description updated for dual-account review protocol with curl, Section 12.1.2 permissions rationale rewritten for MCP-deny/curl-allow, Section 19.5 Security Model rewritten from "single bot account" to dual-account with separate permission scopes; fixed stale "PR Self-Reviewer" references in pr-ci-test-fixer.md; fixed 2 remaining "Two-Step Review Protocol" → "Dual-Account Review Protocol" in spec
2026-04-10 1.34.0 Thirty-seventh pass (stale references, diagram, and count fixes): Fixed stale "PR Self-Reviewer" references in pr-ci-test-fixer.md (3 occurrences); fixed Section 6.17.2 diagram (removed 2 orphaned old nodes from single-account era, updated node labels to show curl+FORGEJO_REVIEWER_PAT); fixed Section 6.17.2 step descriptions to reference curl instead of MCP tools; fixed edit:deny count from 41 to 42 (forgejo-signature-appender was added in pass 7); added missing --- separator after diagram
2026-04-10 1.33.0 Thirty-sixth pass (review template and credential completeness): Fixed 3 agent definitions: pr-reviewer.md (renamed from "PR Self-Reviewer" to "PR Reviewer", rewrote both APPROVE and REQUEST_CHANGES step templates to use curl instead of denied MCP tools, corrected step ordering to formal-review-first/backup-comment-second), pr-review-pool-supervisor.md (added all 3 reviewer credentials to stuck-PR prompt which was missing them entirely), spec Section 6.17 updated to include FORGEJO_REVIEWER_PASSWORD in introduction
2026-04-10 1.32.0 Thirty-fifth pass (MCP token limitation and curl workaround): Added Section 6.17.0 documenting the fundamental MCP token constraint — MCP tools authenticate as a single server-level token, cannot be overridden per-call; PR Reviewer must use curl for write operations; rewrote Section 21.22 from "Total Bash Lockdown" to "Restricted Bash with curl"; fixed 4 agent definitions: pr-reviewer.md (added curl *: allow, denied forgejo_create_pull_review and forgejo_create_issue_comment MCP tools, added curl-based review/comment API call patterns with FORGEJO_REVIEWER_PAT), pr-review-pool-supervisor.md (passes all 3 reviewer credentials including PASSWORD, documents READ-via-MCP/WRITE-via-curl split), product-builder.md (passes FORGEJO_REVIEWER_PASSWORD when launching review pool), shared/credential_security.md (already had FORGEJO_REVIEWER_PASSWORD from previous pass)
2026-04-10 1.31.0 Thirty-fourth pass (dual-account completeness audit): Added missing FORGEJO_REVIEWER_PASSWORD to spec Section 6.17 env table and Appendix C (needed by ci-log-fetcher when invoked by PR Reviewer); removed ALL stale "self-approval"/"shared bot account"/"same bot account" language from 6 agent definitions and 2 spec sections: implementation-worker.md (2 approval function docstrings), shared/merge_safety.md (approval function docstring + comment), pr-merge-pool-supervisor.md (2 stale self-approval references), pr-reviewer.md (stale self-approval fallback), project-bootstrapper.md (branch protection self-approval note), shared/credential_security.md (stale comment); updated spec Sections 8.3.2 and 8.3.3 to reference dual-account architecture
2026-04-10 1.30.0 Thirty-third pass (dual-account architecture): Rewrote Section 6.17 from "Shared Bot Account Problem" to "Dual-Account Architecture" — introduced FORGEJO_REVIEWER_PAT and FORGEJO_REVIEWER_USERNAME environment variables for a separate reviewer Forgejo account; formal APPROVED reviews are now the PRIMARY approval path (not a workaround); updated Section 6.17.2 from "Two-Step Review Protocol" to "Dual-Account Review Protocol" (formal review first, backup comment second); added environment variables to Appendix C table; fixed 4 agent definitions: pr-reviewer.md (rewrote review protocol to use reviewer credentials as primary), pr-review-pool-supervisor.md (passes reviewer credentials to dispatched pr-reviewer instances), pr-merge-pool-supervisor.md (updated approval detection to recognize reviewer account as primary approver), product-builder.md (passes reviewer credentials when launching review pool supervisor); updated shared/credential_security.md with dual credential scheme
2026-04-10 1.29.0 Thirty-second pass (subagent specialization, eliminate duplication): Added Section 6.0 (Subagent Specialization Principle — centralize, don't duplicate); moved interval calculation from 17 duplicated agent blocks into ATM CREATE_TRACKING_ISSUE via new sleep_interval_default parameter; added ATM operation #11 CYCLE_ANNOUNCEMENT_REVIEW combining read + review + close in one call; updated spec Section 5.3.4 to document ATM-centralized interval calculation; updated Section 5.4 operations table to 11 operations; updated shared/tracking_discovery_guide.md to reference ATM-handled interval; removed 17 duplicated rolling average calculation blocks from all supervisor agents and replaced with single --sleep-interval-default parameter
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)