From 986ebfe25ed1b06f3da243160ae47c1349216a25 Mon Sep 17 00:00:00 2001 From: Harper Reed Date: Sun, 8 Nov 2026 15:18:45 -0600 Subject: [PATCH] feat: support unlimited native agent turns Preserve explicit -1 through native execution while retaining existing guards and finite defaults. Isolate Git fixtures so normal commit hooks cannot write into the caller repository. --- agent/checkpoint.go | 3 + agent/config.go | 7 +- agent/session_loop.go | 2 +- agent/session_unlimited_test.go | 154 +++++++++++++++++++ docs/architecture/adapter.md | 2 +- docs/architecture/backends.md | 28 ++++ gotchas.md | 8 + pipeline/dippin_adapter.go | 2 +- pipeline/handlers/backend_acp.go | 12 +- pipeline/handlers/backend_acp_config.go | 29 ++++ pipeline/handlers/backend_claudecode.go | 3 + pipeline/handlers/backend_native.go | 2 +- pipeline/handlers/codergen.go | 19 +-- pipeline/handlers/codergen_turns.go | 20 +++ pipeline/handlers/codergen_unlimited_test.go | 153 ++++++++++++++++++ pipeline/node_config.go | 4 +- tracker_doctor_test.go | 1 + tracker_first_win_test.go | 2 + tracker_git_fixture_test.go | 72 +++++++++ tracker_git_preflight_integration_test.go | 17 +- 20 files changed, 498 insertions(+), 42 deletions(-) create mode 100644 agent/session_unlimited_test.go create mode 100644 pipeline/handlers/backend_acp_config.go create mode 100644 pipeline/handlers/codergen_turns.go create mode 100644 pipeline/handlers/codergen_unlimited_test.go create mode 100644 tracker_git_fixture_test.go diff --git a/agent/checkpoint.go b/agent/checkpoint.go index 02cbc339..35555a6e 100644 --- a/agent/checkpoint.go +++ b/agent/checkpoint.go @@ -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). diff --git a/agent/config.go b/agent/config.go index 0d8cf8cb..38ea7135 100644 --- a/agent/config.go +++ b/agent/config.go @@ -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 @@ -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 @@ -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) diff --git a/agent/session_loop.go b/agent/session_loop.go index 119d0a90..7ac2c40c 100644 --- a/agent/session_loop.go +++ b/agent/session_loop.go @@ -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) diff --git a/agent/session_unlimited_test.go b/agent/session_unlimited_test.go new file mode 100644 index 00000000..7a0a8e93 --- /dev/null +++ b/agent/session_unlimited_test.go @@ -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) + } + } + }) + } +} diff --git a/docs/architecture/adapter.md b/docs/architecture/adapter.md index fda7b401..2bc68fa0 100644 --- a/docs/architecture/adapter.md +++ b/docs/architecture/adapter.md @@ -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` | | diff --git a/docs/architecture/backends.md b/docs/architecture/backends.md index 85586631..ab2eb3be 100644 --- a/docs/architecture/backends.md +++ b/docs/architecture/backends.md @@ -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 | diff --git a/gotchas.md b/gotchas.md index c8d08492..c069a999 100644 --- a/gotchas.md +++ b/gotchas.md @@ -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. diff --git a/pipeline/dippin_adapter.go b/pipeline/dippin_adapter.go index 0652ba12..ff949bf7 100644 --- a/pipeline/dippin_adapter.go +++ b/pipeline/dippin_adapter.go @@ -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 { diff --git a/pipeline/handlers/backend_acp.go b/pipeline/handlers/backend_acp.go index ab6df4ba..ff39d76a 100644 --- a/pipeline/handlers/backend_acp.go +++ b/pipeline/handlers/backend_acp.go @@ -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) diff --git a/pipeline/handlers/backend_acp_config.go b/pipeline/handlers/backend_acp_config.go new file mode 100644 index 00000000..be653c73 --- /dev/null +++ b/pipeline/handlers/backend_acp_config.go @@ -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 +} diff --git a/pipeline/handlers/backend_claudecode.go b/pipeline/handlers/backend_claudecode.go index 6421141b..46225019 100644 --- a/pipeline/handlers/backend_claudecode.go +++ b/pipeline/handlers/backend_claudecode.go @@ -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", diff --git a/pipeline/handlers/backend_native.go b/pipeline/handlers/backend_native.go index 578d6149..9725efc5 100644 --- a/pipeline/handlers/backend_native.go +++ b/pipeline/handlers/backend_native.go @@ -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 != "" { diff --git a/pipeline/handlers/codergen.go b/pipeline/handlers/codergen.go index d202871e..a6dca30a 100644 --- a/pipeline/handlers/codergen.go +++ b/pipeline/handlers/codergen.go @@ -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, @@ -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 @@ -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. diff --git a/pipeline/handlers/codergen_turns.go b/pipeline/handlers/codergen_turns.go new file mode 100644 index 00000000..b337cd64 --- /dev/null +++ b/pipeline/handlers/codergen_turns.go @@ -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 +} diff --git a/pipeline/handlers/codergen_unlimited_test.go b/pipeline/handlers/codergen_unlimited_test.go new file mode 100644 index 00000000..8a10ccfa --- /dev/null +++ b/pipeline/handlers/codergen_unlimited_test.go @@ -0,0 +1,153 @@ +// ABOUTME: Tests unlimited turns through real Dippin parsing and native session construction. +// ABOUTME: Pins defaults, warm continuation, invalid negatives, and external-backend refusal. +package handlers + +import ( + "context" + "fmt" + "strings" + "testing" + "time" + + "github.com/2389-research/dippin-lang/ir" + "github.com/2389-research/dippin-lang/parser" + "github.com/2389-research/tracker/agent" + "github.com/2389-research/tracker/llm" + "github.com/2389-research/tracker/pipeline" +) + +func TestDippinNativeTurnPolicy(t *testing.T) { + for _, tc := range []struct { + field string + want int + valid bool + }{ + {"max_turns: -1", -1, true}, + {"max_turns: 7", 7, true}, + {"max_turns: 0", 80, true}, + {"", 80, true}, + {"max_turns: -2", -2, false}, + } { + t.Run(tc.field, func(t *testing.T) { + src := fmt.Sprintf(`workflow Turns + start: Work + exit: Work + agent Work + %s + prompt: Finish the task +`, tc.field) + wf, err := parser.NewParser(src, "turns.dip").Parse() + if err != nil { + t.Fatal(err) + } + if tc.want < 0 && wf.Nodes[0].Config.(ir.AgentConfig).MaxTurns != tc.want { + t.Fatal("parser dropped negative turn policy") + } + graph, err := pipeline.FromDippinIR(wf) + if err != nil { + t.Fatal(err) + } + node := graph.Nodes["Work"] + if tc.want < 0 && node.AgentConfig(nil).MaxTurns != tc.want { + t.Fatalf("node turn policy = %d, want %d", node.AgentConfig(nil).MaxTurns, tc.want) + } + h := NewCodergenHandler(nil, t.TempDir()) + backend := NewNativeBackend(nil, nil) + runCfg, err := h.buildRunConfig(node, "work", backend, pipeline.NewPipelineContext()) + if err != nil { + t.Fatal(err) + } + cfg := backend.buildSessionConfig(runCfg) + if cfg.MaxTurns != tc.want || runCfg.MaxTurns != tc.want { + t.Fatalf("run/session turns = %d/%d, want %d", runCfg.MaxTurns, cfg.MaxTurns, tc.want) + } + // Construct the real session; no model call is needed to validate the boundary. + if _, err := agent.NewSession(nil, cfg); (err == nil) != tc.valid { + t.Fatalf("session error=%v, want valid=%v", err, tc.valid) + } + }) + } +} + +func TestUnlimitedWarmContinueKeepsTurnPolicy(t *testing.T) { + workdir := t.TempDir() + writeTurnOverride(t, workdir, "Work", "130") + h := NewCodergenHandler(nil, workdir) + node := &pipeline.Node{ID: "Work", Attrs: map[string]string{"max_turns": "-1"}} + if got := h.buildConfig(node).MaxTurns; got != -1 { + t.Fatalf("unlimited warm continuation turns = %d, want -1", got) + } + if got := resolveMaxTurns(workdir, "Work", -2); got != -2 { + t.Fatalf("override masked invalid negative policy: %d", got) + } +} + +func TestNativeBackendDirectTurnPolicy(t *testing.T) { + for _, turns := range []int{-2, -1, 0, 4} { + cfg := NewNativeBackend(nil, nil).buildSessionConfig(pipeline.AgentRunConfig{MaxTurns: turns}) + want := turns + if turns == 0 { + want = agent.DefaultConfig().MaxTurns + } + if cfg.MaxTurns != want { + t.Errorf("direct MaxTurns=%d became %d, want %d", turns, cfg.MaxTurns, want) + } + } +} + +func TestExternalBackendsRejectUnlimitedTurns(t *testing.T) { + h := NewCodergenHandler(nil, t.TempDir()) + node := &pipeline.Node{ID: "Work", Attrs: map[string]string{"max_turns": "-1"}} + for _, backend := range []pipeline.AgentBackend{&ClaudeCodeBackend{}, &ACPBackend{}} { + _, err := h.buildRunConfig(node, "work", backend, pipeline.NewPipelineContext()) + if err == nil || !strings.Contains(err.Error(), "native") { + t.Errorf("backend %T config error=%v, want native-only refusal", backend, err) + } + } + if _, err := buildArgs(pipeline.AgentRunConfig{MaxTurns: -1}); err == nil { + t.Error("direct claude-code config silently dropped unlimited turns") + } + if _, err := (&ACPBackend{}).Run(context.Background(), pipeline.AgentRunConfig{MaxTurns: -1}, nil); err == nil || !strings.Contains(err.Error(), "native") { + t.Errorf("direct ACP config error=%v, want native-only refusal", err) + } +} + +func TestDippinUnlimitedNativeDeadlineIntegration(t *testing.T) { + src := `workflow Turns + start: Work + exit: Work + agent Work + backend: native + max_turns: -1 + prompt: Finish the task +` + wf, err := parser.NewParser(src, "turns.dip").Parse() + if err != nil { + t.Fatal(err) + } + graph, err := pipeline.FromDippinIR(wf) + if err != nil { + t.Fatal(err) + } + // A deadline that has already elapsed exercises real handler/backend/session + // execution without a provider request, fixture, or external service. + ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(-time.Second)) + defer cancel() + h := NewCodergenHandler(&llm.Client{}, t.TempDir()) + starts, ends := 0, 0 + h.eventHandler = agent.EventHandlerFunc(func(evt agent.Event) { + switch evt.Type { + case agent.EventSessionStart: + starts++ + case agent.EventSessionEnd: + ends++ + } + }) + outcome, err := h.Execute(ctx, graph.Nodes["Work"], pipeline.NewPipelineContext()) + if err != nil { + t.Fatal(err) + } + if starts != 1 || ends != 1 || outcome.ContextUpdates[pipeline.ContextKeyLastResponse] != context.DeadlineExceeded.Error() { + t.Fatalf("deadline outcome=%+v, session starts/ends=%d/%d", outcome, starts, ends) + } +} diff --git a/pipeline/node_config.go b/pipeline/node_config.go index 4ad616a6..fc7eeecd 100644 --- a/pipeline/node_config.go +++ b/pipeline/node_config.go @@ -234,10 +234,10 @@ func (n *Node) applyNoProgressNode(cfg *AgentNodeConfig) { } } -// applyMaxTurns resolves the node-only max_turns attr (positive only). +// applyMaxTurns resolves nonzero node-only max_turns; session validation checks negatives. func (n *Node) applyMaxTurns(cfg *AgentNodeConfig) { if v := n.Attrs["max_turns"]; v != "" { - if i, err := strconv.Atoi(v); err == nil && i > 0 { + if i, err := strconv.Atoi(v); err == nil && i != 0 { cfg.MaxTurns = i } } diff --git a/tracker_doctor_test.go b/tracker_doctor_test.go index a0028e54..8afc47b8 100644 --- a/tracker_doctor_test.go +++ b/tracker_doctor_test.go @@ -1123,6 +1123,7 @@ func gitInitWithEnvFile(t *testing.T, tracked bool) string { run := func(args ...string) { t.Helper() cmd := exec.Command("git", append([]string{"-C", dir, "-c", "user.name=t", "-c", "user.email=t@example.com"}, args...)...) + cmd.Env = cleanGitEnv() if out, err := cmd.CombinedOutput(); err != nil { t.Fatalf("git %v: %v\n%s", args, err, out) } diff --git a/tracker_first_win_test.go b/tracker_first_win_test.go index 9d884b2e..7b44eddc 100644 --- a/tracker_first_win_test.go +++ b/tracker_first_win_test.go @@ -38,6 +38,7 @@ func (g *approvingGate) answer(p string) (string, error) { } func TestFirstWin_QuickfixApproveCommitsToItsBranch(t *testing.T) { + isolateTestGit(t) gitPath, err := exec.LookPath("git") if err != nil { t.Skip("git not on PATH") @@ -65,6 +66,7 @@ func TestFirstWin_QuickfixApproveCommitsToItsBranch(t *testing.T) { t.Helper() cmd := exec.Command("git", args...) cmd.Dir = repo + cmd.Env = cleanGitEnv() out, err := cmd.CombinedOutput() if err != nil { t.Fatalf("git %v: %v\n%s", args, err, out) diff --git a/tracker_git_fixture_test.go b/tracker_git_fixture_test.go new file mode 100644 index 00000000..385d35d0 --- /dev/null +++ b/tracker_git_fixture_test.go @@ -0,0 +1,72 @@ +// ABOUTME: Runs Git fixture tests under the repository pointers exported by hooks. +// ABOUTME: Proves fixtures leave the caller's real Git history and index untouched. +package tracker + +import ( + "os" + "os/exec" + "path/filepath" + "strings" + "testing" +) + +// isolateTestGit also covers shell commands spawned through library workflows. +func isolateTestGit(t *testing.T) { + t.Helper() + for _, entry := range os.Environ() { + key, value, _ := strings.Cut(entry, "=") + if testGitRedirectVars[strings.ToUpper(key)] { + t.Setenv(key, value) // Register restoration before removing the variable. + if err := os.Unsetenv(key); err != nil { + t.Fatal(err) + } + } + } +} + +func TestGitFixturesIgnoreHookRepository(t *testing.T) { + requireGit(t) + outer := t.TempDir() + git := func(args ...string) string { + t.Helper() + prefix := []string{"-C", outer, "-c", "user.name=fixture", "-c", "user.email=fixture@example.com"} + cmd := exec.Command("git", append(prefix, args...)...) + cmd.Env = cleanGitEnv() + out, err := cmd.CombinedOutput() + if err != nil { + t.Fatalf("git %v: %v\n%s", args, err, out) + } + return strings.TrimSpace(string(out)) + } + git("init", "-q") + if err := os.WriteFile(filepath.Join(outer, "README.md"), []byte("caller repository\n"), 0600); err != nil { + t.Fatal(err) + } + git("add", "README.md") + git("commit", "-qm", "caller baseline") + head := git("rev-parse", "HEAD") + if err := os.WriteFile(filepath.Join(outer, "README.md"), []byte("caller staged work\n"), 0600); err != nil { + t.Fatal(err) + } + git("add", "README.md") + index, err := os.ReadFile(filepath.Join(outer, ".git", "index")) + if err != nil { + t.Fatal(err) + } + + cmd := exec.Command(os.Args[0], "-test.run=^(TestCheckWorkdirWarnsWhenEnvFileIsGitTracked|TestFirstWin_QuickfixApproveCommitsToItsBranch)$") + cmd.Env = append(cleanGitEnv(), "GIT_DIR="+filepath.Join(outer, ".git"), "GIT_WORK_TREE="+outer, "GIT_INDEX_FILE="+filepath.Join(outer, ".git", "index")) + if out, err := cmd.CombinedOutput(); err != nil { + t.Errorf("fixture subprocess failed under hook environment: %v\n%s", err, out) + } + if got := git("rev-parse", "HEAD"); got != head { + t.Errorf("fixture moved caller HEAD: %s -> %s", head, got) + } + after, err := os.ReadFile(filepath.Join(outer, ".git", "index")) + if err != nil { + t.Fatal(err) + } + if string(after) != string(index) { + t.Error("fixture modified caller index") + } +} diff --git a/tracker_git_preflight_integration_test.go b/tracker_git_preflight_integration_test.go index 6659200c..ebeeb5e0 100644 --- a/tracker_git_preflight_integration_test.go +++ b/tracker_git_preflight_integration_test.go @@ -25,6 +25,14 @@ func requireGit(t *testing.T) { } } +var testGitRedirectVars = map[string]bool{ + "GIT_DIR": true, + "GIT_INDEX_FILE": true, + "GIT_WORK_TREE": true, + "GIT_OBJECT_DIRECTORY": true, + "GIT_COMMON_DIR": true, +} + // cleanGitEnv returns os.Environ() with git-internal repository pointers // stripped. Tests in this package create throwaway git repos via `git init` // in t.TempDir(); git honors an inherited GIT_DIR/GIT_INDEX_FILE over a @@ -36,18 +44,11 @@ func requireGit(t *testing.T) { // added ToUpper so a mixed-case redirect var can't slip past on environments // that canonicalize env-var casing. func cleanGitEnv() []string { - stripped := map[string]bool{ - "GIT_DIR": true, - "GIT_INDEX_FILE": true, - "GIT_WORK_TREE": true, - "GIT_OBJECT_DIRECTORY": true, - "GIT_COMMON_DIR": true, - } src := os.Environ() out := make([]string, 0, len(src)) for _, e := range src { name := strings.ToUpper(strings.SplitN(e, "=", 2)[0]) - if !stripped[name] { + if !testGitRedirectVars[name] { out = append(out, e) } }