oficina / equipo Public

Mac slice F task 16: M9b to M9e, M9h, M9i on the fake Mac worker

TestMacWorker gains the rest of slice F's single-version scenarios on
the fake Mac worker: a fix round from the worker's checks output that
resumes the kept session, a refused push and Retry republishing the
same commit (M9b); a rebase round on the pinned worker (M9c); a SIGKILL
mid-Engineering that stays unproven until the person clears the
incomplete record, then Retry on the same worker (M9e); asking the
implementer on the worker, refused for another attempt or session and
offline (M9d); a secret in the candidate (M9h); a step that runs out of
time, unfinished through publication (M9i).

The fake is now one setup: its report composed with what the Mac's
guards and records say (credential_unproven, record_incomplete, the
claude tag only when ready), and its gate's proofs made by the Mac's
executor over its turns, as a Mac's checks gate's are. The fake CLI
gains stepwait and afterwait; the worker process takes a MaxStep.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 8f99c3334c183948eb6437ec026703a73486d2a2 parent bae4df7
7 files changed, +529 −15
  • internal/fakeclaude/fake.go +24 −1
  • internal/headless/env_test.go +6 −2
  • internal/headless/mac_test.go +443 −2
  • internal/headless/merge_test.go +6 −5
  • internal/runner/thin/fakeworker.go +4 −3
  • internal/runner/thin/fakeworker_testbuild.go +44 −0
  • internal/runner/thin/run.go +2 −2
diff --git a/internal/fakeclaude/fake.go b/internal/fakeclaude/fake.go
index db16ef4c..9e0fb1ae 100644
--- a/internal/fakeclaude/fake.go
+++ b/internal/fakeclaude/fake.go
@@ -67,7 +67,10 @@
// and, if allowed, copies its bytes to /workspace/<path> (asking for
// Write); "rowrite:<absolute path>" writes there directly, asking
// nobody, and says whether the filesystem refused (with its errno);
-// "stepsleep:<ms>" pauses before editing; "bytes:<path>|<base64>"
+// "stepsleep:<ms>" pauses before editing, "stepwait:<absolute path>"
+// waits before editing while that file exists, and "afterwait:<absolute
+// path>" waits the same way after editing, before the reply (at most ten
+// minutes each); "bytes:<path>|<base64>"
// asks for Write and writes the decoded bytes (a binary file);
// "symlink:<path>|<target>" asks for Write and makes a symbolic link;
// "say:<text>" (to ";" or the line's end) adds the text to the reply;
@@ -577,6 +580,22 @@ var symlinkWord = regexp.MustCompile(`symlink:([^|\s]+)\|([^;\s]+)`)
var sayWord = regexp.MustCompile(`say:([^;\n]*)`)
var moveWord = regexp.MustCompile(`move:([^|\s]+)\|([^;\s]+)`)
var limitLeave = regexp.MustCompile(`limitleave:([^;\s]+)`)
+var stepWait = regexp.MustCompile(`stepwait:(/[^;\s]+)`)
+var afterWait = regexp.MustCompile(`afterwait:(/[^;\s]+)`)
+
+// holdWhile waits, at most ten minutes, while the file the prompt's word
+// names exists: a test decides when the step goes on.
+func holdWhile(word *regexp.Regexp, prompt string) {
+ m := word.FindStringSubmatch(prompt)
+ if m == nil {
+ return
+ }
+ for deadline := time.Now().Add(10 * time.Minute); time.Now().Before(deadline); time.Sleep(50 * time.Millisecond) {
+ if _, err := os.Lstat(m[1]); err != nil {
+ return
+ }
+ }
+}
// workspaceRoot is the workspace the model's paths name: /workspace in
// Linux's namespace; on a darwin launch (CLAUDE_CODE_PROJECT_DIR_NAME
@@ -606,6 +625,7 @@ func (f *fake) engineer(prompt string, turn int, emit func(any)) string {
ms, _ := strconv.Atoi(m[1])
time.Sleep(time.Duration(ms) * time.Millisecond)
}
+ holdWhile(stepWait, prompt)
var done []string
ask := func(i int, tool string, input map[string]any) bool {
id := fmt.Sprintf("toolu_fake_%d_e%d", turn, i)
@@ -754,6 +774,9 @@ func (f *fake) engineer(prompt string, turn int, emit func(any)) string {
for _, m := range sayWord.FindAllStringSubmatch(prompt, -1) {
done = append(done, strings.TrimSpace(m[1]))
}
+ // The work is in the tree; hold before replying (a step that runs out
+ // of time with its work done so far).
+ holdWhile(afterWait, prompt)
headline := ""
if strings.Contains(prompt, "Headline: ") {
// The step prompt asks for a headline line first.
diff --git a/internal/headless/env_test.go b/internal/headless/env_test.go
index ffa7d942..5c465758 100644
--- a/internal/headless/env_test.go
+++ b/internal/headless/env_test.go
@@ -530,6 +530,10 @@ type processConfig struct {
CodexDigest, CodexHostDigest, AccountsRoot string
NoMoveIn bool
Idle, LockWait, MaxTurn, Margin time.Duration
+ // MaxStep bounds an Engineering step (thin.Options.MaxStep; 0 is the
+ // default). The fake Mac worker's is a minute, so a step runs out of
+ // time within a scenario.
+ MaxStep time.Duration
// Forge is the local forge's state, so a runner process works on the
// same bare repositories as an in-process one.
Forge *localForgeState
@@ -545,7 +549,7 @@ func runnerProcess(path string) int {
cfg := runner.Config{MachineLabel: p.MachineLabel, Origin: p.Origin, InstanceID: p.InstanceID, StateDir: p.StateDir, AccountBindingsPath: p.AccountBindingsPath, AmadanCredentialPath: p.AmadanCredentialPath, ClaudePath: p.ClaudePath, CodexPath: p.CodexPath, CodexCodeModeHostPath: p.CodexCodeModeHostPath, BwrapPath: p.BwrapPath, GoRoot: p.GoRoot, ModuleCache: p.ModuleCache, GoBinary: p.GoBinary, WorkspaceRoot: p.WorkspaceRoot, ScratchRoot: p.ScratchRoot, GitPath: p.GitPath, AmadanPath: p.AmadanPath, ToolProxyPath: p.ToolProxy, Executable: self}
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, os.Interrupt)
defer stop()
- opts := thin.Options{Version: "test", Logger: slog.New(slog.NewTextHandler(os.Stderr, nil)), NoMoveIn: p.NoMoveIn, MergeEvery: time.Second, FakePlatform: p.FakePlatform, FakeBin: p.FakeBin, FakeSandbox: p.FakeSandbox}
+ opts := thin.Options{Version: "test", Logger: slog.New(slog.NewTextHandler(os.Stderr, nil)), NoMoveIn: p.NoMoveIn, MergeEvery: time.Second, FakePlatform: p.FakePlatform, FakeBin: p.FakeBin, FakeSandbox: p.FakeSandbox, MaxStep: p.MaxStep}
if p.Forge != nil {
opts.Forge = p.Forge.forge()
}
@@ -575,7 +579,7 @@ func (r *localRunner) startProcess(t *testing.T) {
if lf, ok := r.opts.Forge.(*localForge); ok {
fs = lf.state()
}
- raw, _ := json.Marshal(processConfig{Forge: fs, Origin: c.Origin, InstanceID: c.InstanceID, StateDir: c.StateDir, AccountBindingsPath: c.AccountBindingsPath, AmadanCredentialPath: c.AmadanCredentialPath, ClaudePath: c.ClaudePath, CodexPath: c.CodexPath, CodexCodeModeHostPath: c.CodexCodeModeHostPath, BwrapPath: c.BwrapPath, GoRoot: c.GoRoot, ModuleCache: c.ModuleCache, GoBinary: c.GoBinary, WorkspaceRoot: c.WorkspaceRoot, ScratchRoot: c.ScratchRoot, GitPath: c.GitPath, AmadanPath: c.AmadanPath, ToolProxy: c.ToolProxyPath, Digest: o.Digest, MoveInNote: o.MoveInNote, CodexDigest: r.opts.Codex.Digest, CodexHostDigest: r.opts.Codex.HostDigest, MachineLabel: c.MachineLabel, FakePlatform: r.opts.FakePlatform, FakeBin: r.opts.FakeBin, FakeSandbox: r.opts.FakeSandbox, AccountsRoot: r.opts.AccountsRoot, NoMoveIn: r.opts.NoMoveIn, Idle: o.Idle, LockWait: o.LockWait, MaxTurn: o.MaxTurn, Margin: o.Margin})
+ raw, _ := json.Marshal(processConfig{Forge: fs, Origin: c.Origin, InstanceID: c.InstanceID, StateDir: c.StateDir, AccountBindingsPath: c.AccountBindingsPath, AmadanCredentialPath: c.AmadanCredentialPath, ClaudePath: c.ClaudePath, CodexPath: c.CodexPath, CodexCodeModeHostPath: c.CodexCodeModeHostPath, BwrapPath: c.BwrapPath, GoRoot: c.GoRoot, ModuleCache: c.ModuleCache, GoBinary: c.GoBinary, WorkspaceRoot: c.WorkspaceRoot, ScratchRoot: c.ScratchRoot, GitPath: c.GitPath, AmadanPath: c.AmadanPath, ToolProxy: c.ToolProxyPath, Digest: o.Digest, MoveInNote: o.MoveInNote, CodexDigest: r.opts.Codex.Digest, CodexHostDigest: r.opts.Codex.HostDigest, MachineLabel: c.MachineLabel, FakePlatform: r.opts.FakePlatform, FakeBin: r.opts.FakeBin, FakeSandbox: r.opts.FakeSandbox, AccountsRoot: r.opts.AccountsRoot, NoMoveIn: r.opts.NoMoveIn, Idle: o.Idle, LockWait: o.LockWait, MaxTurn: o.MaxTurn, Margin: o.Margin, MaxStep: r.opts.MaxStep})
path := filepath.Join(r.root, "runner.json")
if err := os.WriteFile(path, raw, 0600); err != nil {
t.Fatal(err)
diff --git a/internal/headless/mac_test.go b/internal/headless/mac_test.go
index d7952500..41ba52ff 100644
--- a/internal/headless/mac_test.go
+++ b/internal/headless/mac_test.go
@@ -4,13 +4,17 @@ package headless
import (
"context"
+ "database/sql"
+ "encoding/base64"
"encoding/json"
+ "fmt"
"io"
"log/slog"
"net/http"
"net/url"
"os"
"path/filepath"
+ "slices"
"strings"
"testing"
"time"
@@ -99,7 +103,7 @@ func macWorker(t *testing.T, inst *thintest.Instance, primary *localRunner) (*lo
cfg.StateDir, cfg.WorkspaceRoot, cfg.ScratchRoot, cfg.MachineLabel = state, filepath.Join(root, "work"), filepath.Join(root, "scratch"), "Tito Studio"
cfg.AccountBindingsPath = filepath.Join(config, "bindings.json")
writeJSON(t, cfg.AccountBindingsPath, []map[string]any{})
- w := &localRunner{inst: inst, root: root, cfg: cfg, subprocess: true, runnerID: cred.RunnerID, opts: thin.Options{Version: "test", Logger: slog.New(slog.NewTextHandler(io.Discard, nil)), FakePlatform: "darwin/arm64", FakeBin: bin, FakeSandbox: wire.SandboxSeatbelt, Claude: primary.opts.Claude, AccountsRoot: private(t, filepath.Join(root, "accounts"))}}
+ w := &localRunner{inst: inst, root: root, cfg: cfg, subprocess: true, runnerID: cred.RunnerID, opts: thin.Options{Version: "test", Logger: slog.New(slog.NewTextHandler(io.Discard, nil)), FakePlatform: "darwin/arm64", FakeBin: bin, FakeSandbox: wire.SandboxSeatbelt, Claude: primary.opts.Claude, AccountsRoot: private(t, filepath.Join(root, "accounts")), MaxStep: time.Minute}}
w.addToken(t, macClaude, "mac@example.com")
t.Cleanup(func() {
w.stop(t)
@@ -113,6 +117,81 @@ func macWorker(t *testing.T, inst *thintest.Instance, primary *localRunner) (*lo
return w, filepath.Join(bin, "xcodebuild")
}
+// refusePushes makes the local forge refuse every push to bare until
+// refuse(false), as a hub that is down would.
+func refusePushes(t *testing.T, bare string) (refuse func(bool)) {
+ t.Helper()
+ flag := filepath.Join(bare, "refuse-pushes")
+ hook := filepath.Join(bare, "hooks", "pre-receive")
+ if err := os.MkdirAll(filepath.Dir(hook), 0700); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(hook, []byte("#!/bin/sh\n[ -e '"+flag+"' ] && { echo refused >&2; exit 1; }\nexit 0\n"), 0700); err != nil {
+ t.Fatal(err)
+ }
+ refuse = func(on bool) {
+ if !on {
+ os.Remove(flag)
+ return
+ }
+ if err := os.WriteFile(flag, nil, 0600); err != nil {
+ t.Fatal(err)
+ }
+ }
+ refuse(true)
+ t.Cleanup(func() { refuse(false) })
+ return refuse
+}
+
+// macAskPin is the Engineering attempt and session the instance froze on
+// a question, and the session the worker kept for that attempt.
+func macAskPin(t *testing.T, inst *thintest.Instance, worker *localRunner, question string) (attempt int64, session, kept string) {
+ t.Helper()
+ var step string
+ if err := inst.DB.Writer().QueryRow("SELECT step_id, coalesce(eng_attempt, 0), coalesce(eng_session, '') FROM chat_questions WHERE id = ?", question).Scan(&step, &attempt, &session); err != nil {
+ t.Fatal(err)
+ }
+ d, err := sql.Open("sqlite", "file:"+filepath.Join(worker.cfg.StateDir, "thin.db")+"?mode=ro&_pragma=busy_timeout(5000)")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer d.Close()
+ _ = d.QueryRow("SELECT session_id FROM kept_sessions WHERE step_id=? AND attempt=?", step, attempt).Scan(&kept)
+ return attempt, session, kept
+}
+
+// engineeringProcs are the live processes of a Mac Engineering launch:
+// the darwin launch marks them EQUIPO_ATTEMPT=engineering-<key>.
+func engineeringProcs() []string {
+ var out []string
+ entries, _ := os.ReadDir("/proc")
+ for _, p := range entries {
+ raw, err := os.ReadFile(filepath.Join("/proc", p.Name(), "environ"))
+ if err != nil || !strings.Contains(string(raw), "EQUIPO_ATTEMPT=engineering-") {
+ continue
+ }
+ if stat, err := os.ReadFile(filepath.Join("/proc", p.Name(), "stat")); err == nil && !strings.Contains(string(stat), ") Z ") {
+ out = append(out, p.Name())
+ }
+ }
+ return out
+}
+
+// macCaps is the capability report of runner's newest hello, as the
+// instance keeps it (what the Machines page reads).
+func macCaps(t *testing.T, inst *thintest.Instance, runner string) wire.Capabilities {
+ t.Helper()
+ var raw string
+ if err := inst.DB.Writer().QueryRow("SELECT hello FROM runner_sessions WHERE runner_id = ?", runner).Scan(&raw); err != nil {
+ t.Fatal(err)
+ }
+ var h wire.Hello
+ if err := json.Unmarshal([]byte(raw), &h); err != nil || h.Capabilities == nil {
+ t.Fatalf("hello %s: %v", raw, err)
+ }
+ return *h.Capabilities
+}
+
// macClaude is the fake Mac's own Claude token connection.
const macClaude = "mac-claude"
@@ -149,6 +228,15 @@ func (s *session) changeDiff(t *testing.T, id, sha, path string) wire.ChangeDiff
return out
}
+// stepKinds is a task's steps in one line, for a failure message.
+func stepKinds(k wire.Task) string {
+ var out []string
+ for _, st := range k.Steps {
+ out = append(out, fmt.Sprintf("%s[r%d a%d %s %s %s rebase=%v pushed=%v pub=%s on=%s]", st.Specialist, st.Round, st.Attempt, st.State, firstOf(st.Checks, st.Verdict), st.Reason, st.Rebase, st.Pushed, st.Publication, st.RunnerLabel))
+ }
+ return strings.Join(out, " ")
+}
+
func stepOf(k wire.Task, specialist string, n int) wire.Step {
for _, s := range k.Steps {
if s.Specialist == specialist {
@@ -186,7 +274,8 @@ func (s *session) mergeWorkerPass(t *testing.T, id string, timeout time.Duration
t.Fatalf("missing trusted-base evidence not recorded: %+v", k.MergeDecision)
}
for _, step := range k.Steps {
- if step.Specialist == wire.SpecialistMerge {
+ // A merge of an earlier candidate (one that conflicted) is history.
+ if step.Specialist == wire.SpecialistMerge && step.CandidateSHA == k.CandidateSHA {
t.Fatal("merge dispatched before the person's decision")
}
}
@@ -460,4 +549,356 @@ func TestMacWorker(t *testing.T) {
t.Fatalf("merge %+v", k)
}
})
+
+ // M9b: the new pane's test fails on the worker; the fix round works
+ // from that output on the worker, resuming the session that made the
+ // candidate (in a new worktree: each attempt checks out its own). The
+ // first publication's push fails (the forge refuses it), and Retry
+ // publishes the same commit again without running Engineering.
+ var paneTask string
+ t.Run("M9b", func(t *testing.T) {
+ bare := env.ForgePath(panes)
+ refuse := refusePushes(t, bare)
+ before := macDispatches(t, inst, worker.runnerID)
+ sent := s.send(t, "tool:record_task:woodstar/panes|Pane back gesture|Add the back gesture to the panes.\ntool:start_task:$task|create:Woodstar/Pane.swift|let paneBack = false")
+ id := s.taskOf(t, sent.Turn.ID)
+ paneTask = id
+ s.wait(t, "the publication refused", 3*time.Minute, func(c *thintest.Conversation) bool {
+ e := stepOf(c.Tasks[id], wire.SpecialistEngineering, 0)
+ return e.Publication == wire.PublicationFailed || e.State == wire.StepFailed || e.Pushed
+ })
+ k, err := env.Client.Task(s.ctx, id)
+ if err != nil {
+ t.Fatal(err)
+ }
+ first := stepOf(k, wire.SpecialistEngineering, 0)
+ if first.Publication != wire.PublicationFailed || first.Pushed || first.CandidateSHA == "" || first.RunnerID != worker.runnerID || forgeHead(t, bare, k.Branch) != "" {
+ t.Fatalf("refused publication %+v", first)
+ }
+ refuse(false)
+ if acc, err := env.Client.RetryTask(s.ctx, id); err != nil || acc.Attempt != 1 {
+ t.Fatalf("retry the publication: %+v %v", acc, err)
+ }
+ s.wait(t, "published again", 2*time.Minute, func(c *thintest.Conversation) bool {
+ return stepOf(c.Tasks[id], wire.SpecialistEngineering, 0).Pushed
+ })
+ k = s.settled(t, id, 4*time.Minute)
+ again := stepOf(k, wire.SpecialistEngineering, 0)
+ if again.ID != first.ID || again.Attempt != 1 || again.CandidateSHA != first.CandidateSHA || forgeShow(t, bare, "-s", "--format=%H", again.CandidateSHA) != first.CandidateSHA+"\n" {
+ t.Fatalf("republished %+v, first %+v", again, first)
+ }
+ failed, fix, passed := stepOf(k, wire.SpecialistChecks, 0), stepOf(k, wire.SpecialistEngineering, 1), stepOf(k, wire.SpecialistChecks, 1)
+ if failed.Checks != wire.ChecksFailed || failed.RunnerID != worker.runnerID || failed.CandidateSHA != first.CandidateSHA {
+ t.Fatalf("checks of the first candidate %+v", failed)
+ }
+ if fix.Round != 1 || fix.RunnerID != worker.runnerID || fix.BaseSHA != first.CandidateSHA || !fix.Pushed || !strings.Contains(fix.Summary, "(resumed session)") || fix.Account != macClaude {
+ t.Fatalf("fix round %+v", fix)
+ }
+ if passed.Checks != wire.ChecksPassed || passed.CandidateSHA != fix.CandidateSHA || k.Stage != wire.StageReadyToMerge || k.CandidateSHA != fix.CandidateSHA {
+ t.Fatalf("after the fix round %+v / %+v", passed, k)
+ }
+ // Engineering went to the worker twice: the first round and the
+ // fix round. Retry of the publication sent it nothing.
+ if n := macDispatches(t, inst, worker.runnerID) - before; n != 2 {
+ t.Fatalf("%d Engineering dispatches to the worker, want 2", n)
+ }
+ })
+
+ // M9c: main moves under the ready task with a conflicting change, so
+ // the person's Merge conflicts; the rebase round runs on the worker
+ // (pinned), resolves the conflict, and its candidate is checked on
+ // the worker and reviewed on the primary again.
+ t.Run("M9c", func(t *testing.T) {
+ if paneTask == "" {
+ t.Skip("needs M9b's task")
+ }
+ id, bare := paneTask, env.ForgePath(panes)
+ work := t.TempDir()
+ gitRun(t, work, "clone", "-q", bare, "w")
+ if err := os.WriteFile(filepath.Join(work, "w", "Woodstar", "Pane.swift"), []byte("let paneBack = true // from main\n"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ gitRun(t, work+"/w", "add", "-A")
+ gitRun(t, work+"/w", "commit", "-q", "-m", "main moves")
+ gitRun(t, work+"/w", "push", "-q", "origin", "main")
+ moved := forgeHead(t, bare, "main")
+ card := s.mergeCard(t, id)
+ if _, err := env.Client.Answer(s.ctx, card.ID, wire.ChoiceMerge, card.Revision); err != nil {
+ t.Fatal(err)
+ }
+ defer func() {
+ if t.Failed() {
+ k, _ := env.Client.Task(context.Background(), id)
+ t.Logf("task %s %s needs %q: %s", k.Stage, k.CandidateSHA, k.NeedsYou, stepKinds(k))
+ }
+ }()
+ // The rebase keeps the task's side of its first commit (the pane's
+ // test failing), so its checks fail on the worker and a fix round
+ // there mends it: ready to merge once review approves that.
+ s.wait(t, "the rebase round judged", 3*time.Minute, func(c *thintest.Conversation) bool {
+ k := c.Tasks[id]
+ rebased := false
+ for _, st := range k.Steps {
+ rebased = rebased || st.Rebase && st.Pushed
+ if st.Rebase && st.State == wire.StepFailed {
+ return true
+ }
+ }
+ last := k.Steps[len(k.Steps)-1]
+ return rebased && k.Stage == wire.StageReadyToMerge && last.Specialist == wire.SpecialistReview && last.CandidateSHA == k.CandidateSHA || k.Stage == wire.StageDone || k.Stage == wire.StageCancelled
+ })
+ k := s.mergeWorkerPass(t, id, 4*time.Minute)
+ var rebase wire.Step
+ for _, st := range k.Steps {
+ if st.Rebase {
+ rebase = st
+ }
+ if st.Specialist == wire.SpecialistEngineering && st.RunnerID != worker.runnerID {
+ t.Fatalf("Engineering off the pinned worker: %s", stepKinds(k))
+ }
+ }
+ if !rebase.Rebase || rebase.RunnerID != worker.runnerID || rebase.BaseSHA != moved || !rebase.Pushed || k.BaseSHA != moved {
+ t.Fatalf("rebase round %+v (task base %s, main %s)", rebase, k.BaseSHA, moved)
+ }
+ if parent := strings.TrimSpace(forgeShow(t, bare, "-s", "--format=%P", rebase.CandidateSHA)); parent != moved {
+ t.Fatalf("rebased candidate's parent %s, want %s", parent, moved)
+ }
+ if src := forgeShow(t, bare, "main:Woodstar/Pane.swift"); strings.Contains(src, "<<<<<<<") {
+ t.Fatalf("main after the rebase: %s", src)
+ }
+ })
+
+ // M9e: the worker is SIGKILLed while the CLI works. On restart the
+ // worker ends what the launch left, but the turn's record never got
+ // its final note, so (task 9's ruling) the attempt is never proven
+ // over: no Retry, and the Mac says why (record_incomplete; its Claude
+ // connection is closed, credential_unproven). The person's decision
+ // clears the record (today: removing the owed file, then a restart);
+ // then the end is proven by process group, and Retry runs Engineering
+ // again on the same worker, to done.
+ var killedTask string
+ t.Run("M9e", func(t *testing.T) {
+ hold := filepath.Join(t.TempDir(), "hold")
+ if err := os.WriteFile(hold, nil, 0600); err != nil {
+ t.Fatal(err)
+ }
+ sent := s.send(t, "tool:record_task:woodstar/panes|Killed mid Engineering|Name the app in About.\ntool:start_task:$task|stepwait:"+hold+" edit:Woodstar/About.swift|An iOS reading app|An iOS reading app with panes\nedit:Woodstar/Swipe.swift|edgeSwipe = false|edgeSwipe = true")
+ id := s.taskOf(t, sent.Turn.ID)
+ killedTask = id
+ s.wait(t, "Engineering running on the worker", 3*time.Minute, func(c *thintest.Conversation) bool {
+ e := stepOf(c.Tasks[id], wire.SpecialistEngineering, 0)
+ return e.RunnerID == worker.runnerID && e.State == wire.StepRunning && e.StartedAt != nil
+ })
+ // The CLI is in its turn: its process carries the attempt's marker.
+ for deadline := time.Now().Add(time.Minute); len(engineeringProcs()) == 0; time.Sleep(50 * time.Millisecond) {
+ if time.Now().After(deadline) {
+ t.Fatal("the CLI never started on the worker")
+ }
+ }
+ worker.kill(t)
+ if _, err := env.Client.RetryTask(s.ctx, id); thintest.Status(err) != 409 {
+ t.Fatalf("retry before the worker proved the end: %v", err)
+ }
+ if err := os.Remove(hold); err != nil {
+ t.Fatal(err)
+ }
+ worker.start(t)
+ s.wait(t, "the restart's word on the killed attempt", 2*time.Minute, func(c *thintest.Conversation) bool {
+ return stepOf(c.Tasks[id], wire.SpecialistEngineering, 0).State == wire.StepFailed
+ })
+ k, err := env.Client.Task(s.ctx, id)
+ if err != nil {
+ t.Fatal(err)
+ }
+ e := stepOf(k, wire.SpecialistEngineering, 0)
+ if e.Reason != "runner_restarted" || e.Terminated || e.RunnerID != worker.runnerID {
+ t.Fatalf("killed mid-turn, proven over: %+v", e)
+ }
+ if left := engineeringProcs(); len(left) > 0 {
+ t.Fatalf("processes %v of the killed attempt survived the restart", left)
+ }
+ if _, err := env.Client.RetryTask(s.ctx, id); thintest.Status(err) != 409 {
+ t.Fatalf("retry of an attempt never proven over: %v", err)
+ }
+ if caps := macCaps(t, inst, worker.runnerID); caps.Unproven != wire.UnprovenCredential || caps.Engineering == nil || caps.Engineering.State == wire.EngineeringReady || slices.Contains(caps.Tags, wire.TagClaude) {
+ t.Fatalf("the Mac's report after the kill: unproven %q, engineering %+v, tags %v", caps.Unproven, caps.Engineering, caps.Tags)
+ }
+ // The person's decision.
+ worker.stop(t)
+ if err := os.Remove(filepath.Join(worker.cfg.StateDir, "mac-gate.lock.owed")); err != nil {
+ t.Fatal(err)
+ }
+ worker.start(t)
+ s.wait(t, "the end proven", 2*time.Minute, func(c *thintest.Conversation) bool {
+ return stepOf(c.Tasks[id], wire.SpecialistEngineering, 0).Terminated
+ })
+ if k, err = env.Client.Task(s.ctx, id); err != nil {
+ t.Fatal(err)
+ }
+ if e = stepOf(k, wire.SpecialistEngineering, 0); e.State != wire.StepFailed || e.Reason != "runner_restarted" || e.TerminationKind != wire.TerminationProcessGroup || k.NeedsYou != wire.NeedsRetry {
+ t.Fatalf("after the record was cleared %+v (needs %q)", e, k.NeedsYou)
+ }
+ s.wait(t, "the Mac ready again", time.Minute, func(*thintest.Conversation) bool {
+ caps := macCaps(t, inst, worker.runnerID)
+ return caps.Unproven == "" && caps.Engineering != nil && caps.Engineering.State == wire.EngineeringReady
+ })
+ before := macDispatches(t, inst, worker.runnerID)
+ if _, err := env.Client.RetryTask(s.ctx, id); err != nil {
+ t.Fatal(err)
+ }
+ s.wait(t, "the second attempt judged", 3*time.Minute, func(c *thintest.Conversation) bool {
+ k := c.Tasks[id]
+ e := stepOf(k, wire.SpecialistEngineering, 0)
+ last := k.Steps[len(k.Steps)-1]
+ return e.Attempt == 2 && e.State == wire.StepFailed || e.Attempt == 2 && e.Pushed && k.Stage == wire.StageReadyToMerge && last.Specialist == wire.SpecialistReview && last.CandidateSHA == k.CandidateSHA
+ })
+ if k, err = env.Client.Task(s.ctx, id); err != nil {
+ t.Fatal(err)
+ }
+ e = stepOf(k, wire.SpecialistEngineering, 0)
+ if e.Attempt != 2 || e.State != wire.StepDone || !e.Pushed || e.RunnerID != worker.runnerID || k.Stage != wire.StageReadyToMerge || macDispatches(t, inst, worker.runnerID) != before+1 {
+ t.Fatalf("Engineering after Retry %+v (task %s: %s)", e, k.Stage, stepKinds(k))
+ }
+ })
+
+ // M9d: the person asks Engineering about its work on the killed and
+ // retried task: the worker answers from the session its second
+ // attempt kept, on that commit. A question pinned to the first
+ // attempt (which kept nothing: it was killed) or to a session the
+ // worker did not keep is refused; with the worker stopped, Ask says
+ // it is offline and queues nothing.
+ t.Run("M9d", func(t *testing.T) {
+ if killedTask == "" {
+ t.Skip("needs M9e's task")
+ }
+ id := killedTask
+ k, err := env.Client.Task(s.ctx, id)
+ if err != nil {
+ t.Fatal(err)
+ }
+ eng := stepOf(k, wire.SpecialistEngineering, 0)
+ if !eng.Askable {
+ t.Fatalf("Engineering kept no session: %+v", eng)
+ }
+ q, _ := s.asked(t, id, "What did you change and why? ask:git ask:read:Woodstar/About.swift", wire.SpecialistEngineering, time.Minute)
+ if q.State != wire.QuestionAnswered || q.StepID != eng.ID || !strings.HasPrefix(q.Answer, "From my session:") || !strings.Contains(q.Answer, "The change: +") || !strings.Contains(q.Answer, "with panes") {
+ t.Fatalf("answer from the worker %+v", q)
+ }
+ if attempt, session, kept := macAskPin(t, inst, worker, q.ID); attempt != 2 || session == "" || session != kept {
+ t.Fatalf("pinned to attempt %d session %q; the worker kept %q", attempt, session, kept)
+ }
+ // The instance names what it asks about; the worker answers only
+ // for what it kept (the pins are forged on the instance's step).
+ forge := func(column string, value any) func() {
+ db := inst.DB.Writer()
+ var old any
+ if err := db.QueryRow("SELECT "+column+" FROM chat_steps WHERE id = ?", eng.ID).Scan(&old); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := db.Exec("UPDATE chat_steps SET "+column+" = ? WHERE id = ?", value, eng.ID); err != nil {
+ t.Fatal(err)
+ }
+ return func() {
+ if _, err := db.Exec("UPDATE chat_steps SET "+column+" = ? WHERE id = ?", old, eng.ID); err != nil {
+ t.Fatal(err)
+ }
+ }
+ }
+ restore := forge("attempt", 1)
+ gone, _ := s.asked(t, id, "And the first time?", wire.SpecialistEngineering, time.Minute)
+ restore()
+ if gone.State != wire.QuestionFailed || gone.Reason != "session_gone" {
+ t.Fatalf("asked about the killed attempt: %+v", gone)
+ }
+ restore = forge("session_id", "00000000-0000-4000-8000-0000000000ff")
+ other, _ := s.asked(t, id, "And in another session?", wire.SpecialistEngineering, time.Minute)
+ restore()
+ if other.State != wire.QuestionFailed || other.Reason != "policy_rejected" {
+ t.Fatalf("asked about a session the worker did not keep: %+v", other)
+ }
+ worker.stop(t)
+ s.wait(t, "the worker offline", 30*time.Second, func(c *thintest.Conversation) bool {
+ for _, r := range c.Runners {
+ if r.ID == worker.runnerID {
+ return !r.Online
+ }
+ }
+ return false
+ })
+ var n int
+ inst.DB.Writer().QueryRow("SELECT count(*) FROM chat_questions WHERE task_id = ?", id).Scan(&n)
+ if _, err := env.Client.Ask(s.ctx, id, "Still there?", wire.SpecialistEngineering, key()); thintest.Status(err) != 409 || !strings.Contains(err.Error(), "runner_offline") {
+ t.Fatalf("ask while the worker is offline: %v", err)
+ }
+ var after int
+ inst.DB.Writer().QueryRow("SELECT count(*) FROM chat_questions WHERE task_id = ?", id).Scan(&after)
+ if after != n {
+ t.Fatalf("an offline ask queued a question (%d, then %d)", n, after)
+ }
+ worker.start(t)
+ if _, err := env.Client.CancelTask(s.ctx, id); err != nil {
+ t.Fatal(err)
+ }
+ })
+
+ // M9h: the change holds a secret (a GitHub token in a new file, by
+ // bytes the prompt does not show): the worker's scan refuses it
+ // before anything leaves, so nothing is uploaded or pushed.
+ t.Run("M9h", func(t *testing.T) {
+ secret := base64.StdEncoding.EncodeToString([]byte("let token = \"ghs_" + strings.Repeat("k7Qm", 9) + "\"\n"))
+ sent := s.send(t, "tool:record_task:woodstar/panes|Add the sync token|Sync the panes.\ntool:start_task:$task|bytes:Woodstar/Sync.swift|"+secret)
+ id := s.taskOf(t, sent.Turn.ID)
+ k := s.settled(t, id, 3*time.Minute)
+ e := stepOf(k, wire.SpecialistEngineering, 0)
+ if e.State != wire.StepFailed || e.Reason != wire.ReasonSecretInCandidate || e.Pushed || e.CandidateSHA != "" || e.RunnerID != worker.runnerID || e.Askable {
+ t.Fatalf("secret in the candidate %+v", e)
+ }
+ if head := forgeHead(t, env.ForgePath(panes), k.Branch); head != "" {
+ t.Fatalf("pushed %s", head)
+ }
+ for _, st := range k.Steps {
+ if st.Specialist != wire.SpecialistEngineering {
+ t.Fatalf("a step after the refusal: %s", stepKinds(k))
+ }
+ }
+ if _, err := env.Client.CancelTask(s.ctx, id); err != nil {
+ t.Fatal(err)
+ }
+ })
+
+ // M9i: the step runs out of time on the worker (its limit is a
+ // minute) with its change made: the worker commits it as unfinished
+ // work, the primary publishes it, and it is never shown as finished
+ // work (step_timeout through publication; Review is told).
+ t.Run("M9i", func(t *testing.T) {
+ hold := filepath.Join(t.TempDir(), "hold")
+ if err := os.WriteFile(hold, nil, 0600); err != nil {
+ t.Fatal(err)
+ }
+ sent := s.send(t, "tool:record_task:woodstar/panes|Slow pane titles|Title each pane.\ntool:start_task:$task|edit:Woodstar/About.swift|An iOS reading app|An iOS reading app with titled panes afterwait:"+hold)
+ id := s.taskOf(t, sent.Turn.ID)
+ s.wait(t, "the unfinished work published", 3*time.Minute, func(c *thintest.Conversation) bool {
+ e := stepOf(c.Tasks[id], wire.SpecialistEngineering, 0)
+ return e.Pushed || e.State == wire.StepFailed || e.State == wire.StepCancelled
+ })
+ k, err := env.Client.Task(s.ctx, id)
+ if err != nil {
+ t.Fatal(err)
+ }
+ e := stepOf(k, wire.SpecialistEngineering, 0)
+ if e.State != wire.StepDone || !e.Pushed || e.Reason != "step_timeout" || e.RunnerID != worker.runnerID || e.Publication != wire.PublicationPublished {
+ t.Fatalf("unfinished work %+v", e)
+ }
+ if msg := forgeShow(t, env.ForgePath(panes), "-s", "--format=%B", e.CandidateSHA); !strings.Contains(msg, "ran out of time before it finished") {
+ t.Fatalf("commit message %q", msg)
+ }
+ k = s.settled(t, id, 3*time.Minute)
+ if e := stepOf(k, wire.SpecialistEngineering, 0); e.Reason != "step_timeout" || k.Stage == wire.StageDone || k.Merged != nil {
+ t.Fatalf("shown as finished %+v / %s", e, stepKinds(k))
+ }
+ if _, err := env.Client.CancelTask(s.ctx, id); err != nil {
+ t.Fatal(err)
+ }
+ })
+
}
diff --git a/internal/headless/merge_test.go b/internal/headless/merge_test.go
index 3cde52d0..a7f041e9 100644
--- a/internal/headless/merge_test.go
+++ b/internal/headless/merge_test.go
@@ -59,18 +59,19 @@ func (s *session) mergedLine(t *testing.T, id, want string) {
})
}
-// mergeCard waits for the task's merge card.
+// mergeCard waits for the task's merge card: its open one when it has
+// one (a merge that conflicted leaves its answered card behind).
func (s *session) mergeCard(t *testing.T, id string) wire.Card {
t.Helper()
var card wire.Card
s.wait(t, "merge card", 5*time.Minute, func(c *thintest.Conversation) bool {
+ found := false
for _, k := range c.Cards {
- if k.Kind == wire.CardMerge && k.TaskID == id {
- card = k
- return true
+ if k.Kind == wire.CardMerge && k.TaskID == id && (!found || k.State == wire.CardOpen) {
+ card, found = k, true
}
}
- return false
+ return found
})
return card
}
diff --git a/internal/runner/thin/fakeworker.go b/internal/runner/thin/fakeworker.go
index cdb17519..93e38ecf 100644
--- a/internal/runner/thin/fakeworker.go
+++ b/internal/runner/thin/fakeworker.go
@@ -16,9 +16,10 @@ type fakeMac interface {
// sandbox is sandbox (seatbelt: probe P2 denied).
probe(sandbox string) func(context.Context) wire.Capabilities
gate(bin, sandbox string) GateRunner
- // engineering is the fake Mac's credential operations and its
- // Engineering pieces (Mac runners slice F, task 16).
- engineering(ctx context.Context, c *runner.Config, o Options) (*macCreds, *WorkerEngineering, error)
+ // setup is the whole fake Mac worker for c and o: its report and
+ // gate, its credential operations and its Engineering pieces (Mac
+ // runners slice F, task 16). It may change c as a Mac's would be.
+ setup(ctx context.Context, c *runner.Config, o Options) (workerSetup, error)
}
var fake fakeMac
diff --git a/internal/runner/thin/fakeworker_testbuild.go b/internal/runner/thin/fakeworker_testbuild.go
index 28c4c177..ec2d8d60 100644
--- a/internal/runner/thin/fakeworker_testbuild.go
+++ b/internal/runner/thin/fakeworker_testbuild.go
@@ -11,6 +11,7 @@ import (
"os"
"os/exec"
"path/filepath"
+ "slices"
"strings"
"amadan.net/oficina/equipo/internal/runner"
@@ -103,6 +104,49 @@ const fakeCLIScript = "#!/bin/sh\nexec '%s' \"$@\"\n"
// XcodeExec does).
const fakeUserTemp = mac.UserTempPrefix + "/eq/fake-worker/T"
+// setup is the fake Mac worker: the fixture report, composed as a Mac
+// composes its own with what its guards and records say now; the gate,
+// whose proofs go through the Mac's turns as a Mac's checks gate's do
+// (its checks run without a turn, as before); and the Mac's credential
+// operations and Engineering pieces (engineering).
+func (f fakeWorker) setup(ctx context.Context, c *runner.Config, o Options) (workerSetup, error) {
+ m, eng, err := f.engineering(ctx, c, o)
+ if err != nil {
+ return workerSetup{}, err
+ }
+ fixture := f.probe(o.FakeSandbox)
+ probe := func(ctx context.Context) wire.Capabilities {
+ caps := fixture(ctx)
+ if left, err := m.keychain.Unproven(); err != nil || len(left) > 0 {
+ caps.Unproven = wire.UnprovenCredential
+ } else if m.turns.Incomplete() {
+ caps.Unproven = wire.UnprovenRecordIncomplete
+ }
+ // The guards first, then a credential launch whose end is not
+ // proven (task 14's order); else the fixture's ready.
+ status := m.status()
+ if status == nil && caps.Unproven == wire.UnprovenCredential {
+ status = &wire.EngineeringStatus{State: wire.EngineeringNoConnection, Reason: wire.UnprovenCredential}
+ }
+ if status != nil {
+ caps.Engineering = status
+ caps.Tags = slices.DeleteFunc(caps.Tags, func(t string) bool { return t == wire.TagClaude })
+ }
+ return caps
+ }
+ return workerSetup{probe: probe, gate: fakeGate{GateRunner: f.gate(o.FakeBin, o.FakeSandbox), exec: m.exec}, creds: m, engineering: eng}, nil
+}
+
+// fakeGate is the fake's gate, its proofs made by the Mac's executor
+// over its turns: an attempt killed mid-turn has an incomplete record,
+// so it is never proven over (task 9's ruling), as on a Mac.
+type fakeGate struct {
+ GateRunner
+ exec *mac.Executor
+}
+
+func (g fakeGate) Verify(id string) bool { return g.exec.Verify(id) }
+
// engineering is the fake Mac's credential operations and Engineering
// pieces. Its home is the directory above its state dir (the runner
// user's home on a Mac); the stand-in is provisioned into the install
diff --git a/internal/runner/thin/run.go b/internal/runner/thin/run.go
index de78d17b..8f45bf25 100644
--- a/internal/runner/thin/run.go
+++ b/internal/runner/thin/run.go
@@ -154,11 +154,11 @@ func Run(ctx context.Context, c runner.Config, o Options) error {
if o.Logger != nil {
o.Logger.Warn("test build: the fake Mac worker runs checks in a process group without a sandbox", "build", fake.marker())
}
- m, eng, err := fake.engineering(ctx, &c, o)
+ w, err := fake.setup(ctx, &c, o)
if err != nil {
return err
}
- return runWorker(ctx, c, o, platform, workerSetup{probe: fake.probe(o.FakeSandbox), gate: fake.gate(o.FakeBin, o.FakeSandbox), creds: m, engineering: eng})
+ return runWorker(ctx, c, o, platform, w)
}
if runtime.GOOS == "darwin" {
return runMac(ctx, c, o)