8000 Fix #300: Count worktree file activity toward the idle timeout and keep a killed agent's work by vicgupta · Pull Request #303 · vicgupta/auto-mini-factory · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ OPENAI_API_KEY=sk-proj-... # optional: OpenAI API key for codex
# AMF_PRIMARY_AGENT=codex # optional: claudecode, codex or opencode; the agent for issues without a pipeline
# AMF_SECONDARY_AGENT=claudecode # optional: claudecode, codex, opencode or none; runs when the primary fails
# AMF_AGENT_TIMEOUT=60m # optional: how long each agent run may take (--agent-timeout overrides it)
# AMF_AGENT_IDLE_TIMEOUT=15m # optional: stop an agent that produces no output for this long (off disables it)
# AMF_AGENT_IDLE_TIMEOUT=30m # optional: stop an agent that produces no output or changes no worktree file for this long (off disables it)
# AMF_LOG_LEVEL=info # optional: debug, info, warn or error, for the terminal and the event log in .amf/runs/
AMF_TRUSTED=login1,login2... # optional: only work on issues opened by these GitHub users
# AMF_POSTGRES_URL=postgres://user:password@localhost:5432/postgres # optional: also save the logs to database amflogs on this PostgreSQL server
9 changes: 6 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -192,9 +192,12 @@ Or run `amf watch` to process open issues labeled `amf:ready`, oldest first.
saves a token; `amf auth status`, `amf auth logout` and `amf auth token` (with
`-f, --force` to print to a terminal) manage it. Every flag has a long and a
short form: `amf help flags` lists them, including `-D, --draft` and
`-O, --color=auto|always|never`. An agent that prints no output for
`AMF_AGENT_IDLE_TIMEOUT` (default 15m; `off` disables it) is stopped and the
run fails, so the fallback agent can try.
`-O, --color=auto|always|never`. An agent that prints no output and changes
no file in the worktree for `AMF_AGENT_IDLE_TIMEOUT` (default 30m; `off`
disables it) is stopped and the run fails, so the fallback agent can try.
When amf kills an agent, it saves the agent's partial work on a local-only
`amf/wip/issue-N-<UTC time>` branch (nothing is pushed); the failure comment
names it and says how to inspect it.

For all settings and defaults, run `amf help env` or see the
[configuration guide](docs/CONFIGURATION.md).
Expand Down
2 changes: 1 addition & 1 deletion cmd/amf/auto.go
Original file line number Diff line number Diff line change
Expand Up @@ -317,7 +317,7 @@ func (r *Runner) autoPlan(ctx context.Context, sentence string, max int) ([]plan
r.event(slog.LevelInfo, "auto.plan", 0, fmt.Sprintf("planning with %s (timeout %s)", agentName(agent), r.Timeout),
"action", "planning", "agent", agentName(agent), "model", model, "sentence", sentence, "max_issues", max)
log := filepath.Join(r.Root, ".amf", "logs", fmt.Sprintf("auto-plan-%s.log", agentName(agent)))
out, err := r.runAgent(ctx, agent, "", model, wt, autoPlanPrompt(r.Repo, sentence, max), log, filepath.Join(wt, ".amf", "plan.md"))
out, err := r.runAgent(ctx, agent, "", model, wt, base, autoPlanPrompt(r.Repo, sentence, max), log, filepath.Join(wt, ".amf", "plan.md"))
if err == nil {
var issues []plannedIssue
if issues, err = parsePlan(out, max); err == nil {
Expand Down
7 changes: 4 additions & 3 deletions cmd/amf/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,9 @@ type Config struct {
AgentTimeout string

// AgentIdleTimeout is AMF_AGENT_IDLE_TIMEOUT as written: how long an
// agent may produce no output before amf stops it. "" means the default,
// "off" disables it. newRunner parses it, like AgentTimeout.
// agent may produce no output and change no worktree file before amf
// stops it. "" means the default, "off" disables it. newRunner parses
// it, like AgentTimeout.
AgentIdleTimeout string

// LogLevel is AMF_LOG_LEVEL as written; newRunner parses it, like
Expand Down Expand Up @@ -199,7 +200,7 @@ func parseAgentIdleTimeout(v string) (time.Duration, error) {
}
d, err := time.ParseDuration(v)
if err != nil {
return 0, fmt.Errorf("AMF_AGENT_IDLE_TIMEOUT=%q: not a duration (use e.g. 15m, or off)", v)
return 0, fmt.Errorf("AMF_AGENT_IDLE_TIMEOUT=%q: not a duration (use e.g. 30m, or off)", v)
}
if d <= 0 {
return 0, fmt.Errorf("AMF_AGENT_IDLE_TIMEOUT: the idle timeout must be positive, got %s (use off to disable it)", d)
Expand Down
12 changes: 9 additions & 3 deletions cmd/amf/help.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,11 @@ amf run --dry-run makes the change on the local amf/issue-N branch and prints
the pull request it would open, without labeling, commenting, pushing,
opening a PR or merging.

If amf stops an agent at the agent timeout or idle timeout, it keeps what the
agent changed on a local-only amf/wip/issue-N-<UTC time> branch, pushed
nowhere, and the failure comment names it; an agent that changed nothing gets
no WIP branch.

An issue that already has an open amf pull request is labeled amf:pr-open
and skipped. A leftover amf/issue-N branch whose work is already merged
into the default branch (by ancestry or a merged PR at its tip) is reused:
Expand Down Expand Up @@ -268,9 +273,10 @@ Placeholders ending in ..., and owner/name, count as unset.
How long each agent run may take, as a Go duration; --agent-timeout (or
its deprecated alias --timeout) overrides it. Must be at least 1m and at
most 24h
AMF_AGENT_IDLE_TIMEOUT (default: 15m)
How long an agent may produce no output on stdout or stderr before amf
stops it and fails the run, as a Go duration; off disables it
AMF_AGENT_IDLE_TIMEOUT (default: 30m)
How long an agent may produce no output, and change no file in the
worktree, before amf stops it and fails the run, as a Go duration; off
disables it
AMF_STALE_TIMEOUT (default: max(2x agent timeout, 2h))
How long watch lets an issue stay amf: 8000 in-progress with no amf working on
it before putting it back to amf:ready; off disables it. --stale-timeout
Expand Down
2 changes: 1 addition & 1 deletion cmd/amf/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ var envTemplate = []envVar{
{"AMF_PRIMARY_AGENT", defaultPrimaryAgent, "optional: claudecode, codex or opencode; the agent for issues without a pipeline", true},
{"AMF_SECONDARY_AGENT", defaultSecondaryAgent, "optional: claudecode, codex, opencode or none; runs when the primary fails", true},
{"AMF_AGENT_TIMEOUT", fmt.Sprintf("%dm", defaultAgentTimeout/time.Minute), "optional: how long each agent run may take (--agent-timeout overrides it)", true},
{"AMF_AGENT_IDLE_TIMEOUT", fmt.Sprintf("%dm", defaultAgentIdleTimeout/time.Minute), "optional: stop an agent that produces no output for this long (off disables it)", true},
{"AMF_AGENT_IDLE_TIMEOUT", fmt.Sprintf("%dm", defaultAgentIdleTimeout/time.Minute), "optional: stop an agent that produces no output or changes no worktree file for this long (off disables it)", true},
{"AMF_LOG_LEVEL", "info", "optional: debug, info, warn or error, for the terminal and the event log in .amf/runs/", true},
{"AMF_TRUSTED", "login1,login2...", "optional: only work on issues opened by these GitHub users", false},
{"AMF_POSTGRES_URL", "postgres://user:password@localhost:5432/postgres", "optional: also save the logs to database amflogs on this PostgreSQL server", true},
Expand Down
7 changes: 4 additions & 3 deletions cmd/amf/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,10 @@ func buildVersion() string {
// permission, so a run without a limit could watch forever.
const defaultAgentTimeout = 60 * time.Minute

// defaultAgentIdleTimeout is how long an agent may produce no output before
// amf stops it, without AMF_AGENT_IDLE_TIMEOUT saying otherwise.
const defaultAgentIdleTimeout = 15 * time.Minute
// defaultAgentIdleTimeout is how long an agent may produce no output and
// change no file in the worktree before amf stops it, without
// AMF_AGENT_IDLE_TIMEOUT saying otherwise.
const defaultAgentIdleTimeout = 30 * time.Minute

const troubleshootingURL = "https://github.com/vicgupta/auto-mini-factory/blob/main/docs/TROUBLESHOOTING.md"

Expand Down
158 changes: 144 additions & 14 deletions cmd/amf/pipeline.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"errors"
"fmt"
"io"
"io/fs"
"log/slog"
"net/http"
"net/url"
Expand Down Expand Up @@ -378,7 +379,7 @@ func (r *Runner) runPipeline(ctx context.Context, wt string, issue Issue, branch

var plan string
if p.Plan != nil {
out, err := r.runReadOnly(ctx, p.Plan, n, "plan", wt, planPrompt(r.Repo, branch, issue, p.Plan))
out, err := r.runReadOnly(ctx, p.Plan, n, "plan", wt, base, planPrompt(r.Repo, branch, issue, p.Plan))
if err != nil {
return "", "", err
}
Expand Down Expand Up @@ -406,7 +407,7 @@ func (r *Runner) runPipeline(ctx context.Context, wt string, issue Issue, branch
rounds = k
r.event(slog.LevelDebug, "issue.code.round", n, fmt.Sprintf("#%d: code round %d", n, k), "round", k)
name := fmt.Sprintf("code-%d", k)
out, err := r.runStage(ctx, p.Code, n, name, wt, codePrompt(r.Repo, branch, issue, p.Code, plan, review))
out, err := r.runStage(ctx, p.Code, n, name, wt, base, codePrompt(r.Repo, branch, issue, p.Code, plan, review))
if err != nil {
return "", "", err
}
Expand All @@ -423,7 +424,7 @@ func (r *Runner) runPipeline(ctx context.Context, wt string, issue Issue, branch
return "", "", err
}
name = fmt.Sprintf("eval-%d", k)
out, err = r.runReadOnly(ctx, p.Eval, n, name, wt, evalPrompt(r.Repo, branch, base, issue, p.Eval, plan, summary, diff))
out, err = r.runReadOnly(ctx, p.Eval, n, name, wt, base, evalPrompt(r.Repo, branch, base, issue, p.Eval, plan, summary, diff))
if err != nil {
return "", "", err
}
Expand Down Expand Up @@ -500,12 +501,12 @@ func blocked(plan string) (string, bool) {

// runReadOnly runs a stage that must not change the branch, then discards
// whatever it changed anyway.
func (r *Runner) runReadOnly(ctx context.Context, s *Stage, n int, name, wt, prompt string) (string, error) {
func (r *Runner) runReadOnly(ctx context.Context, s *Stage, n int, name, wt, base, prompt string) (string, error) {
head, err := git(ctx, wt, "rev-parse", "HEAD")
if err != nil {
return "", err
}
out, runErr := r.runStage(ctx, s, n, name, wt, prompt)
out, runErr := r.runStage(ctx, s, n, name, wt, base, prompt)
if _, err := git(ctx, wt, "reset", "--hard", head); err != nil {
return "", err
}
Expand All @@ -515,7 +516,7 @@ func (r *Runner) runReadOnly(ctx context.Context, s *Stage, n int, name, wt, pro
return out, runErr
}

func (r *Runner) runStage(ctx context.Context, s *Stage, n int, name, wt, prompt string) (string, error) {
func (r *Runner) runStage(ctx context.Context, s *Stage, n int, name, wt, base, prompt string) (string, error) {
model := r.agentModel(s.Agent, s.Model)
shown := model
if shown == "" {
Expand All @@ -524,7 +525,7 @@ func (r *Runner) runStage(ctx context.Context, s *Stage, n int, name, wt, prompt
r.event(slog.LevelInfo, "issue.stage", n, fmt.Sprintf("#%d: %s: running %s (%s, timeout %s)", n, name, s.Agent, shown, r.Timeout),
"stage", name, "agent", s.Agent, "model", shown, "timeout", r.Timeout.String())
log := filepath.Join(r.Root, ".amf", "logs", fmt.Sprintf("issue-%d-%s.log", n, name))
return r.runAgent(ctx, s.Agent, s.Name, model, wt, prompt, log, filepath.Join(wt, ".amf", name+".md"))
return r.runAgent(ctx, s.Agent, s.Name, model, wt, base, prompt, log, filepath.Join(wt, ".amf", name+".md"))
}

// logIssue is the issue number in a log file's name, issue-N.log or
Expand Down Expand Up @@ -569,7 +570,7 @@ func commitRound(ctx context.Context, wt string, k int, base string, s *Stage) e
// message write it to outPath instead. Claude doesn't need outPath. stage
// names the run for timeout errors: plan, code or eval, or "" without a
// pipeline.
func (r *Runner) runAgent(ctx context.Context, agent, stage, model, wt, prompt, logPath, outPath string) (summary string, err error) {
func (r *Runner) runAgent(ctx context.Context, agent, stage, model, wt, base, prompt, logPath, outPath string) (summary string, err error) {
if err := os.MkdirAll(filepath.Dir(logPath), 0o755); err != nil {
return "", err
}
Expand Down Expand Up @@ -650,6 +651,12 @@ func (r *Runner) runAgent(ctx context.Context, agent, stage, model, wt, prompt,
activity := make(chan struct{}, 1)
cmd.Stdout = io.MultiWriter(&stdout, outLog, activityWriter(activity))
cmd.Stderr = io.MultiWriter(&stderrBytes, errLog, activityWriter(activity))
// An agent that edits files without printing still counts as active:
// scan the worktree for changes while it runs, ignoring .git.
filesDone := make(chan struct{})
if r.IdleTimeout > 0 {
go watchFileActivity(wt, fileActivityInterval(r.IdleTimeout), activity, filesDone)
}

// The agent runs in its own process group, so a deadline or Ctrl-C can
// stop it and everything it spawned, not just the direct child. The kill
Expand Down Expand Up @@ -713,6 +720,7 @@ func (r *Runner) runAgent(ctx context.Context, agent, stage, model, wt, prompt,
callEvent(ctx, "agent.exit", fmt.Sprintf("%s: %s exited %d", stageName(stage), agentName(agent), code), attrs...)
}()
runErr := cmd.Run()
close(filesDone)
close(exited)
stopIdle()
outLog.Flush()
Expand All @@ -739,13 +747,16 @@ func (r *Runner) runAgent(ctx context.Context, agent, stage, model, wt, prompt,
"agent", agentName(agent), "stage", stageName(stage), "limit", r.IdleTimeout.String(), "elapsed", elapsed.String(),
"grace", grace.String(), "pgid", cmd.Process.Pid, "bytes", stdout.Len(), "log", logPath, "idle", true)
partial := keepPartial(logPath, outPath, r.Redact)
wip := r.saveWIP(ctx, wt, logIssue(logPath), base, logOut)
return "", &agentTimeoutError{
Agent: agentName(agent),
Stage: stage,
Limit: r.IdleTimeout,
Elapsed: elapsed,
LogPath: logPath,
Partial: partial,
WIP: wip,
Base: base,
Idle: true,
}
} else if runErr != nil || ctx.Err() != nil {
Expand All @@ -767,13 +778,16 @@ func (r *Runner) runAgent(ctx context.Context, agent, stage, model, wt, prompt,
"agent", agentName(agent), "stage", stageName(stage), "limit", r.Timeout.String(), "elapsed", elapsed.String(),
"grace", grace.String(), "pgid", cmd.Process.Pid, "bytes", stdout.Len(), "log", logPath)
partial := keepPartial(logPath, outPath, r.Redact)
wip := r.saveWIP(ctx, wt, logIssue(logPath), base, logOut)
return "", &agentTimeoutError{
Agent: agentName(agent),
Stage: stage,
Limit: r.Timeout,
Elapsed: elapsed,
LogPath: logPath,
Partial: partial,
WIP: wip,
Base: base,
}
}
if runErr == nil { // ctx was cancelled and the agent still exited cleanly
Expand Down Expand Up @@ -822,6 +836,89 @@ func (a activityWriter) Write(p []byte) (int, error) {
return len(p), nil
}

// fileActivityInterval is how often to scan the worktree for the idle
// watcher: a quarter of the limit, at least 10ms (for tests) and at most
// 30s, so a big worktree isn't walked more often than that.
func fileActivityInterval(limit time.Duration) time.Duration {
d := limit / 4
if d < 10*time.Millisecond {
d = 10 * time.Millisecond
}
if d > 30*time.Second {
d = 30 * time.Second
}
return d
}

// fileState is a file's mtime and size, enough to see it change cheaply.
type fileState struct {
mod time.Time
size int64
}

// watchFileActivity reports activity whenever a file in root is created,
// changed or removed, ignoring .git. It ends when done is closed.
func watchFileActivity(root string, interval time.Duration, activity chan<- struct{}, done <-chan struct{}) {
last := scanWorktree(root)
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
select {
case <-done:
return
case <-ticker.C:
now := scanWorktree(root)
if filesChanged(last, now) {
select {
case activity <- struct{}{}:
default:
}
}
last = now
}
}
}

// scanWorktree records the mtime and size of every file under root, leaving
// out .git.
func scanWorktree(root string) map[string]fileState {
files := map[string]fileState{}
filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return nil
}
if d.Name() == ".git" {
if d.IsDir() {
return fs.SkipDir
}
return nil
}
if d.IsDir() {
return nil
}
info, err := d.Info()
if err != nil {
return nil
}
files[path] = fileState{mod: info.ModTime(), size: info.Size()}
return nil
})
return files
}

// filesChanged reports whether any file was created, changed or removed.
func filesChanged(before, after map[string]fileState) bool {
if len(before) != len(after) {
return true
}
for path, state := range before {
if after[path] != state {
return true
}
}
return false
}

// watchIdle closes the returned channel and calls stop when nothing is
// written to activity for limit. The returned func ends the watch; it is
// safe to call after the channel closed.
Expand Down Expand Up @@ -942,15 +1039,43 @@ func killAfter(d time.Duration, done <-chan struct{}, kill func()) {
}()
}

// saveWIP commits whatever the agent changed so far on a local-only branch
// and returns its name, or "" when it changed nothing. A failure is only
// logged as a warning, so it never replaces the agent's timeout.
func (r *Runner) saveWIP(ctx context.Context, wt string, n int, base string, log io.Writer) string {
if n <= 0 {
return ""
}
cctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)
defer cancel()
branch, err := saveWIPBranch(cctx, wt, n, base)
if err != nil {
fmt.Fprintf(log, "amf: could not save partial work: %v\n", err)
r.event(slog.LevelWarn, "issue.wip", n, fmt.Sprintf("#%d: could not save partial work: %v", n, err), "error", err)
return ""
}
if branch == "" {
return ""
}
fmt.Fprintf(log, "amf: saved partial work on %s (to inspect: git log -p %s..%s)\n", branch, base, branch)
r.event(slog.LevelInfo, "issue.wip", n, fmt.Sprintf("#%d: saved partial work on %s (git log -p %s..%s)", n, branch, base, branch),
"branch", branch, "base", base)
return branch
}

// agentTimeoutError is a run that hit the agent timeout, or produced no
// output for its idle timeout: amf killed the agent's whole process group.
// Such a run has no branch worth pushing, so no push is made and no PR is
// opened or updated, and the worktree is removed.
// Such a run pushes nothing and opens or updates no PR, and its worktree is
// removed; its changes are kept on a local-only WIP branch when there are
// any.
type agentTimeoutError struct {
Agent, Stage string
Limit, Elapsed time.Duration
LogPath string
Partial string // where the agent's final message so far is kept, or ""
// WIP is the local-only branch holding the agent's partial work, or "";
// Base is the branch it was compared with, for how to inspect it.
WIP, Base string
// Idle says amf stopped the run because it produced no output for Limit,
// not because the run took longer than the agent timeout.
Idle bool
Expand Down Expand Up @@ -982,18 +1107,23 @@ func (e *agentTimeoutError) comment(root string) string {
if e.Partial != "" {
kept += fmt.Sprintf(" (its final message so far: `%s`)", relLog(root, e.Partial))
}
wip := ""
if e.WIP != "" {
wip = fmt.Sprintf(" Its partial work is on the local branch `%s`; inspect it with `git log -p %s..%s`.", 8
e.WIP, e.Base, e.WIP)
}
before := ""
if e.Before != "" {
before = fmt.Sprintf("First %s; amf fell back to **%s**. ", e.Before, e.Agent)
}
retry := "To retry with more time, set `AMF_AGENT_TIMEOUT` or `--agent-timeout` and re-add the `" + labelReady + "` label."
if e.Idle {
retry = "To allow more time without output, set `AMF_AGENT_IDLE_TIMEOUT` (or `off` to disable it) and re-add the `" + labelReady + "` label."
return fmt.Sprintf("%samf stopped **%s** %s and opened no pull request: `%s produced no output for %s; stopped it`. %s. %s",
before, e.Agent, when, e.Agent, e.Limit, kept, retry)
return fmt.Sprintf("%samf stopped **%s** %s and opened no pull request: `%s produced no output for %s; stopped it`. %s.%s %s",
before, e.Agent, when, e.Agent, e.Limit, kept, wip, retry)
}
return fmt.Sprintf("%samf stopped **%s** %s and opened no pull request. %s. %s",
before, e.Agent, when, kept, retry)
return fmt.Sprintf("%samf stopped **%s** %s and opened no pull request. %s.%s %s",
before, e.Agent, when, kept, wip, retry)
}

// relLog is a log path relative to the checkout, as one would type it.
Expand Down
Loading
Loading
0