agent_manager.go

175 lines
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
package internal

import (
	"fmt"
	"log"
	"os/exec"
	"strings"
	"sync"
	"time"

	"congo.gg/dev/models"
)

// AgentManager runs work cycles using Claude Code in print mode.
// Each cycle: check tasks → do work → log results → heartbeat.
// The Monitor goroutine runs cycles and restarts on failure.
type AgentManager struct {
	running bool
	mu      sync.Mutex
	stop    chan struct{}
	done    chan struct{}
}

// DefaultAgent is the singleton agent manager.
var DefaultAgent = &AgentManager{
	stop: make(chan struct{}),
	done: make(chan struct{}),
}

// Monitor waits for code-server to be ready, then runs work cycles.
// Call Stop() to gracefully shut down.
func (m *AgentManager) Monitor() {
	defer close(m.done)

	// Wait for code-server + claude to be ready (up to 10 minutes)
	for i := 0; i < 60; i++ {
		select {
		case <-m.stop:
			log.Println("agent: monitor stopped during startup")
			return
		default:
		}
		if IsCoderRunning() && IsAgentAvailable() {
			break
		}
		time.Sleep(10 * time.Second)
	}

	if !IsAgentAvailable() {
		log.Println("agent: claude not authenticated — monitor idle (authenticate via: claude auth login)")
		return
	}

	log.Println("agent: monitor started, running work cycles every 5 minutes")

	for {
		m.runWorkCycle()

		// Wait between cycles, checking for stop signal
		select {
		case <-m.stop:
			log.Println("agent: monitor stopped")
			return
		case <-time.After(5 * time.Minute):
		}
	}
}

// Stop signals the monitor to shut down and waits for it to finish.
func (m *AgentManager) Stop() {
	select {
	case <-m.stop:
		// Already stopped
	default:
		close(m.stop)
	}
	// Wait for Monitor to exit (with timeout)
	select {
	case <-m.done:
	case <-time.After(30 * time.Second):
		log.Println("agent: stop timed out")
	}
}

// runWorkCycle executes one agent work cycle via claude -p.
func (m *AgentManager) runWorkCycle() {
	m.mu.Lock()
	m.running = true
	m.mu.Unlock()
	defer func() {
		m.mu.Lock()
		m.running = false
		m.mu.Unlock()
	}()

	prompt := `You are the Congo Developer agent. Check for tasks and do work.

1. Run: DB_PATH=/home/coder/data/congo-dev.db congo task list
2. If there are todo tasks, pick the highest priority one
3. Do the work (edit code in repos, run builds, etc.)
4. Run: DB_PATH=/home/coder/data/congo-dev.db congo task update TASK_ID --status done
5. Run: DB_PATH=/home/coder/data/congo-dev.db congo log "what you did"
6. Run: DB_PATH=/home/coder/data/congo-dev.db congo heartbeat

If no tasks, just run heartbeat and idle.`

	cmd := exec.Command("docker", "exec",
		"-w", "/home/coder",
		"-e", "DB_PATH=/home/coder/data/congo-dev.db",
		coderContainer,
		claudeBin, "-p", prompt,
		"--dangerously-skip-permissions",
		"--max-turns", "25",
	)

	out, err := cmd.CombinedOutput()
	result := strings.TrimSpace(string(out))

	if err != nil {
		log.Printf("agent: work cycle failed: %v", err)
		if result != "" {
			log.Printf("agent: output: %s", result[:min(len(result), 500)])
		}
		return
	}

	// Log the cycle
	summary := result
	if len(summary) > 200 {
		summary = summary[:200] + "..."
	}
	models.LogEntries.Insert(&models.LogEntry{
		Type: "work", Summary: "Agent work cycle completed", Detail: summary, Author: "agent",
	})
	log.Printf("agent: work cycle done (%d chars output)", len(result))
}

// IsAlive returns whether a work cycle is currently running.
func (m *AgentManager) IsAlive() bool {
	m.mu.Lock()
	defer m.mu.Unlock()
	return m.running
}

// AgentStatus returns status for templates.
func AgentStatus() string {
	if DefaultAgent.IsAlive() {
		return "working"
	}
	// Check last heartbeat
	entry, _ := models.LogEntries.First("WHERE Type = 'heartbeat' ORDER BY CreatedAt DESC")
	if entry != nil && time.Since(entry.CreatedAt) < 10*time.Minute {
		return "idle"
	}
	if IsAgentAvailable() {
		return "idle"
	}
	return "not authenticated"
}

// AgentLastHeartbeat returns when the last heartbeat was.
func AgentLastHeartbeat() string {
	entry, _ := models.LogEntries.First("WHERE Type = 'heartbeat' ORDER BY CreatedAt DESC")
	if entry == nil {
		return "never"
	}
	age := time.Since(entry.CreatedAt)
	if age < time.Minute {
		return "just now"
	}
	if age < time.Hour {
		return fmt.Sprintf("%dm ago", int(age.Minutes()))
	}
	return fmt.Sprintf("%dh ago", int(age.Hours()))
}