# Bug Hunter Automation Tracking Update

This document provides the required updates to convert bug-hunter.md from the old session state system to the new individual tracking issue system.

## Changes Required

### 1. Update Setup Section

**Replace this section:**
```
You receive:
- **SESSION STATE ISSUE** — Issue number for all health signals and status updates (REQUIRED)
- **Repo owner/name** — for Forgejo API calls
```

**With this:**
```
You receive:
- **Repo owner/name** — for Forgejo API calls
```

**Add these parameters:**
```
- **Cycle number** — Current cycle number for tracking issue naming
```

### 2. Add Automation Tracking System Section

Insert this section after the "Pool Supervisor Mode" header:

```markdown
## Automation Tracking System

**Updated**: This agent creates individual tracking issues instead of posting comments to a session state issue.

### Tracking Issue Format
- **Pool Status Updates**: `[AUTO-BUG-POOL] Bug Detection Pool Status (Cycle N)`
- **Analysis Reports**: `[AUTO-BUG-POOL] Bug Analysis Report (Cycle N)`  
- **Announcements**: `[AUTO-BUG-POOL] Announce: <message summary>`
- **Labels**: "Automation Tracking" + any relevant priority labels

### Cleanup Protocol
- **ONE ISSUE PER CYCLE**: Delete previous cycle's tracking issue before creating new one
- **PRESERVE ANNOUNCEMENTS**: Don't delete announcement issues

### Bug Hunter Tracking Functions

```bash
# Find and delete previous bug hunter pool tracking issue
function cleanup_previous_bug_hunter_tracking() {
    local previous_issue=$(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("[AUTO-BUG-POOL] Bug Detection Pool Status")) | .number' | head -1)
    
    if [[ -n "$previous_issue" && "$previous_issue" != "null" ]]; then
        echo "Cleaning up previous bug hunter tracking issue #$previous_issue"
        
        # Close with final comment
        curl -s -X POST "https://git.cleverthis.com/api/v1/repos/$owner/$repo/issues/$previous_issue/comments" \
          -H "Authorization: token $FORGEJO_PAT" \
          -H "Content-Type: application/json" \
          -d "{\"body\": \"Bug hunting cycle completed. Closing this tracking issue.\\n\\n---\\n**Automated by CleverAgents Bot**\\nSupervisor: Bug Detection Pool | Agent: bug-hunter\"}"
        
        # Close the issue
        curl -s -X PATCH "https://git.cleverthis.com/api/v1/repos/$owner/$repo/issues/$previous_issue" \
          -H "Authorization: token $FORGEJO_PAT" \
          -H "Content-Type: application/json" \
          -d '{"state": "closed"}'
        
        echo "✓ Previous bug hunter tracking issue #$previous_issue closed"
        sleep 2
    fi
}

# Create bug detection pool tracking issue
function create_bug_hunter_tracking_issue() {
    local cycle="$1"
    local title="[AUTO-BUG-POOL] Bug Detection Pool Status (Cycle $cycle)"
    local body="$2"
    
    local response=$(curl -s -X POST "https://git.cleverthis.com/api/v1/repos/$owner/$repo/issues" \
      -H "Authorization: token $FORGEJO_PAT" \
      -H "Content-Type: application/json" \
      -d "{\"title\": \"$title\", \"body\": \"$body\"}")
    
    local issue_number=$(echo "$response" | jq -r '.number')
    
    if [[ "$issue_number" != "null" && -n "$issue_number" ]]; then
        echo "✓ Created bug hunter tracking issue #$issue_number"
        
        # CRITICAL: Apply "Automation Tracking" label
        curl -s -X PUT "https://git.cleverthis.com/api/v1/repos/$owner/$repo/issues/$issue_number/labels" \
          -H "Authorization: token $FORGEJO_PAT" \
          -H "Content-Type: application/json" \
          -d '{"labels": ["Automation Tracking"]}'
        
        echo "✓ Applied 'Automation Tracking' label to issue #$issue_number"
        return 0
    else
        echo "✗ Failed to create bug hunter tracking issue"
        return 1
    fi
}

# Create bug hunter announcement issue
function create_bug_hunter_announcement_issue() {
    local message="$1"
    local priority="$2"  
    local body="$3"
    
    # Use automation-tracking-manager for consistent announcement handling
    local result=$(task automation-tracking-manager "CREATE_ANNOUNCEMENT_ISSUE" \
      --agent-prefix "AUTO-BUG-POOL" \
      --message "$message" \
      --priority "$priority" \
      --body "$body" \
      --repo-owner "$owner" \
      --repo-name "$repo")
    
    local issue_number=$(echo "$result" | grep -o 'issue #[0-9]*' | grep -o '[0-9]*')
    
    if [[ -n "$issue_number" ]]; then
        echo "✓ Created bug hunter announcement issue #$issue_number via tracking manager"
        return 0
    else
        echo "✗ Failed to create bug hunter announcement issue"
        return 1
    fi
}
```
```

### 3. Remove Session State Issue Validation

**Remove this code:**
```
# Check if session state issue number was provided
# Now uses individual tracking issues instead of session state issue
# No SESSION_STATE_ISSUE_NUMBER parameter needed
```

**Replace with:**
```
# Initialize tracking system - no session state issue required
```

### 4. Update Health Signal Posting

**Replace this code:**
```
if cycle % 60 == 0:  # Every ~10 minutes with 10-second monitoring
    post comment on session state issue:
        "[HEALTH] bug-hunter | Iteration: <cycle> | Status: active\n" +
         "- Type: pool-supervisor\n" +
         "- Active workers: <len(active)> / <N>\n" +
         "- Work completed: <len(scanned_modules)>/<len(all_modules)> modules scanned\n" +
         "- Findings filed: <findings_total>\n" +
         "- Last action: <brief description>\n" +
         "- Next check: in 10 minutes\n\n" +
         "---\n" +
         "**Automated by CleverAgents Bot**\n" +
         "Supervisor: Bug Hunting | Agent: bug-hunter"
```

**With this:**
```
if cycle % 60 == 0:  # Every ~10 minutes with 10-second monitoring
    next_health_time=$(date -d "+10 minutes" -Iseconds)
    tracking_body="# Bug Detection Pool Status — $(date +'%Y-%m-%d %H:%M:%S')

**Agent**: bug-hunter
**Cycle**: $cycle
**Reporting Interval**: 10 minutes (Next report expected: $next_health_time)
**Status**: active

## Summary

Bug detection pool managing ${#active_workers[@]} workers scanning ${#all_modules[@]} modules with $findings_total findings filed.

## Details

**Pool Status**: Active - scanning for potential bugs across codebase
**Active Workers**: ${#active_workers[@]} / $N
**Progress**: ${#scanned_modules[@]}/${#all_modules[@]} modules scanned ($(( ${#scanned_modules[@]} * 100 / ${#all_modules[@]} ))%)
**Findings Filed**: $findings_total total findings

### Module Scanning Progress

| Module | Status | Worker | Findings | Duration |
|--------|--------|---------|----------|----------|
$(for module in "${!active_workers[@]}"; do
    local worker="${active_workers[$module]:0:8}..."
    local findings="${module_findings[$module]:-0}"
    local duration="$(( ($(date +%s) - ${worker_start_times[$module]}) / 60 ))min"
    echo "| $module | In Progress | $worker | $findings | $duration |"
done)

### Completed Modules
$(for module in "${scanned_modules[@]}" | head -10; do
    echo "- $module (${module_findings[$module]:-0} findings)"
done)

## Health Indicators

- **Module Completion**: ${#scanned_modules[@]}/${#all_modules[@]} ($(( ${#scanned_modules[@]} * 100 / ${#all_modules[@]} ))%)
- **Worker Utilization**: ${#active_workers[@]}/$N ($(( ${#active_workers[@]} * 100 / N ))%)
- **Bug Detection Rate**: $findings_total findings across ${#scanned_modules[@]} modules
- **System Status**: Operational and actively scanning

## Next Actions

- Continue monitoring ${#active_workers[@]} active scan workers
- Dispatch workers to remaining ${#unscanned_modules[@]} unscanned modules  
- Process findings from completed scans
- Next health report in ~10 minutes

---
**Automated by CleverAgents Bot**
Supervisor: Bug Detection Pool | Agent: bug-hunter"

    cleanup_previous_bug_hunter_tracking
    create_bug_hunter_tracking_issue $cycle "$tracking_body"
```

### 5. Update Worker Coordination

**Replace this code:**
```
4. **Post coordination comment** on the session state issue:
   ```
   Bug hunter instance <INSTANCE_ID> starting.
   Module focus: <module_focus>
   Clone: $CLONE_DIR
   ```
```

**With this:**
```
4. **Post coordination via tracking issue**:
   local coordination_body="# 🕵️ Bug Hunter Worker Started

**Instance ID**: $INSTANCE_ID
**Module Focus**: $module_focus  
**Clone Directory**: $CLONE_DIR
**Timestamp**: $(date +'%Y-%m-%d %H:%M:%S')

## Scanning Plan

This worker instance will perform comprehensive bug detection analysis on the assigned module, focusing on:
- Error handling patterns
- Concurrency safety
- Security vulnerabilities  
- Boundary condition handling
- Resource management issues

## Coordination

Other automation agents can track this worker's progress through this tracking issue and related bug reports.

---
**Automated by CleverAgents Bot**
Worker: Bug Detection | Agent: bug-hunter
**Worker Type**: Module Scanner"

   create_bug_hunter_announcement_issue "Worker $INSTANCE_ID Started" "Medium" "$coordination_body"
```

## Implementation Notes

1. **Apply these changes manually** to the bug-hunter.md file since automated editing is having issues
2. **Test tracking issue creation** by ensuring the "Automation Tracking" label is properly applied
3. **Verify cross-agent coordination** works with the new discovery functions
4. **Update any other references** to session state issues that may exist elsewhere in the file

This update ensures bug-hunter.md uses the standardized automation tracking system and can be discovered and monitored by other agents like system-watchdog.