diff --git a/docs/development/agent-system-specification.md b/docs/development/agent-system-specification.md index a9b604d85..68456aad8 100644 --- a/docs/development/agent-system-specification.md +++ b/docs/development/agent-system-specification.md @@ -26,6 +26,8 @@ The CleverAgents autonomous development system is a **multi-agent architecture** 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](#22-division-of-responsibilities-and-redundancy-model). + ### 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. @@ -1423,6 +1425,54 @@ blockdiag { } ``` +### 7.8 Product Builder Responsibilities + +| Responsibility | Role | Redundancy Layer | Section | +|---------------|------|-----------------|---------| +| [R-01: Supervisor Liveness](#221-r-01-supervisor-liveness-and-health-monitoring) | **Primary**: 60-second monitoring loop, immediate re-launch of dead supervisors; deep inspection of pool supervisors every 5 heartbeats | Layer 1 + Layer 2 | [22.1](#221-r-01-supervisor-liveness-and-health-monitoring) | +| [R-04: Issue Implementation](#224-r-04-issue-implementation) | Orchestrates by launching Implementation Pool Supervisor | Dispatch chain | [22.4](#224-r-04-issue-implementation) | +| [R-12: Merge Safety](#2212-r-12-merge-safety-and-branch-protection) | Invokes Project Bootstrapper for initial branch protection setup | Setup chain | [22.12](#2212-r-12-merge-safety-and-branch-protection) | +| [R-20: Automation Tracking](#2220-r-20-automation-tracking-and-inter-agent-coordination) | Creates own tracking issues; reads all supervisor tracking for convergence | Layer 2 (self-cleanup) | [22.20](#2220-r-20-automation-tracking-and-inter-agent-coordination) | +| [R-65: Spec PR Monitoring](#2265-r-65-specification-pr-monitoring-and-lifecycle) | Tracks spec PRs; rebases stale ones; reloads spec on merge; creates follow-up on rejection | Layer 1 (monitoring) | [22.65](#2265-r-65-specification-pr-monitoring-and-lifecycle) | +| [R-67: Product Verification](#2267-r-67-product-completion-verification) | Invokes Product Verifier for 10-point completion check every 10 monitoring cycles | Dispatch | [22.67](#2267-r-67-product-completion-verification) | +| [R-80: Non-Return Guarantee](#2280-r-80-non-return-guarantee-enforcement) | 14 scenarios that are NOT valid exit; only 3 valid exits (COMPLETE, user stop, 401/403) | Self-constraint | [22.80](#2280-r-80-non-return-guarantee-enforcement) | +| [R-81: Worker Allocation](#2281-r-81-tiered-worker-allocation-formula) | Configures N/N÷2/N÷4/1 allocation across 18 supervisors | Configuration | [22.81](#2281-r-81-tiered-worker-allocation-formula) | +| [R-87: Project Classification](#2287-r-87-five-state-project-classification) | Classifies project as Fresh/Bootstrapped/Designed/InProgress/NearComplete to select phases | Startup routing | [22.87](#2287-r-87-five-state-project-classification) | +| [R-121: Bootstrap Skip](#22121-r-121-phase-a-bootstrap-skip-condition) | Skips Phase A if pyproject.toml + noxfile.py + CI + CONTRIBUTING.md all exist | Phase gate | [22.121](#22121-r-121-phase-a-bootstrap-skip-condition) | +| [R-122: prompt_async](#22122-r-122-prompt-async-mandatory-for-supervisor-launch) | Supervisors via prompt_async (fire-and-forget); Task tool FORBIDDEN (would block forever) | Architectural | [22.122](#22122-r-122-prompt-async-mandatory-for-supervisor-launch) | +| [R-123: 18 Mandatory](#22123-r-123-all-18-supervisors-mandatory-verification) | Post-launch verification: ALL 18 must have active sessions; re-launch any missing | Verification | [22.123](#22123-r-123-all-18-supervisors-mandatory-verification) | +| [R-124: Convergence](#22124-r-124-convergence-check-algorithm) | Every 10 heartbeats: zero open issues + PRs + spec PRs → invoke Product Verifier | Lifecycle gate | [22.124](#22124-r-124-convergence-check-algorithm) | +| [R-125: Never Edits](#22125-r-125-product-builder-never-edits-or-merges-directly) | FORBIDDEN: implement, edit code, create PR, merge PR, review PR, fix CI — always re-launch supervisor | Prohibition | [22.125](#22125-r-125-product-builder-never-edits-or-merges-directly) | +| [R-126: No Duplicates](#22126-r-126-no-duplicate-supervisor-instances) | One instance per supervisor type; checks for existing session before launch | Layer 1 (prevention) | [22.126](#22126-r-126-no-duplicate-supervisor-instances) | +| [R-21: Crash Recovery](#2221-r-21-crash-recovery-and-state-persistence) | Session adoption (Phase C.0); re-launches crashed supervisors; Startup State Recovery Protocol | Product Builder + Supervisor levels | [22.21](#2221-r-21-crash-recovery-and-state-persistence) | + +--- + +### 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.8) shares most of these but has its own variants. + +| Responsibility | What Every Supervisor Must Do | Section | +|---------------|------------------------------|---------| +| [R-141: Startup Sequence](#22141-r-141-supervisor-mandatory-startup-sequence) | Execute 4-step startup: READ_TRACKING_STATE → parse recovered state → CREATE_TRACKING_ISSUE → begin main loop | [22.141](#22141-r-141-supervisor-mandatory-startup-sequence) | +| [R-142: State Recovery](#22142-r-142-startup-state-recovery-before-tracking-creation) | Read most recent tracking issue BEFORE creating new one; parse previous cycle's work items, health indicators | [22.142](#22142-r-142-startup-state-recovery-before-tracking-creation) | +| [R-20: Tracking Coordination](#2220-r-20-automation-tracking-and-inter-agent-coordination) | Create status tracking issues via ATM every N cycles; update with current state | [22.20](#2220-r-20-automation-tracking-and-inter-agent-coordination) | +| [R-143: Dual Cleanup](#22143-r-143-dual-status-issue-cleanup-defense-in-depth) | Close ALL own old status issues before creating new one (via ATM's close-all protocol) | [22.143](#22143-r-143-dual-status-issue-cleanup-defense-in-depth) | +| [R-133: Announcement Consumption](#22133-r-133-announcement-consumption-priority-protocol) | Read announcements from relevant agents at appropriate priority depth per the consumption table | [22.133](#22133-r-133-announcement-consumption-priority-protocol) | +| [R-43: Announcement Lifecycle](#2243-r-43-announcement-lifecycle-management) | Review own announcements every 3 cycles; close resolved ones | [22.43](#2243-r-43-announcement-lifecycle-management) | +| [R-44: Context Self-Management](#2244-r-44-context-window-self-management) | Periodically discard accumulated tool outputs; retain only persistent state | [22.44](#2244-r-44-context-window-self-management) | +| [R-113: Resource Cleanup](#22113-r-113-guaranteed-resource-cleanup-via-cleanupmanager) | Guarantee resource release (claims, clones, temps) via try/finally | [22.113](#22113-r-113-guaranteed-resource-cleanup-via-cleanupmanager) | +| [R-114: Credential Validation](#22114-r-114-startup-credential-validation-gate) | Validate all required credentials at startup before any work | [22.114](#22114-r-114-startup-credential-validation-gate) | +| [R-63: Bot Signature](#2263-r-63-bot-signature-standardization) | Append standardized bot signature to ALL Forgejo content | [22.63](#2263-r-63-bot-signature-standardization) | +| [R-41: Worker Dispatch](#2241-r-41-worker-dispatch-and-sliding-window-management) | *Pool supervisors only*: maintain sliding window of N workers; fill slots immediately from priority queue | [22.41](#2241-r-41-worker-dispatch-and-sliding-window-management) | +| [R-78: Structured Logging](#2278-r-78-structured-logging-protocol) | Use `[AGENT:][SESSION:][ACTION:][LEVEL:]` format for all logs | [22.78](#2278-r-78-structured-logging-protocol) | +| [R-79: Performance Monitoring](#2279-r-79-performance-monitoring-and-health-scoring) | Track operation durations, success rates, resource usage; adaptive timeouts | [22.79](#2279-r-79-performance-monitoring-and-health-scoring) | +| [R-77: Push Conflict Recovery](#2277-r-77-push-conflict-recovery-protocol) | *Cloning agents only*: rebase-and-retry on push rejection; reclone after 5 failures | [22.77](#2277-r-77-push-conflict-recovery-protocol) | +| [R-127: No Label Creation](#22127-r-127-label-creation-prohibition-enforcement) | Never create labels; delegate to Forgejo Label Manager | [22.127](#22127-r-127-label-creation-prohibition-enforcement) | +| [R-134: No Internet](#22134-r-134-internet-access-restriction) | No webfetch access; work from local files, Forgejo API, and OpenCode API only | [22.134](#22134-r-134-internet-access-restriction) | + --- ## 8. Pool Supervisors (Tier 1) @@ -1513,6 +1563,22 @@ activitydiag { | `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](#79-universal-supervisor-responsibilities-all-18-supervisors):* + +| Responsibility | Role | Redundancy Layer | Section | +|---------------|------|-----------------|---------| +| [R-49: PR Ownership & Scoring](#2249-r-49-pr-ownership-detection-and-work-scoring) | Classifies PRs by `pr.user.login`; scores by work type (95/90/85/80/60) + age bonus | Single | [22.49](#2249-r-49-pr-ownership-detection-and-work-scoring) | +| [R-98: Dispatch Ordering](#2298-r-98-issue-dispatch-priority-ordering-rules) | 7-level priority: CI-Blocker → Critical bugs → lowest milestone → In Progress → Priority → MoSCoW → unblock score | Single | [22.98](#2298-r-98-issue-dispatch-priority-ordering-rules) | +| [R-04: Issue Implementation](#224-r-04-issue-implementation) | **Primary dispatcher**: finds verified issues, manages sliding window of N workers, enforces PR-first priority gate | Dispatch | [22.4](#224-r-04-issue-implementation) | +| [R-50: Worker Adoption](#2250-r-50-worker-session-adoption-and-lifecycle) | Scans for existing worker sessions on startup; validates status; adopts into tracking | Layer 1 | [22.50](#2250-r-50-worker-session-adoption-and-lifecycle) | +| [R-51: Pagination & Truncation](#2251-r-51-forgejo-api-pagination-and-truncation-recovery) | Paginates ALL PR pages; reads truncated output files; logs verification counts | Most affected | [22.51](#2251-r-51-forgejo-api-pagination-and-truncation-recovery) | +| [R-07: PR Fixing](#227-r-07-pr-fixing-and-ci-remediation) | PR-first priority gate guarantees every bot PR has an active worker before any new issues | Layer 1 | [22.7](#227-r-07-pr-fixing-and-ci-remediation) | +| [R-08: PR Merging](#228-r-08-pr-merging-and-post-merge-verification) | Dispatches workers with `ready-to-merge` work type for approved PRs | Layer 2 (backup) | [22.8](#228-r-08-pr-merging-and-post-merge-verification) | +| [R-20: Automation Tracking](#2220-r-20-automation-tracking-and-inter-agent-coordination) | Creates tracking issues; reads announcements from watchdog, architecture, groomer | Layer 2 (self-cleanup) | [22.20](#2220-r-20-automation-tracking-and-inter-agent-coordination) | +| [R-21: Crash Recovery](#2221-r-21-crash-recovery-and-state-persistence) | Adopts existing worker sessions; parses previous tracking for active PRs/issues | Worker level | [22.21](#2221-r-21-crash-recovery-and-state-persistence) | + --- ### 8.2 PR Review Pool Supervisor @@ -1558,6 +1624,23 @@ Each review session receives specific focus areas that rotate through ten catego 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](#79-universal-supervisor-responsibilities-all-18-supervisors):* + +| Responsibility | Role | Redundancy Layer | Section | +|---------------|------|-----------------|---------| +| [R-05: Code Review](#225-r-05-code-review-and-quality-assessment) | **Primary dispatcher**: polls for unreviewed PRs, dispatches N/2 parallel PR Reviewer instances with rotating focus areas | Layer 1 | [22.5](#225-r-05-code-review-and-quality-assessment) | +| [R-52: Dual-Account Auth](#2252-r-52-dual-account-review-authentication) | Passes all 3 reviewer credentials (PAT, username, password) to each dispatched PR Reviewer instance | Credential distribution | [22.52](#2252-r-52-dual-account-review-authentication) | +| [R-53: Anti-Pattern Detection](#2253-r-53-anti-pattern-and-code-smell-detection) | Assigns rotating focus areas (10 categories) to each reviewer instance, ensuring diverse detection | Layer 1 (rotation) | [22.53](#2253-r-53-anti-pattern-and-code-smell-detection) | +| [R-101: Flaky Test Detection](#22101-r-101-flaky-test-16-pattern-detection) | Reviewers check for 16 specific non-deterministic test patterns; REQUEST_CHANGES immediately on match | Layer 1 (per-PR) | [22.101](#22101-r-101-flaky-test-16-pattern-detection) | +| [R-135: File Organization](#22135-r-135-file-organization-enforcement) | Checks files in correct directories per CONTRIBUTING.md | Layer 2 (review) | [22.135](#22135-r-135-file-organization-enforcement) | +| [R-136: No type:ignore](#22136-r-136-static-typing-and-type-ignore-prohibition) | Scans diff for `type: ignore`; requests changes if found | Layer 2 (review) | [22.136](#22136-r-136-static-typing-and-type-ignore-prohibition) | +| [R-137: 500-Line Limit](#22137-r-137-maximum-file-size-enforcement-500-lines) | Checks file sizes in diff; requests changes for files exceeding 500 lines | Layer 2 (review) | [22.137](#22137-r-137-maximum-file-size-enforcement-500-lines) | +| [R-138: Framework Selection](#22138-r-138-testing-framework-selection-rules) | Rejects xUnit-style tests; verifies correct framework per test level | Layer 2 (review) | [22.138](#22138-r-138-testing-framework-selection-rules) | +| [R-140: Commit Format](#22140-r-140-conventional-changelog-commit-format) | Checks Conventional Changelog format in PR commits | Layer 2 (review) | [22.140](#22140-r-140-conventional-changelog-commit-format) | +| [R-20: Automation Tracking](#2220-r-20-automation-tracking-and-inter-agent-coordination) | Creates tracking issues; reads critical announcements from watchdog/liaison | Layer 2 (self-cleanup) | [22.20](#2220-r-20-automation-tracking-and-inter-agent-coordination) | + --- ### 8.3 PR Merge Pool Supervisor @@ -1629,6 +1712,23 @@ When a branch is behind the base branch (`merge_base != base.sha`), the PR Merge **Subagents**: `ref-reader`, `pr-status-analyzer`, `automation-tracking-manager`, `repo-isolator`, `git-commit-helper` +#### 8.3.6 PR Merge Pool Supervisor Responsibilities + +*In addition to the [universal supervisor responsibilities](#79-universal-supervisor-responsibilities-all-18-supervisors):* + +| Responsibility | Role | Redundancy Layer | Section | +|---------------|------|-----------------|---------| +| [R-99: 7 Merge Criteria](#2299-r-99-pr-merge-seven-criteria-checklist) | ALL seven criteria verified before every merge: approval, CI, conflicts, staleness, needs-feedback, blocked, issue state | Protocol | [22.99](#2299-r-99-pr-merge-seven-criteria-checklist) | +| [R-100: Blocking Detection](#22100-r-100-blocking-review-temporal-detection) | REQUEST_CHANGES only blocks if more recent than latest approval from any of the 3 tiers | Protocol | [22.100](#22100-r-100-blocking-review-temporal-detection) | +| [R-54: 3-Tier Approval](#2254-r-54-three-tier-approval-detection) | `check_pr_approval()` implements 3-tier detection: formal reviews → review bodies → issue comments | Consumer | [22.54](#2254-r-54-three-tier-approval-detection) | +| [R-08: PR Merging](#228-r-08-pr-merging-and-post-merge-verification) | **Primary merger**: polls every 5 minutes for merge-ready PRs, verifies 7 merge criteria, handles pre-merge rebase | Layer 1 | [22.8](#228-r-08-pr-merging-and-post-merge-verification) | +| [R-55: Post-Merge Verification](#2255-r-55-post-merge-state-verification) | After every merge: `forgejo_get_pull_request_by_index` to confirm `merged == true` AND `state == "closed"` | Layer 1 (inline) | [22.55](#2255-r-55-post-merge-state-verification) | +| [R-30: Branch Management](#2230-r-30-branch-management-and-rebase) | Pre-merge staleness check (merge_base vs base.sha); automatic rebase for behind-but-no-conflict PRs | Layer 2 | [22.30](#2230-r-30-branch-management-and-rebase) | +| [R-12: Merge Safety](#2212-r-12-merge-safety-and-branch-protection) | Implements `safe_merge_pr()` with all 7 mandatory rules | Layer 2 (enforcement) | [22.12](#2212-r-12-merge-safety-and-branch-protection) | +| [R-139: 97% Coverage](#22139-r-139-coverage-threshold-enforcement-97-percent) | CI coverage check at merge gate; failing coverage blocks merge | Layer 2 (merge gate) | [22.139](#22139-r-139-coverage-threshold-enforcement-97-percent) | +| [R-28: Issue Closure](#2228-r-28-issue-closure-and-post-merge-cleanup) | After verified merge: updates linked issues to State/Completed | Layer 1b (immediate) | [22.28](#2228-r-28-issue-closure-and-post-merge-cleanup) | +| [R-20: Automation Tracking](#2220-r-20-automation-tracking-and-inter-agent-coordination) | Creates tracking issues; reads critical announcements from watchdog | Layer 2 (self-cleanup) | [22.20](#2220-r-20-automation-tracking-and-inter-agent-coordination) | + --- ### 8.4 PR Fix Pool Supervisor @@ -1655,6 +1755,17 @@ Before dispatching workers, failures are grouped into categories: Common root causes are identified (e.g., if >3 tests fail with the same import error, a single worker handles the import fix). This prevents redundant work. +#### 8.4.3 PR Fix Pool Supervisor Responsibilities + +*In addition to the [universal supervisor responsibilities](#79-universal-supervisor-responsibilities-all-18-supervisors):* + +| Responsibility | Role | Redundancy Layer | Section | +|---------------|------|-----------------|---------| +| [R-07: PR Fixing](#227-r-07-pr-fixing-and-ci-remediation) | **Specialized analyzer**: groups CI failures by common root cause, dispatches targeted fix workers, detects stuck PRs and requests human help | Layer 2 | [22.7](#227-r-07-pr-fixing-and-ci-remediation) | +| [R-06: Quality Gate Enforcement](#226-r-06-quality-gate-enforcement) | Dispatches workers to fix specific quality gate failures (lint, typecheck, test, coverage) | Layer 2 (post-PR) | [22.6](#226-r-06-quality-gate-enforcement) | +| [R-27: CI Log Retrieval](#2227-r-27-ci-log-retrieval-and-diagnosis) | Invokes `ci-log-fetcher` to retrieve failure logs before dispatching fix workers | Consumer | [22.27](#2227-r-27-ci-log-retrieval-and-diagnosis) | +| [R-112: Conflict Matrix](#22112-r-112-pr-concurrent-work-conflict-matrix) | Coordinates with other PR-modifying agents via conflict matrix before dispatching | Protocol user | [22.112](#22112-r-112-pr-concurrent-work-conflict-matrix) | + --- ### 8.5 UAT Test Pool Supervisor @@ -1682,6 +1793,20 @@ This agent operates in two modes: 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](#79-universal-supervisor-responsibilities-all-18-supervisors):* + +| Responsibility | Role | Redundancy Layer | Section | +|---------------|------|-----------------|---------| +| [R-16: Bug Detection](#2216-r-16-bug-detection-and-proactive-quality-assurance) | Tests feature areas against specification; files bug issues for gaps and spec deviations | Layer 2 (spec compliance) | [22.16](#2216-r-16-bug-detection-and-proactive-quality-assurance) | +| [R-66: Finding Validation](#2266-r-66-finding-validation-gate-before-issue-filing) | Checks open PRs for keywords matching feature area before filing bugs | Layer (UAT gate) | [22.66](#2266-r-66-finding-validation-gate-before-issue-filing) | +| [R-86: Open PR Awareness](#2286-r-86-open-pr-awareness-before-bug-filing) | Skips bug filing if open PR already addresses the gap | Layer 1 | [22.86](#2286-r-86-open-pr-awareness-before-bug-filing) | +| [R-88: Feature Retest](#2288-r-88-uat-feature-area-retest-on-code-changes) | Maps changed files to feature areas; invalidates tested_areas set to force retest | Single | [22.88](#2288-r-88-uat-feature-area-retest-on-code-changes) | +| [R-17: Documentation](#2217-r-17-documentation-and-timeline-maintenance) | Generates showcase documentation from successful end-to-end test runs | Supplementary | [22.17](#2217-r-17-documentation-and-timeline-maintenance) | +| [R-19: Scope Management](#2219-r-19-scope-management-and-milestone-control) | Milestone Scope Guard: only critical bugs to active milestone, non-critical to backlog | Layer 3b (prevention at testing) | [22.19](#2219-r-19-scope-management-and-milestone-control) | +| [R-15: Backlog Hygiene](#2215-r-15-backlog-hygiene-and-duplicate-detection) | Worker coordination via Forgejo comments to avoid duplicate testing | Layer 2c (self-dedup) | [22.15](#2215-r-15-backlog-hygiene-and-duplicate-detection) | + --- ### 8.6 Bug Hunt Pool Supervisor @@ -1715,6 +1840,19 @@ Proactive bug detection through deep code analysis combined with specification c 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](#79-universal-supervisor-responsibilities-all-18-supervisors):* + +| Responsibility | Role | Redundancy Layer | Section | +|---------------|------|-----------------|---------| +| [R-16: Bug Detection](#2216-r-16-bug-detection-and-proactive-quality-assurance) | **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](#2216-r-16-bug-detection-and-proactive-quality-assurance) | +| [R-66: Finding Validation](#2266-r-66-finding-validation-gate-before-issue-filing) | 5-check gate: code evidence, environment verification, actionability, codebase freshness, severity match | Layer (Bug Hunt gate) | [22.66](#2266-r-66-finding-validation-gate-before-issue-filing) | +| [R-70: TDD Awareness](#2270-r-70-tdd-workflow-awareness-in-bug-reports) | Includes TDD Note in every bug report for subsequent test-first workflow | Layer 1 (filing) | [22.70](#2270-r-70-tdd-workflow-awareness-in-bug-reports) | +| [R-86: Open PR Awareness](#2286-r-86-open-pr-awareness-before-bug-filing) | Validates finding is not already being addressed by open PR | Layer 2 | [22.86](#2286-r-86-open-pr-awareness-before-bug-filing) | +| [R-14: Codebase Coherence](#2214-r-14-codebase-coherence-and-technical-debt) | Pass 8 (code consistency) and Pass 9 (data flow) identify inconsistent patterns across modules | Layer 2 (per-module analysis) | [22.14](#2214-r-14-codebase-coherence-and-technical-debt) | +| [R-15: Backlog Hygiene](#2215-r-15-backlog-hygiene-and-duplicate-detection) | Finding validation: five rules before filing any bug issue to prevent duplicates and false positives | Layer 2b (self-dedup) | [22.15](#2215-r-15-backlog-hygiene-and-duplicate-detection) | + --- ### 8.7 Test Infrastructure Pool Supervisor @@ -1747,6 +1885,18 @@ Analyzes testing infrastructure and proposes improvements. Never disables or wea 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](#79-universal-supervisor-responsibilities-all-18-supervisors):* + +| Responsibility | Role | Redundancy Layer | Section | +|---------------|------|-----------------|---------| +| [R-06: Quality Gate Enforcement](#226-r-06-quality-gate-enforcement) | Proposes improvements to CI pipeline and test infrastructure; never disables existing checks | Improvement (indirect) | [22.6](#226-r-06-quality-gate-enforcement) | +| [R-71: Never-Disable-Checks](#2271-r-71-never-disable-checks-safety-constraint) | Hard constraint: never disable coverage, type checking, linting, security. Never reduce below 97%. Never remove CI steps. | Layer 1 (self-constraint) | [22.71](#2271-r-71-never-disable-checks-safety-constraint) | +| [R-138: Framework Selection](#22138-r-138-testing-framework-selection-rules) | Verifies all three test levels exist per module; never weakens framework requirements | Layer 3 (infrastructure) | [22.138](#22138-r-138-testing-framework-selection-rules) | +| [R-66: Finding Validation](#2266-r-66-finding-validation-gate-before-issue-filing) | Five mandatory dedup checks with `### Duplicate Check` section in every issue body | Layer (Test Infra gate) | [22.66](#2266-r-66-finding-validation-gate-before-issue-filing) | +| [R-15: Backlog Hygiene](#2215-r-15-backlog-hygiene-and-duplicate-detection) | Strongest self-dedup of any agent — historical 48+ duplicates motivate 5-step protocol | Layer 2 (self-dedup) | [22.15](#2215-r-15-backlog-hygiene-and-duplicate-detection) | + --- ## 9. Singleton Supervisors (Tier 1) @@ -1770,6 +1920,17 @@ Documented as the "#1 problem with this agent" due to historical creation of 48+ **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](#79-universal-supervisor-responsibilities-all-18-supervisors):* + +| Responsibility | Role | Redundancy Layer | Section | +|---------------|------|-----------------|---------| +| [R-13: Specification Governance](#2213-r-13-specification-and-architecture-governance) | **Primary spec writer**: writes/extends `docs/specification.md`, defines module boundaries, interfaces, data models, patterns | Layer 1 (spec → code) | [22.13](#2213-r-13-specification-and-architecture-governance) | +| [R-73: Spec Classification](#2273-r-73-spec-change-classification-and-two-step-proposal) | Classifies changes: initial → direct commit; major → PR with `needs feedback`; minor → direct commit | Layer 1 (classification) | [22.73](#2273-r-73-spec-change-classification-and-two-step-proposal) | +| [R-03: Work Planning](#223-r-03-work-planning-and-decomposition) | Provides the specification that drives epic/issue decomposition | Layer 1 (specification) | [22.3](#223-r-03-work-planning-and-decomposition) | +| [R-18: Human Escalation](#2218-r-18-human-communication-and-escalation) | Creates `needs feedback` PRs for major architectural changes requiring human approval | Layer 4 (proposal escalation) | [22.18](#2218-r-18-human-communication-and-escalation) | + ### 9.2 Epic Planning Supervisor | Property | Value | @@ -1794,6 +1955,21 @@ Documented as the "#1 problem with this agent" due to historical creation of 48+ **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](#79-universal-supervisor-responsibilities-all-18-supervisors):* + +| Responsibility | Role | Redundancy Layer | Section | +|---------------|------|-----------------|---------| +| [R-03: Work Planning](#223-r-03-work-planning-and-decomposition) | **Primary decomposer**: breaks milestones into Epics and Issues with dependency chains; four phases per cycle | Layer 2 (decomposition) | [22.3](#223-r-03-work-planning-and-decomposition) | +| [R-11: Dependency Integrity](#2211-r-11-dependency-and-hierarchy-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](#2211-r-11-dependency-and-hierarchy-integrity) | +| [R-69: Orphan Remediation](#2269-r-69-orphaned-issue-and-epic-remediation) | Phase 1: scans ALL open issues/epics for missing parents; finds or creates suitable parents; fixes reversed directions | Layer 1 (enforcement) | [22.69](#2269-r-69-orphaned-issue-and-epic-remediation) | +| [R-68: Epic/Legendary Closure](#2268-r-68-epic-and-legendary-closure-evaluation) | Phase 2: evaluates closure candidates where all children completed; closes with acceptance criteria check | Layer 1 (evaluation) | [22.68](#2268-r-68-epic-and-legendary-closure-evaluation) | +| [R-40: Spec-First Enforcement](#2240-r-40-specification-first-development-enforcement) | Phase 3: identifies features requiring spec changes, creates ADR→Spec→Implementation dependency chains | Layer 1 (planning gate) | [22.40](#2240-r-40-specification-first-development-enforcement) | +| [R-38: Body & DoD Compliance](#2238-r-38-issue-body-and-dod-compliance) | Creates issues with CONTRIBUTING.md-compliant body format (Metadata, Subtasks, DoD) | Layer 1 (at creation) | [22.38](#2238-r-38-issue-body-and-dod-compliance) | +| [R-37: Milestone Assignment](#2237-r-37-milestone-assignment-and-scope-guard) | Milestone Scope Guard: skips converging milestones; new work goes to backlog | Layer 2 (planning-level guard) | [22.37](#2237-r-37-milestone-assignment-and-scope-guard) | +| [R-19: Scope Management](#2219-r-19-scope-management-and-milestone-control) | Milestone Scope Guard: prevents new issue creation in converging milestones | Layer 2 (prevention at planning) | [22.19](#2219-r-19-scope-management-and-milestone-control) | + ### 9.3 Human Liaison Supervisor | Property | Value | @@ -1828,6 +2004,25 @@ Documented as the "#1 problem with this agent" due to historical creation of 48+ **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](#79-universal-supervisor-responsibilities-all-18-supervisors):* + +| Responsibility | Role | Redundancy Layer | Section | +|---------------|------|-----------------|---------| +| [R-105: 10-Step Loop](#22105-r-105-human-liaison-10-step-monitoring-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](#22105-r-105-human-liaison-10-step-monitoring-loop) | +| [R-106: Closed Issue Response](#22106-r-106-closed-issue-comment-response-patterns) | 4 patterns: answer questions, refuse reopening, create new bug for related reports, acknowledge feedback | Single | [22.106](#22106-r-106-closed-issue-comment-response-patterns) | +| [R-18: Human Communication](#2218-r-18-human-communication-and-escalation) | **Primary bridge**: handles all human activity, Feedback Incorporation Protocol | Layer 1 (primary bridge) | [22.18](#2218-r-18-human-communication-and-escalation) | +| [R-46: Feedback Incorporation](#2246-r-46-feedback-incorporation-protocol) | **Exclusive owner**: updates descriptions when discussion changes ticket nature, posts diff for user, confirms completion | Layer 1 (single) | [22.46](#2246-r-46-feedback-incorporation-protocol) | +| [R-47: Timeout Management](#2247-r-47-human-response-timeout-management) | Tracks 5 timeout types (48h/24h/72h/48h/24h), creates provisional decisions, escalates | Layer 1 (tracking) | [22.47](#2247-r-47-human-response-timeout-management) | +| [R-48: Developer Assignment](#2248-r-48-developer-expertise-discovery-and-assignment) | Tags developers in comments based on expertise areas when guidance is needed | Layer 2 (tagging) | [22.48](#2248-r-48-developer-expertise-discovery-and-assignment) | +| [R-02: Issue Triage](#222-r-02-issue-triage-verification-and-priority-management) | Triages human-created issues with full triage authority; fastest polling interval (2 min) | Layer 2 (human issues) | [22.2](#222-r-02-issue-triage-verification-and-priority-management) | +| [R-36: Story Points](#2236-r-36-story-point-estimation) | Estimates story points during triage (XS 1pt through XXL 13pt) | Layer 1 (triage-time) | [22.36](#2236-r-36-story-point-estimation) | +| [R-03: Work Planning](#223-r-03-work-planning-and-decomposition) | Plans implementation for verified issues; Epic/Legendary gap analysis every 10th cycle | Layer 4 (human requests) | [22.3](#223-r-03-work-planning-and-decomposition) | +| [R-40: Spec-First Enforcement](#2240-r-40-specification-first-development-enforcement) | For features requiring spec changes: creates spec issue, tracks spec PR, creates impl issues after merge | Layer 3 (feedback channel) | [22.40](#2240-r-40-specification-first-development-enforcement) | +| [R-22: Self-Improvement](#2222-r-22-self-improvement-and-agent-evolution) | Channels human feedback about agent behavior into the improvement pipeline | Layer 3 (human feedback) | [22.22](#2222-r-22-self-improvement-and-agent-evolution) | +| [R-09: Label Correctness](#229-r-09-label-and-metadata-correctness) | Sets labels on issues it creates via Forgejo Label Manager | Layer 2 (initial assignment) | [22.9](#229-r-09-label-and-metadata-correctness) | + ```kroki-activitydiag activitydiag { "Poll Forgejo" -> "New Human Activity?"; @@ -1879,6 +2074,18 @@ activitydiag { **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](#79-universal-supervisor-responsibilities-all-18-supervisors):* + +| Responsibility | Role | Redundancy Layer | Section | +|---------------|------|-----------------|---------| +| [R-22: Self-Improvement](#2222-r-22-self-improvement-and-agent-evolution) | **Primary evolution agent**: seven analysis steps, two-step proposal workflow (proposal issue → implementation PR after human approval) | Layer 1 (proactive analysis) | [22.22](#2222-r-22-self-improvement-and-agent-evolution) | +| [R-85: Pattern Detection](#2285-r-85-agent-improvement-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](#2285-r-85-agent-improvement-pattern-detection) | +| [R-57: Clone Isolation](#2257-r-57-clone-isolation-and-safety) | Creates clone to modify `.opencode/agents/` files; pushes agent definition changes via PR | Protocol user | [22.57](#2257-r-57-clone-isolation-and-safety) | +| [R-135: File Organization](#22135-r-135-file-organization-enforcement) | Only modifies files in `.opencode/agents/` — never modifies source code | Self-constraint | [22.135](#22135-r-135-file-organization-enforcement) | +| [R-18: Human Escalation](#2218-r-18-human-communication-and-escalation) | Creates `needs feedback` proposals for agent definition changes | Layer 4 (proposal escalation) | [22.18](#2218-r-18-human-communication-and-escalation) | + ### 9.5 Architecture Guard | Property | Value | @@ -1905,6 +2112,17 @@ activitydiag { 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](#79-universal-supervisor-responsibilities-all-18-supervisors):* + +| Responsibility | Role | Redundancy Layer | Section | +|---------------|------|-----------------|---------| +| [R-14: Codebase Coherence](#2214-r-14-codebase-coherence-and-technical-debt) | **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](#2214-r-14-codebase-coherence-and-technical-debt) | +| [R-74: SHA-Based Idle Detection](#2274-r-74-sha-based-idle-detection-for-scanners) | Compares master SHA with last known; skips scanning when unchanged; only scans on new code | Single | [22.74](#2274-r-74-sha-based-idle-detection-for-scanners) | +| [R-13: Specification Governance](#2213-r-13-specification-and-architecture-governance) | Check 7: detects specification drift — implementation diverged from spec | Layer 3 (drift detection) | [22.13](#2213-r-13-specification-and-architecture-governance) | +| [R-16: Bug Detection](#2216-r-16-bug-detection-and-proactive-quality-assurance) | Check 6: test quality (tests not verifying meaningful behavior), Check 5: technical debt indicators | Layer 4 (architecture-level) | [22.16](#2216-r-16-bug-detection-and-proactive-quality-assurance) | + ### 9.6 Specification Evolution Supervisor | Property | Value | @@ -1933,6 +2151,20 @@ Each finding creates a `Type/Refactor` issue with `State/Unverified`. Only scans **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](#79-universal-supervisor-responsibilities-all-18-supervisors):* + +| Responsibility | Role | Redundancy Layer | Section | +|---------------|------|-----------------|---------| +| [R-13: Specification Governance](#2213-r-13-specification-and-architecture-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](#2213-r-13-specification-and-architecture-governance) | +| [R-73: Two-Step Proposal](#2273-r-73-spec-change-classification-and-two-step-proposal) | Proposal issue first with `needs feedback`; implementation PR only after human approval; tracks rejected proposals | Layer 2 (proposal workflow) | [22.73](#2273-r-73-spec-change-classification-and-two-step-proposal) | +| [R-74: SHA-Based Idle](#2274-r-74-sha-based-idle-detection-for-scanners) | Compares master SHA; proactive deep scan every 5th idle cycle (~75 min) | Single | [22.74](#2274-r-74-sha-based-idle-detection-for-scanners) | +| [R-92: Proactive Scan](#2292-r-92-proactive-specification-scan-protocol) | Module-by-module spec-vs-code comparison; classifies discrepancies; generates ≥1 proposal per scan | Single | [22.92](#2292-r-92-proactive-specification-scan-protocol) | +| [R-65: Spec PR Lifecycle](#2265-r-65-specification-pr-monitoring-and-lifecycle) | Rebases own spec PRs when master advances; preserves `needs feedback` label | Layer 2 (self-rebase) | [22.65](#2265-r-65-specification-pr-monitoring-and-lifecycle) | +| [R-59: PR Description](#2259-r-59-pr-description-preservation) | Re-sends full body on every PR update to prevent Forgejo API description deletion | Layer 2 | [22.59](#2259-r-59-pr-description-preservation) | +| [R-18: Human Escalation](#2218-r-18-human-communication-and-escalation) | Creates `needs feedback` proposals for spec changes | Layer 4 (proposal escalation) | [22.18](#2218-r-18-human-communication-and-escalation) | + ### 9.7 Backlog Grooming Supervisor | Property | Value | @@ -1983,6 +2215,43 @@ Each finding creates a `Type/Refactor` issue with `State/Unverified`. Only scans 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 Backlog Grooming Supervisor Responsibilities + +*In addition to the [universal supervisor responsibilities](#79-universal-supervisor-responsibilities-all-18-supervisors):* + +!!! 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](#229-r-09-label-and-metadata-correctness) | Pass 4: auto-fixes missing State/Type/Priority labels; Pass 19: PR-issue label synchronization | Layer 3 (verification & auto-fix) | [22.9](#229-r-09-label-and-metadata-correctness) | +| [R-35: PR-Issue Label Sync](#2235-r-35-pr-issue-label-synchronization) | Pass 19: copies missing Priority/MoSCoW/Points labels from issue to PR, removes stale labels, syncs milestones | Layer 2 (ongoing sync) | [22.35](#2235-r-35-pr-issue-label-synchronization) | +| [R-10: Issue State Management](#2210-r-10-issue-state-lifecycle-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](#2210-r-10-issue-state-lifecycle-management) | +| [R-36: Story Points](#2236-r-36-story-point-estimation) | 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](#2236-r-36-story-point-estimation) | +| [R-37: Milestone Assignment](#2237-r-37-milestone-assignment-and-scope-guard) | Pass 4: assigns milestone to Verified+ issues without one | Layer 3 (compliance fill) | [22.37](#2237-r-37-milestone-assignment-and-scope-guard) | +| [R-11: Dependency Integrity](#2211-r-11-dependency-and-hierarchy-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](#2211-r-11-dependency-and-hierarchy-integrity) | +| [R-02: Issue Triage](#222-r-02-issue-triage-verification-and-priority-management) | Pass 4: fills missing labels with safe defaults (`State/Unverified`, `Priority/Backlog`) | Layer 3 (gap filler) | [22.2](#222-r-02-issue-triage-verification-and-priority-management) | +| [R-03: Work Planning](#223-r-03-work-planning-and-decomposition) | Passes 12-13: detects incomplete epics/legendaries, creates missing child issues | Layer 3 (gap detection) | [22.3](#223-r-03-work-planning-and-decomposition) | +| [R-24: Work Claiming](#2224-r-24-work-item-claiming-and-coordination) | Pass 3: detects stale In Progress issues (>48h no activity), implying abandoned claims | Layer 2 (stale detection) | [22.24](#2224-r-24-work-item-claiming-and-coordination) | +| [R-15: Backlog Hygiene](#2215-r-15-backlog-hygiene-and-duplicate-detection) | **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](#2215-r-15-backlog-hygiene-and-duplicate-detection) | +| [R-38: Body & DoD Compliance](#2238-r-38-issue-body-and-dod-compliance) | Pass 11: checks for Metadata/Subtasks/DoD sections; Pass 7: audits DoD checklist accuracy | Layer 2 (verification) | [22.38](#2238-r-38-issue-body-and-dod-compliance) | +| [R-39: Blocked Chains](#2239-r-39-blocked-chain-analysis-and-resolution) | Pass 8: detects circular dependencies, orphaned blockers, impossible chains | Layer 1 (analysis) | [22.39](#2239-r-39-blocked-chain-analysis-and-resolution) | +| [R-102: Post-Merge Closure](#22102-r-102-merged-pr-issue-closure-with-dependency-cleanup) | Pass 15: removes satisfied dependency links (merged PRs, closed issues) via DELETE API before closing issues | Layer 2 (dependency cleanup) | [22.102](#22102-r-102-merged-pr-issue-closure-with-dependency-cleanup) | +| [R-103: Wrong-Direction Fix](#22103-r-103-wrong-direction-dependency-auto-fix) | Pass 16: detects issue-blocks-PR (deadlock); DELETE wrong + POST correct direction (PR blocks issue) | Layer 1 (detection & fix) | [22.103](#22103-r-103-wrong-direction-dependency-auto-fix) | +| [R-104: Priority Consistency](#22104-r-104-priority-consistency-cross-check) | Pass 5: High blocked by Low, current milestone low while next has high | Layer 1 (detection) | [22.104](#22104-r-104-priority-consistency-cross-check) | +| [R-28: Issue Closure](#2228-r-28-issue-closure-and-post-merge-cleanup) | Pass 14: closes issues whose PRs merged; Pass 6: closes issues with completed DoD; removes stale dependency links | Layer 2 (catch-up) | [22.28](#2228-r-28-issue-closure-and-post-merge-cleanup) | +| [R-19: Scope Management](#2219-r-19-scope-management-and-milestone-control) | Pass 18: scope creep detection via creation-vs-closure rate monitoring | Layer 1 (detection) | [22.19](#2219-r-19-scope-management-and-milestone-control) | +| [R-20: Automation Tracking](#2220-r-20-automation-tracking-and-inter-agent-coordination) | Pass 19: cleans stale tracking tickets; Pass 20: deduplicates status issues | Layer 3 (redundant cleanup) | [22.20](#2220-r-20-automation-tracking-and-inter-agent-coordination) | +| [R-130: Issue Body Format](#22130-r-130-standard-issue-body-format-enforcement) | Pass 11: verifies Metadata, Subtasks, DoD sections; posts comment listing missing sections | Layer 2 (verification) | [22.130](#22130-r-130-standard-issue-body-format-enforcement) | +| [R-128: State Transitions](#22128-r-128-valid-state-transition-matrix-enforcement) | Pass 4/9: detects issues in impossible states; corrects to valid transitions | Layer 2 | [22.128](#22128-r-128-valid-state-transition-matrix-enforcement) | +| [R-129: Priority Ordering](#22129-r-129-priority-ordering-rules-for-milestone-work) | Pass 5: detects priority inconsistencies within and across milestones | Layer (detection) | [22.129](#22129-r-129-priority-ordering-rules-for-milestone-work) | +| [R-42: Tracking Cleanup](#2242-r-42-tracking-issue-cleanup-and-deduplication) | 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](#2242-r-42-tracking-issue-cleanup-and-deduplication) | +| [R-43: Announcements](#2243-r-43-announcement-lifecycle-management) | Pass 19: auto-closure inquiry, 24h grace period, respects PERSIST/KEEP_OPEN markers | Layer 3 (stale cleanup) | [22.43](#2243-r-43-announcement-lifecycle-management) | +| [R-68: Epic/Legendary Closure](#2268-r-68-epic-and-legendary-closure-evaluation) | Passes 12-13: detects parents with all children closed; creates missing children or flags for closure | Layer 2 (detection) | [22.68](#2268-r-68-epic-and-legendary-closure-evaluation) | +| [R-69: Orphan Remediation](#2269-r-69-orphaned-issue-and-epic-remediation) | Pass 2: flags orphan issues not linked to any parent Epic | Layer 2 (detection) | [22.69](#2269-r-69-orphaned-issue-and-epic-remediation) | +| [R-72: Stale PR Detection](#2272-r-72-stale-pr-detection-and-remediation) | Pass 17: detects PRs with no milestone, duplicates, targeting completed issues, >72h no reviews | Layer 1 (detection) | [22.72](#2272-r-72-stale-pr-detection-and-remediation) | + ### 9.8 Documentation Supervisor | Property | Value | @@ -2007,6 +2276,17 @@ Status tracking issues (title contains `Status:`) are cleaned up aggressively (1 **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](#79-universal-supervisor-responsibilities-all-18-supervisors):* + +| Responsibility | Role | Redundancy Layer | Section | +|---------------|------|-----------------|---------| +| [R-17: Documentation](#2217-r-17-documentation-and-timeline-maintenance) | **Exclusive documentation owner**: generates/updates README, API docs, architecture docs, changelog, module docs. Always extends, never overwrites. | Single (exclusive domain) | [22.17](#2217-r-17-documentation-and-timeline-maintenance) | +| [R-89: Doc Generation](#2289-r-89-documentation-generation-by-type) | Five doc types: README, API (from docstrings), Architecture (from spec), Changelog (Keep a Changelog), Module docs. mkdocs-compatible. | Single | [22.89](#2289-r-89-documentation-generation-by-type) | +| [R-57: Clone Isolation](#2257-r-57-clone-isolation-and-safety) | Creates isolated clone for doc generation (edit:allow agent); pushes and cleans up | Protocol user | [22.57](#2257-r-57-clone-isolation-and-safety) | +| [R-61: Reference Loading](#2261-r-61-reference-material-caching-and-distribution) | Loads spec and project state via ref-reader before generating docs | Protocol user | [22.61](#2261-r-61-reference-material-caching-and-distribution) | + ### 9.9 Timeline Update Supervisor | Property | Value | @@ -2035,6 +2315,16 @@ Status tracking issues (title contains `Status:`) are cleaned up aggressively (1 **Day Number Calculation**: `(today - 2026-02-09).days + 1` +#### 9.9.1 Timeline Update Supervisor Responsibilities + +*In addition to the [universal supervisor responsibilities](#79-universal-supervisor-responsibilities-all-18-supervisors):* + +| Responsibility | Role | Redundancy Layer | Section | +|---------------|------|-----------------|---------| +| [R-17: Documentation](#2217-r-17-documentation-and-timeline-maintenance) | **Exclusive timeline owner**: `docs/timeline.md` only. Nine sections including Gantt charts, status, completion history, risk tables. | Single (exclusive domain) | [22.17](#2217-r-17-documentation-and-timeline-maintenance) | +| [R-82: Surgical Edit](#2282-r-82-timeline-surgical-edit-and-append-only-protocol) | Append-only history, one entry per day, strikethrough for resolved risks, conservative data policy, PlantUML Gantt color codes | Single (exclusive protocol) | [22.82](#2282-r-82-timeline-surgical-edit-and-append-only-protocol) | +| [R-57: Clone Isolation](#2257-r-57-clone-isolation-and-safety) | Creates isolated clone for timeline edits; pushes via PR workflow | Protocol user | [22.57](#2257-r-57-clone-isolation-and-safety) | + ### 9.10 Project Owner Supervisor | Property | Value | @@ -2066,6 +2356,22 @@ Status tracking issues (title contains `Status:`) are cleaned up aggressively (1 **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](#79-universal-supervisor-responsibilities-all-18-supervisors):* + +| Responsibility | Role | Redundancy Layer | Section | +|---------------|------|-----------------|---------| +| [R-02: Issue Triage](#222-r-02-issue-triage-verification-and-priority-management) | **Primary triager**: assigns MoSCoW labels (exclusive authority), sets priorities, verifies issues, transitions states | Layer 1 (strategic triage) | [22.2](#222-r-02-issue-triage-verification-and-priority-management) | +| [R-107: MoSCoW Framework](#22107-r-107-moscow-decision-framework) | 11-signal framework: Must (MUST/required/blocks/demo), Should (SHOULD/quality/perf), Could (MAY/polish/refactor) | Single (exclusive) | [22.107](#22107-r-107-moscow-decision-framework) | +| [R-108: Priority Re-eval](#22108-r-108-strategic-priority-re-evaluation) | Every 10 cycles: MoSCoW drift, milestone health (>50% open + >50% time), scope health (creation/closure rates) | Single | [22.108](#22108-r-108-strategic-priority-re-evaluation) | +| [R-109: Assignment Gate](#22109-r-109-developer-assignment-decision-gate) | 4-condition gate: expertise >0.7, capacity, velocity >1.3×, no blocking risks. 5 blocking scenarios. Golden Rule. | Single | [22.109](#22109-r-109-developer-assignment-decision-gate) | +| [R-48: Developer Assignment](#2248-r-48-developer-expertise-discovery-and-assignment) | **Primary assigner**: git history analysis, expertise mapping, strategic delegation | Layer 1 (discovery & assignment) | [22.48](#2248-r-48-developer-expertise-discovery-and-assignment) | +| [R-47: Timeout Management](#2247-r-47-human-response-timeout-management) | Follows up on developer questions after 48h, triages independently after 96h | Layer 2 (follow-up) | [22.47](#2247-r-47-human-response-timeout-management) | +| [R-18: Human Communication](#2218-r-18-human-communication-and-escalation) | Tags developers with questions, assigns developers to issues based on expertise, follows up on pending questions | Layer 2 (strategic questions) | [22.18](#2218-r-18-human-communication-and-escalation) | +| [R-19: Scope Management](#2219-r-19-scope-management-and-milestone-control) | Strategic priority review every 10th cycle: MoSCoW re-evaluation, milestone health check, scope health check | Governance | [22.19](#2219-r-19-scope-management-and-milestone-control) | +| [R-09: Label Correctness](#229-r-09-label-and-metadata-correctness) | Assigns MoSCoW, priority, and type labels via Forgejo Label Manager | Layer 2 (initial assignment) | [22.9](#229-r-09-label-and-metadata-correctness) | + ### 9.11 System Watchdog Supervisor | Property | Value | @@ -2141,6 +2447,41 @@ When the System Watchdog detects violations, it dispatches one-off fix agents vi | 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](#79-universal-supervisor-responsibilities-all-18-supervisors):* + +!!! 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](#221-r-01-supervisor-liveness-and-health-monitoring) | 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](#221-r-01-supervisor-liveness-and-health-monitoring) | +| [R-32: Master CI Emergency](#2232-r-32-master-ci-health-emergency-response) | Audit 0 (EMERGENCY): detects master CI failures, parses logs for specific failing tests, creates CI-Blocker issues | Layer 1 (detection & triage) | [22.32](#2232-r-32-master-ci-health-emergency-response) | +| [R-06: Quality Gate Enforcement](#226-r-06-quality-gate-enforcement) | Audit 1: quality gate compliance; Audit 2: branch protection verification | Layer 3 (post-merge audit) | [22.6](#226-r-06-quality-gate-enforcement) | +| [R-33: Flaky Test Detection](#2233-r-33-flaky-test-detection-and-prevention) | Audit 9: monitors CI execution times, detects recurring failures on same tests across PRs | Layer 2 (infrastructure detection) | [22.33](#2233-r-33-flaky-test-detection-and-prevention) | +| [R-07: PR Fixing](#227-r-07-pr-fixing-and-ci-remediation) | Audit 5b: detects struggling PRs with 3+ fix attempts; requests human help | Layer 3 (struggling detection) | [22.7](#227-r-07-pr-fixing-and-ci-remediation) | +| [R-55: Post-Merge Verification](#2255-r-55-post-merge-state-verification) | Monitors for "merged successfully" comments on still-open PRs (false-merge detection) | Layer 3 (audit) | [22.55](#2255-r-55-post-merge-state-verification) | +| [R-08: PR Merging](#228-r-08-pr-merging-and-post-merge-verification) | Audit 5: tracks PR aging, review coverage, merge throughput | Layer (health monitoring) | [22.8](#228-r-08-pr-merging-and-post-merge-verification) | +| [R-09: Label Correctness](#229-r-09-label-and-metadata-correctness) | Audit 7: verifies all issues have required labels and dependency links | Layer 4 (audit) | [22.9](#229-r-09-label-and-metadata-correctness) | +| [R-39: Blocked Chains](#2239-r-39-blocked-chain-analysis-and-resolution) | Audit 7/8: detects orphan issues and hierarchy violations in dependency graph | Layer 3 (audit) | [22.39](#2239-r-39-blocked-chain-analysis-and-resolution) | +| [R-10: Issue State Management](#2210-r-10-issue-state-lifecycle-management) | Audit 3: checks closed issues with wrong state, In Review without PR, multiple State labels | Layer 3 (audit) | [22.10](#2210-r-10-issue-state-lifecycle-management) | +| [R-11: Dependency Integrity](#2211-r-11-dependency-and-hierarchy-integrity) | Audit 8: verifies Epic→Legendary hierarchy intact, minimum children, orphan detection | Layer 3 (audit) | [22.11](#2211-r-11-dependency-and-hierarchy-integrity) | +| [R-12: Merge Safety](#2212-r-12-merge-safety-and-branch-protection) | Audit 2: verifies branch protection configuration; dispatches Quality Enforcer for violations | Layer 3 (audit) | [22.12](#2212-r-12-merge-safety-and-branch-protection) | +| [R-02: Issue Triage](#222-r-02-issue-triage-verification-and-priority-management) | Audit 4: verifies priority/milestone ordering is correct | Layer 3b (audit) | [22.2](#222-r-02-issue-triage-verification-and-priority-management) | +| [R-18: Human Escalation](#2218-r-18-human-communication-and-escalation) | Audit 5b: independently requests human assistance for struggling PRs | Layer 3b (independent escalation) | [22.18](#2218-r-18-human-communication-and-escalation) | +| [R-20: Automation Tracking](#2220-r-20-automation-tracking-and-inter-agent-coordination) | Audit 11: monitors tracking health, detects stalled agents, triggers recovery | Layer 4 (health monitoring) | [22.20](#2220-r-20-automation-tracking-and-inter-agent-coordination) | +| [R-45: Cycle Interval](#2245-r-45-estimated-cycle-interval-maintenance) | Audit 11: parses estimated interval from tracking issues, detects frozen agents when age > 2× interval | Layer 2 (consumption) | [22.45](#2245-r-45-estimated-cycle-interval-maintenance) | +| [R-44: Context Management](#2244-r-44-context-window-self-management) | Audit 6: detects context-exhausted zombies via sleep-only pattern in session messages | Layer 2 (external detection) | [22.44](#2244-r-44-context-window-self-management) | +| [R-22: Self-Improvement](#2222-r-22-self-improvement-and-agent-evolution) | Deep session introspection detects misbehavior patterns; creates `needs-feedback` issues for systemic problems | Layer 2 (problem detection) | [22.22](#2222-r-22-self-improvement-and-agent-evolution) | +| [R-23: Security](#2223-r-23-security-and-credential-management) | Audit 12/13: session spot-checks for forbidden patterns (`force_merge`, `type: ignore`, direct master push) | Layer 3 (behavioral audit) | [22.23](#2223-r-23-security-and-credential-management) | +| [R-71: Never-Disable-Checks](#2271-r-71-never-disable-checks-safety-constraint) | Audits for coverage reduction, CI step removal, `type: ignore` additions | Layer 3 (audit) | [22.71](#2271-r-71-never-disable-checks-safety-constraint) | +| [R-136: No type:ignore](#22136-r-136-static-typing-and-type-ignore-prohibition) | Audit 12/13: session spot-checks for `type: ignore` in tool outputs | Layer 3 (audit) | [22.136](#22136-r-136-static-typing-and-type-ignore-prohibition) | +| [R-139: 97% Coverage](#22139-r-139-coverage-threshold-enforcement-97-percent) | Audit 1: verifies master commits have passing coverage | Layer 3 (audit) | [22.139](#22139-r-139-coverage-threshold-enforcement-97-percent) | +| [R-72: Stale PR Detection](#2272-r-72-stale-pr-detection-and-remediation) | Audit 5: detects PRs >24h without reviews, approved >6h without merge, CI failing >2h | Layer 2 (pipeline) | [22.72](#2272-r-72-stale-pr-detection-and-remediation) | +| [R-90: Alert Dispatch](#2290-r-90-watchdog-alert-response-and-dispatch) | Dispatches Quality Enforcer, State Reconciler; re-launches offending supervisors; creates needs-feedback issues | Single (dispatcher) | [22.90](#2290-r-90-watchdog-alert-response-and-dispatch) | + --- ## 10. Implementation Workers (Tier 2) @@ -2314,6 +2655,36 @@ The Implementation Worker calls more subagents than any other agent in the syste | `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](#224-r-04-issue-implementation) | **Primary executor**: claims issue, creates clone, implements subtasks via wave dispatch, creates PR, shepherds to merge | Execution | [22.4](#224-r-04-issue-implementation) | +| [R-93: Wave Dispatch](#2293-r-93-subtask-wave-dispatch-and-parallel-conflict-resolution) | Builds dependency graph, dispatches parallel waves, detects post-wave conflicts, auto-resolves or re-runs sequentially | Single | [22.93](#2293-r-93-subtask-wave-dispatch-and-parallel-conflict-resolution) | +| [R-24: Work Claiming](#2224-r-24-work-item-claiming-and-coordination) | Posts `[CLAIM]`/`[HEARTBEAT]`/`[RELEASE]` comments; checks for existing claims; try/finally release guarantee | Layer 1 (claiming) | [22.24](#2224-r-24-work-item-claiming-and-coordination) | +| [R-25: Test Writing](#2225-r-25-test-writing-and-tdd-lifecycle) | Removes `@tdd_expected_fail` from passing TDD tests after bug fixes; delegates test creation to testers | Layer 2 (TDD cleanup) | [22.25](#2225-r-25-test-writing-and-tdd-lifecycle) | +| [R-07: PR Fixing](#227-r-07-pr-fixing-and-ci-remediation) | In pr-fix mode: fixes CI, handles review feedback, resolves merge conflicts | Worker level | [22.7](#227-r-07-pr-fixing-and-ci-remediation) | +| [R-94: Deep Context](#2294-r-94-deep-context-gathering-before-pr-fixes) | 7-step context gathering: spec, timeline, comments, commits, previous fixes, CI logs, actual code | Single | [22.94](#2294-r-94-deep-context-gathering-before-pr-fixes) | +| [R-95: Loop Prevention](#2295-r-95-fix-attempt-loop-prevention-and-stuck-detection) | Hash-based duplicate detection, CI error signature comparison, stuck_counter escalation after 3 | Layer 1 (self-detect) | [22.95](#2295-r-95-fix-attempt-loop-prevention-and-stuck-detection) | +| [R-96: PR Lifecycle](#2296-r-96-pr-lifecycle-monitoring-loop) | Max 10 review cycles at 5-min intervals; checks merge/conflict/review/CI each cycle | Single | [22.96](#2296-r-96-pr-lifecycle-monitoring-loop) | +| [R-97: Feedback Routing](#2297-r-97-review-feedback-type-based-routing) | Parses feedback via regex into code/test/docs/style; routes to specialist subagent | Single | [22.97](#2297-r-97-review-feedback-type-based-routing) | +| [R-27: CI Log Retrieval](#2227-r-27-ci-log-retrieval-and-diagnosis) | Invokes `ci-log-fetcher` subagent for CI failure diagnosis | Layer 3 (consumer) | [22.27](#2227-r-27-ci-log-retrieval-and-diagnosis) | +| [R-54: 3-Tier Approval](#2254-r-54-three-tier-approval-detection) | `has_required_approvals()` checks formal reviews, review bodies, issue comments for approval keywords | Consumer | [22.54](#2254-r-54-three-tier-approval-detection) | +| [R-08: PR Merging](#228-r-08-pr-merging-and-post-merge-verification) | In ready-to-merge mode: verifies approvals, rebases if needed, delegates to `safe_merge_pr()` | Layer 2 (backup merger) | [22.8](#228-r-08-pr-merging-and-post-merge-verification) | +| [R-55: Post-Merge Verification](#2255-r-55-post-merge-state-verification) | After merge: verifies `merged == true` via API; only posts "(verified)" comment after confirmation | Layer 1 (inline) | [22.55](#2255-r-55-post-merge-state-verification) | +| [R-28: Issue Closure](#2228-r-28-issue-closure-and-post-merge-cleanup) | After verified merge: transitions issue to State/Completed, posts final comment, deletes clone | Layer 1 (immediate) | [22.28](#2228-r-28-issue-closure-and-post-merge-cleanup) | +| [R-57: Clone Isolation](#2257-r-57-clone-isolation-and-safety) | Creates clone at `/tmp/cleveragents-`, configures auth/remotes, deletes on exit | Protocol user | [22.57](#2257-r-57-clone-isolation-and-safety) | +| [R-30: Branch Management](#2230-r-30-branch-management-and-rebase) | Pre-commit rebase onto master; pre-merge rebase if behind; auto-resolves simple conflicts | Layer 3 (worker rebase) | [22.30](#2230-r-30-branch-management-and-rebase) | +| [R-34: Test Stability](#2234-r-34-test-stability-enforcement) | Enforces strict determinism rules: no timing deps, no unseeded random, no shared filesystem, no network deps | Layer 1 (rules) | [22.34](#2234-r-34-test-stability-enforcement) | +| [R-18: Human Escalation](#2218-r-18-human-communication-and-escalation) | After 3 stuck detections: posts diagnostic comment, adds `needs feedback` label, exits gracefully | Layer 3 (self-escalation) | [22.18](#2218-r-18-human-communication-and-escalation) | +| [R-21: Crash Recovery](#2221-r-21-crash-recovery-and-state-persistence) | Phase 0.5 crash recovery: checks for existing clone, PR, commits, uncommitted changes; resumes from appropriate phase | Worker level | [22.21](#2221-r-21-crash-recovery-and-state-persistence) | +| [R-70: TDD Workflow](#2270-r-70-tdd-workflow-awareness-in-bug-reports) | Searches for `@tdd_issue_N` tests; removes `@tdd_expected_fail` after bug fix | Layer 2 (TDD execution) | [22.70](#2270-r-70-tdd-workflow-awareness-in-bug-reports) | +| [R-84: Checkpoint Persistence](#2284-r-84-checkpoint-and-state-persistence-via-forgejo-comments) | Posts `[CHECKPOINT]` comments with phase state JSON for crash recovery | Single (per worker) | [22.84](#2284-r-84-checkpoint-and-state-persistence-via-forgejo-comments) | +| [R-135: File Organization](#22135-r-135-file-organization-enforcement) | Delegates to specialist testers that know their target directories | Layer 1 (implementation) | [22.135](#22135-r-135-file-organization-enforcement) | +| [R-137: 500-Line Limit](#22137-r-137-maximum-file-size-enforcement-500-lines) | "Maximum 500 lines per file" — must split files growing beyond this | Layer 1 (implementation) | [22.137](#22137-r-137-maximum-file-size-enforcement-500-lines) | +| [R-141: Startup Sequence](#22141-r-141-supervisor-mandatory-startup-sequence) | Not a supervisor but follows the issue-impl startup sequence: announcements → crash recovery → claiming | Protocol | [22.141](#22141-r-141-supervisor-mandatory-startup-sequence) | +| [R-09: Label Correctness](#229-r-09-label-and-metadata-correctness) | Sets labels on issues/PRs it creates via Forgejo Label Manager delegation | Layer 2 (initial assignment) | [22.9](#229-r-09-label-and-metadata-correctness) | + --- ## 11. Progressive Escalation (Tier 3) @@ -2380,6 +2751,33 @@ These agents have no model specified in their frontmatter; they inherit the mode | **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](#2231-r-31-progressive-model-escalation) | **Orchestrator**: manages haiku→codex→sonnet→opus schedule; persists state as HTML comments | [22.31](#2231-r-31-progressive-model-escalation) | +| [R-56: Meaningful Change](#2256-r-56-meaningful-change-verification) | Rejects <3 functional lines; prevents trivial implementations from passing gates | [22.56](#2256-r-56-meaningful-change-verification) | +| [R-110: Per-Gate Tier Tracking](#22110-r-110-per-gate-independent-tier-tracking) | Independent `{gate: tier}` map; 5 inner passes; selective re-run; individual gate escalation | [22.110](#22110-r-110-per-gate-independent-tier-tracking) | +| [R-111: Opus Diagnostics](#22111-r-111-periodic-diagnostics-at-opus-tier) | Posts diagnostic comments every 3 attempts after attempt 4 at opus tier | [22.111](#22111-r-111-periodic-diagnostics-at-opus-tier) | +| [R-25: Test Writing](#2225-r-25-test-writing-and-tdd-lifecycle) | Launches Behave + Robot + ASV testers in parallel; monitors with 10s polling | [22.25](#2225-r-25-test-writing-and-tdd-lifecycle) | +| [R-06: Quality Gates](#226-r-06-quality-gate-enforcement) | Runs lint, typecheck, unit, integration, coverage gates before PR creation | [22.6](#226-r-06-quality-gate-enforcement) | +| [R-62: Correctness Verification](#2262-r-62-implementation-correctness-verification) | Invokes Implementation Reviewer after quality gates pass | [22.62](#2262-r-62-implementation-correctness-verification) | +| [R-56b: Transient Errors](#2256b-r-56b-transient-error-classification-and-retry) | Retries transient errors (timeout, 429) without incrementing attempt counter | [22.56b](#2256b-r-56b-transient-error-classification-and-retry) | +| [R-144: Tier Pass-Through](#22144-r-144-tier-selector-pure-pass-through-constraint) | Invokes tier selectors that must forward context unmodified | [22.144](#22144-r-144-tier-selector-pure-pass-through-constraint) | + +#### 11.4.1 Specialized Worker Responsibilities + +| Worker | Responsibilities | Sections | +|--------|-----------------|---------| +| **Implementer** | [R-04](#224-r-04-issue-implementation) (code writing), [R-135](#22135-r-135-file-organization-enforcement) (correct directories), [R-137](#22137-r-137-maximum-file-size-enforcement-500-lines) (500-line limit), [R-64](#2264-r-64-nox-routing-enforcement) (nox routing) | 22.4, 22.135, 22.137, 22.64 | +| **Behave Tester** | [R-25](#2225-r-25-test-writing-and-tdd-lifecycle) (BDD tests), [R-138](#22138-r-138-testing-framework-selection-rules) (Behave framework), [R-34](#2234-r-34-test-stability-enforcement) (determinism), [R-70](#2270-r-70-tdd-workflow-awareness-in-bug-reports) (TDD tags) | 22.25, 22.138, 22.34, 22.70 | +| **Robot Tester** | [R-25](#2225-r-25-test-writing-and-tdd-lifecycle) (integration tests), [R-138](#22138-r-138-testing-framework-selection-rules) (Robot framework, no mocking), [R-34](#2234-r-34-test-stability-enforcement) (determinism) | 22.25, 22.138, 22.34 | +| **Lint Fixer** | [R-06](#226-r-06-quality-gate-enforcement) (lint gate), [R-64](#2264-r-64-nox-routing-enforcement) (`nox -e lint`) | 22.6, 22.64 | +| **Typecheck Fixer** | [R-06](#226-r-06-quality-gate-enforcement) (typecheck gate), [R-136](#22136-r-136-static-typing-and-type-ignore-prohibition) (no `type: ignore`), [R-64](#2264-r-64-nox-routing-enforcement) (`nox -e typecheck`) | 22.6, 22.136, 22.64 | +| **Coverage Improver** | [R-139](#22139-r-139-coverage-threshold-enforcement-97-percent) (≥97% threshold), [R-06](#226-r-06-quality-gate-enforcement) (coverage gate) | 22.139, 22.6 | +| **Test Fixer** | [R-06](#226-r-06-quality-gate-enforcement) (test fixing), [R-34](#2234-r-34-test-stability-enforcement) (distinguishes obsolete from genuine bugs) | 22.6, 22.34 | +| **Unit/Integration Test Runner** | [R-06](#226-r-06-quality-gate-enforcement) (test execution), [R-64](#2264-r-64-nox-routing-enforcement) (`nox -e unit_tests`/`integration_tests`) | 22.6, 22.64 | + --- ## 12. Supporting Agents @@ -2459,6 +2857,16 @@ The PR Reviewer warrants detailed specification because of its critical dual-acc **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](#2226-r-26-pr-creation-and-metadata-inheritance) (label inheritance, dependency link, state transition), [R-35](#2235-r-35-pr-issue-label-synchronization) (initial label sync), [R-131](#22131-r-131-standard-pr-body-format-enforcement) (body format), [R-127](#22127-r-127-label-creation-prohibition-enforcement) (via Label Manager delegation) | 22.26, 22.35, 22.131, 22.127 | +| **PR CI Test Fixer** | [R-91](#2291-r-91-amend-only-commit-protocol-for-ci-fixes) (amend-only, force-push-with-lease), [R-27](#2227-r-27-ci-log-retrieval-and-diagnosis) (CI log consumption), [R-06](#226-r-06-quality-gate-enforcement) (post-PR quality fixes), [R-59](#2259-r-59-pr-description-preservation) (body preservation on amend) | 22.91, 22.27, 22.6, 22.59 | +| **PR Editor** | [R-59](#2259-r-59-pr-description-preservation) (**primary enforcer**: fetch-before-edit for body preservation), [R-127](#22127-r-127-label-creation-prohibition-enforcement) (labels via Label Manager only) | 22.59, 22.127 | +| **PR Reviewer** | [R-05](#225-r-05-code-review-and-quality-assessment), [R-52](#2252-r-52-dual-account-review-authentication), [R-53](#2253-r-53-anti-pattern-and-code-smell-detection), [R-101](#22101-r-101-flaky-test-16-pattern-detection), [R-135](#22135-r-135-file-organization-enforcement), [R-136](#22136-r-136-static-typing-and-type-ignore-prohibition), [R-137](#22137-r-137-maximum-file-size-enforcement-500-lines), [R-138](#22138-r-138-testing-framework-selection-rules), [R-140](#22140-r-140-conventional-changelog-commit-format) | 22.5, 22.52, 22.53, 22.101, 22.135–22.140 | +| **PR Status Analyzer** | [R-118](#22118-r-118-pr-status-analyzer-5-dimension-framework) (5-dimension analysis) | 22.118 | + ### 12.2 Issue Management Agents | Agent | Purpose | Model | @@ -2487,6 +2895,17 @@ The New Issue Creator applies a strict scope guard for milestone assignment: 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](#2210-r-10-issue-state-lifecycle-management) (state transitions), [R-60](#2260-r-60-state-transition-precondition-enforcement) (precondition validation, blocker checks, PR sync), [R-128](#22128-r-128-valid-state-transition-matrix-enforcement) (valid transition matrix), [R-127](#22127-r-127-label-creation-prohibition-enforcement) (one of two agents permitted to call `forgejo_add_issue_labels`) | 22.10, 22.60, 22.128, 22.127 | +| **New Issue Creator** | [R-37](#2237-r-37-milestone-assignment-and-scope-guard) (milestone scope guard), [R-130](#22130-r-130-standard-issue-body-format-enforcement) (Metadata/Subtasks/DoD format), [R-38](#2238-r-38-issue-body-and-dod-compliance) (body compliance at creation), [R-11](#2211-r-11-dependency-and-hierarchy-integrity) (child-blocks-parent Epic link), [R-127](#22127-r-127-label-creation-prohibition-enforcement) (labels via Label Manager) | 22.37, 22.130, 22.38, 22.11, 22.127 | +| **Issue Analyzer** | [R-115](#22115-r-115-issue-analyzer-structured-data-extraction) (structured data extraction: metadata, subtasks, DoD, comments, deps) | 22.115 | +| **Issue Note Writer** | [R-117](#22117-r-117-issue-note-writer-logical-reference-protocol) (logical code references, never line numbers, mandatory 7-section format) | 22.117 | +| **Subtask Checker** | [R-116](#22116-r-116-subtask-checker-fuzzy-match-checkbox-toggle) (fuzzy-match checkbox toggle, body preservation) | 22.116 | +| **Issue Comment Formatter** | [R-83](#2283-r-83-issue-comment-type-formatting-standards) (5 comment types: progress/error/success/analysis/status) | 22.83 | + ### 12.3 Git and Repository Agents | Agent | Purpose | Model | @@ -2497,6 +2916,16 @@ The New Issue Creator applies a strict scope guard for milestone assignment: | **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](#2257-r-57-clone-isolation-and-safety) (clone creation in `/tmp/isolated-*`, auth URL construction, safety validation — refuses `/`, `/tmp`, `/app` deletion, retry cleanup 3×), [R-114](#22114-r-114-startup-credential-validation-gate) (PAT validation before clone) | 22.57, 22.114 | +| **Branch Setup** | [R-30](#2230-r-30-branch-management-and-rebase) (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](#2229-r-29-commit-formatting-and-git-operations) (stage all, commit, dual-remote push: origin then upstream, both required, error reporting with full context) | 22.29 | +| **Git Commit Helper** | [R-29](#2229-r-29-commit-formatting-and-git-operations) (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](#2227-r-27-ci-log-retrieval-and-diagnosis) (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 | @@ -2519,6 +2948,15 @@ The Ref Material Loader implements a parent-child caching model to reduce redund 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](#2261-r-61-reference-material-caching-and-distribution) (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](#2261-r-61-reference-material-caching-and-distribution) (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](#2261-r-61-reference-material-caching-and-distribution) (issue-relevant extraction: filters full spec to applicable modules, interfaces, data models, cross-cutting concerns) | 22.61 | +| **Difficulty Evaluator** | [R-119](#22119-r-119-difficulty-evaluator-5-criteria-assessment) (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 | @@ -2527,6 +2965,14 @@ The Difficulty Evaluator recommends starting model tiers based on a five-axis as | **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](#229-r-09-label-and-metadata-correctness) (label application), [R-58](#2258-r-58-label-name-to-id-resolution-and-conflict-prevention) (name→ID resolution, conflict detection, MoSCoW exclusivity), [R-127](#22127-r-127-label-creation-prohibition-enforcement) (cannot create labels — only apply existing) | 22.9, 22.58, 22.127 | +| **Forgejo Signature Appender** | [R-63](#2263-r-63-bot-signature-standardization) (3 format types, signature dedup on updates, format validation) | 22.63 | +| **Automation Tracking Manager** | [R-20](#2220-r-20-automation-tracking-and-inter-agent-coordination) (11 tracking operations), [R-42](#2242-r-42-tracking-issue-cleanup-and-deduplication) (close-all protocol), [R-45](#2245-r-45-estimated-cycle-interval-maintenance) (rolling average calculation), [R-143](#22143-r-143-dual-status-issue-cleanup-defense-in-depth) (primary close-all-then-create), [R-132](#22132-r-132-subagent-specialization-principle) (centralized tracking logic) | 22.20, 22.42, 22.45, 22.143, 22.132 | + ### 12.6 Quality and Verification Agents | Agent | Purpose | Model | @@ -2537,6 +2983,16 @@ The Difficulty Evaluator recommends starting model tiers based on a five-axis as | **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](#2262-r-62-implementation-correctness-verification) (requirement-by-requirement cross-reference; "would-fail" test reasoning; rejects for functional gaps, not style) | 22.62 | +| **Milestone Reviewer** | [R-120](#22120-r-120-milestone-reviewer-holistic-integration-review) (8-area cross-issue review; PASS/PASS WITH ISSUES/FAIL assessment; creates issues for gaps) | 22.120 | +| **Product Verifier** | [R-67](#2267-r-67-product-completion-verification) (10-point checklist: milestones, issues, PRs, tests, coverage, spec, docs, code quality, blockers, branches) | 22.67 | +| **Quality Enforcer** | [R-12](#2212-r-12-merge-safety-and-branch-protection) (branch protection repair), [R-32](#2232-r-32-master-ci-health-emergency-response) (`Priority/CI-Blocker` issue creation), [R-90](#2290-r-90-watchdog-alert-response-and-dispatch) (dispatched by Watchdog for violations) | 22.12, 22.32, 22.90 | +| **State Reconciler** | [R-10](#2210-r-10-issue-state-lifecycle-management) (8 reconciliation rules for bulk fixes), [R-09](#229-r-09-label-and-metadata-correctness) (bulk label correction), [R-11](#2211-r-11-dependency-and-hierarchy-integrity) (dependency direction fixes) | 22.10, 22.9, 22.11 | + ### 12.7 Session Management Agents | Agent | Purpose | Model | @@ -2548,6 +3004,13 @@ The Difficulty Evaluator recommends starting model tiers based on a five-axis as | **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](#2275-r-75-session-naming-and-tag-convention) (`[TAG] display-name` convention, 24+ prefixes, duplicate prevention), [R-122](#22122-r-122-prompt-async-mandatory-for-supervisor-launch) (exclusive `localhost:4096` access), [R-56b](#2256b-r-56b-transient-error-classification-and-retry) (5-attempt exponential backoff) | 22.75, 22.122, 22.56b | +| **Async Agent Monitor** | [R-76](#2276-r-76-async-session-health-detection) (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. @@ -3452,6 +3915,2783 @@ The Branch Setup agent creates or checks out branches with a strict rebase-only --- +## 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 7–12) 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 (A–H) in the index. Each category is subdivided into 2–8 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](#223-r-03-work-planning-and-decomposition) | Work Planning and Decomposition | Double | Epic Planner, Architecture Supervisor | +| [R-68](#2268-r-68-epic-and-legendary-closure-evaluation) | Epic and Legendary Closure Evaluation | Double | Epic Planner, Backlog Groomer | +| [R-69](#2269-r-69-orphaned-issue-and-epic-remediation) | Orphaned Issue and Epic Remediation | Triple | Epic Planner, Backlog Groomer, Watchdog | +| [R-24](#2224-r-24-work-item-claiming-and-coordination) | Work Item Claiming and Coordination | Double | Implementation Worker, Backlog Groomer | +| [R-49](#2249-r-49-pr-ownership-detection-and-work-scoring) | PR Ownership Detection and Work Scoring | Single | Implementation Pool | +| [R-98](#2298-r-98-issue-dispatch-priority-ordering-rules) | Issue Dispatch Priority Ordering Rules | Single | Implementation Pool | +| [R-119](#22119-r-119-difficulty-evaluator-5-criteria-assessment) | Difficulty Evaluator 5-Criteria Assessment | Single | Difficulty Evaluator | + +**A.2 — Implementation and Testing** + +| ID | Responsibility | Redundancy | Primary Agent(s) | +|----|---------------|-----------|-------------------| +| [R-04](#224-r-04-issue-implementation) | Issue Implementation | Single (crash recovery) | Implementation Pool, Implementation Worker | +| [R-93](#2293-r-93-subtask-wave-dispatch-and-parallel-conflict-resolution) | Subtask Wave Dispatch and Parallel Conflict Resolution | Single | Implementation Worker | +| [R-56](#2256-r-56-meaningful-change-verification) | Meaningful Change Verification | Single | Subtask Loop | +| [R-31](#2231-r-31-progressive-model-escalation) | Progressive Model Escalation | Single | Subtask Loop, Tier Selectors | +| [R-25](#2225-r-25-test-writing-and-tdd-lifecycle) | Test Writing and TDD Lifecycle | Double | Behave Tester, Robot Tester, Implementation Worker | + +**A.3 — Quality Gates** + +| ID | Responsibility | Redundancy | Primary Agent(s) | +|----|---------------|-----------|-------------------| +| [R-06](#226-r-06-quality-gate-enforcement) | Quality Gate Enforcement | Triple | Subtask Loop, PR CI Test Fixer, System Watchdog | +| [R-110](#22110-r-110-per-gate-independent-tier-tracking) | Per-Gate Independent Tier Tracking | Single | Subtask Loop | +| [R-111](#22111-r-111-periodic-diagnostics-at-opus-tier) | Periodic Diagnostics at Opus Tier | Single | Subtask Loop | +| [R-91](#2291-r-91-amend-only-commit-protocol-for-ci-fixes) | 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](#2226-r-26-pr-creation-and-metadata-inheritance) | PR Creation and Metadata Inheritance | Double | PR Creator, Backlog Groomer | +| [R-05](#225-r-05-code-review-and-quality-assessment) | Code Review and Quality Assessment | Double | PR Review Pool, PR Reviewer | +| [R-52](#2252-r-52-dual-account-review-authentication) | Dual-Account Review Authentication | Single | PR Reviewer | +| [R-53](#2253-r-53-anti-pattern-and-code-smell-detection) | Anti-Pattern and Code Smell Detection | Triple | PR Reviewer, Architecture Guard, Bug Hunt Pool | +| [R-97](#2297-r-97-review-feedback-type-based-routing) | Review Feedback Type-Based Routing | Single | Implementation Worker | +| [R-112](#22112-r-112-pr-concurrent-work-conflict-matrix) | 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](#227-r-07-pr-fixing-and-ci-remediation) | PR Fixing and CI Remediation | Double | PR Fix Pool, Implementation Pool | +| [R-27](#2227-r-27-ci-log-retrieval-and-diagnosis) | CI Log Retrieval and Diagnosis | Single (shared tool) | CI Log Fetcher, System Watchdog | +| [R-94](#2294-r-94-deep-context-gathering-before-pr-fixes) | Deep Context Gathering Before PR Fixes | Single | Implementation Worker | +| [R-95](#2295-r-95-fix-attempt-loop-prevention-and-stuck-detection) | Fix Attempt Loop Prevention and Stuck Detection | Single | Implementation Worker | +| [R-96](#2296-r-96-pr-lifecycle-monitoring-loop) | PR Lifecycle Monitoring Loop | Single | Implementation Worker | + +**A.6 — Merging and Post-Merge** + +| ID | Responsibility | Redundancy | Primary Agent(s) | +|----|---------------|-----------|-------------------| +| [R-54](#2254-r-54-three-tier-approval-detection) | Three-Tier Approval Detection | Single (shared protocol) | PR Merge Pool, Implementation Worker | +| [R-99](#2299-r-99-pr-merge-seven-criteria-checklist) | PR Merge Seven Criteria Checklist | Single | PR Merge Pool | +| [R-100](#22100-r-100-blocking-review-temporal-detection) | Blocking Review Temporal Detection | Single | PR Merge Pool, Implementation Worker | +| [R-08](#228-r-08-pr-merging-and-post-merge-verification) | PR Merging and Post-Merge Verification | Double | PR Merge Pool, Implementation Worker | +| [R-55](#2255-r-55-post-merge-state-verification) | Post-Merge State Verification | Triple | PR Merge Pool, Implementation Worker, System Watchdog | +| [R-28](#2228-r-28-issue-closure-and-post-merge-cleanup) | Issue Closure and Post-Merge Cleanup | Triple | Implementation Worker, Backlog Groomer, PR Merge Pool | +| [R-102](#22102-r-102-merged-pr-issue-closure-with-dependency-cleanup) | 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](#2229-r-29-commit-formatting-and-git-operations) | Commit Formatting and Git Operations | Single (delegation) | Git Committer, Commit Message Formatter | +| [R-30](#2230-r-30-branch-management-and-rebase) | Branch Management and Rebase | Double | Branch Setup, PR Merge Pool | +| [R-59](#2259-r-59-pr-description-preservation) | PR Description Preservation | Double | PR Editor, Spec Evolution | +| [R-77](#2277-r-77-push-conflict-recovery-protocol) | Push Conflict Recovery Protocol | Single (shared) | All pushing agents | + +**A.8 — Lifecycle Events** + +| ID | Responsibility | Redundancy | Primary Agent(s) | +|----|---------------|-----------|-------------------| +| [R-65](#2265-r-65-specification-pr-monitoring-and-lifecycle) | Specification PR Monitoring and Lifecycle | Double | Product Builder, Spec Evolution | +| [R-66](#2266-r-66-finding-validation-gate-before-issue-filing) | Finding Validation Gate Before Issue Filing | Triple | Bug Hunt, Test Infra, UAT | +| [R-67](#2267-r-67-product-completion-verification) | Product Completion Verification | Single | Product Verifier | +| [R-93](#2293-r-93-subtask-wave-dispatch-and-parallel-conflict-resolution) | Subtask Wave Dispatch and Parallel Conflict Resolution | Single | Implementation Worker | +| [R-94](#2294-r-94-deep-context-gathering-before-pr-fixes) | Deep Context Gathering Before PR Fixes | Single | Implementation Worker | +| [R-95](#2295-r-95-fix-attempt-loop-prevention-and-stuck-detection) | Fix Attempt Loop Prevention and Stuck Detection | Single | Implementation Worker | +| [R-96](#2296-r-96-pr-lifecycle-monitoring-loop) | PR Lifecycle Monitoring Loop | Single | Implementation Worker | +| [R-97](#2297-r-97-review-feedback-type-based-routing) | Review Feedback Type-Based Routing | Single | Implementation Worker | +| [R-98](#2298-r-98-issue-dispatch-priority-ordering-rules) | Issue Dispatch Priority Ordering Rules | Single | Implementation Pool | +| [R-112](#22112-r-112-pr-concurrent-work-conflict-matrix) | PR Concurrent Work Conflict Matrix | Single (shared protocol) | All PR-modifying agents | +| [R-91](#2291-r-91-amend-only-commit-protocol-for-ci-fixes) | 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](#2232-r-32-master-ci-health-emergency-response) | Master CI Health Emergency Response | Double | System Watchdog, Quality Enforcer | +| [R-12](#2212-r-12-merge-safety-and-branch-protection) | Merge Safety and Branch Protection | Triple | PR Merge Pool, System Watchdog, Quality Enforcer | +| [R-71](#2271-r-71-never-disable-checks-safety-constraint) | 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](#2233-r-33-flaky-test-detection-and-prevention) | Flaky Test Detection and Prevention | Double | PR Reviewer, System Watchdog | +| [R-34](#2234-r-34-test-stability-enforcement) | Test Stability Enforcement | Triple | Implementation Worker, PR Reviewer, Subtask Loop | +| [R-101](#22101-r-101-flaky-test-16-pattern-detection) | Flaky Test 16-Pattern Detection Checklist | Single | PR Reviewer | +| [R-70](#2270-r-70-tdd-workflow-awareness-in-bug-reports) | 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](#2262-r-62-implementation-correctness-verification) | Implementation Correctness Verification | Double | Implementation Reviewer, Milestone Reviewer | +| [R-120](#22120-r-120-milestone-reviewer-holistic-integration-review) | Milestone Reviewer Holistic Integration Review | Single (post-milestone) | Milestone Reviewer | +| [R-53](#2253-r-53-anti-pattern-and-code-smell-detection) | Anti-Pattern and Code Smell Detection | Triple | PR Reviewer, Architecture Guard, Bug Hunt Pool | +| [R-14](#2214-r-14-codebase-coherence-and-technical-debt) | 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](#2216-r-16-bug-detection-and-proactive-quality-assurance) | Bug Detection and Proactive Quality Assurance | Quadruple | Bug Hunt Pool, UAT Test Pool, PR Reviewer, Architecture Guard | +| [R-66](#2266-r-66-finding-validation-gate-before-issue-filing) | Finding Validation Gate Before Issue Filing | Triple | Bug Hunt, Test Infra, UAT | +| [R-86](#2286-r-86-open-pr-awareness-before-bug-filing) | 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](#229-r-09-label-and-metadata-correctness) | Label and Metadata Correctness | Quadruple | Forgejo Label Manager, Backlog Groomer | +| [R-58](#2258-r-58-label-name-to-id-resolution-and-conflict-prevention) | Label-Name-to-ID Resolution and Conflict Prevention | Single (centralized) | Forgejo Label Manager | +| [R-35](#2235-r-35-pr-issue-label-synchronization) | PR-Issue Label Synchronization | Double | Backlog Groomer, PR Creator | +| [R-36](#2236-r-36-story-point-estimation) | Story Point Estimation | Double | Backlog Groomer, Human Liaison | +| [R-127](#22127-r-127-label-creation-prohibition-enforcement) | 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](#2210-r-10-issue-state-lifecycle-management) | Issue State Lifecycle Management | Quadruple | Issue State Updater, Backlog Groomer | +| [R-60](#2260-r-60-state-transition-precondition-enforcement) | State Transition Precondition Enforcement | Double | Issue State Updater, Backlog Groomer | +| [R-128](#22128-r-128-valid-state-transition-matrix-enforcement) | 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](#2211-r-11-dependency-and-hierarchy-integrity) | Dependency and Hierarchy Integrity | Triple | Epic Planner, Backlog Groomer, System Watchdog | +| [R-103](#22103-r-103-wrong-direction-dependency-auto-fix) | Wrong-Direction Dependency Auto-Fix | Double | Backlog Groomer, Epic Planner | +| [R-104](#22104-r-104-priority-consistency-cross-check) | Priority Consistency Cross-Check | Double | Backlog Groomer, System Watchdog | + +**C.4 — Milestones and Scope** + +| ID | Responsibility | Redundancy | Primary Agent(s) | +|----|---------------|-----------|-------------------| +| [R-37](#2237-r-37-milestone-assignment-and-scope-guard) | Milestone Assignment and Scope Guard | Triple | New Issue Creator, Epic Planner, UAT Test Pool | +| [R-129](#22129-r-129-priority-ordering-rules-for-milestone-work) | 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](#2238-r-38-issue-body-and-dod-compliance) | Issue Body and Definition of Done Compliance | Double | Backlog Groomer, New Issue Creator | +| [R-130](#22130-r-130-standard-issue-body-format-enforcement) | Standard Issue Body Format Enforcement | Double | New Issue Creator, Backlog Groomer | +| [R-131](#22131-r-131-standard-pr-body-format-enforcement) | Standard PR Body Format Enforcement | Double | PR Creator, PR Description Writer | +| [R-115](#22115-r-115-issue-analyzer-structured-data-extraction) | Issue Analyzer Structured Data Extraction | Single (subagent) | Issue Analyzer | +| [R-116](#22116-r-116-subtask-checker-fuzzy-match-checkbox-toggle) | Subtask Checker Fuzzy Match Checkbox Toggle | Single (subagent) | Subtask Checker | +| [R-117](#22117-r-117-issue-note-writer-logical-reference-protocol) | Issue Note Writer Logical Reference Protocol | Single (subagent) | Issue Note Writer | +| [R-118](#22118-r-118-pr-status-analyzer-5-dimension-framework) | PR Status Analyzer 5-Dimension Framework | Single (subagent) | PR Status Analyzer | + +**C.6 — Backlog Hygiene** + +| ID | Responsibility | Redundancy | Primary Agent(s) | +|----|---------------|-----------|-------------------| +| [R-15](#2215-r-15-backlog-hygiene-and-duplicate-detection) | Backlog Hygiene and Duplicate Detection | Double | Backlog Groomer, Test Infrastructure Pool | +| [R-72](#2272-r-72-stale-pr-detection-and-remediation) | Stale PR Detection and Remediation | Double | Backlog Groomer, System Watchdog | +| [R-39](#2239-r-39-blocked-chain-analysis-and-resolution) | 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](#2213-r-13-specification-and-architecture-governance) | Specification and Architecture Governance | Double | Architecture Supervisor, Spec Evolution | +| [R-40](#2240-r-40-specification-first-development-enforcement) | Specification-First Development Enforcement | Double | Epic Planner, Architecture Supervisor | +| [R-73](#2273-r-73-spec-change-classification-and-two-step-proposal) | Spec Change Classification and Two-Step Proposal | Double | Architecture Supervisor, Spec Evolution | +| [R-92](#2292-r-92-proactive-specification-scan-protocol) | Proactive Specification Scan Protocol | Single | Spec Evolution | + +**D.2 — Codebase Scanning** + +| ID | Responsibility | Redundancy | Primary Agent(s) | +|----|---------------|-----------|-------------------| +| [R-74](#2274-r-74-sha-based-idle-detection-for-scanners) | SHA-Based Idle Detection for Scanners | Single | Architecture Guard, Spec Evolution | +| [R-132](#22132-r-132-subagent-specialization-principle) | 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](#221-r-01-supervisor-liveness-and-health-monitoring) | Supervisor Liveness and Health Monitoring | Triple | Product Builder, System Watchdog | +| [R-50](#2250-r-50-worker-session-adoption-and-lifecycle) | Worker Session Adoption and Lifecycle | Single per pool | Pool Supervisors | +| [R-41](#2241-r-41-worker-dispatch-and-sliding-window-management) | Worker Dispatch and Sliding Window Management | Single per pool | Pool Supervisors | +| [R-81](#2281-r-81-tiered-worker-allocation-formula) | Tiered Worker Allocation Formula | Single | Product Builder | +| [R-76](#2276-r-76-async-session-health-detection) | Async Session Health Detection | Double | Async Agent Monitor, Product Builder | +| [R-75](#2275-r-75-session-naming-and-tag-convention) | Session Naming and Tag Convention | Single (centralized) | Async Agent Manager | +| [R-122](#22122-r-122-prompt-async-mandatory-for-supervisor-launch) | prompt_async Mandatory for Supervisor Launch | Single (architectural) | Product Builder | +| [R-123](#22123-r-123-all-18-supervisors-mandatory-verification) | All 18 Supervisors Mandatory Verification | Single | Product Builder | +| [R-126](#22126-r-126-no-duplicate-supervisor-instances) | No Duplicate Supervisor Instances | Double | Product Builder, System Watchdog | + +**E.2 — Automation Tracking and Coordination** + +| ID | Responsibility | Redundancy | Primary Agent(s) | +|----|---------------|-----------|-------------------| +| [R-20](#2220-r-20-automation-tracking-and-inter-agent-coordination) | Automation Tracking and Inter-Agent Coordination | Triple | Automation Tracking Manager, Backlog Groomer, System Watchdog | +| [R-42](#2242-r-42-tracking-issue-cleanup-and-deduplication) | Tracking Issue Cleanup and Deduplication | Triple | Automation Tracking Manager, Backlog Groomer, Each Supervisor | +| [R-43](#2243-r-43-announcement-lifecycle-management) | Announcement Lifecycle Management | Double | Each Supervisor, Backlog Groomer | +| [R-133](#22133-r-133-announcement-consumption-priority-protocol) | Announcement Consumption Priority Protocol | Universal | All supervisors (per consumption table) | +| [R-45](#2245-r-45-estimated-cycle-interval-maintenance) | 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](#2221-r-21-crash-recovery-and-state-persistence) | Crash Recovery and State Persistence | Multi-level | Every agent (per level) | +| [R-84](#2284-r-84-checkpoint-and-state-persistence-via-forgejo-comments) | Checkpoint and State Persistence via Forgejo Comments | Single (per worker) | Implementation Worker | +| [R-44](#2244-r-44-context-window-self-management) | Context Window Self-Management | Single (per agent) | Long-running agents | +| [R-124](#22124-r-124-convergence-check-algorithm) | Convergence Check Algorithm | Single | Product Builder | +| [R-80](#2280-r-80-non-return-guarantee-enforcement) | Non-Return Guarantee Enforcement | Single | Product Builder | +| [R-125](#22125-r-125-product-builder-never-edits-or-merges-directly) | Product Builder Never Edits or Merges Directly | Single (prohibition) | Product Builder | + +**E.4 — Universal Agent Protocols** + +| ID | Responsibility | Redundancy | Primary Agent(s) | +|----|---------------|-----------|-------------------| +| [R-51](#2251-r-51-forgejo-api-pagination-and-truncation-recovery) | Forgejo API Pagination and Truncation Recovery | Universal | All Forgejo-querying agents | +| [R-57](#2257-r-57-clone-isolation-and-safety) | Clone Isolation and Safety | Single (protocol) | Repo Isolator, All cloning agents | +| [R-56b](#2256b-r-56b-transient-error-classification-and-retry) | Transient Error Classification and Retry | Single (shared module) | All agents via Error Handling module | +| [R-113](#22113-r-113-guaranteed-resource-cleanup-via-cleanupmanager) | Guaranteed Resource Cleanup via CleanupManager | Universal | All resource-acquiring agents | +| [R-114](#22114-r-114-startup-credential-validation-gate) | Startup Credential Validation Gate | Universal | All agents at startup | +| [R-63](#2263-r-63-bot-signature-standardization) | Bot Signature Standardization | Single (centralized) | Forgejo Signature Appender | +| [R-78](#2278-r-78-structured-logging-protocol) | Structured Logging Protocol | Single (shared module) | All agents | +| [R-79](#2279-r-79-performance-monitoring-and-health-scoring) | Performance Monitoring and Health Scoring | Single (shared module) | All agents | +| [R-61](#2261-r-61-reference-material-caching-and-distribution) | Reference Material Caching and Distribution | Single (optimization) | Ref Material Loader | +| [R-134](#22134-r-134-internet-access-restriction) | Internet Access Restriction | Universal | All autonomous agents (denied) | + +**E.5 — Content Formatting Standards** + +| ID | Responsibility | Redundancy | Primary Agent(s) | +|----|---------------|-----------|-------------------| +| [R-83](#2283-r-83-issue-comment-type-formatting-standards) | Issue Comment Type Formatting Standards | Single (centralized) | Issue Comment Formatter | +| [R-82](#2282-r-82-timeline-surgical-edit-and-append-only-protocol) | Timeline Surgical Edit and Append-Only Protocol | Single | Timeline Supervisor | +| [R-77](#2277-r-77-push-conflict-recovery-protocol) | 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](#222-r-02-issue-triage-verification-and-priority-management) | Issue Triage, Verification, and Priority Management | Triple | Project Owner, Human Liaison | +| [R-107](#22107-r-107-moscow-decision-framework) | MoSCoW Decision Framework | Single (exclusive) | Project Owner | +| [R-108](#22108-r-108-strategic-priority-re-evaluation) | Strategic Priority Re-evaluation | Single | Project Owner | +| [R-48](#2248-r-48-developer-expertise-discovery-and-assignment) | Developer Expertise Discovery and Assignment | Double | Project Owner, Human Liaison | +| [R-109](#22109-r-109-developer-assignment-decision-gate) | Developer Assignment Decision Gate | Single | Project Owner | + +**F.2 — Human Communication and Monitoring** + +| ID | Responsibility | Redundancy | Primary Agent(s) | +|----|---------------|-----------|-------------------| +| [R-18](#2218-r-18-human-communication-and-escalation) | Human Communication and Escalation | Double | Human Liaison, System Watchdog | +| [R-105](#22105-r-105-human-liaison-10-step-monitoring-loop) | Human Liaison 10-Step Monitoring Loop | Single | Human Liaison | +| [R-106](#22106-r-106-closed-issue-comment-response-patterns) | Closed Issue Comment Response Patterns | Single | Human Liaison | +| [R-46](#2246-r-46-feedback-incorporation-protocol) | Feedback Incorporation Protocol | Single | Human Liaison | +| [R-47](#2247-r-47-human-response-timeout-management) | Human Response Timeout Management | Double | Human Liaison, Project Owner | +| [R-48](#2248-r-48-developer-expertise-discovery-and-assignment) | 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](#2219-r-19-scope-management-and-milestone-control) | Scope Management and Milestone Control | Triple | Backlog Groomer, Epic Planner, New Issue Creator | +| [R-87](#2287-r-87-five-state-project-classification) | Five-State Project Classification | Single | Product Builder | +| [R-88](#2288-r-88-uat-feature-area-retest-on-code-changes) | UAT Feature Area Retest on Code Changes | Single | UAT Test Pool | +| [R-67](#2267-r-67-product-completion-verification) | Product Completion Verification | Single | Product Verifier | + +**G.2 — Self-Improvement and Evolution** + +| ID | Responsibility | Redundancy | Primary Agent(s) | +|----|---------------|-----------|-------------------| +| [R-22](#2222-r-22-self-improvement-and-agent-evolution) | Self-Improvement and Agent Evolution | Double | Agent Evolution, System Watchdog | +| [R-85](#2285-r-85-agent-improvement-pattern-detection) | Agent Improvement Pattern Detection | Double | Agent Evolution, System Watchdog | +| [R-90](#2290-r-90-watchdog-alert-response-and-dispatch) | Watchdog Alert Response and Dispatch | Single | System Watchdog | + +**G.3 — Documentation and Reporting** + +| ID | Responsibility | Redundancy | Primary Agent(s) | +|----|---------------|-----------|-------------------| +| [R-17](#2217-r-17-documentation-and-timeline-maintenance) | Documentation and Timeline Maintenance | Single (exclusive domains) | Documentation Supervisor, Timeline Supervisor | +| [R-89](#2289-r-89-documentation-generation-by-type) | Documentation Generation by Type | Single | Documentation Supervisor | + +**G.4 — Security** + +| ID | Responsibility | Redundancy | Primary Agent(s) | +|----|---------------|-----------|-------------------| +| [R-23](#2223-r-23-security-and-credential-management) | Security and Credential Management | Double | Shared Credential Security module, System Watchdog | +| [R-134](#22134-r-134-internet-access-restriction) | 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](#2264-r-64-nox-routing-enforcement) | Nox Routing Enforcement | Universal | All code-executing agents | +| [R-135](#22135-r-135-file-organization-enforcement) | File Organization Enforcement | Triple | Implementation Worker, PR Reviewer, Backlog Groomer | +| [R-136](#22136-r-136-static-typing-and-type-ignore-prohibition) | Static Typing and `type: ignore` Prohibition | Triple | Typecheck Fixer, PR Reviewer, System Watchdog | +| [R-137](#22137-r-137-maximum-file-size-enforcement-500-lines) | Maximum File Size Enforcement (500 Lines) | Double | Implementation Worker, PR Reviewer | + +**H.2 — Testing Standards** + +| ID | Responsibility | Redundancy | Primary Agent(s) | +|----|---------------|-----------|-------------------| +| [R-138](#22138-r-138-testing-framework-selection-rules) | Testing Framework Selection Rules | Triple | Behave Tester, Robot Tester, PR Reviewer | +| [R-139](#22139-r-139-coverage-threshold-enforcement-97-percent) | 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](#22140-r-140-conventional-changelog-commit-format) | Conventional Changelog Commit Format | Double | Commit Message Formatter, PR Reviewer | +| [R-131](#22131-r-131-standard-pr-body-format-enforcement) | Standard PR Body Format Enforcement | Double | PR Creator, PR Reviewer | + +**H.4 — Startup and Lifecycle Protocols** + +| ID | Responsibility | Redundancy | Primary Agent(s) | +|----|---------------|-----------|-------------------| +| [R-141](#22141-r-141-supervisor-mandatory-startup-sequence) | Supervisor Mandatory Startup Sequence | Universal | All 18 supervisors | +| [R-142](#22142-r-142-startup-state-recovery-before-tracking-creation) | Startup State Recovery Before Tracking Creation | Universal | All 18 supervisors | +| [R-143](#22143-r-143-dual-status-issue-cleanup-defense-in-depth) | Dual Status Issue Cleanup (Defense-in-Depth) | Double | Each supervisor, Backlog Groomer | +| [R-144](#22144-r-144-tier-selector-pure-pass-through-constraint) | 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](#7-product-builder-tier-0-orchestrator) | 60-second monitoring loop queries session status via Async Agent Manager; immediately re-launches any dead supervisor (Section [4.3](#43-the-monitoring-loop)) | Session no longer appears in OpenCode Server API response | Re-launch with same parameters within 60 seconds | +| **2 (Deep Inspection)** | [Product Builder](#7-product-builder-tier-0-orchestrator) | Every 5 heartbeats (~5 minutes), reads last 100 messages from each pool supervisor to verify active worker dispatching (Section [7.6](#76-phase-details)) | No worker activity patterns in last 15 minutes | Announces zombie warning, may force-restart | +| **3 (Behavioral Analysis)** | [System Watchdog](#911-system-watchdog-supervisor) | 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](#9112-critical-audit-details)) | 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](#911-system-watchdog-supervisor) | 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](#9112-critical-audit-details)) | 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](#910-project-owner-supervisor) | 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](#910-project-owner-supervisor)) | 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](#93-human-liaison-supervisor) | 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](#93-human-liaison-supervisor)) | 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](#97-backlog-grooming-supervisor) | 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](#97-backlog-grooming-supervisor)) | All open issues with missing required labels | Safety net — catches issues that slip through triage | +| **3b (Audit)** | [System Watchdog](#911-system-watchdog-supervisor) | Audit 4 verifies priority/milestone ordering is correct; flags issues worked on out of order. (Section [9.11.2](#9112-critical-audit-details)) | 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](#91-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](#91-architecture-supervisor)) | New milestones without spec coverage, spec ambiguities, human requests | "Most consequential agent — bad architecture cascades everywhere" | +| **2 (Decomposition)** | [Epic Planner](#92-epic-planning-supervisor) | 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](#92-epic-planning-supervisor)) | Milestones without issues, epics without children, human requests | Enforces Legendary→Epic→Issue hierarchy | +| **3 (Gap Detection)** | [Backlog Groomer](#97-backlog-grooming-supervisor) | Passes 12-13 detect incomplete epics and legendaries; creates missing child issues when gaps are identified. (Section [9.7](#97-backlog-grooming-supervisor)) | Epics with zero or incomplete children, legendaries with missing child epics | Redundant check on Epic Planner's completeness | +| **4 (Human Requests)** | [Human Liaison](#93-human-liaison-supervisor) | Step 7 (every 10th cycle): Epic/Legendary gap analysis. Also decomposes human-created issues into implementation plans. (Section [9.3](#93-human-liaison-supervisor)) | 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](#101-implementation-worker) | Posts `[CLAIM: agent=, session=, timestamp=]` 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](#612-work-item-claiming-protocol)) | Claim posting, heartbeat maintenance, release guarantee, stale claim detection | +| **2 (Stale Detection)** | [Backlog Groomer](#97-backlog-grooming-supervisor) | Pass 3: detects `State/In Progress` issues with no comments for >48 hours, implying stale or abandoned claims. Posts staleness comment. (Section [9.7](#97-backlog-grooming-supervisor)) | 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](#81-implementation-pool-supervisor) | 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](#621-pr-ownership-detection)) | Login identity comparison only | +| **2 (Scoring)** | [Implementation Pool](#81-implementation-pool-supervisor) | 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](#812-pr-first-priority-gate)) | 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](#81-implementation-pool-supervisor) | Finds verified issues, dispatches workers via Async Agent Manager, manages sliding window of N workers. Enforces PR-first priority gate. (Section [8.1](#81-implementation-pool-supervisor)) | Only agent that dispatches implementation workers | +| **Execution** | [Implementation Worker](#101-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](#101-implementation-worker)) | One instance per branch/PR; owns work to merge | +| **Subtask Orchestration** | [Subtask Loop](#113-subtask-loop-workflow) | Manages progressive escalation for each subtask. Evaluates difficulty, selects starting tier, loops through implement→test→quality gates→review until passing. (Section [11.3](#113-subtask-loop-workflow)) | Escalates haiku→codex→sonnet→opus on failure | +| **Code Writing** | [Implementer](#114-specialized-workers) | Writes code for subtasks. Never writes tests. Verifies domain model fields exist before referencing them. (Section [11.4](#114-specialized-workers), [21.4](#214-implementer-domain-model-verification-rule)) | Inherits model from tier selector | +| **Unit Testing** | [Behave Tester](#114-specialized-workers) | Writes BDD/Gherkin unit tests in `features/`. (Section [11.4](#114-specialized-workers)) | Inherits model from tier selector | +| **Integration Testing** | [Robot Tester](#114-specialized-workers) | Writes Robot Framework integration tests in `robot/`. No mocking. (Section [11.4](#114-specialized-workers)) | Inherits model from tier selector | +| **Performance Testing** | [ASV Benchmarker](#114-specialized-workers) | Writes Airspeed Velocity benchmarks in `benchmarks/`. (Section [11.4](#114-specialized-workers)) | 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](#1016-issue-implementation-work-claiming-and-crash-recovery)), the Subtask Loop preserves escalation state in HTML comments (Section [16](#16-escalation-state-persistence)), 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](#114-specialized-workers) | Writes BDD/Gherkin unit tests in `features/`. Tags bug-fix tests with `@tdd_issue`, `@tdd_issue_`, `@tdd_expected_fail`. (Section [11.4](#114-specialized-workers)) | Creates `.feature` files with Given/When/Then scenarios | +| **1b (Integration)** | [Robot Tester](#114-specialized-workers) | Writes Robot Framework integration tests in `robot/`. No mocking allowed. Tags with `tdd_issue_` for bug fixes. (Section [11.4](#114-specialized-workers)) | Creates `.robot` files with keyword-driven tests | +| **1c (Performance)** | [ASV Benchmarker](#114-specialized-workers) | Writes Airspeed Velocity benchmarks in `benchmarks/` for performance-sensitive code. (Section [11.4](#114-specialized-workers)) | Creates benchmark classes with `time_*` and `mem_*` methods | +| **2 (TDD Tag Cleanup)** | [Implementation Worker](#101-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](#613-tdd-issue-test-tags-system)) | Tag removal from passing TDD tests | +| **2b (TDD Verification)** | [PR Reviewer](#1212-pr-reviewer-detailed-specification) | For bug-fix PRs: verifies all `@tdd_issue_N` tests had `@tdd_expected_fail` removed. (Section [12.1.2](#1212-pr-reviewer-detailed-specification)) | Verifies TDD tag correctness in reviews | +| **3 (Parallel Launch)** | [Subtask Loop](#113-subtask-loop-workflow) | 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](#215-subtask-loop-async-test-writer-launching)) | 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](#113-subtask-loop-workflow) | 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](#215-subtask-loop-async-test-writer-launching)) | 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](#121-pr-management-agents) | 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](#121-pr-management-agents)) | PR creation, label inheritance, dependency linking, state transition, compliance verification | +| **2 (Sync Verification)** | [Backlog Groomer](#97-backlog-grooming-supervisor) | 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](#97-backlog-grooming-supervisor)) | 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 Pool](#82-pr-review-pool-supervisor) → [PR Reviewer](#1212-pr-reviewer-detailed-specification) | 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](#82-pr-review-pool-supervisor), [12.1.2](#1212-pr-reviewer-detailed-specification)) | 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](#155-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](#155-implementation-reviewer)) | 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](#1212-pr-reviewer-detailed-specification) | 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](#1212-pr-reviewer-detailed-specification)) | 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](#1212-pr-reviewer-detailed-specification) | 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](#6170-mcp-token-limitation-and-the-curl-workaround)) | MCP tools for all reads | +| **2 (WRITE ops)** | [PR Reviewer](#1212-pr-reviewer-detailed-specification) | 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](#6172-dual-account-review-protocol)) | 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](#1212-pr-reviewer-detailed-specification) | 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](#1212-pr-reviewer-detailed-specification)) | Implementation-level anti-patterns | +| **2 (Codebase-wide)** | [Architecture Guard](#95-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](#95-architecture-guard)) | Structural anti-patterns | +| **3 (Per-module)** | [Bug Hunt Pool](#86-bug-hunt-pool-supervisor) | Pass 8 (code consistency): identifies inconsistent patterns within and across modules. Pass 6 (type safety): detects type system abuse. (Section [8.6.2](#862-nine-analysis-passes)) | 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 Loop](#113-subtask-loop-workflow) → [Lint Fixer](#114-specialized-workers), [Typecheck Fixer](#114-specialized-workers), [Unit Test Runner](#114-specialized-workers), [Integration Test Runner](#114-specialized-workers), [Coverage Improver](#114-specialized-workers) | 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](#113-subtask-loop-workflow)) | Before PR creation | Catches issues before they enter the CI pipeline | +| **2 (Post-PR CI)** | [PR CI Test Fixer](#1211-critical-pr-management-behavioral-rules) | 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](#121-pr-management-agents)) | After PR creation, when CI fails | Handles issues that the pre-PR gates missed (environment differences, test isolation) | +| **3 (Post-Merge Audit)** | [System Watchdog](#911-system-watchdog-supervisor) | 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](#9112-critical-audit-details)) | Continuously, every 5 minutes | Catches cases where code reached master despite quality gates | +| **3b (Enforcement Repair)** | [Quality Enforcer](#151-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](#151-quality-enforcer)) | 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](#81-implementation-pool-supervisor) | 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](#812-pr-first-priority-gate)) | Worker re-assignment: existing workers shift to PR fixing | Guarantees every PR gets attention before new work starts | +| **2 (Specialized Analysis)** | [PR Fix Pool](#84-pr-fix-pool-supervisor) | Groups CI failures by common root cause before dispatching workers. Detects when >3 tests fail with the same import error and sends a single worker for the root cause instead of N workers for N tests. (Section [8.4](#84-pr-fix-pool-supervisor)) | Intelligent root-cause grouping reduces redundant work | Uses synchronous Task dispatch (not async) for coordination | +| **3 (Struggling Detection)** | [System Watchdog](#911-system-watchdog-supervisor) | 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](#9112-critical-audit-details)) | 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](#83-pr-merge-pool-supervisor) | Singleton that continuously polls for merge-ready PRs every 5 minutes. Verifies all 7 merge criteria (Section [8.3.2](#832-merge-criteria)). Handles pre-merge rebase. Uses `safe_merge_pr()` with mandatory post-merge verification. (Section [8.3](#83-pr-merge-pool-supervisor)) | Polls PRs → verifies criteria → rebases if needed → merges → verifies | Primary merge path for all PRs | +| **2 (Worker Merge)** | [Implementation Worker](#101-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](#1014-pr-fix-mode-workflow)) | 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](#136-merge-safety-sharedmerge_safetymd) | `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](#618-merge-safety-protocol), [8.3.4](#834-mandatory-merge-verification-protocol)) | Post-merge API verification | Prevents the false "merged successfully" bug (Forgejo silently fails when branch is behind) | +| **4 (False-Merge Monitoring)** | [System Watchdog](#911-system-watchdog-supervisor) | Monitors for "merged successfully" comments on PRs that are still open. (Section [13.6](#136-merge-safety-sharedmerge_safetymd)) | 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](#83-pr-merge-pool-supervisor) (`check_pr_approval()`), [Implementation Worker](#101-implementation-worker) (`has_required_approvals()`), [Shared Merge Safety](#136-merge-safety-sharedmerge_safetymd) (`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](#83-pr-merge-pool-supervisor), [Implementation Worker](#101-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](#834-mandatory-merge-verification-protocol)) | Post-merge API verification | +| **2 (Shared)** | [Shared Merge Safety](#136-merge-safety-sharedmerge_safetymd) | `safe_merge_pr()` includes mandatory verification step. Rule 6: "Never post 'merged successfully' without verifying `merged == true`". (Section [13.6](#136-merge-safety-sharedmerge_safetymd)) | Protocol-level enforcement | +| **3 (Audit)** | [System Watchdog](#911-system-watchdog-supervisor) | Monitors for "merged successfully" comments on PRs that are still open — the telltale sign of a false merge. (Section [13.6](#136-merge-safety-sharedmerge_safetymd)) | 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](#121-pr-management-agents) | 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](#1211-critical-pr-management-behavioral-rules)) | Fetch-before-edit protocol | +| **2 (Spec Evolution)** | [Spec Evolution](#96-specification-evolution-supervisor) | Explicitly warned about this bug: "When updating PRs via the Forgejo API, always re-send the full PR body." (Section [9.6](#96-specification-evolution-supervisor)) | 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](#123-git-and-repository-agents) | 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](#1015-ci-artifact-mapping)) | Web login, CSRF extraction, run ID parsing, log download, cookie cleanup | +| **2 (Consumer: Watchdog)** | [System Watchdog](#911-system-watchdog-supervisor) | 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](#9112-critical-audit-details)) | Log parsing for specific failing test identification | +| **3 (Consumer: Workers)** | [Implementation Worker](#101-implementation-worker), [PR CI Test Fixer](#1211-critical-pr-management-behavioral-rules), [PR Reviewer](#1212-pr-reviewer-detailed-specification) | All invoke `ci-log-fetcher` as subagent to retrieve CI logs for their respective purposes (fixing, reviewing, diagnosing). (Sections [10.1](#101-implementation-worker), [12.1](#121-pr-management-agents)) | 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](#101-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](#101-implementation-worker)) | State transition, final comment, cleanup | +| **1b (Immediate)** | [PR Merge Pool](#83-pr-merge-pool-supervisor) | After verified merge: updates linked issues to `State/Completed`. (Section [8.3](#83-pr-merge-pool-supervisor)) | State transition after merge | +| **2 (Catch-up)** | [Backlog Groomer](#97-backlog-grooming-supervisor) | 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](#97-backlog-grooming-supervisor)) | Stale dependency removal, issue closure catch-up | +| **3 (Reconciliation)** | [State Reconciler](#152-state-reconciler) | Rule 3: issues with merged PRs must be closed and marked `State/Completed`. (Section [15.2](#152-state-reconciler)) | 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](#2118-commit-message-formatter-three-part-format) | 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](#2118-commit-message-formatter-three-part-format)) | Message formatting from issue metadata | +| **2 (Execution)** | [Git Committer](#123-git-and-repository-agents) | Stages all changes, commits with formatted message, pushes to BOTH remotes in sequence: `git push -u origin ` then `git push upstream `. Both pushes required. Reports errors with full details. (Section [12.1](#121-pr-management-agents)) | Staging, committing, dual-remote pushing | +| **2b (Safe Commit)** | [Git Commit Helper](#2121-git-commit-helper-safe-commit-with-rollback) | 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](#2121-git-commit-helper-safe-commit-with-rollback)) | Validated commit with rollback capability | +| **3 (Amend-only)** | [PR CI Test Fixer](#1211-critical-pr-management-behavioral-rules) | 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](#121-pr-management-agents)) | 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](#2123-branch-setup-rebase-only-policy) | 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](#2123-branch-setup-rebase-only-policy)) | Branch creation, checkout, rebase-only enforcement | +| **2 (Pre-merge Rebase)** | [PR Merge Pool](#83-pr-merge-pool-supervisor) | Pre-merge staleness check: compares `merge_base` vs `base.sha`. If behind without conflicts: clones via repo-isolator, fetches latest, rebases, force-pushes with lease. Waits for CI (does NOT merge immediately). If behind with conflicts: posts comment requesting manual rebase. (Section [8.3.5](#835-pre-merge-rebase-protocol)) | Pre-merge rebase, conflict detection | +| **3 (Worker Rebase)** | [Implementation Worker](#101-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](#101-implementation-worker)) | 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](#113-subtask-loop-workflow) | 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](#112-escalation-schedule), [11.3](#113-subtask-loop-workflow)) | Escalation scheduling, transient error detection, state persistence | +| **2 (Tier Selection)** | [Tier Selectors](#111-tier-selector-architecture) (`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](#111-tier-selector-architecture)) | Model selection, context forwarding | +| **3 (Difficulty Pre-assessment)** | [Difficulty Evaluator](#124-reference-and-knowledge-agents) | Five-axis assessment (scope, complexity, novelty, integration, ambiguity). Conservative bias: when in doubt, recommends LOWER tier. (Section [12.4](#124-reference-and-knowledge-agents)) | Starting tier recommendation | + +**Sub-responsibilities**: Meaningful change verification (rejects <3 functional lines), per-gate independent tier tracking, escalation state persistence as `` 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](#155-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](#155-implementation-reviewer)) | Requirement-by-requirement cross-reference | +| **2 (Per-Milestone)** | [Milestone Reviewer](#2117-milestone-reviewer-holistic-review-protocol) | 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](#2117-milestone-reviewer-holistic-review-protocol)) | 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](#214-implementer-domain-model-verification-rule)). + +--- + +### 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](#911-system-watchdog-supervisor) | 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](#9112-critical-audit-details)) | Failure detection, log parsing, CI-Blocker issue creation | +| **2 (Enforcement Repair)** | [Quality Enforcer](#151-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](#151-quality-enforcer)) | CI-Blocker issue creation, branch protection repair | +| **3 (Priority Override)** | [Implementation Pool](#81-implementation-pool-supervisor) | `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](#812-pr-first-priority-gate)) | 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](#2110-forgejo-label-manager-five-operations) | Centralized label operations. Handles name-to-organization-ID mapping. Five operations: validation, application, reading, inference, compliance checking. (Section [12.5](#125-label-and-forgejo-agents)) | 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](#92-epic-planning-supervisor), [New Issue Creator](#122-issue-management-agents), [Project Owner](#910-project-owner-supervisor), [Human Liaison](#93-human-liaison-supervisor), [Bug Hunt Pool](#86-bug-hunt-pool-supervisor), [UAT Test Pool](#85-uat-test-pool-supervisor), [Test Infra Pool](#87-test-infrastructure-pool-supervisor), [Architecture Guard](#95-architecture-guard), [System Watchdog](#911-system-watchdog-supervisor) | Sets initial labels when creating issues, via Label Manager delegation. (Section [6.19](#619-label-application-delegation)) | At issue creation time | Responsible for getting labels right the first time | +| **3 (Verification & Auto-Fix)** | [Backlog Groomer](#97-backlog-grooming-supervisor) | 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](#97-backlog-grooming-supervisor)) | Every 5-minute grooming cycle | Catches and fixes any gaps left by Layer 2 | +| **4 (Audit)** | [System Watchdog](#911-system-watchdog-supervisor) | Audit 7: verifies all issues have required labels and dependency links. (Section [9.11.2](#9112-critical-audit-details)) | Every 5-minute watchdog cycle | Detects systemic labeling failures | +| **4b (Bulk Fix)** | [State Reconciler](#152-state-reconciler) | Dispatched by Watchdog for mass label correction. Rule 6: every issue must have State, Type, and Priority labels. (Section [15.2](#152-state-reconciler)) | 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](#122-issue-management-agents) | 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](#122-issue-management-agents)) | Direct label manipulation via REST API (one of two agents permitted to do so) | The canonical state transition engine | +| **2 (Reconciliation)** | [Backlog Groomer](#97-backlog-grooming-supervisor) | 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](#97-backlog-grooming-supervisor)) | Scans all issues and cross-references with PR state | Catches issues where state transitions were missed or incomplete | +| **3 (Audit)** | [System Watchdog](#911-system-watchdog-supervisor) | Audit 3: checks closed issues with wrong state labels, In Review without PR, multiple State labels on same issue. (Section [9.11.2](#9112-critical-audit-details)) | Cross-references issue state against Forgejo actual status | Detects systemic state integrity violations | +| **4 (Bulk Fix)** | [State Reconciler](#152-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](#152-state-reconciler)) | 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](#92-epic-planning-supervisor) — issue→epic→legendary links; [PR Creator](#121-pr-management-agents) — PR→issue links | Create dependency links with correct direction at creation time. (Sections [9.2](#92-epic-planning-supervisor), [12.1](#121-pr-management-agents)) | Epic Planner: child BLOCKS parent; PR Creator: PR BLOCKS issue | Responsible for getting direction right the first time | +| **2 (Verification & Auto-Fix)** | [Backlog Groomer](#97-backlog-grooming-supervisor) | 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](#97-backlog-grooming-supervisor)) | All dependency types: issue→epic, epic→legendary, PR→issue | Most active dependency fixer — catches and corrects wrong directions | +| **3 (Audit)** | [System Watchdog](#911-system-watchdog-supervisor) | 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](#9112-critical-audit-details)) | Hierarchy completeness and correctness | Detects systemic hierarchy violations | +| **3b (Bulk Fix)** | [State Reconciler](#152-state-reconciler) | Rule 7: fixes dependency link directions (child blocks parent Epic, Epic blocks Legendary, PR blocks issue). (Section [15.2](#152-state-reconciler)) | 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](#153-project-bootstrapper) | Configures branch protection for master: status checks required, 1 approval, dismiss stale reviews, block on rejected, push disabled. (Section [15.3](#153-project-bootstrapper)) | Initial configuration | One-time setup; must be correct because it is the foundation | +| **2 (Enforcement)** | [Shared Merge Safety module](#136-merge-safety-sharedmerge_safetymd) | `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](#136-merge-safety-sharedmerge_safetymd)) | Every merge attempt | Used by PR Merge Pool and Implementation Worker | +| **3 (Audit)** | [System Watchdog](#911-system-watchdog-supervisor) | 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](#9112-critical-audit-details)) | Continuous verification that protection is intact | Catches silent disablement or misconfiguration | +| **4 (Repair)** | [Quality Enforcer](#151-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](#151-quality-enforcer)) | 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](#91-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](#91-architecture-supervisor)) | Specification drives implementation (forward-looking) | "Most consequential agent — bad architecture cascades everywhere" | +| **2 (Code → Spec)** | [Spec Evolution](#96-specification-evolution-supervisor) | 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](#96-specification-evolution-supervisor)) | Implementation corrects specification (backward-looking) | Critical rule: never removes unimplemented spec content | +| **3 (Drift Detection)** | [Architecture Guard](#95-architecture-guard) | Check 7: detects specification drift — implementation that has diverged from the specification. Creates `Type/Refactor` issues. (Section [9.5](#95-architecture-guard)) | Detects divergence in either direction | Uses Gemini 2.5 Pro's massive context window for full-codebase analysis | +| **4 (Milestone Review)** | [Milestone Reviewer](#2117-milestone-reviewer-holistic-review-protocol) | Area 3: verifies every specification requirement has corresponding implementation and test. (Section [21.17](#2117-milestone-reviewer-holistic-review-protocol)) | 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](#92-epic-planning-supervisor) | 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](#92-epic-planning-supervisor)) | ADR→Spec→Implementation dependency chain creation | +| **2 (Governance)** | [Architecture Supervisor](#91-architecture-supervisor) | Major architectural changes go through PRs with `needs feedback` label. Minor clarifications committed directly. (Section [9.1](#91-architecture-supervisor)) | Human-approval workflow for major changes | +| **3 (Feedback Channel)** | [Human Liaison](#93-human-liaison-supervisor) | 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](#93-human-liaison-supervisor)) | 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](#95-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](#95-architecture-guard)) | Codebase-wide, triggered by master SHA changes | Uses Gemini 2.5 Pro for massive context analysis | +| **2 (Per-Module Analysis)** | [Bug Hunt Pool](#86-bug-hunt-pool-supervisor) | Pass 8: code consistency analysis. Pass 9: data flow analysis. Identifies inconsistent patterns across modules. (Section [8.6.2](#862-nine-analysis-passes)) | Module-by-module, nine-pass deep analysis | Different perspective — code analysis rather than architecture review | +| **3 (Per-PR Review)** | [PR Reviewer](#1212-pr-reviewer-detailed-specification) | Focus areas 1 (architecture alignment), 4 (API consistency), 7 (code maintainability). Detects architectural drift and pattern violations per-PR. (Section [12.1.2](#1212-pr-reviewer-detailed-specification)) | 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](#1212-pr-reviewer-detailed-specification) | 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](#1212-pr-reviewer-detailed-specification)) | Pattern detection in PR diffs, CI cross-analysis | +| **2 (Infrastructure Detection)** | [System Watchdog](#911-system-watchdog-supervisor) | Audit 9: monitors CI execution times (flags >30 minutes), detects recurring failures on same tests across different PRs. (Section [9.11.2](#9112-critical-audit-details)) | Cross-PR failure pattern analysis | +| **2b (Infrastructure Analysis)** | [Test Infrastructure Pool](#87-test-infrastructure-pool-supervisor) | Area 4: dedicated flaky test analysis pass across the full test suite. (Section [8.7.2](#872-eight-analysis-areas)) | 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](#101-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](#1018-test-stability-requirements)) | Rule enforcement during implementation | +| **2 (Review)** | [PR Reviewer](#1212-pr-reviewer-detailed-specification) | Detects all six non-deterministic patterns in PR diffs and requests changes. (Section [12.1.2](#1212-pr-reviewer-detailed-specification)) | Pattern detection in code review | +| **3 (Quality Gate)** | [Subtask Loop](#113-subtask-loop-workflow) | 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](#113-subtask-loop-workflow)) | 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](#97-backlog-grooming-supervisor) | 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](#97-backlog-grooming-supervisor)) | All open issues and PRs | The primary hygiene agent — most comprehensive | +| **2 (Self-Dedup)** | [Test Infrastructure Pool](#87-test-infrastructure-pool-supervisor) | 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](#873-duplicate-avoidance)) | Its own issue creation only | Documented as "#1 problem with this agent" — historical 48+ duplicates | +| **2b (Self-Dedup)** | [Bug Hunt Pool](#86-bug-hunt-pool-supervisor) | Finding validation: must have actual code evidence, verify environment assumptions, verify actionable, verify against actual codebase, severity must match evidence. (Section [21.8](#218-bug-hunt-clone-failure-handling-and-finding-validation)) | Its own issue creation only | Prevents filing issues about infrastructure failures | +| **2c (Self-Dedup)** | [UAT Test Pool](#85-uat-test-pool-supervisor) | Worker coordination through Forgejo comments to avoid duplicate testing. (Section [8.5](#85-uat-test-pool-supervisor)) | 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](#2110-forgejo-label-manager-five-operations) | 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](#2110-forgejo-label-manager-five-operations)) | 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](#121-pr-management-agents) | Inherits ALL Type/, Priority/, MoSCoW/, Points/ labels from issue to PR. Adds State/In Review. Copies milestone. (Section [12.1](#121-pr-management-agents)) | Initial label inheritance | +| **2 (Ongoing Sync)** | [Backlog Groomer](#97-backlog-grooming-supervisor) | 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](#97-backlog-grooming-supervisor)) | 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](#93-human-liaison-supervisor) | 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](#93-human-liaison-supervisor)) | Estimation during human issue triage | +| **2 (Compliance Fill)** | [Backlog Groomer](#97-backlog-grooming-supervisor) | 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](#97-backlog-grooming-supervisor)) | 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](#122-issue-management-agents) | 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](#122-issue-management-agents)) | Milestone assignment with scope guard | +| **2 (Planning)** | [Epic Planner](#92-epic-planning-supervisor) | Milestone Scope Guard: will not create new issues in converging milestones (closed > open). New discovered work goes to backlog. (Section [9.2](#92-epic-planning-supervisor)) | Planning-level scope guard | +| **3 (Compliance)** | [Backlog Groomer](#97-backlog-grooming-supervisor) | Pass 4: assigns milestone to non-Epic/non-Legendary issues in Verified+ without one. (Section [9.7](#97-backlog-grooming-supervisor)) | Missing milestone fill | +| **3b (Testing)** | [UAT Test Pool](#85-uat-test-pool-supervisor) | Milestone Scope Guard: only critical bugs assigned to active milestone. (Section [8.5.3](#853-milestone-scope-guard)) | 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](#122-issue-management-agents) | 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](#122-issue-management-agents)) | Precondition validation, terminal state closure, PR sync | +| **2 (Cross-check)** | [Backlog Groomer](#97-backlog-grooming-supervisor) | 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](#97-backlog-grooming-supervisor)) | 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](#122-issue-management-agents), [Epic Planner](#92-epic-planning-supervisor) | 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](#614-standard-issue-body-format)) | Compliant issue creation | +| **2 (Verification)** | [Backlog Groomer](#97-backlog-grooming-supervisor) | 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](#97-backlog-grooming-supervisor)) | 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](#97-backlog-grooming-supervisor) | 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](#97-backlog-grooming-supervisor)) | Dependency graph analysis, problem detection | +| **2 (State Enforcement)** | [Issue State Updater](#122-issue-management-agents) | When transitioning from `State/Paused`: validates that the blocking issue is actually resolved before allowing transition. Prevents premature unblocking. (Section [12.2](#122-issue-management-agents)) | Transition precondition enforcement | +| **3 (Audit)** | [System Watchdog](#911-system-watchdog-supervisor) | Audit 7/8: detects orphan issues and hierarchy violations. (Section [9.11.2](#9112-critical-audit-details)) | 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](#86-bug-hunt-pool-supervisor) | Nine analysis passes per module: error handling, concurrency, security, boundary conditions, resource management, type safety, specification alignment, code consistency, data flow. (Section [8.6](#86-bug-hunt-pool-supervisor)) | Static code analysis against spec | Uses Gemini 2.5 Pro for cross-module analysis | +| **2 (Spec Compliance)** | [UAT Test Pool](#85-uat-test-pool-supervisor) | Tests feature areas against the specification. Files bug issues for gaps and spec deviations. Captures successful workflows as documentation. (Section [8.5](#85-uat-test-pool-supervisor)) | Dynamic testing against spec | Finds issues Bug Hunt cannot (runtime behavior) | +| **3 (Per-PR Detection)** | [PR Reviewer](#1212-pr-reviewer-detailed-specification) | Focus areas 2 (error handling/edge cases), 5 (security), 6 (performance), 10 (behavior correctness). Flaky test detection. (Section [12.1.2](#1212-pr-reviewer-detailed-specification)) | Code review of changes | Catches bugs at the point of introduction | +| **4 (Architecture-Level)** | [Architecture Guard](#95-architecture-guard) | Check 6: test quality (tests that do not verify meaningful behavior, missing edge cases). Check 5: technical debt indicators. (Section [9.5](#95-architecture-guard)) | 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](#98-documentation-supervisor) | Generates and updates five documentation types: README, API docs, architecture docs, changelog, module docs. Always extends, never overwrites. (Section [9.8](#98-documentation-supervisor)) | All files EXCEPT `docs/timeline.md` | Must NOT modify timeline (exclusive to Timeline Supervisor) | +| **Timeline** | [Timeline Supervisor](#99-timeline-update-supervisor) | Keeps `docs/timeline.md` accurate. Makes surgical updates to nine sections including Gantt charts, status summaries, completion history, risk tables. (Section [9.9](#99-timeline-update-supervisor)) | `docs/timeline.md` exclusively | Never deletes historical data; append-only for history sections | +| **Showcase Docs** | [UAT Test Pool](#85-uat-test-pool-supervisor) | Generates showcase documentation from successful end-to-end test runs demonstrating real-world usage patterns. (Section [21.3](#213-uat-test-pool-supervisor-complete-subagent-list)) | 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](#93-human-liaison-supervisor) | 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](#93-human-liaison-supervisor)) | 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](#910-project-owner-supervisor) | 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](#910-project-owner-supervisor)) | Unassigned critical/blocking issues, strategic questions | Complements Liaison with strategic focus | +| **3 (Automated Escalation)** | [Implementation Worker](#101-implementation-worker) | After 3 stuck detections: posts diagnostic comment, adds `needs feedback` label, exits gracefully. (Section [10.1.4](#1014-pr-fix-mode-workflow)) | Repeated implementation failures on the same error | Self-escalation when automation is stuck | +| **3b (Independent Escalation)** | [System Watchdog](#911-system-watchdog-supervisor) | Audit 5b: independently detects struggling PRs (3+ fix attempts), requests human assistance. (Section [9.11.2](#9112-critical-audit-details)) | PR-level repeated failures detected from outside | Catches cases where the worker itself did not escalate | +| **4 (Proposal Escalation)** | [Agent Evolution](#94-agent-evolution-supervisor), [Spec Evolution](#96-specification-evolution-supervisor), [Architecture Supervisor](#91-architecture-supervisor) | Create `needs feedback` proposals for major changes requiring human approval. (Sections [9.4](#94-agent-evolution-supervisor), [9.6](#96-specification-evolution-supervisor), [9.1](#91-architecture-supervisor)) | 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](#93-human-liaison-supervisor) | 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](#93-human-liaison-supervisor)) | 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](#93-human-liaison-supervisor) | 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](#93-human-liaison-supervisor)) | Timeout tracking, escalation actions, provisional decisions | +| **2 (Question Follow-up)** | [Project Owner](#910-project-owner-supervisor) | 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](#910-project-owner-supervisor)) | 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](#910-project-owner-supervisor) | 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](#910-project-owner-supervisor)) | Git history analysis, expertise mapping, strategic assignment | +| **2 (Expertise Tagging)** | [Human Liaison](#93-human-liaison-supervisor) | Tags specific developers in comments based on their expertise areas when guidance is needed. Cross-references known developer specializations. (Section [9.3](#93-human-liaison-supervisor)) | 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](#97-backlog-grooming-supervisor) | Pass 18: scope creep detection. Calculates convergence ratio, 24h creation/closure rates. Alerts when creation rate > 2× closure rate. (Section [9.7](#97-backlog-grooming-supervisor)) | Creation-vs-closure rate monitoring | Creates `Priority/High` announcement issues for scope alerts | +| **2 (Prevention at Planning)** | [Epic Planner](#92-epic-planning-supervisor) | Milestone Scope Guard: does not create new issues in converging milestones. New discovered work goes to backlog. (Section [9.2](#92-epic-planning-supervisor)) | Prevents new issue creation in converging milestones | Applied at the planning level | +| **3 (Prevention at Creation)** | [New Issue Creator](#122-issue-management-agents) | Strict scope guard: critical bugs → current milestone; all other discovered issues → no milestone, `Priority/Backlog`. (Section [12.2](#122-issue-management-agents)) | Milestone assignment rules at creation time | Applied at the issue creation level | +| **3b (Prevention at Testing)** | [UAT Test Pool](#85-uat-test-pool-supervisor) | Milestone Scope Guard: only critical bugs assigned to active milestone. Non-critical issues go to backlog with no milestone. (Section [8.5.3](#853-milestone-scope-guard)) | 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](#125-label-and-forgejo-agents) | 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](#54-tracking-operations)) | 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](#521-status-issue-lifecycle-one-at-a-time-protocol), [5.3.1](#531-announcement-issue-lifecycle)) | Agent-side cleanup | Primary cleanup mechanism | +| **3 (Redundant Cleanup)** | [Backlog Groomer](#97-backlog-grooming-supervisor) | 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](#97-backlog-grooming-supervisor)) | Age-based and duplicate-based cleanup | Safety net for agent-side cleanup failures | +| **4 (Health Monitoring)** | [System Watchdog](#911-system-watchdog-supervisor) | Audit 11: monitors tracking issue age against expected interval. Triggers recovery for stalled agents. (Section [9.11.2](#9112-critical-audit-details)) | 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](#7-product-builder-tier-0-orchestrator) | Re-invoke → detects existing sessions via OpenCode API (Phase C.0) → adopts running supervisors → resumes monitoring. (Section [7.6](#76-phase-details)) | OpenCode Server session list | Human must re-invoke, but existing sessions survive | +| **Supervisor crash** | [Product Builder](#7-product-builder-tier-0-orchestrator) | 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](#43-the-monitoring-loop), [5.3.3](#533-startup-state-recovery-protocol)) | Forgejo tracking issues | New session recovers state from previous session's tracking issue | +| **Worker crash** | [Pool Supervisors](#8-pool-supervisors-tier-1) | Detect dead worker → slot becomes available → re-dispatches. New worker checks for existing PR/branch. (Section [10.1.6](#1016-issue-implementation-work-claiming-and-crash-recovery)) | Git branches, existing PRs, Forgejo comments | Work-in-progress preserved if committed/pushed | +| **Subtask Loop crash** | [Subtask Loop](#113-subtask-loop-workflow) | Reads escalation state from HTML comments in PR comments. Resumes from correct tier and attempt number. (Section [16](#16-escalation-state-persistence)) | PR comment HTML | Embedded state survives session death | +| **Git push failure** | [Shared Error Handling](#133-error-handling-sharederror_handlingmd) | Retry with exponential backoff. Clone preserved until successful push. (Section [13.3](#133-error-handling-sharederror_handlingmd)) | Clone directory in `/tmp/` | Clone survives worker crash but not machine reboot | +| **Forgejo API failure** | [Shared Error Handling](#133-error-handling-sharederror_handlingmd) | All API calls retry with exponential backoff (1s, 2s, 4s base; 60s for rate limits). (Section [13.3](#133-error-handling-sharederror_handlingmd)) | 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](#814-worker-adoption)) | Session scanning, status verification, dictionary adoption | +| **2 (Lifecycle)** | All pool supervisors | Periodically query `/session/status` for tracked workers. Remove dead sessions from tracking. Terminate excess workers when count exceeds `max_workers` (LIFO, issue workers before PR workers). (Section [8.1](#81-implementation-pool-supervisor)) | Status polling, dead worker cleanup, limit enforcement | + +--- + +### 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](#620-forgejo-api-pagination-requirement)) | Mandatory pagination loop | +| **2 (Truncation)** | [Implementation Pool](#81-implementation-pool-supervisor) (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](#812-pr-first-priority-gate)) | 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](#123-git-and-repository-agents) | 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](#62-clone-isolation-protocol)) | Clone creation, auth setup | +| **2 (Safety)** | [Repo Isolator](#123-git-and-repository-agents) | 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](#123-git-and-repository-agents)) | Deletion safety, retry with verification | +| **3 (Branch Verification)** | [Repo Isolator](#123-git-and-repository-agents) | Checks `refs/heads/{branch}` then `refs/remotes/origin/{branch}` as fallback. Separate paths for checkout vs. create-and-checkout. (Section [12.3](#123-git-and-repository-agents)) | 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](#81-implementation-pool-supervisor) | `implementation-worker` | N (full) | Async (via Async Agent Manager) | +| PR Review | [PR Review Pool](#82-pr-review-pool-supervisor) | `pr-reviewer` | N/2 (half) | Async (via Async Agent Manager) | +| PR Fix | [PR Fix Pool](#84-pr-fix-pool-supervisor) | `implementation-worker` (pr-fix mode) | N/4 (quarter) | Sync (via Task tool — for coordination) | +| UAT Test | [UAT Test Pool](#85-uat-test-pool-supervisor) | self (worker mode) | N/4 (quarter) | Async (via Async Agent Manager) | +| Bug Hunt | [Bug Hunt Pool](#86-bug-hunt-pool-supervisor) | self (worker mode) | N/4 (quarter) | Async (via Async Agent Manager) | +| Test Infra | [Test Infra Pool](#87-test-infrastructure-pool-supervisor) | self (worker mode) | 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](#125-label-and-forgejo-agents) | `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](#521-status-issue-lifecycle-one-at-a-time-protocol)) | 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](#531-announcement-issue-lifecycle)) | Agent-side announcement review | +| **3 (Cross-Agent)** | [Backlog Groomer](#97-backlog-grooming-supervisor) | 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](#97-backlog-grooming-supervisor)) | 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: ` title, priority label, and detailed body. Reviews own announcements via `REVIEW_OWN_ANNOUNCEMENTS` every 3 cycles. Closes resolved announcements. (Section [5.3](#53-announcement-issues)) | 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](#532-tracking-issue-consumption-protocol)) | Priority-filtered reading at appropriate depth | +| **3 (Stale Cleanup)** | [Backlog Groomer](#97-backlog-grooming-supervisor) | 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](#97-backlog-grooming-supervisor)) | 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](#217-context-self-management-pattern)) | Periodic context pruning | +| **2 (External Detection)** | [System Watchdog](#911-system-watchdog-supervisor) | Audit 6: detects zombied agents via sleep-only pattern (context exhausted, agent only sleeping). (Section [9.11.2](#9112-critical-audit-details)) | 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](#124-reference-and-knowledge-agents) | 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](#124-reference-and-knowledge-agents)) | Cycle-based caching, expiry management | +| **2 (Extraction)** | [Spec Reader](#124-reference-and-knowledge-agents) | 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](#124-reference-and-knowledge-agents)) | 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](#68-reference-material-loading)) | 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](#125-label-and-forgejo-agents) | 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](#57-bot-signature-block), [21.12](#2112-forgejo-signature-appender-three-format-variants)) | 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](#57-bot-signature-block)) | Universal signature requirement | + +**Signature template**: `---\n**Automated by CleverAgents Bot**\nSupervisor: | Agent: ` + +--- + +### 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](#64-contributingmd-compliance)). 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](#125-label-and-forgejo-agents) | 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](#534-estimated-cycle-interval-rolling-average)) | Rolling average calculation, body injection | +| **2 (Consumption)** | [System Watchdog](#911-system-watchdog-supervisor) | 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](#9112-critical-audit-details)) | 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](#94-agent-evolution-supervisor) | 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](#94-agent-evolution-supervisor)) | Tracking issues, PR comments, failure patterns | Two-step workflow: proposal issue first, implementation PR only after approval | +| **2 (Problem Detection)** | [System Watchdog](#911-system-watchdog-supervisor) | 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](#9112-critical-audit-details)) | Session message analysis | Provides evidence that triggers Agent Evolution proposals | +| **3 (Human Feedback)** | [Human Liaison](#93-human-liaison-supervisor) | Incorporates human feedback about agent behavior. Feedback Incorporation Protocol ensures changes to ticket nature are captured. (Section [9.3](#93-human-liaison-supervisor)) | 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](#132-credential-security-sharedcredential_securitymd) | 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](#132-credential-security-sharedcredential_securitymd)) | 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](#23-permission-block-syntax)) | OpenCode permission system | Structural enforcement — agents literally cannot call forbidden tools | +| **3 (Behavioral Audit)** | [System Watchdog](#911-system-watchdog-supervisor) | 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](#9112-critical-audit-details)) | Active monitoring of agent behavior | Catches violations that structural enforcement misses | +| **4 (Account Separation)** | [Dual-Account Architecture](#617-dual-account-architecture-and-approval-detection) | 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](#617-dual-account-architecture-and-approval-detection)) | 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](#7-product-builder-tier-0-orchestrator) | 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](#2114-product-builder-specification-pr-monitoring)) | Staleness detection, rebase, outcome propagation | +| **2 (Rebase)** | [Spec Evolution](#96-specification-evolution-supervisor) | Keeps own spec PRs up to date via rebase when master advances; force-pushes, preserves `needs feedback` label, posts rebase comment. (Section [9.6](#96-specification-evolution-supervisor)) | 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](#86-bug-hunt-pool-supervisor) | 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](#218-bug-hunt-clone-failure-handling-and-finding-validation)) | Evidence, environment, actionability, freshness, severity | +| [Test Infra Pool](#87-test-infrastructure-pool-supervisor) | 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](#873-duplicate-avoidance)) | Keyword, cross-area, closed, proof, uncertainty | +| [UAT Test Pool](#85-uat-test-pool-supervisor) | 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](#85-uat-test-pool-supervisor)) | 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](#92-epic-planning-supervisor) | 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](#92-epic-planning-supervisor)) | Acceptance criteria evaluation, closure | +| **2 (Detection)** | [Backlog Groomer](#97-backlog-grooming-supervisor) | Pass 12-13: detects Epics/Legendaries where all children closed but parent still open. Creates missing children or flags for closure. (Section [9.7](#97-backlog-grooming-supervisor)) | 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](#92-epic-planning-supervisor) | 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](#92-epic-planning-supervisor)) | Orphan detection, parent assignment, direction fixing | +| **2 (Detection)** | [Backlog Groomer](#97-backlog-grooming-supervisor) | Pass 2: flags orphan issues with no parent Epic. (Section [9.7](#97-backlog-grooming-supervisor)) | Orphan flagging | +| **3 (Audit)** | [System Watchdog](#911-system-watchdog-supervisor) | Audit 7/8: verifies orphan counts and hierarchy integrity. (Section [9.11.2](#9112-critical-audit-details)) | 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_`, 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](#86-bug-hunt-pool-supervisor) | Includes TDD Note in every bug report body. (Section [8.6](#86-bug-hunt-pool-supervisor)) | TDD note in bug body | +| **2 (TDD Execution)** | [Implementation Worker](#101-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](#613-tdd-issue-test-tags-system)) | 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](#87-test-infrastructure-pool-supervisor) | 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](#87-test-infrastructure-pool-supervisor)) | Self-prohibition | +| **2 (Review)** | [PR Reviewer](#1212-pr-reviewer-detailed-specification) | Reviews for: removal of test cases, lowered coverage thresholds, added `# type: ignore`, weakened CI pipeline. (Section [12.1.2](#1212-pr-reviewer-detailed-specification)) | Detection in review | +| **3 (Audit)** | [System Watchdog](#911-system-watchdog-supervisor) | Session spot-checks for `type: ignore`, coverage reduction commands, CI step removal. (Section [9.11.2](#9112-critical-audit-details)) | 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](#97-backlog-grooming-supervisor) | 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](#97-backlog-grooming-supervisor)) | Four staleness patterns | +| **2 (Pipeline)** | [System Watchdog](#911-system-watchdog-supervisor) | Audit 5: detects PRs open >24h with no reviews, approved PRs not merged >6h, PRs with CI failing >2h. (Section [9.11.2](#9112-critical-audit-details)) | 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](#91-architecture-supervisor) | Classifies changes: Initial (no prior spec) → commit directly. Major (new modules, changed interfaces) → create branch `spec/architecture-`, PR with `needs feedback`. Minor (typos, formatting) → commit directly. (Section [9.1](#91-architecture-supervisor)) | Classification + needs-feedback PR | +| **2 (Spec Evolution)** | [Spec Evolution](#96-specification-evolution-supervisor) | 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](#96-specification-evolution-supervisor)) | 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](#95-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](#95-architecture-guard)) | Sleep on unchanged SHA | +| [Spec Evolution](#96-specification-evolution-supervisor) | Compares master SHA; proactive deep scan every 5th idle cycle (~75 min) even without new merges. (Section [9.6](#96-specification-evolution-supervisor)) | 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](#42-the-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](#421-session-naming-convention)) | 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](#42-the-async-agent-manager)) | 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](#2120-async-agent-monitor-four-operations) | 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](#2120-async-agent-monitor-four-operations)) | Health detection, auto-restart | +| **2 (Product Builder)** | [Product Builder](#7-product-builder-tier-0-orchestrator) | 60-second monitoring loop detects dead supervisor sessions; deep inspection every 5 heartbeats reads last 100 messages to detect zombies. (Section [4.3](#43-the-monitoring-loop)) | 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 ` 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](#101-implementation-worker), [PR CI Test Fixer](#1211-critical-pr-management-behavioral-rules), [PR Merge Pool](#83-pr-merge-pool-supervisor), [Spec Evolution](#96-specification-evolution-supervisor). + +--- + +### 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 `
` 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](#94-agent-evolution-supervisor) | 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](#94-agent-evolution-supervisor)) | Eight evidence-based pattern categories | +| **2 (Trigger)** | [System Watchdog](#911-system-watchdog-supervisor) | Deep session introspection detects misbehavior (forbidden flags, policy violations, stuck loops, identical-call patterns) and creates `needs-feedback` issues. (Section [9.11.2](#9112-critical-audit-details)) | 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](#85-uat-test-pool-supervisor) | 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](#85-uat-test-pool-supervisor)) | PR keyword search before filing | +| **2 (Bug Hunt)** | [Bug Hunt Pool](#86-bug-hunt-pool-supervisor) | Finding validation rule 3: verify finding is actionable and not already being addressed. (Section [21.8](#218-bug-hunt-clone-failure-handling-and-finding-validation)) | 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 ..` | +| 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](#151-quality-enforcer) | Repair branch protection, create CI-Blocker issues | +| State label mismatch (bulk) | [State Reconciler](#152-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](#101-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](#101-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](#101-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](#101-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](#101-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](#101-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](#124-reference-and-knowledge-agents) | 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](#101-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](#911-system-watchdog-supervisor) | 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_timestamp` → **blocking** (merge prevented) | +| 4 | If `latest_approval_timestamp > request_changes_timestamp` → **superseded** (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](#101-implementation-worker) and [PR Merge Pool](#83-pr-merge-pool-supervisor) | After verified merge: transition issue to `State/Completed`, close issue. | +| **2 (Dependency Cleanup)** | [Backlog Groomer](#97-backlog-grooming-supervisor) | 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](#152-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](#97-backlog-grooming-supervisor) | 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](#92-epic-planning-supervisor) | 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](#97-backlog-grooming-supervisor) | 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](#911-system-watchdog-supervisor) | 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](#96-specification-evolution-supervisor) | 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](#96-specification-evolution-supervisor)) | 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:]` 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](#7-product-builder-tier-0-orchestrator) | Tracks active sessions by type. Checks for existing session with matching tag before launch. Skips launch for already-running types. | +| **2 (Detection)** | [System Watchdog](#911-system-watchdog-supervisor) | 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](#2110-forgejo-label-manager-five-operations), 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](#122-issue-management-agents) | Validates preconditions before each transition. Rejects invalid transitions. | +| **2** | [Backlog Groomer](#97-backlog-grooming-supervisor) | 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](#81-implementation-pool-supervisor) | Issue dispatch ordering (R-98): CI-Blocker → Critical bugs across all milestones → lowest milestone → In Progress → Priority → MoSCoW → unblock score. | +| **2 (Audit)** | [System Watchdog](#911-system-watchdog-supervisor) | 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](#122-issue-management-agents), [Epic Planner](#92-epic-planning-supervisor) | 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](#97-backlog-grooming-supervisor) | 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](#121-pr-management-agents) | Generates PR body with standard sections. Includes closing keywords for linked issues. | +| **2 (Review)** | [PR Reviewer](#1212-pr-reviewer-detailed-specification) | 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](#2110-forgejo-label-manager-five-operations) | Name-to-ID mapping, conflict detection | +| Tracking issue lifecycle | [Automation Tracking Manager](#125-label-and-forgejo-agents) | 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](#136-merge-safety-sharedmerge_safetymd) | 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](#101-implementation-worker) | Delegates to specialist testers that know their target directories | +| **2 (Review)** | [PR Reviewer](#1212-pr-reviewer-detailed-specification) | Checks files are in correct directories per CONTRIBUTING.md | +| **3 (Hygiene)** | [Backlog Groomer](#97-backlog-grooming-supervisor) | 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](#114-specialized-workers) | Runs `nox -e typecheck` (Pyright) and fixes errors. Explicit instruction: "Never uses `# type: ignore`." Must resolve the actual type error. | +| **2 (Review)** | [PR Reviewer](#1212-pr-reviewer-detailed-specification) | CONTRIBUTING.md compliance check: scans diff for `type: ignore` strings, requests changes if found. | +| **3 (Audit)** | [System Watchdog](#911-system-watchdog-supervisor) | 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](#101-implementation-worker) | Rule in system prompt: "Maximum 500 lines per file." Workers must split files that grow beyond this limit. | +| **2 (Review)** | [PR Reviewer](#1212-pr-reviewer-detailed-specification) | 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](#114-specialized-workers), [Robot Tester](#114-specialized-workers), [ASV Benchmarker](#114-specialized-workers) | Each tester writes in its designated framework only | +| **2 (Review)** | [PR Reviewer](#1212-pr-reviewer-detailed-specification) | Checks that new tests use correct framework; rejects xUnit-style tests | +| **3 (Infrastructure)** | [Test Infrastructure Pool](#87-test-infrastructure-pool-supervisor) | 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](#114-specialized-workers) | Writes additional tests until coverage ≥97% before PR creation | +| **2 (Merge Gate)** | [PR Merge Pool](#83-pr-merge-pool-supervisor) | CI check includes coverage; failing coverage blocks merge | +| **3 (Audit)** | [System Watchdog](#911-system-watchdog-supervisor) | 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](#2118-commit-message-formatter-three-part-format) | Constructs three-part message: exact `type(scope): description` from issue Metadata, implementation body, `ISSUES CLOSED: #N` footer | +| **2 (Review)** | [PR Reviewer](#1212-pr-reviewer-detailed-specification) | 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](#97-backlog-grooming-supervisor) | 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](#229-r-09-label-and-metadata-correctness) | Quadruple | Label Manager → Creating agents → Groomer → Watchdog → Reconciler | Wrong labels cascade: wrong priority → wrong work order → milestone delays | +| [R-10](#2210-r-10-issue-state-lifecycle-management) | Quadruple | State Updater → Groomer → Watchdog → Reconciler | Wrong state prevents work from progressing through the pipeline | +| [R-16](#2216-r-16-bug-detection-and-proactive-quality-assurance) | Quadruple | Bug Hunt (code) → UAT (spec) → Reviewer (per-PR) → Guard (structure) | Undetected bugs reach production | +| [R-01](#221-r-01-supervisor-liveness-and-health-monitoring) | Triple | PB session check → PB deep inspection → Watchdog behavioral analysis | Dead supervisor = entire capability gap | +| [R-06](#226-r-06-quality-gate-enforcement) | Triple | Pre-PR gates → Post-PR CI fixer → Post-merge Watchdog audit | Bad code on master breaks everything | +| [R-12](#2212-r-12-merge-safety-and-branch-protection) | 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 | @@ -3579,6 +6819,19 @@ The Branch Setup agent creates or checks out branches with a strict rebase-only | 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-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 |