Skip to content
Open
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
41 changes: 41 additions & 0 deletions cmd/codeaf/chatv3_clientdoor_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ import (
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync"
"testing"

Expand Down Expand Up @@ -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")
}
}
12 changes: 12 additions & 0 deletions cmd/codeaf/chatv3_subharness.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
11 changes: 11 additions & 0 deletions cmd/codeaf/exec.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
83 changes: 83 additions & 0 deletions cmd/codeaf/exec_smoke_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
50 changes: 46 additions & 4 deletions cmd/codeaf/layout_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 2 additions & 3 deletions cmd/codeaf/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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)
Expand Down
29 changes: 29 additions & 0 deletions cmd/codeaf/scratch.go
Original file line number Diff line number Diff line change
@@ -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
}
12 changes: 12 additions & 0 deletions cmd/codeaf/subharness_run.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
34 changes: 34 additions & 0 deletions cmd/codeaf/subharness_run_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
"io"
"os"
"path/filepath"
"strings"
"testing"
"time"

Expand Down Expand Up @@ -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
Expand Down
11 changes: 6 additions & 5 deletions docs/HEADLESS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`. |
Expand Down Expand Up @@ -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/<workspace-name>` (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.
Expand Down
8 changes: 8 additions & 0 deletions docs/changes/unreleased/1758-exec-scratch-out-of-workspace.md
Original file line number Diff line number Diff line change
@@ -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/<workspace-name>`, 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."
---
Loading