# Agent Tracking Discovery and Coordination Guide

This document explains how ALL CleverAgents should discover, interact with, and coordinate through the automation tracking issue system. Every agent should understand how to find what other agents are doing and how to communicate with them.

## MANDATORY: Startup State Recovery Protocol

**Every supervisor MUST recover state from its previous tracking issue on startup, BEFORE deleting old issues.** The correct startup sequence is:

1. **READ** — Call `READ_TRACKING_STATE` to get the most recent tracking issue (body + all comments + timestamps)
2. **ANALYZE** — Parse the recovered state for agent-specific information (active work items, health, queues)
3. **CREATE** — Call `CREATE_TRACKING_ISSUE` which closes all old issues and creates a fresh one
4. **RESUME** — Use recovered state to prioritize resuming in-progress work before starting new work

```bash
# CORRECT ORDER: Read THEN Create
recovered_state = task automation-tracking-manager "READ_TRACKING_STATE" \
  --agent-prefix "{YOUR_PREFIX}" \
  --tracking-type "{YOUR_TYPE}" \
  --repo-owner "$owner" \
  --repo-name "$repo"

# Parse offline duration — affects recovery urgency
offline_minutes = recovered_state.offline_duration_minutes
if offline_minutes > 120:
    log("[RECOVERY] Offline >2h — performing full domain re-scan")

# NOW safe to create new tracking issue (which closes old ones)
task automation-tracking-manager "CREATE_TRACKING_ISSUE" ...
```

**WRONG ORDER (destroys state):** If you `CREATE_TRACKING_ISSUE` first, it closes all old status issues. Then `READ_TRACKING_STATE` reads your brand-new empty issue instead of the previous session's state.

## Estimated Cycle Interval (Handled by ATM)

The `**Estimated Cycle Interval**: Nmin` field is automatically calculated and injected by the Automation Tracking Manager when you pass the `--sleep-interval-default` parameter to `CREATE_TRACKING_ISSUE`. **Agents do NOT need to calculate this themselves.**

```bash
# The ATM handles interval calculation internally:
task automation-tracking-manager "CREATE_TRACKING_ISSUE" \
  --agent-prefix "{YOUR_PREFIX}" \
  --tracking-type "{YOUR_TYPE}" \
  --body "$tracking_body" \
  --sleep-interval-default {YOUR_SLEEP_MINUTES} \
  --repo-owner "$owner" \
  --repo-name "$repo"
```

The ATM uses a rolling average formula: `new = old * 0.90 + actual * 0.10`. See spec Section 5.3.4 for details.

## MANDATORY: Announcement Review Protocol

**Every agent that creates announcement issues MUST also review its own announcements periodically.** At least once every 3 cycles, invoke:

```
task automation-tracking-manager "REVIEW_OWN_ANNOUNCEMENTS" \
  --agent-prefix "{YOUR_PREFIX}" \
  --repo-owner "$owner" \
  --repo-name "$repo"
```

For each returned announcement, evaluate whether the announced condition is still relevant, valid, and correct. Close any announcements that are no longer applicable via `CLOSE_ANNOUNCEMENT_ISSUE`. Failing to close stale announcements degrades signal quality for all consuming agents.

## MANDATORY: Announcement Consumption Protocol

**Every supervisor MUST read announcements from other agents at least once per cycle.** The read depth and source filtering depends on the agent's role:

- **System Watchdog / Product Builder**: Read ALL announcements at ALL priorities (full body + comments)
- **Human Liaison**: Read ALL announcements at Priority/High+ (full body + comments)
- **Implementation Pool / Backlog Grooming**: Read Watchdog + Liaison + Owner announcements at Priority/High+ (summary only)
- **All other supervisors**: Read Watchdog announcements at Priority/Critical only (title + label only)

Use the `READ_ANNOUNCEMENTS` operation with the appropriate `min_priority` and `agent_prefixes` parameters:

```
announcements = task automation-tracking-manager "READ_ANNOUNCEMENTS" \
  --agent-prefixes "AUTO-WATCHDOG" \
  --min-priority "Critical" \
  --repo-owner "$owner" \
  --repo-name "$repo"
```

Process Critical announcements IMMEDIATELY. Process High announcements before starting the next work cycle. Process Medium/Low announcements opportunistically.

## CRITICAL: Universal Label Requirement

**ALL automation tracking issues MUST have the "Automation Tracking" label.** This is the universal discovery mechanism that allows agents to find each other's activities.

## Core Discovery Patterns

### 1. Finding All Active Automation Agents

```bash
function discover_all_automation_activity() {
    echo "[DISCOVERY] Scanning for all automation agent activity..."
    
    # Get all open issues with "Automation Tracking" label
    local tracking_issues=$(curl -s "https://git.cleverthis.com/api/v1/repos/$owner/$repo/issues?state=open&type=issues&labels=Automation+Tracking" \
        -H "Authorization: token $FORGEJO_PAT")
    
    if [[ -z "$tracking_issues" || "$tracking_issues" == "[]" ]]; then
        echo "[DISCOVERY] No automation tracking issues found - no agents currently active"
        return 1
    fi
    
    echo "[DISCOVERY] Found automation activity:"
    echo "$tracking_issues" | jq -r '.[] | "  - [\(.title)] Issue #\(.number) (created \(.created_at))"'
    
    # Extract unique agent prefixes to see which agents are active
    local active_agents=$(echo "$tracking_issues" | jq -r '.[].title' | \
        grep -o '\[AUTO-[^]]*\]' | sort | uniq)
    
    echo "[DISCOVERY] Active agent types:"
    echo "$active_agents" | sed 's/\[AUTO-//g; s/\]//g' | while read -r agent; do
        echo "  - $agent"
    done
    
    return 0
}
```

### 2. Checking Specific Agent Activity

```bash
function check_agent_activity() {
    local agent_prefix="$1"  # e.g., "AUTO-GROOMER", "AUTO-LIAISON"
    local max_age_hours="${2:-24}"  # Default 24 hours
    
    echo "[AGENT-CHECK] Checking activity for $agent_prefix (last ${max_age_hours}h)..."
    
    # Find recent tracking issues for this agent
    local agent_issues=$(curl -s "https://git.cleverthis.com/api/v1/repos/$owner/$repo/issues?state=open&type=issues&labels=Automation+Tracking" \
        -H "Authorization: token $FORGEJO_PAT" | \
        jq -r ".[] | select(.title | contains(\"[$agent_prefix]\")) | \"\\(.number)|\\(.title)|\\(.created_at)\"")\n    \n    if [[ -z "$agent_issues" ]]; then\n        echo "[AGENT-CHECK] ⚠️  No recent activity from $agent_prefix"\n        return 1\n    fi\n    \n    # Check ages and report status\n    local current_time=$(date +%s)\n    local has_recent_activity=false\n    \n    echo "$agent_issues" | while IFS='|' read -r issue_num title created_at; do\n        local created_timestamp=$(date -d "$created_at" +%s 2>/dev/null || echo "0")\n        local age_hours=$(( (current_time - created_timestamp) / 3600 ))\n        \n        if (( age_hours <= max_age_hours )); then\n            has_recent_activity=true\n            echo "[AGENT-CHECK] ✓ Issue #$issue_num: $title (${age_hours}h ago)"\n        fi\n    done\n    \n    if [[ "$has_recent_activity" == "false" ]]; then\n        echo "[AGENT-CHECK] ⚠️  $agent_prefix has no activity within last ${max_age_hours}h"\n        return 2\n    fi\n    \n    return 0\n}\n```\n\n### 3. Reading Agent Status Details\n\n```bash\nfunction get_agent_status_details() {\n    local agent_prefix="$1"\n    \n    echo "[STATUS] Getting detailed status for $agent_prefix..."\n    \n    # Find the most recent status tracking issue\n    local latest_issue=$(curl -s "https://git.cleverthis.com/api/v1/repos/$owner/$repo/issues?state=open&type=issues&labels=Automation+Tracking" \\\n        -H "Authorization: token $FORGEJO_PAT" | \\\n        jq -r ".[] | select(.title | contains(\"[$agent_prefix]\") and (contains(\"Status\") or contains(\"Report\"))) | \"\\(.number)|\\(.title)|\\(.created_at)\"" | \\\n        sort -t'|' -k3 -r | head -1)\n    \n    if [[ -z "$latest_issue" ]]; then\n        echo "[STATUS] No status tracking issue found for $agent_prefix"\n        return 1\n    fi\n    \n    local issue_number=$(echo "$latest_issue" | cut -d'|' -f1)\n    local title=$(echo "$latest_issue" | cut -d'|' -f2)\n    \n    echo "[STATUS] Latest status: $title (Issue #$issue_number)"\n    \n    # Get the issue body for detailed status\n    local issue_body=$(curl -s "https://git.cleverthis.com/api/v1/repos/$owner/$repo/issues/$issue_number" \\\n        -H "Authorization: token $FORGEJO_PAT" | jq -r '.body')\n    \n    if [[ -n "$issue_body" ]]; then\n        echo "[STATUS] Status details:"\n        # Extract key status lines (first 10 lines of body)\n        echo "$issue_body" | head -10 | sed 's/^/  /'\n        \n        # Look for health indicators section\n        if echo "$issue_body" | grep -q "Health Indicators"; then\n            echo "[STATUS] Health indicators:"\n            echo "$issue_body" | sed -n '/## Health Indicators/,/##/p' | head -10 | sed 's/^/  /'\n        fi\n    fi\n    \n    return 0\n}\n```\n\n### 4. Cross-Agent Communication\n\n```bash\nfunction send_coordination_message() {\n    local target_agent_prefix="$1"  # e.g., "AUTO-LIAISON"\n    local sender_agent_name="$2"    # e.g., "implementation-pool-supervisor"\n    local message="$3"              # The message content\n    local priority="${4:-Medium}"   # Default to Medium priority\n    \n    echo "[COORDINATION] Sending message to $target_agent_prefix from $sender_agent_name"\n    \n    local announcement_body="# 📨 Inter-Agent Coordination Message\n\n**From**: $sender_agent_name\n**To**: $target_agent_prefix\n**Priority**: $priority\n**Timestamp**: $(date +'%Y-%m-%d %H:%M:%S')\n\n## Message\n\n$message\n\n## Action Required\n\nThe target agent should review this message and respond through their tracking issues or comments if coordination is needed.\n\n## Context\n\nThis is an automated coordination message between CleverAgents to ensure smooth system operation.\n\n---\n**Automated by CleverAgents Bot**\n**Message Type**: Inter-Agent Coordination\n**Sender**: $sender_agent_name | **Recipient**: $target_agent_prefix"\n    \n    # Create the coordination message as an announcement issue\n    local title="[COORD-MSG] Message to $target_agent_prefix"\n    local response=$(curl -s -X POST "https://git.cleverthis.com/api/v1/repos/$owner/$repo/issues" \\\n      -H "Authorization: token $FORGEJO_PAT" \\\n      -H "Content-Type: application/json" \\\n      -d "{\"title\": \"$title\", \"body\": \"$announcement_body\"}")\n    \n    local issue_number=$(echo "$response" | jq -r '.number')\n    \n    if [[ "$issue_number" != "null" && -n "$issue_number" ]]; then\n        echo "[COORDINATION] ✓ Created coordination message: Issue #$issue_number"\n        \n        # CRITICAL: Apply \"Automation Tracking\" label\n        curl -s -X PUT "https://git.cleverthis.com/api/v1/repos/$owner/$repo/issues/$issue_number/labels" \\\n          -H "Authorization: token $FORGEJO_PAT" \\\n          -H "Content-Type: application/json" \\\n          -d '{\"labels\": ["Automation Tracking"]}'\n        \n        echo "[COORDINATION] ✓ Message delivered to $target_agent_prefix via Issue #$issue_number"\n        return 0\n    else\n        echo "[COORDINATION] ✗ Failed to deliver message to $target_agent_prefix"\n        return 1\n    fi\n}\n```\n\n### 5. Adding Comments to Other Agents' Issues\n\n```bash\nfunction add_comment_to_agent_issue() {\n    local target_agent_prefix="$1"\n    local comment_message="$2"\n    local sender_agent_name="$3"\n    \n    echo "[COMMENT] Adding comment to latest $target_agent_prefix issue..."\n    \n    # Find the most recent tracking issue for the target agent\n    local latest_issue=$(curl -s "https://git.cleverthis.com/api/v1/repos/$owner/$repo/issues?state=open&type=issues&labels=Automation+Tracking" \\\n        -H "Authorization: token $FORGEJO_PAT" | \\\n        jq -r ".[] | select(.title | contains(\"[$target_agent_prefix]\")) | \"\\(.number)|\\(.title)|\\(.created_at)\"" | \\\n        sort -t'|' -k3 -r | head -1)\n    \n    if [[ -z "$latest_issue" ]]; then\n        echo "[COMMENT] No tracking issue found for $target_agent_prefix to comment on"\n        return 1\n    fi\n    \n    local issue_number=$(echo "$latest_issue" | cut -d'|' -f1)\n    local title=$(echo "$latest_issue" | cut -d'|' -f2)\n    \n    echo "[COMMENT] Adding comment to Issue #$issue_number: $title"\n    \n    # Create formatted comment\n    local formatted_comment="## 💬 Cross-Agent Comment from $sender_agent_name\n\n**Timestamp**: $(date +'%Y-%m-%d %H:%M:%S')\n\n$comment_message\n\n---\n**Automated by CleverAgents Bot**\n**Comment Type**: Cross-Agent Coordination\n**From**: $sender_agent_name | **To**: $target_agent_prefix"\n    \n    # Post the comment\n    local response=$(curl -s -X POST "https://git.cleverthis.com/api/v1/repos/$owner/$repo/issues/$issue_number/comments" \\\n      -H "Authorization: token $FORGEJO_PAT" \\\n      -H "Content-Type: application/json" \\\n      -d "{\"body\": \"$formatted_comment\"}")\n    \n    if [[ -n "$response" ]]; then\n        echo "[COMMENT] ✓ Added comment to $target_agent_prefix Issue #$issue_number"\n        return 0\n    else\n        echo "[COMMENT] ✗ Failed to add comment to $target_agent_prefix issue"\n        return 1\n    fi\n}\n```\n\n## Agent Prefix Reference\n\nEvery agent should know these prefixes for coordination:\n\n| Agent Type | Prefix | Purpose |\n|------------|--------|----------|\n| Session Persister | `AUTO-SESSION` | Session state tracking |\n| System Watchdog | `AUTO-WATCHDOG` | System health monitoring |\n| Backlog Groomer | `AUTO-GROOMER` | Issue grooming and cleanup |\n| Human Liaison | `AUTO-LIAISON` | Human interaction coordination |\n| Implementation Pool | `AUTO-IMP-POOL` | Implementation orchestration |\n| PR Review Pool | `AUTO-REV-POOL` | PR review coordination |\n| UAT Tester Pool | `AUTO-UAT-POOL` | User acceptance testing |\n| Bug Hunter Pool | `AUTO-BUG-POOL` | Bug detection analysis |\n| Test Infra Pool | `AUTO-INF-POOL` | Testing infrastructure |\n| Architect | `AUTO-ARCH` | Architecture oversight |\n| Epic Planner | `AUTO-EPIC` | Epic planning and breakdown |\n| Agent Evolver | `AUTO-EVLV` | Agent self-improvement |\n| Architecture Guard | `AUTO-GUARD` | Code architecture analysis |\n| Spec Updater | `AUTO-SPEC` | Specification maintenance |\n| Timeline Updater | `AUTO-TIME` | Timeline tracking |\n| Docs Writer | `AUTO-DOCS` | Documentation generation |\n| Project Owner | `AUTO-OWNR` | Project triage and ownership |\n\n## Common Coordination Scenarios\n\n### Scenario 1: Implementation Worker Needs to Know System Status\n\n```bash\n# Check if system is healthy before starting work\ndiscover_all_automation_activity\n\nif check_agent_activity \"AUTO-WATCHDOG\" 30; then\n    echo "[COORDINATION] System watchdog is active - proceeding with implementation"\nelse\n    echo "[COORDINATION] ⚠️  System watchdog not seen recently - potential system issues"\n    send_coordination_message \"AUTO-WATCHDOG\" \"implementation-worker\" \"System health check requested before starting work on Issue #$issue_number\"\nfi\n\n# Check if backlog groomer is active\nif check_agent_activity \"AUTO-GROOMER\" 60; then\n    echo "[COORDINATION] Backlog groomer active - issues are being maintained"\nelse\n    echo "[COORDINATION] Notice: Backlog groomer not seen recently"\nfi\n```\n\n### Scenario 2: System Watchdog Coordinating with Implementation Pool\n\n```bash\n# System watchdog detecting issues and coordinating with implementation pool\nif detected_ci_blocker_issues; then\n    send_coordination_message \"AUTO-IMP-POOL\" \"system-watchdog\" \\\n        \"URGENT: CI blocker issues detected. Implementation pool should prioritize these issues over regular PRs.\" \\\n        \"High\"\nfi\n\n# Check implementation pool status\nif get_agent_status_details \"AUTO-IMP-POOL\"; then\n    echo "[WATCHDOG] Implementation pool status confirmed"\nelse\n    echo "[WATCHDOG] ⚠️  Cannot read implementation pool status - may be stalled"\nfi\n```\n\n### Scenario 3: Human Liaison Broadcasting Important Information\n\n```bash\n# Broadcast important human requests to all relevant agents\nif human_requested_milestone_change; then\n    # Notify multiple agents about the change\n    for agent in \"AUTO-IMP-POOL\" \"AUTO-GROOMER\" \"AUTO-REV-POOL\"; do\n        send_coordination_message \"$agent\" \"human-liaison\" \\\n            \"PRIORITY UPDATE: Human has requested focus on Milestone 2. Please adjust work priorities accordingly.\"\n    done\nfi\n```\n\n### Scenario 4: Adding Status Comments to Other Agents\n\n```bash\n# Implementation worker reporting blocking issue to system watchdog\nif encountered_blocking_issue; then\n    add_comment_to_agent_issue \"AUTO-WATCHDOG\" \\\n        \"BLOCKING ISSUE: Implementation worker for Issue #$issue_number encountered $blocking_issue. System attention needed.\" \\\n        \"implementation-worker\"\nfi\n```\n\n## Best Practices for Agent Coordination\n\n### 1. Always Check System Health First\n```bash\n# At the start of any significant operation\ndiscover_all_automation_activity\ncheck_agent_activity \"AUTO-WATCHDOG\" 60  # Ensure system monitoring is active\n```\n\n### 2. Coordinate Before Making System-Wide Changes\n```bash\n# Before making changes that affect other agents\nsend_coordination_message \"AUTO-GROOMER\" \"my-agent\" \\\n    \"Planning to create $issue_count new issues. This will affect backlog size.\"\n```\n\n### 3. Report Critical Issues Immediately\n```bash\n# When encountering critical issues\nfor critical_agent in \"AUTO-WATCHDOG\" \"AUTO-LIAISON\"; do\n    send_coordination_message \"$critical_agent\" \"my-agent\" \\\n        \"CRITICAL: $critical_issue_description\" \"Critical\"\ndone\n```\n\n### 4. Provide Status Updates During Long Operations\n```bash\n# During long-running operations\nif (( operation_duration > 30 )); then  # 30 minutes\n    add_comment_to_agent_issue \"AUTO-WATCHDOG\" \\\n        \"STATUS: Long operation in progress - $operation_description (${operation_duration}min elapsed). Normal operation.\" \\\n        \"my-agent\"\nfi\n```\n\n### 5. Always Use the \"Automation Tracking\" Label\n```bash\n# CRITICAL: When creating any tracking issue\ncurl -s -X PUT "https://git.cleverthis.com/api/v1/repos/$owner/$repo/issues/$issue_number/labels" \\\n  -H "Authorization: token $FORGEJO_PAT" \\\n  -H "Content-Type: application/json" \\\n  -d '{\"labels\": [\"Automation Tracking\"]}'\n```\n\n## Integration Template\n\nEvery agent should include this coordination capability:\n\n```bash\n# Add this to every agent that needs coordination\nAGENT_NAME="my-agent-name"                    # Set this to the agent's actual name\nAGENT_PREFIX="AUTO-MY-PREFIX"                 # Set this to the agent's tracking prefix\n\n# Source the shared coordination functions\n# (Functions from this document should be available to all agents)\n\n# Use coordination at key points:\n# 1. At startup - check system health\n# 2. Before major operations - coordinate with relevant agents  \n# 3. During long operations - provide status updates\n# 4. When encountering issues - alert appropriate agents\n# 5. At shutdown - notify completion\n```\n\nThis system ensures that ALL agents can discover each other's activities, coordinate effectively, and maintain situational awareness across the entire CleverAgents ecosystem.