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
3 changes: 3 additions & 0 deletions agent/checkpoint.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ import "math"
// turn number that equals ceil(fraction * maxTurns). Callers do not need to
// track fired state — the turn-number match is deterministic.
func evalCheckpoint(checkpoints []Checkpoint, turn, maxTurns int) string {
if maxTurns < 1 {
return "" // Unlimited sessions have no turn-budget fractions.
}
for _, cp := range checkpoints {
// Compute the exact turn this checkpoint fires on.
// Ceiling: fraction=0.51 with maxTurns=10 fires on turn 6 (not 5).
Expand Down
7 changes: 4 additions & 3 deletions agent/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ const (
)

type SessionConfig struct {
MaxTurns int
MaxTurns int // -1 means unlimited model turns; otherwise must be positive.
CommandTimeout time.Duration
MaxCommandTimeout time.Duration
LoopDetectionThreshold int
Expand Down Expand Up @@ -70,6 +70,7 @@ type SessionConfig struct {
// Checkpoints are messages injected at specific turn-budget fractions.
// Each checkpoint fires exactly once, on the turn where the fraction is
// first reached. Fraction is in [0, 1] — e.g. 0.6 means "at 60% of MaxTurns".
// Unlimited sessions skip these fractional messages.
Checkpoints []Checkpoint

// VerifyBroadCommand is an optional second verification command run after
Expand Down Expand Up @@ -304,8 +305,8 @@ func (c SessionConfig) validateCheckpoints() error {

// validateTimeouts checks turn, command timeout, and loop detection fields.
func (c SessionConfig) validateTimeouts() error {
if c.MaxTurns < 1 {
return fmt.Errorf("MaxTurns must be >= 1, got %d", c.MaxTurns)
if c.MaxTurns != -1 && c.MaxTurns < 1 {
return fmt.Errorf("MaxTurns must be -1 (unlimited) or >= 1, got %d", c.MaxTurns)
}
if c.CommandTimeout <= 0 {
return fmt.Errorf("CommandTimeout must be > 0, got %v", c.CommandTimeout)
Expand Down
2 changes: 1 addition & 1 deletion agent/session_loop.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ func (s *Session) runTurnLoop(ctx context.Context, start time.Time, tracker *Con
// snapshot before any resumed turn runs, so cost/loop/no-progress budgets
// continue rather than reset. No-op on a fresh run or a v1 snapshot.
s.applyResumeProgress(result, tracker, ts)
for turn := s.resumeTurn + 1; turn <= s.config.MaxTurns; turn++ {
for turn := s.resumeTurn + 1; s.config.MaxTurns == -1 || turn <= s.config.MaxTurns; turn++ {
if err := ctx.Err(); err != nil {
result.Error = err
result.Duration = time.Since(start)
Expand Down
154 changes: 154 additions & 0 deletions agent/session_unlimited_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
// ABOUTME: Tests the native session's explicit unlimited model-turn policy.
// ABOUTME: Covers natural completion, cancellation, durable resume, and budget checkpoints.
package agent

import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"testing"

"github.com/2389-research/tracker/llm"
)

func TestConfigMaxTurnsPolicy(t *testing.T) {
for _, turns := range []int{-3, -2, -1, 0, 1, 80} {
t.Run(fmt.Sprint(turns), func(t *testing.T) {
cfg := DefaultConfig()
cfg.MaxTurns = turns
wantValid := turns == -1 || turns > 0
if err := cfg.Validate(); (err == nil) != wantValid {
t.Fatalf("MaxTurns=%d validation = %v, want valid=%v", turns, err, wantValid)
}
})
}
}

func unlimitedToolResponses(count int, name string) []*llm.Response {
responses := make([]*llm.Response, count)
for i := range responses {
responses[i] = toolCallResponse(fmt.Sprint(i), name)
// Distinct calls represent progress without weakening loop detection.
responses[i].Message.Content[0].ToolCall.Arguments = json.RawMessage(fmt.Sprintf(`{"step":%d}`, i))
}
return responses
}

func TestSessionUnlimitedNaturalCompletion(t *testing.T) {
client := &mockCompleter{responses: unlimitedToolResponses(82, "work")}
cfg := DefaultConfig()
cfg.MaxTurns = -1
cfg.Checkpoints = []Checkpoint{{Fraction: 0.5, Message: "turn budget halfway"}}
var budgetMessages int
client.onComplete = func(req *llm.Request) {
for _, msg := range req.Messages {
if msg.Text() == "turn budget halfway" {
budgetMessages++
}
}
}
sess := mustNewSession(t, client, cfg, WithTools(&stubTool{name: "work", output: "ok"}))
result, err := sess.Run(context.Background(), "work until complete")
if err != nil {
t.Fatal(err)
}
if result.Turns != 83 || result.TotalToolCalls() != 82 || result.MaxTurnsUsed || result.LoopDetected {
t.Fatalf("unexpected result: %+v", result)
}
if budgetMessages != 0 {
t.Fatalf("injected fractional budget checkpoint without a budget (%d sightings)", budgetMessages)
}
}

func TestSessionUnlimitedCancellationAndResume(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
cfg := DefaultConfig()
cfg.MaxTurns = -1
cfg.WorkingDir = t.TempDir()
cfg.TurnCheckpointPath = filepath.Join(t.TempDir(), "turn.json")
tool := &cancelOnNthTool{name: "work", n: 81, cancel: cancel}
client := &mockCompleter{responses: unlimitedToolResponses(82, "work")}
sess := mustNewSession(t, client, cfg, WithTools(tool))
result, err := sess.Run(ctx, "work until complete")
if !errors.Is(err, context.Canceled) || result.MaxTurnsUsed || result.Turns != 81 {
t.Fatalf("canceled result: turns=%d exhausted=%v err=%v", result.Turns, result.MaxTurnsUsed, err)
}
snap, err := LoadTurnSnapshot(cfg.TurnCheckpointPath)
if err != nil || snap == nil || snap.Turn != 81 {
t.Fatalf("cancellation snapshot = %+v, err=%v", snap, err)
}
resumed := mustNewSession(t, &mockCompleter{}, cfg)
result, err = resumed.Run(context.Background(), "resume")
if err != nil || result.Turns != 82 || result.MaxTurnsUsed || result.TotalToolCalls() != 81 {
t.Fatalf("resumed result = %+v, err=%v", result, err)
}
if _, err := os.Stat(cfg.TurnCheckpointPath); !errors.Is(err, os.ErrNotExist) {
t.Fatalf("terminal snapshot cleanup: %v", err)
}
}

func TestEvalCheckpoints_Unlimited(t *testing.T) {
cps := []Checkpoint{{Fraction: 0.5, Message: "halfway"}}
if got := evalCheckpoint(cps, 1, -1); got != "" {
t.Fatalf("unlimited checkpoint = %q, want none", got)
}
}

func TestSessionFiniteAndDefaultTurnLimits(t *testing.T) {
for _, limit := range []int{3, DefaultConfig().MaxTurns} {
t.Run(fmt.Sprint(limit), func(t *testing.T) {
cfg := DefaultConfig()
cfg.MaxTurns = limit
client := &mockCompleter{responses: unlimitedToolResponses(82, "work")}
sess := mustNewSession(t, client, cfg, WithTools(&stubTool{name: "work", output: "ok"}))
result, err := sess.Run(context.Background(), "work")
if err != nil || result.Turns != limit || !result.MaxTurnsUsed || result.LoopDetected {
t.Fatalf("finite result=%+v, err=%v", result, err)
}
})
}
}

func TestSessionUnlimitedRetainsGuards(t *testing.T) {
for _, guard := range []string{"cost", "progress", "loop"} {
t.Run(guard, func(t *testing.T) {
cfg := DefaultConfig()
cfg.MaxTurns = -1
responses := []*llm.Response{lengthTruncatedResponse(0.006), lengthTruncatedResponse(0.006)}
switch guard {
case "cost":
cfg.MaxCostUSD = 0.01
case "progress":
cfg.NoProgressTurns = 2
case "loop":
responses = nil
for range cfg.LoopDetectionThreshold {
responses = append(responses, toolCallResponse("repeat", "work"))
}
}
sess := mustNewSession(t, &mockCompleter{responses: responses}, cfg, WithTools(&stubTool{name: "work", output: "ok"}))
result, err := sess.Run(context.Background(), "work")
if err != nil {
t.Fatal(err)
}
switch guard {
case "cost":
if !result.NodeCostExceeded || result.MaxTurnsUsed {
t.Fatalf("cost guard result=%+v", result)
}
case "progress":
if !result.NoProgressDetected || result.MaxTurnsUsed {
t.Fatalf("progress guard result=%+v", result)
}
case "loop":
if !result.LoopDetected || result.Turns != cfg.LoopDetectionThreshold {
t.Fatalf("loop guard result=%+v", result)
}
}
})
}
}
2 changes: 1 addition & 1 deletion docs/architecture/adapter.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ Unknown kinds return `ErrUnknownNodeKind`.
| `SystemPrompt` | `system_prompt` | |
| `Model` | `llm_model` | **renamed** |
| `Provider` | `llm_provider` | **renamed** |
| `MaxTurns` | `max_turns` | int → decimal string |
| `MaxTurns` | `max_turns` | nonzero int → decimal string; `-1` means unlimited native turns; invalid negatives reach session validation |
| `CmdTimeout` | `command_timeout` | `time.Duration.String()` |
| `CacheTools` | `cache_tool_results` | `"true"` when set |
| `Compaction` | `context_compaction` | |
Expand Down
28 changes: 28 additions & 0 deletions docs/architecture/backends.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,34 @@ One method. One struct. Backends put their own rich config in `Extra`:
- `*ClaudeCodeConfig` — claude-code backend, carries MCP server list, allowed/disallowed tools, budget, permission mode.
- `*ACPConfig` — ACP backend, carries an explicit agent binary override.

## Native model-turn limit

Set `max_turns: -1` on an agent node with `backend: native` (or the
`codergen` alias) to run without a model-turn ceiling:

```text
agent Work
backend: native
max_turns: -1
prompt: Complete the task and verify the result.
```

This mode stops on normal model completion, cancellation, or the existing
loop, progress, and cost guards. It preserves the caller's context deadline,
tool timeouts, and durable turn snapshots. Fractional turn-budget messages do
not fire because there is no turn budget. Warm continuation overrides cannot
replace unlimited turns with a finite limit.

Omitting `max_turns`, or setting it to zero, keeps the native default of 80.
Positive limits keep their existing behavior. A direct `agent.SessionConfig`
requires a positive `MaxTurns` or exactly `-1`; zero and other negatives are
invalid. The `claude-code` and ACP backends reject negative `max_turns` before
starting an agent; this option describes Tracker's native loop only.

`tracker estimate` uses its existing eight-turn heuristic when a node has no
positive turn limit, including `-1`. Its high estimate is not a spending ceiling
for unlimited nodes; use the existing runtime budgets or a context deadline.

## Comparison

| Dimension | native | claude-code | ACP |
Expand Down
8 changes: 8 additions & 0 deletions gotchas.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,14 @@

Distilled, team-readable notes. Add your own entries; don't regenerate the file.

- 2026-11-08: Git hooks export repository pointers such as `GIT_DIR` and
`GIT_INDEX_FILE`. A fixture's working directory or `git -C` does not override
them: an unfiltered fixture can commit the caller's staged changes. Give
fixture Git subprocesses `cleanGitEnv()`; workflow tests that also launch
shell Git commands need `isolateTestGit(t)`. The two share the redirect-name
set. `TestGitFixturesIgnoreHookRepository` checks both fixtures against an
owned caller repository and verifies its HEAD and index remain unchanged.

## Herdr agent-state reporting

Herdr (herdr.dev) is a terminal **pane manager**, not an HTTP/webhook target.
Expand Down
2 changes: 1 addition & 1 deletion pipeline/dippin_adapter.go
Original file line number Diff line number Diff line change
Expand Up @@ -377,7 +377,7 @@ func extractAgentExecutionAttrs(cfg ir.AgentConfig, attrs map[string]string) {

// extractAgentLimitsAttrs sets turn limits, timeouts, and context management attrs.
func extractAgentLimitsAttrs(cfg ir.AgentConfig, attrs map[string]string) {
if cfg.MaxTurns > 0 {
if cfg.MaxTurns != 0 {
attrs["max_turns"] = strconv.Itoa(cfg.MaxTurns)
}
if cfg.CmdTimeout > 0 {
Expand Down
12 changes: 2 additions & 10 deletions pipeline/handlers/backend_acp.go
Original file line number Diff line number Diff line change
Expand Up @@ -135,16 +135,8 @@ func NewACPBackend() *ACPBackend {
// prompt, and collects results. The agent binary is selected based on the
// provider in cfg or the ACPConfig.Agent override.
func (b *ACPBackend) Run(ctx context.Context, cfg pipeline.AgentRunConfig, emit func(agent.Event)) (agent.SessionResult, error) {
// tool_access enforcement (issue #258): the ACP backend has no verified
// deny-equivalent for the directive — the protocol exposes session
// permissions but tracker has not yet audited the spelling against the
// upstream ACP agents (claude-code-acp, codex-acp, gemini). Per the
// spec's "fallback unsupported → refuse" rule, refuse session creation
// with a clear error rather than ship a soft-no that silently allows
// tool execution. Lifting this requires a follow-up that pins ACP's
// session.permission_modes (or equivalent) against each known agent.
if strings.TrimSpace(cfg.ToolAccess) != "" {
return agent.SessionResult{}, fmt.Errorf("acp backend cannot enforce tool_access=%q yet — see github.com/2389-research/tracker#258 (use the native backend, or open a follow-up issue once the ACP deny-equivalent is verified for your agent)", cfg.ToolAccess)
if err := validateACPConfig(cfg); err != nil {
return agent.SessionResult{}, err
}

agentName := b.resolveAgentName(cfg)
Expand Down
29 changes: 29 additions & 0 deletions pipeline/handlers/backend_acp_config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// ABOUTME: Validates Tracker directives before starting an ACP agent process.
// ABOUTME: Refuses native-only turn policy and unsupported tool-access restrictions.
package handlers

import (
"fmt"
"strings"

"github.com/2389-research/tracker/pipeline"
)

func validateACPConfig(cfg pipeline.AgentRunConfig) error {
if cfg.MaxTurns < 0 {
return fmt.Errorf("negative max_turns requires the native backend (-1 means unlimited)")
}
// tool_access enforcement (issue #258): the ACP backend has no verified
// deny-equivalent for the directive — the protocol exposes session
// permissions but tracker has not yet audited the spelling against the
// upstream ACP agents (claude-code-acp, codex-acp, gemini). Per the
// spec's "fallback unsupported → refuse" rule, refuse session creation
// with a clear error rather than ship a soft-no that silently allows
// tool execution. Lifting this requires a follow-up that pins ACP's
// session.permission_modes (or equivalent) against each known agent.
if strings.TrimSpace(cfg.ToolAccess) != "" {
return fmt.Errorf("acp backend cannot enforce tool_access=%q yet — see github.com/2389-research/tracker#258 (use the native backend, or open a follow-up issue once the ACP deny-equivalent is verified for your agent)", cfg.ToolAccess)
}

return nil
}
3 changes: 3 additions & 0 deletions pipeline/handlers/backend_claudecode.go
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,9 @@ func buildResult(state *runState) (agent.SessionResult, error) {
// buildArgs constructs the CLI arguments for the claude command from the run config.
// Returns an error if ClaudeCodeConfig contains invalid values.
func buildArgs(cfg pipeline.AgentRunConfig) ([]string, error) {
if cfg.MaxTurns < 0 {
return nil, fmt.Errorf("negative max_turns requires the native backend (-1 means unlimited)")
}
args := []string{
"--print",
"--verbose",
Expand Down
2 changes: 1 addition & 1 deletion pipeline/handlers/backend_native.go
Original file line number Diff line number Diff line change
Expand Up @@ -258,7 +258,7 @@ func applyRunConfigOverrides(base agent.SessionConfig, cfg pipeline.AgentRunConf
if cfg.Provider != "" {
base.Provider = cfg.Provider
}
if cfg.MaxTurns > 0 {
if cfg.MaxTurns != 0 {
base.MaxTurns = cfg.MaxTurns
}
if cfg.SystemPrompt != "" {
Expand Down
19 changes: 4 additions & 15 deletions pipeline/handlers/codergen.go
Original file line number Diff line number Diff line change
Expand Up @@ -284,6 +284,9 @@ func (h *CodergenHandler) ensureACPBackend() (pipeline.AgentBackend, error) {
// and placed in Extra instead.
func (h *CodergenHandler) buildRunConfig(node *pipeline.Node, prompt string, backend pipeline.AgentBackend, pctx *pipeline.PipelineContext) (pipeline.AgentRunConfig, error) {
sessionCfg := h.buildConfig(node)
if _, native := backend.(*NativeBackend); !native && sessionCfg.MaxTurns < 0 {
return pipeline.AgentRunConfig{}, fmt.Errorf("negative max_turns requires the native backend (-1 means unlimited)")
}

cfg := pipeline.AgentRunConfig{
Prompt: prompt,
Expand Down Expand Up @@ -614,20 +617,6 @@ const maxTurnsOverrideSubdir = ".tracker/turn_overrides"
// bumps (≤170). #318.
const maxTurnsOverrideCeiling = 1000

// resolveMaxTurns returns the warm-continue MaxTurns override for nodeID under
// workingDir when one is present, else base. A warm continue only ever RAISES
// the budget, so an override that does not exceed base (stale/smaller, or left
// by a different workflow that reused the node ID) is ignored, as is one past
// the ceiling (corruption). Overrides are scoped per working dir + node ID.
// Keeps the branch out of buildConfig (already a long flat attr sequence). #318.
func resolveMaxTurns(workingDir, nodeID string, base int) int {
override := readMaxTurnsOverride(workingDir, nodeID)
if override <= base || override > maxTurnsOverrideCeiling {
return base
}
return override
}

// safeNodeFilename reports whether nodeID is usable as a single path element —
// a bare filename with no separators or parent refs. dippin IDs are identifiers,
// but readMaxTurnsOverride is a general working-dir file read, so it fails closed
Expand Down Expand Up @@ -833,7 +822,7 @@ func applyModelIdentity(config *agent.SessionConfig, cfg pipeline.AgentNodeConfi
if cfg.SystemPrompt != "" {
config.SystemPrompt = cfg.SystemPrompt
}
if cfg.MaxTurns > 0 {
if cfg.MaxTurns != 0 {
config.MaxTurns = cfg.MaxTurns
}
// #304: per-node cost ceiling and no-progress detector.
Expand Down
20 changes: 20 additions & 0 deletions pipeline/handlers/codergen_turns.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// ABOUTME: Resolves the native model-turn policy for warm continuation.
// ABOUTME: Keeps unlimited and invalid negative policies intact through disk overrides.
package handlers

// resolveMaxTurns returns the warm-continue MaxTurns override for nodeID under
// workingDir when one is present, else base. A warm continue only ever RAISES
// the budget, so an override that does not exceed base (stale/smaller, or left
// by a different workflow that reused the node ID) is ignored, as is one past
// the ceiling (corruption). Overrides are scoped per working dir + node ID.
// Keeps the branch out of buildConfig (already a long flat attr sequence). #318.
func resolveMaxTurns(workingDir, nodeID string, base int) int {
if base < 0 {
return base // Never cap unlimited turns or mask an invalid negative policy.
}
override := readMaxTurnsOverride(workingDir, nodeID)
if override <= base || override > maxTurnsOverrideCeiling {
return base
}
return override
}
Loading