From 9f0f8e65e50e8d05fa64a43c4d8d69b1c020601b Mon Sep 17 00:00:00 2001 From: zeropoint95 Date: Tue, 1 Dec 2026 13:07:45 -0500 Subject: [PATCH] exec: codeaf exec leaves its turn trace untracked in the person's repository (.codeaf/trace) Assisted-by: CodeAF Co-Authored-By: CodeAF <267109073+agentfield-bot@users.noreply.github.com> --- cmd/codeaf/chatv3_clientdoor_test.go | 41 +++++++++ cmd/codeaf/chatv3_subharness.go | 12 +++ cmd/codeaf/exec.go | 11 +++ cmd/codeaf/exec_smoke_test.go | 83 +++++++++++++++++++ cmd/codeaf/layout_test.go | 50 ++++++++++- cmd/codeaf/run.go | 5 +- cmd/codeaf/scratch.go | 29 +++++++ cmd/codeaf/subharness_run.go | 12 +++ cmd/codeaf/subharness_run_test.go | 34 ++++++++ docs/HEADLESS.md | 11 +-- .../1758-exec-scratch-out-of-workspace.md | 8 ++ 11 files changed, 284 insertions(+), 12 deletions(-) create mode 100644 cmd/codeaf/scratch.go create mode 100644 docs/changes/unreleased/1758-exec-scratch-out-of-workspace.md diff --git a/cmd/codeaf/chatv3_clientdoor_test.go b/cmd/codeaf/chatv3_clientdoor_test.go index 3783ed16a4..7c99962bf6 100644 --- a/cmd/codeaf/chatv3_clientdoor_test.go +++ b/cmd/codeaf/chatv3_clientdoor_test.go @@ -6,6 +6,9 @@ import ( "io" "net/http" "net/http/httptest" + "os" + "path/filepath" + "strings" "sync" "testing" @@ -247,3 +250,41 @@ func TestAConversationOpenedAfterFirstRunGetsTheLiveDefaultKey(t *testing.T) { t.Fatalf("later conversation inherited stale account: scalar=%q source=%q", launch.Config.APIKey, launch.Config.Sources.Default().Key) } } + +// #1758 ON THE CONVERSATION SURFACE, end to end: a program launched from a +// conversation runs through the same leaf plumbing as exec — the registry's +// runner is a fronted linear, and a linear opens its turn recorder through the +// workspace's scratch path on every run. This surface used to build that +// workspace without moving scratch, so a launch in a person's repository left +// `.codeaf/trace/` untracked in it — the identical omission the issue names, +// on the last production door. It is wired through scratchRootFor in the same +// change as the headless doors, and pinned the same way: a real run in a fresh +// repository leaves `git status --porcelain` empty. +func TestAConversationSubharnessRunLeavesTheRepositoryClean(t *testing.T) { + workspace := gitWorkspaceOn(t, "work-branch") + t.Setenv("HOME", t.TempDir()) + t.Setenv("CODEAF_HOME", t.TempDir()) + server := fakeOpenRouter(t) + wiring := v3Subharnesses(config.Config{APIKey: "smoke-test-key", BaseURL: server.URL}, nil, "test/model", 0, workspace, nil) + if wiring.Registry == nil { + t.Fatal("the subharness registry was not built") + } + runner, err := wiring.Registry.Subharness(exec.LinearSubharness) + if err != nil { + t.Fatalf("resolve the linear subharness: %v", err) + } + input, _ := json.Marshal(exec.TaskInput{Brief: "reply with ok"}) + if _, err := runner.Run(context.Background(), input, nil); err != nil { + t.Fatalf("run subharness: %v", err) + } + out, err := gitIn(workspace, "status", "--porcelain") + if err != nil { + t.Fatalf("git status: %v\n%s", err, out) + } + if strings.TrimSpace(out) != "" { + t.Fatalf("the run left untracked machinery in the repository:\n%s", out) + } + if _, err := os.Stat(filepath.Join(workspace, ".codeaf")); !os.IsNotExist(err) { + t.Fatal(".codeaf exists inside the person's repository") + } +} diff --git a/cmd/codeaf/chatv3_subharness.go b/cmd/codeaf/chatv3_subharness.go index 05e1c54596..097e23e2c0 100644 --- a/cmd/codeaf/chatv3_subharness.go +++ b/cmd/codeaf/chatv3_subharness.go @@ -73,6 +73,18 @@ func v3Subharnesses(settings config.Config, models *catalog.Catalog, model strin if err != nil { return off } + // THE RUNNER'S MACHINERY GOES TO THE STATE ROOT, NOT THE WORKSPACE. The + // registry's runners are leaves (a fronted linear), and a leaf opens its + // turn recorder through the workspace's scratch path on every run. Without + // this, a program launched from a conversation in a person's repository + // would leave `.codeaf/trace/` untracked in it — the #1758 defect, on this + // surface. Same helper the headless doors reach it through; same silent-off + // posture as every other failure this assembly answers. + scratchRoot, err := scratchRootFor(space.Root()) + if err != nil { + return off + } + space = space.WithScratch(scratchRoot) // The client is built the way every other client on this path is // (chatv3_harness.go, and internal/session's own agent.go): a plain adapter // rather than [config.Config.Client]'s router. The router keeps a ledger that diff --git a/cmd/codeaf/exec.go b/cmd/codeaf/exec.go index b3151c12dc..109a69c818 100644 --- a/cmd/codeaf/exec.go +++ b/cmd/codeaf/exec.go @@ -158,6 +158,17 @@ func runExec(args []string) error { if err != nil { return err } + // THE RUN'S OWN MACHINERY DOES NOT GO INTO THE DIRECTORY THE WORKER WORKS + // IN. `-w` may name a person's repository, and the machinery — the turn + // recorder under `.codeaf/trace/`, job logs, `.obs/` spills — used to land + // there as untracked files that `git add -A` published. It goes to codeaf's + // state root instead, keyed by the workspace's base name, exactly as the + // plan run door sends it (scratchRootFor). + scratchRoot, err := scratchRootFor(space.Root()) + if err != nil { + return err + } + space = space.WithScratch(scratchRoot) // AN EXEC RUN'S COMMANDS ARE FENCED to its workspace (fence.go). The seat // replaces the host seat the context was opened with. fence, err := unattendedFence(space.Root(), settings.ProfileDir) diff --git a/cmd/codeaf/exec_smoke_test.go b/cmd/codeaf/exec_smoke_test.go index 210afb5281..bde88befa2 100644 --- a/cmd/codeaf/exec_smoke_test.go +++ b/cmd/codeaf/exec_smoke_test.go @@ -323,3 +323,86 @@ func TestExecBinaryNamesItsKeptBranchAndVerdict(t *testing.T) { t.Fatalf("kept_branch = %v, want work-branch\n%s", got, fields) } } + +// fakeOpenRouterWritingOneFile answers the first completion with a `write` +// tool call and every completion after it with the finished answer, so an +// exec run leaves exactly one file in the workspace. +func fakeOpenRouterWritingOneFile(t *testing.T) *httptest.Server { + t.Helper() + answer, err := json.Marshal(smokeAnswer) + if err != nil { + t.Fatal(err) + } + first := `{"model":"test/model","choices":[{"index":0,"finish_reason":"tool_calls","message":{"role":"assistant","content":"",` + + `"tool_calls":[{"id":"call-1","type":"function","function":{"name":"write","arguments":"{\"path\":\"note.txt\",\"text\":\"the note\"}"}}]}}],` + + `"usage":{"prompt_tokens":10,"completion_tokens":4,"total_tokens":14}}` + finish := `{"model":"test/model","choices":[{"index":0,"finish_reason":"stop",` + + `"message":{"role":"assistant","content":` + string(answer) + `}}],` + + `"usage":{"prompt_tokens":10,"completion_tokens":4,"total_tokens":14}}` + calls := 0 + server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + writer.Header().Set("Content-Type", "application/json") + if strings.Contains(request.URL.Path, "/models") { + _, _ = writer.Write([]byte(`{"data":[]}`)) + return + } + calls++ + if calls == 1 { + _, _ = writer.Write([]byte(first)) + return + } + _, _ = writer.Write([]byte(finish)) + })) + t.Cleanup(server.Close) + return server +} + +// #1758 reproduced end to end: an `exec` in a person's repository leaves no +// untracked machinery behind, because the run's own files — the turn recorder +// under `.codeaf/trace/`, job logs, `.obs/` spills — go to codeaf's state root +// instead of the directory the worker worked in. +func TestExecBinaryLeavesTheRepositoryClean(t *testing.T) { + binary := buildCodeafStamped(t, "v0.0.0-smoke") + server := fakeOpenRouter(t) + env, _ := smokeEnv(t, server.URL) + workspace := gitWorkspaceOn(t, "work-branch") + + stdout, stderr, code := runSmoke(t, binary, env, "say hello\n", + "exec", "--json", "-w", workspace, "--turns", "3", "--budget", "20000", "--timeout", "120") + if code != 0 { + t.Fatalf("exit %d, want 0\nstdout:\n%s\nstderr:\n%s", code, stdout, stderr) + } + out, err := gitIn(workspace, "status", "--porcelain") + if err != nil { + t.Fatalf("git status: %v\n%s", err, out) + } + if strings.TrimSpace(out) != "" { + t.Fatalf("the run left untracked machinery in the repository:\n%s", out) + } + if _, err := os.Stat(filepath.Join(workspace, ".codeaf")); !os.IsNotExist(err) { + t.Fatal(".codeaf exists inside the person's repository") + } +} + +// The same check when the run actually produces work: `git status` shows the +// deliverable and nothing else — the harness's own machinery must not stand +// beside it. +func TestExecBinaryLeavesOnlyTheOneFileTheRunWrote(t *testing.T) { + binary := buildCodeafStamped(t, "v0.0.0-smoke") + server := fakeOpenRouterWritingOneFile(t) + env, _ := smokeEnv(t, server.URL) + workspace := gitWorkspaceOn(t, "work-branch") + + stdout, stderr, code := runSmoke(t, binary, env, "write note.txt\n", + "exec", "--json", "-w", workspace, "--turns", "3", "--budget", "20000", "--timeout", "120") + if code != 0 { + t.Fatalf("exit %d, want 0\nstdout:\n%s\nstderr:\n%s", code, stdout, stderr) + } + out, err := gitIn(workspace, "status", "--porcelain") + if err != nil { + t.Fatalf("git status: %v\n%s", err, out) + } + if strings.TrimSpace(out) != "?? note.txt" { + t.Fatalf("git status shows:\n%s\nwant exactly the one file the run wrote", out) + } +} diff --git a/cmd/codeaf/layout_test.go b/cmd/codeaf/layout_test.go index 41e68de3b6..754aa225e2 100644 --- a/cmd/codeaf/layout_test.go +++ b/cmd/codeaf/layout_test.go @@ -39,16 +39,58 @@ func TestBothSurfacesSendTheirMachineryOutOfTheLeafsDirectory(t *testing.T) { // The headless surface: the workspace may be a person's repository, so the // machinery goes to codeaf's own state root rather than to a sibling of it. - headless := home.Join("scratch", "codeaf-abc123") - if !within(state, headless) { - t.Fatalf("the headless scratch home %s is outside codeaf's state root %s", headless, state) - } + // Both run doors reach it through scratchRootFor, so the claim is tested + // against the production function rather than a second spelling of its path. + stateRoot := home.Dir() repository := filepath.Join(t.TempDir(), "someones-project") + headless, err := scratchRootFor(repository) + if err != nil { + t.Fatal(err) + } + if !within(stateRoot, headless) { + t.Fatalf("the headless scratch home %s is outside codeaf's state root %s", headless, stateRoot) + } if within(repository, headless) { t.Fatalf("the headless surface put its machinery inside the person's workspace %s", repository) } } +// scratchRootFor keys the scratch home by the workspace's base name and not by +// its full path: a resumed run of the same workspace appends to the recorders +// the first attempt wrote, wherever the checkout moved. +func TestScratchRootForKeysTheScratchByWorkspaceName(t *testing.T) { + state := t.TempDir() + t.Setenv(home.EnvVar, state) + + first, err := scratchRootFor(filepath.Join(t.TempDir(), "someones-project")) + if err != nil { + t.Fatal(err) + } + // The claim is about the STATE ROOT as the process actually resolves it. + // A test binary may quarantine even a root a test chose (internal/home + // refuses an inherited root), so home.Dir is the honest spelling. + if !within(home.Dir(), first) { + t.Fatalf("the scratch home %s is outside the state root %s", first, home.Dir()) + } + if _, statErr := os.Stat(first); statErr != nil { + t.Fatalf("scratchRootFor did not create its home: %v", statErr) + } + + // A second project of the SAME name gets the SAME home. + again, err := scratchRootFor(filepath.Join(t.TempDir(), "someones-project")) + if err != nil || again != first { + t.Fatalf("a same-named project got a different scratch home: %q vs %q (err %v)", again, first, err) + } + // A project of ANOTHER name is kept apart. + other, err := scratchRootFor(filepath.Join(t.TempDir(), "another-project")) + if err != nil { + t.Fatal(err) + } + if other == first { + t.Fatalf("projects of different names share one scratch home %q", first) + } +} + // The surface's own note to a node — that an older graph named a worker this // build does not have — has to land in the same file the recorder is about to // open, and the recorder is in the scratch home now. It has been out of step with the recorder diff --git a/cmd/codeaf/run.go b/cmd/codeaf/run.go index a203f98504..ba12cdaa91 100644 --- a/cmd/codeaf/run.go +++ b/cmd/codeaf/run.go @@ -17,7 +17,6 @@ import ( "github.com/Agent-Field/codeaf/internal/config" "github.com/Agent-Field/codeaf/internal/env" "github.com/Agent-Field/codeaf/internal/exec" - "github.com/Agent-Field/codeaf/internal/home" "github.com/Agent-Field/codeaf/internal/plan" "github.com/Agent-Field/codeaf/internal/profile" "github.com/Agent-Field/codeaf/internal/resident" @@ -250,8 +249,8 @@ func runGraph(name string, args []string) error { // cwd" by putting a directory next to their project would have moved the mess // rather than removed it. One home per workspace name, so a resumed run // appends to the recorders it already wrote. - scratchRoot := home.Join("scratch", filepath.Base(space.Root())) - if err := os.MkdirAll(scratchRoot, 0o700); err != nil { + scratchRoot, err := scratchRootFor(space.Root()) + if err != nil { return err } space = space.WithScratch(scratchRoot) diff --git a/cmd/codeaf/scratch.go b/cmd/codeaf/scratch.go new file mode 100644 index 0000000000..9766e391cd --- /dev/null +++ b/cmd/codeaf/scratch.go @@ -0,0 +1,29 @@ +package main + +import ( + "os" + "path/filepath" + + "github.com/Agent-Field/codeaf/internal/home" +) + +// scratchRootFor is where one workspace's harness machinery lives: the +// turn-by-turn recorder, job logs, `.obs` spills — everything that is not the +// work. It goes under codeaf's own state root, keyed by the workspace's base +// name, never inside or beside the directory the worker was told to work in. +// +// Every headless door that runs a leaf reaches it through this one function, +// because the doors have drifted apart once already: the `plan run` door (run.go) +// wired it and the standalone `exec` door (exec.go) did not, so exec left its +// whole machinery — `.codeaf/trace/` and the rest — as untracked files in the +// person's repository, where `git add -A` published them. The headless +// subharness door (subharness_run.go) is wired through it for the same reason. +// One home per workspace name keeps a resumed run appending to the recorders +// it wrote. +func scratchRootFor(workspaceRoot string) (string, error) { + root := home.Join("scratch", filepath.Base(workspaceRoot)) + if err := os.MkdirAll(root, 0o700); err != nil { + return "", err + } + return root, nil +} diff --git a/cmd/codeaf/subharness_run.go b/cmd/codeaf/subharness_run.go index 5640b8dce5..4be703aecb 100644 --- a/cmd/codeaf/subharness_run.go +++ b/cmd/codeaf/subharness_run.go @@ -146,6 +146,18 @@ func runSubharnessCommand(args []string) error { if err != nil { return err } + // THE RUN'S OWN MACHINERY GOES WHERE EVERY HEADLESS DOOR SENDS IT. `--dir` + // may name a person's repository, and this door used to drop the leaf's + // turn recorder underneath `.codeaf/trace/` inside it, untracked. The + // bundle store a repository carries (its own `.codeaf/subharnesses/`) is + // intentionally tracked material and is not affected: only the harness's + // own files move, exactly as the exec and plan run doors send them + // (scratchRootFor). + scratchRoot, err := scratchRootFor(space.Root()) + if err != nil { + return err + } + space = space.WithScratch(scratchRoot) web := exec.NewWeb() // The toolbox is opened HERE, above the registry, rather than beside the env // below: it is what a bundle's tool guard is checked against, and the guards diff --git a/cmd/codeaf/subharness_run_test.go b/cmd/codeaf/subharness_run_test.go index 85f5b26481..7f28dad982 100644 --- a/cmd/codeaf/subharness_run_test.go +++ b/cmd/codeaf/subharness_run_test.go @@ -14,6 +14,7 @@ import ( "io" "os" "path/filepath" + "strings" "testing" "time" @@ -176,6 +177,39 @@ func TestAHeadlessRunLeavesNoPendingJudgeRecordWhenThePoolCannotRead(t *testing. } } +// #1758 ON THE SECOND DOOR THAT SHARED THE DEFECT, end to end: `codeaf run` +// executes its leaves through the same recorder plumbing as exec — the +// generalist is a linear leaf, and that leaf's turn recorder used to open +// through the workspace's scratch path, which this door never moved, so a run +// pointed at a person's repository left its machinery under `.codeaf/trace/` +// there, untracked. The door was wired through scratchRootFor in the same +// change as exec, and it is pinned the same way a real `codeaf run linear` in a +// fresh repository leaves `git status --porcelain` empty. The generalist is +// the road to exercise: it is the leaf whose recorder this defect was about, a +// bundle that ran its own script would not open it. +func TestRunDoorLeavesTheRepositoryClean(t *testing.T) { + binary := buildCodeafStamped(t, "v0.0.0-smoke") + server := fakeOpenRouter(t) + env, _ := smokeEnv(t, server.URL) + workspace := gitWorkspaceOn(t, "work-branch") + + stdout, stderr, code := runSmoke(t, binary, env, `{"brief":"reply with ok"}`, + "run", "linear", "--input", "-", "-w", workspace, "--json") + if code != 0 { + t.Fatalf("exit %d, want 0\nstdout:\n%s\nstderr:\n%s", code, stdout, stderr) + } + out, err := gitIn(workspace, "status", "--porcelain") + if err != nil { + t.Fatalf("git status: %v\n%s", err, out) + } + if strings.TrimSpace(out) != "" { + t.Fatalf("the run left untracked machinery in the repository:\n%s", out) + } + if _, err := os.Stat(filepath.Join(workspace, ".codeaf")); !os.IsNotExist(err) { + t.Fatal(".codeaf exists inside the person's repository") + } +} + // A NON-VERIFIED RUN-DOOR RUN NAMES WHERE ITS WORK IS STANDING AND THE WORD // THAT LEFT IT THERE, on the same terms #1182 gave `do` and #1184 gave the chat // tasks text. The run door edits the directory it was pointed at in place and diff --git a/docs/HEADLESS.md b/docs/HEADLESS.md index 5cb2e1a1cb..61cca54962 100644 --- a/docs/HEADLESS.md +++ b/docs/HEADLESS.md @@ -428,7 +428,7 @@ harness passes anything with newlines in it. | Flag | Default | Meaning | | --- | --- | --- | -| `--dir dir` | `.` | The directory the worker works in, created if missing. Also where its scratch lands — see below. `-w` is the shorthand and keeps working forever. | +| `--dir dir` | `.` | The directory the worker works in, created if missing. The run's own scratch does **not** land here — see below — so a repository pointed at with `--dir` stays clean. `-w` is the shorthand and keeps working forever. | | `--system text` | empty | The working method, passed as the task's contract. | | `--max-turns N` | `200` | Runaway backstop on agent iterations. Hitting it exits `3`. | | `--token-budget N` | `220000` | Token budget for the whole run. Crossing it buys a bounded landing rather than a kill, so the effective ceiling is the budget, plus a fifth of it for the landing, plus the overshoot of the turn crossing the budget and of the final landing turn. Hitting it exits `3`. | @@ -585,10 +585,11 @@ again. to one. - **No delivery gate and no replan.** Nothing judges the answer, and nothing notices the work was bigger than one worker. -- **Scratch lands in `--dir`.** `exec` gives the worker no separate scratch - directory, so the harness's own machinery — `.codeaf/`, `.obs/` — is written - into the workspace beside the work product. Point `--dir` at a directory you - are willing to have written into, not at a repository you want left clean. +- **The run's own machinery never touches `--dir`.** The turn recorder, job + logs and `.obs` spills that `exec` keeps are written under codeaf's state + root, in `~/.codeaf/scratch/` (moved whole by `CODEAF_HOME`), + so a repository you point `--dir` at stays clean: `git status` shows only + what the worker itself wrote. `exec` still reads the state root for two things: the model catalog cache and, if you have one there, a persisted API key. `CODEAF_HOME` moves both. diff --git a/docs/changes/unreleased/1758-exec-scratch-out-of-workspace.md b/docs/changes/unreleased/1758-exec-scratch-out-of-workspace.md new file mode 100644 index 0000000000..185511c67f --- /dev/null +++ b/docs/changes/unreleased/1758-exec-scratch-out-of-workspace.md @@ -0,0 +1,8 @@ +--- +kind: fixed +title: codeaf exec keeps its own machinery out of the repository it works in +pr: 1758 +surface: [engine, docs] +invalidates: + - "The manual said exec's scratch (`.codeaf/` and `.obs/`) lands in `--dir`. It now lives under codeaf's state root in `~/.codeaf/scratch/`, for `exec`, for `codeaf run subharness`, and for a program launched from a conversation, so a run leaves the repository it works in showing only what the worker changed." +---