//go:build testbuild
package headless
import (
"context"
"crypto/rand"
"database/sql"
"debug/elf"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"log/slog"
"net/http"
"net/url"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"syscall"
"testing"
"time"
"amadan.net/oficina/equipo/internal/equipo/chat"
"amadan.net/oficina/equipo/internal/runner/mac/proc"
"amadan.net/oficina/equipo/internal/runner/thin"
"amadan.net/oficina/equipo/internal/runnerproto"
"amadan.net/oficina/equipo/internal/thintest"
"amadan.net/oficina/equipo/internal/wire"
)
const woodstar, panes = "amadan.net/woodstar/woodstar", "amadan.net/woodstar/panes"
// addWoodstar adds an iOS app to the local forge: it has a shared scheme
// and edge swipe does nothing. Its gate runs scripts/test, which runs
// xcodebuild test, so its base does not say it needs a Mac: Engineering
// runs on the Linux primary and a change to its Swift files is checked on
// a Mac. Panes is the same app whose gate runs xcodebuild itself, so
// everything about it is Mac work (Engineering waits for a Mac that can
// make changes, 2026-11-28).
func addWoodstar(t *testing.T, root string, f *localForge) {
t.Helper()
xcode := "xcodebuild test -scheme Woodstar -destination 'platform=iOS Simulator,name=iPhone 16 Pro'\n"
seedIOS(t, root, f, woodstar, map[string]string{".amadan/ci": "#!/bin/sh\nset -e\nexec ./scripts/test\n", "scripts/test": "#!/bin/sh\nset -e\n" + xcode})
seedIOS(t, root, f, panes, map[string]string{".amadan/ci": "#!/bin/sh\nset -e\n" + xcode})
}
func seedIOS(t *testing.T, root string, f *localForge, repo string, gate map[string]string) {
t.Helper()
work := filepath.Join(root, "seed-"+filepath.Base(repo))
files := map[string]string{
"README.md": "# Woodstar\n\nAn iOS reading app with sliding panes.\n",
".gitignore": "build/\n",
".equipo/gates.json": "{\"version\":1,\"files\":[]}\n",
"Woodstar/Swipe.swift": "let edgeSwipe = false\n",
"Woodstar/About.swift": "let about = \"An iOS reading app\"\n",
"Woodstar.xcodeproj/xcshareddata/xcschemes/Woodstar.xcscheme": "\n",
}
for p, body := range gate {
files[p] = body
}
for p, body := range files {
if err := os.MkdirAll(filepath.Dir(filepath.Join(work, p)), 0700); err != nil {
t.Fatal(err)
}
mode := os.FileMode(0600)
if p == ".amadan/ci" || p == "scripts/test" {
mode = 0700
}
if err := os.WriteFile(filepath.Join(work, p), []byte(body), mode); err != nil {
t.Fatal(err)
}
}
gitRun(t, work, "init", "-q", "-b", "main")
gitRun(t, work, "add", "-A")
gitRun(t, work, "commit", "-q", "-m", "seed")
gitRun(t, root, "clone", "-q", "--bare", work, f.path(repo))
f.mu.Lock()
f.repos = append(f.repos, repo)
f.mu.Unlock()
}
// macWorker is the fake Mac worker: the real thin runner of the test
// build with EQUIPO_FAKE_PLATFORM, enrolled as the owner's second runner
// (a worker), its own roots, the fake xcodebuild first on its gates'
// PATH, run as a process so it can be killed. It plays a Mac whose
// probe P2 denied (checks labelled seatbelt). Worker checks are diagnostic
// until they certify immutable base gates, so the person chooses Merge.
//
// Since slice F it is also a Mac that makes changes: its home is root
// (the runner user's, 0700), with its own config dir, bindings and
// accounts root, which its home guard checks; the pinned gitleaks sits
// beside its gate's tools; it holds one Claude token connection of its
// own (macClaude), which only it can use.
func macWorker(t *testing.T, inst *thintest.Instance, primary *localRunner) (*localRunner, string) {
t.Helper()
w, xcodebuild := macWorkerAs(t, inst.EnrolRunner(t), primary)
w.inst = inst
return w, xcodebuild
}
// macWorkerAs is macWorker enrolled as cred (on an instance that may run
// in another process: set inst or instanceDB before start).
func macWorkerAs(t *testing.T, cred runnerproto.RunnerCredential, primary *localRunner) (*localRunner, string) {
t.Helper()
root := private(t, filepath.Join(primary.root, "mac"))
bin := private(t, filepath.Join(root, "bin"))
copyExecutable(t, filepath.Join(bin, "xcodebuild"))
pinnedGitleaks(t, filepath.Join(bin, "gitleaks"))
state := private(t, filepath.Join(root, "state"))
if err := thintest.WriteRunnerCredential(state, cred); err != nil {
t.Fatal(err)
}
config := private(t, filepath.Join(root, "config"))
cfg := primary.cfg
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{root: root, cfg: cfg, subprocess: true, scope: strings.ToLower(rand.Text()), 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)
if t.Failed() {
// The worker process's own log (warnings: why a step stopped).
if raw, err := os.ReadFile(filepath.Join(root, "runner.log")); err == nil {
t.Logf("worker log:\n%s", raw[max(0, len(raw)-8000):])
}
}
})
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 worker's Mac Engineering
// launches: the darwin launch marks them EQUIPO_ATTEMPT=engineering-,
// and the fake's stand-in puts them in its scope.
func engineeringProcs(worker *localRunner) []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-") || !strings.Contains(string(raw), proc.ScopeEnv+"="+worker.scope+"\x00") {
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
}
// woodstarCredentials gives the primary forge credentials that name the
// Woodstar repositories, as a real primary's do: a publication's file
// list is screened against them before it leaves (without them it is
// withheld).
func woodstarCredentials(t *testing.T, primary *localRunner) {
t.Helper()
creds := map[string]any{"agent": "equipo-test", "repositories": map[string]any{woodstar: map[string]string{"api": "amk_test_woodstar", "git": "git_test_woodstar"}, panes: map[string]string{"api": "amk_test_panes", "git": "git_test_panes"}}}
writeJSON(t, primary.cfg.AmadanCredentialPath, creds)
}
// pinnedGitleaks puts at dst a gitleaks the fake worker's scan can start
// in its empty bubblewrap (no libraries, no loader): this test binary
// when it is statically linked (CGO_ENABLED=0, as make builds it),
// else gitleaks built static from the module cache (nothing is
// downloaded). With a gitleaks that cannot start, every scan "could not
// tell" and the worker refuses every candidate, secret_in_candidate.
func pinnedGitleaks(t *testing.T, dst string) {
t.Helper()
self, err := os.Executable()
if err != nil {
t.Fatal(err)
}
if staticBinary(self) {
copyExecutable(t, dst)
return
}
build := exec.Command("go", "build", "-trimpath", "-o", dst, "github.com/zricethezav/gitleaks/v8")
build.Env = append(os.Environ(), "CGO_ENABLED=0", "GOFLAGS=-mod=readonly", "GOPROXY=off")
if out, err := build.CombinedOutput(); err != nil {
t.Fatalf("the fake Mac worker's gitleaks: this test binary is dynamically linked (built with cgo), so it cannot start in the scan's bubblewrap, and a static gitleaks could not be built (%v): %s\nRun with CGO_ENABLED=0, as make does.", err, out)
}
if !staticBinary(dst) {
t.Fatalf("the fake Mac worker's gitleaks at %s is not statically linked", dst)
}
}
// staticBinary: an ELF executable with no program interpreter (a static
// Go binary). Anything unreadable is not.
func staticBinary(path string) bool {
f, err := elf.Open(path)
if err != nil {
return false
}
defer f.Close()
for _, p := range f.Progs {
if p.Type == elf.PT_INTERP {
return false
}
}
return true
}
// procIdentity is a process by pid and start time (/proc's starttime):
// a pid used again is another process.
type procIdentity struct {
PID int
Start string
}
func startTime(pid int) string {
raw, err := os.ReadFile(filepath.Join("/proc", strconv.Itoa(pid), "stat"))
if err != nil {
return ""
}
end := strings.LastIndexByte(string(raw), ')')
f := strings.Fields(string(raw[end+1:]))
if end < 0 || len(f) < 20 || f[0] == "Z" {
return ""
}
return f[19]
}
func (p procIdentity) alive() bool { return p.PID > 0 && startTime(p.PID) == p.Start }
// lingering is the launch's lingering child (the fake CLI's linger:),
// once it has said its pid (in this test's own file), checked to carry
// the attempt's Engineering marker.
func lingering(t *testing.T, pidfile string) procIdentity {
t.Helper()
for deadline := time.Now().Add(30 * time.Second); ; time.Sleep(50 * time.Millisecond) {
raw, err := os.ReadFile(pidfile)
if pid, perr := strconv.Atoi(strings.TrimSpace(string(raw))); err == nil && perr == nil {
env, _ := os.ReadFile(filepath.Join("/proc", strconv.Itoa(pid), "environ"))
if !strings.Contains(string(env), "EQUIPO_ATTEMPT=engineering-") {
t.Fatalf("the lingering child %d is not the attempt's", pid)
}
return procIdentity{PID: pid, Start: startTime(pid)}
}
if time.Now().After(deadline) {
t.Fatal("the launch's lingering child never started")
}
}
}
// workedIn is the directory a fake CLI's reply says it worked in
// (saycwd).
func workedIn(summary string) string {
_, rest, ok := strings.Cut(summary, "Working in ")
if !ok {
return ""
}
dir, _, _ := strings.Cut(rest, " ")
return strings.TrimSuffix(dir, ".")
}
// workerKept is the sessions the worker keeps for a step, from its own
// state.
func workerKept(t *testing.T, worker *localRunner, step string) []string {
t.Helper()
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()
rows, err := d.Query("SELECT session_id FROM kept_sessions WHERE step_id = ? ORDER BY attempt", step)
if err != nil {
t.Fatal(err)
}
defer rows.Close()
var out []string
for rows.Next() {
var sid string
_ = rows.Scan(&sid)
out = append(out, sid)
}
return out
}
// macClaude is the fake Mac's own Claude token connection.
const macClaude = "mac-claude"
// macDispatches counts the Engineering dispatches the instance queued
// for runner, acked or not.
func macDispatches(t *testing.T, inst *thintest.Instance, runner string) int {
t.Helper()
var n int
if err := inst.DB.Writer().QueryRow("SELECT count(*) FROM runner_commands WHERE runner_id = ? AND kind = ? AND instr(body, ?) > 0", runner, wire.FrameDispatch, `"specialist":"engineering"`).Scan(&n); err != nil {
t.Fatal(err)
}
return n
}
// changeDiff is the person API's patch of one changed file of a task's
// candidate.
func (s *session) changeDiff(t *testing.T, id, sha, path string) wire.ChangeDiff {
t.Helper()
c := s.env.Client
req, err := http.NewRequestWithContext(s.ctx, http.MethodGet, c.Origin+"/api/v1/tasks/"+id+"/changes/diff?candidate_sha="+sha+"&path="+url.QueryEscape(path), nil)
if err != nil {
t.Fatal(err)
}
req.Header.Set("Authorization", "Bearer "+c.Token)
resp, err := c.HTTP.Do(req)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
var out wire.ChangeDiff
if resp.StatusCode != http.StatusOK || json.NewDecoder(resp.Body).Decode(&out) != nil {
t.Fatalf("change diff of %s: %s", path, resp.Status)
}
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 {
if n == 0 {
return s
}
n--
}
}
return wire.Step{}
}
// mergeWorkerPass verifies that a worker pass cannot grant merge authority,
// then exercises the person's explicit decision on that exact candidate.
func (s *session) mergeWorkerPass(t *testing.T, id string, timeout time.Duration) wire.Task {
t.Helper()
s.wait(t, "worker checks and review finished", timeout, func(c *thintest.Conversation) bool {
k := c.Tasks[id]
return k.Stage == wire.StageReadyToMerge || k.Stage == wire.StageDone || k.Stage == wire.StageCancelled
})
k, err := s.env.Client.Task(s.ctx, id)
if err != nil {
t.Fatal(err)
}
if k.Stage != wire.StageReadyToMerge || k.Checks != wire.ChecksPassed || k.Verdict != wire.VerdictApprove || k.Merged != nil || k.MergeDecision == nil || k.MergeDecision.Class != "ask" {
t.Fatalf("worker pass granted automatic authority or did not finish: %+v", k)
}
missingBase := false
for _, reason := range k.MergeDecision.Reasons {
if reason.Name == "trusted_base_checks" && !reason.OK {
missingBase = true
}
}
if !missingBase {
t.Fatalf("missing trusted-base evidence not recorded: %+v", k.MergeDecision)
}
for _, step := range k.Steps {
// 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")
}
}
if main := forgeHead(t, s.env.ForgePath(k.Repo), "main"); main != k.BaseSHA {
t.Fatalf("main moved before the person's decision: %s != %s", main, k.BaseSHA)
}
card := s.mergeCard(t, id)
if card.State != wire.CardOpen {
t.Fatalf("merge card not open: %+v", card)
}
if _, err := s.env.Client.Answer(s.ctx, card.ID, wire.ChoiceMerge, card.Revision); err != nil {
t.Fatal(err)
}
s.wait(t, "merged after the person's decision", time.Minute, func(c *thintest.Conversation) bool { return c.Tasks[id].Stage == wire.StageDone })
merged, err := s.env.Client.Task(s.ctx, id)
if err != nil {
t.Fatal(err)
}
if merged.CandidateSHA != k.CandidateSHA || merged.MergeDecision == nil || !strings.HasPrefix(merged.MergeDecision.DecidedBy, "person:") {
t.Fatalf("merge did not preserve person authority and candidate: %+v", merged)
}
mergedOnForge(t, s.env.ForgePath(k.Repo), merged)
return merged
}
// TestMacWorker runs the Mac worker scenarios of the spec (ยง6, M1, M2,
// M4, M5) against a local instance, the primary runner with the fake CLI
// in real bubblewrap, and the fake Mac worker.
func TestMacWorker(t *testing.T) {
env, inst, primary := localEnv(t)
addWoodstar(t, primary.root, primary.opts.Forge.(*localForge))
woodstarCredentials(t, primary)
primary.start(t)
worker, xcodebuild := macWorker(t, inst, primary)
worker.start(t)
s := open(t, env)
s.keep()
s.wait(t, "the worker online", 30*time.Second, func(c *thintest.Conversation) bool {
for _, r := range c.Runners {
if r.Role == wire.RoleWorker && r.Online && r.Label == "Tito Studio" {
return true
}
}
return false
})
// Mac work: Panes' gate runs xcodebuild, so its Engineering never runs
// on the Linux primary, and with EQUIPO_MAC_ENGINEERING unset (M9f)
// the Mac worker takes only checks: it waits, saying why, under Needs
// you.
t.Run("M0", func(t *testing.T) {
sent := s.send(t, "tool:record_task:woodstar/panes|Pane titles|Say what each pane is for.\ntool:start_task:$task|edit:Woodstar/About.swift|An iOS reading app|An iOS reading app with titled panes")
id := s.taskOf(t, sent.Turn.ID)
k := s.settled(t, id, 2*time.Minute)
eng := stepOf(k, wire.SpecialistEngineering, 0)
if k.NeedsYou != wire.NeedsMacEngineering || eng.State != wire.StepQueued || eng.Placement != wire.PlacementMacEngineering || eng.RunnerID != "" {
t.Fatalf("Mac engineering %+v / %+v", k, eng)
}
// M9f: the switch is off, so nothing reaches the worker, though
// it could take it (its report says ready, claude).
if n := macDispatches(t, inst, worker.runnerID); n != 0 {
t.Fatalf("switch off: %d Engineering dispatches queued for the worker", n)
}
if _, err := env.Client.CancelTask(s.ctx, id); err != nil {
t.Fatal(err)
}
})
// M5: the fake gate fails on the worker (a Swift change, judged on a
// Mac); the fix round works from its output; the new candidate's
// checks pass on the worker.
t.Run("M5", func(t *testing.T) {
sent := s.send(t, "tool:record_task:woodstar/woodstar|Describe the panes|Say what the panes are for.\ntool:start_task:$task|edit:Woodstar/About.swift|An iOS reading app|An iOS reading app with sliding panes")
id := s.taskOf(t, sent.Turn.ID)
k := s.mergeWorkerPass(t, id, 4*time.Minute)
first, second := stepOf(k, wire.SpecialistChecks, 0), stepOf(k, wire.SpecialistChecks, 1)
if first.Checks != wire.ChecksFailed || first.ExitCode == nil || *first.ExitCode != 65 || first.RunnerLabel != "Tito Studio" || k.FixRounds != 1 || second.Checks != wire.ChecksPassed || second.CandidateSHA != k.CandidateSHA {
t.Fatalf("fix round from the worker's output: %+v / %+v / rounds %d", first, second, k.FixRounds)
}
})
// M1: an iOS change; its checks are placed on the worker, the
// candidate relayed as a pack, xcodebuild passes there; review stays on
// the primary; the person then chooses Merge.
t.Run("M1", func(t *testing.T) {
sent := s.send(t, "tool:record_task:woodstar/woodstar|iOS edge swipe|Swipe back from the edge feels late.\ntool:start_task:$task|edit:Woodstar/Swipe.swift|edgeSwipe = true|edgeSwipe = true // from the edge")
id := s.taskOf(t, sent.Turn.ID)
k := s.mergeWorkerPass(t, id, 3*time.Minute)
checks, review := stepOf(k, wire.SpecialistChecks, 0), stepOf(k, wire.SpecialistReview, 0)
if checks.RunnerLabel != "Tito Studio" || checks.Checks != wire.ChecksPassed || checks.Gate != ".amadan/ci" || checks.ExitCode == nil || *checks.ExitCode != 0 || checks.TerminationKind != wire.TerminationProcessGroup || strings.Join(checks.Needs, ",") != "macos,xcode,ios_simulator" || checks.CandidateSHA != k.CandidateSHA {
t.Fatalf("checks %+v", checks)
}
if review.RunnerID == checks.RunnerID || review.Verdict != wire.VerdictApprove || review.TerminationKind != wire.TerminationNamespace {
t.Fatalf("review %+v", review)
}
log, err := env.Client.StepLog(s.ctx, checks.ID)
if err != nil || !strings.Contains(log.Tail, "** TEST SUCCEEDED **") {
t.Fatalf("checks log %+v %v", log, err)
}
if k.Merged == nil || k.Merged.WithoutChecks || k.EngineeringRunner == checks.RunnerID {
t.Fatalf("merge %+v", k)
}
})
// M2: the worker is offline; checks wait (no dispatch anywhere), then
// run when it is back. A second task waits 30 minutes (a fake clock)
// and resolves as not run, runner_offline, never a pass; review goes on.
t.Run("M2", func(t *testing.T) {
worker.stop(t)
s.wait(t, "the worker offline", 30*time.Second, func(c *thintest.Conversation) bool {
for _, r := range c.Runners {
if r.Role == wire.RoleWorker && !r.Online {
return true
}
}
return false
})
sent := s.send(t, "tool:record_task:woodstar/woodstar|About while away|Name the app.\ntool:start_task:$task|edit:Woodstar/About.swift|reading app|reading app (m2a)")
id := s.taskOf(t, sent.Turn.ID)
s.wait(t, "checks waiting", 2*time.Minute, func(c *thintest.Conversation) bool {
for _, st := range c.Tasks[id].Steps {
if st.Specialist == wire.SpecialistChecks && st.Placement == wire.PlacementWaiting {
return true
}
}
return false
})
worker.start(t)
k := s.mergeWorkerPass(t, id, 3*time.Minute)
if c := stepOf(k, wire.SpecialistChecks, 0); c.Checks != wire.ChecksPassed || c.RunnerLabel != "Tito Studio" {
t.Fatalf("checks after reconnect %+v", c)
}
worker.stop(t)
sent = s.send(t, "tool:record_task:woodstar/woodstar|About, worker gone|Name it again.\ntool:start_task:$task|edit:Woodstar/About.swift|reading app (m2a)|reading app (m2b)")
late := s.taskOf(t, sent.Turn.ID)
s.wait(t, "checks waiting", 2*time.Minute, func(c *thintest.Conversation) bool {
for _, st := range c.Tasks[late].Steps {
if st.Specialist == wire.SpecialistChecks && st.Placement == wire.PlacementWaiting {
return true
}
}
return false
})
later := time.Now().UTC().Add(chat.OfflineLimit + time.Minute)
inst.Store.Chat().SetClock(func() time.Time { return later })
if err := inst.Store.Chat().Place(context.Background()); err != nil {
t.Fatal(err)
}
inst.Store.Chat().SetClock(func() time.Time { return time.Now().UTC() })
k = s.settled(t, late, 2*time.Minute)
c := stepOf(k, wire.SpecialistChecks, 0)
if c.Checks != wire.ChecksCannotRun || c.Reason != "runner_offline" || k.Checks == wire.ChecksPassed || k.Stage != wire.StageReadyToMerge || stepOf(k, wire.SpecialistReview, 0).Verdict != wire.VerdictApprove {
t.Fatalf("offline checks %+v task %+v", c, k)
}
})
// M4: the worker is SIGKILLed while xcodebuild runs. Its gate's process
// group outlives it; on restart the worker kills what is left, proves
// the end by process group, and only then does Retry run the checks
// again, which pass.
t.Run("M4", func(t *testing.T) {
// Its own precondition: the worker running, started here.
worker.stop(t)
worker.start(t)
if err := os.WriteFile(xcodebuild+".hang", nil, 0600); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { os.Remove(xcodebuild + ".hang") })
sent := s.send(t, "tool:record_task:woodstar/woodstar|Killed mid checks|Tighten the summary line.\ntool:start_task:$task|create:Woodstar/Summary.swift|let summaryTitle = 4\nedit:Woodstar/Swipe.swift|edgeSwipe = false|edgeSwipe = true")
id := s.taskOf(t, sent.Turn.ID)
s.wait(t, "checks running on the worker", 3*time.Minute, func(c *thintest.Conversation) bool {
for _, st := range c.Tasks[id].Steps {
if st.Specialist == wire.SpecialistChecks && st.State == wire.StepRunning && st.StartedAt != nil {
return true
}
}
return false
})
time.Sleep(time.Second)
worker.kill(t)
if _, err := env.Client.RetryTask(s.ctx, id); thintest.Status(err) != 409 {
t.Fatalf("retry before the worker proved termination: %v", err)
}
os.Remove(xcodebuild + ".hang")
worker.start(t)
k := s.settled(t, id, 2*time.Minute)
c := stepOf(k, wire.SpecialistChecks, 0)
if c.State != wire.StepFailed || c.Reason != "runner_restarted" || !c.Terminated || c.TerminationKind != wire.TerminationProcessGroup || k.NeedsYou != wire.NeedsRetry {
t.Fatalf("after the kill %+v", c)
}
// Nothing of the killed attempt is left running (no checks run now).
entries, _ := os.ReadDir("/proc")
for _, e := range entries {
env, err := os.ReadFile(filepath.Join("/proc", e.Name(), "environ"))
if err == nil && strings.Contains(string(env), "EQUIPO_ATTEMPT=checks/") && strings.Contains(string(env), proc.ScopeEnv+"="+worker.scope+"\x00") {
cmdline, _ := os.ReadFile(filepath.Join("/proc", e.Name(), "cmdline"))
t.Fatalf("process %s of the killed attempt survived: %q", e.Name(), strings.ReplaceAll(string(cmdline), "\x00", " "))
}
}
if _, err := env.Client.RetryTask(s.ctx, id); err != nil {
t.Fatal(err)
}
k = s.mergeWorkerPass(t, id, 3*time.Minute)
if c := stepOf(k, wire.SpecialistChecks, 0); c.Attempt != 2 || c.Checks != wire.ChecksPassed || c.RunnerLabel != "Tito Studio" {
t.Fatalf("checks after Retry %+v", c)
}
})
// Mac Engineering (slice F): EQUIPO_MAC_ENGINEERING is set from here.
inst.Store.Chat().SetMacEngineering(true)
// M9a: Panes is Woodstar-shaped (an .xcodeproj with a shared scheme,
// a gate that runs xcodebuild), so its Engineering is Mac work. The
// primary prepares the base, the attempt goes to the worker with the
// inbound pack, the fake CLI edits a Swift file there (darwin launch,
// the pinned stand-in, the worker's own Claude connection), and the
// worker scans, commits and uploads a thin pack the primary pushes.
// The change's files and diffs show, checks run on the worker, review
// on the primary, and Ready to merge asks: a Mac-made candidate is
// never merged by policy.
t.Run("M9a", func(t *testing.T) {
sent := s.send(t, "tool:record_task:woodstar/panes|Edge swipe on the Mac|Swipe back from the edge feels late.\ntool:start_task:$task|edit:Woodstar/Swipe.swift|edgeSwipe = false|edgeSwipe = true")
id := s.taskOf(t, sent.Turn.ID)
s.wait(t, "Engineering placed on the worker", 2*time.Minute, func(c *thintest.Conversation) bool {
e := stepOf(c.Tasks[id], wire.SpecialistEngineering, 0)
return e.RunnerID == worker.runnerID || e.State == wire.StepFailed
})
k, err := env.Client.Task(s.ctx, id)
if err != nil {
t.Fatal(err)
}
eng := stepOf(k, wire.SpecialistEngineering, 0)
if eng.RunnerID != worker.runnerID || eng.RunnerLabel != "Tito Studio" {
t.Fatalf("Engineering not on the worker: %+v", eng)
}
s.wait(t, "the worker's candidate published", 3*time.Minute, func(c *thintest.Conversation) bool {
e := stepOf(c.Tasks[id], wire.SpecialistEngineering, 0)
return e.Pushed || e.State == wire.StepFailed
})
if k, err = env.Client.Task(s.ctx, id); err != nil {
t.Fatal(err)
}
eng = stepOf(k, wire.SpecialistEngineering, 0)
if eng.State != wire.StepDone || !eng.Pushed || eng.Account != macClaude || eng.TerminationKind != wire.TerminationProcessGroup || !eng.Terminated || eng.XcodeAccess != wire.XcodeAccessSandboxed || k.EngineeringRunner != worker.runnerID {
t.Fatalf("Engineering on the worker %+v (task runner %q)", eng, k.EngineeringRunner)
}
if f := eng.ChangeFiles; f == nil || f.SHA != eng.CandidateSHA || len(f.Entries) != 1 || f.Entries[0].Path != "Woodstar/Swipe.swift" {
t.Fatalf("change files %+v", eng.ChangeFiles)
}
if d := s.changeDiff(t, id, eng.CandidateSHA, "Woodstar/Swipe.swift"); !strings.Contains(d.Patch, "+let edgeSwipe = true") {
t.Fatalf("diff %+v", d)
}
// The primary pushed exactly the worker's commit, made as Equipo.
bare := env.ForgePath(panes)
if head := forgeHead(t, bare, k.Branch); head != eng.CandidateSHA {
t.Fatalf("branch %s at %s, want %s", k.Branch, head, eng.CandidateSHA)
}
if who := forgeShow(t, bare, "-s", "--format=%an <%ae>", eng.CandidateSHA); !strings.Contains(who, "Equipo") {
t.Fatalf("candidate author %q", who)
}
k = s.mergeWorkerPass(t, id, 4*time.Minute)
checks, review := stepOf(k, wire.SpecialistChecks, 0), stepOf(k, wire.SpecialistReview, 0)
if checks.RunnerID != worker.runnerID || checks.Checks != wire.ChecksPassed || checks.CandidateSHA != eng.CandidateSHA || review.RunnerID == worker.runnerID || review.Verdict != wire.VerdictApprove {
t.Fatalf("checks %+v review %+v", checks, review)
}
if k.Merged == nil || k.Merged.WithoutChecks {
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)
// The first round also leaves a file its commit ignores (build/),
// and says where it worked; the fix round (from the checks'
// output) says where it works and whether that file is there.
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\ncreate:build/leftover.txt|left by the first round\nsaycwd")
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)
}
// The very session of the first round, resumed in a fresh tree
// of its commit: another directory, without the file the first
// round left uncommitted.
var s0, s1 string
db := inst.DB.Writer()
if err := db.QueryRow("SELECT coalesce(session_id, '') FROM chat_steps WHERE id = ?", first.ID).Scan(&s0); err != nil || s0 == "" {
t.Fatalf("the first round's session %q %v", s0, err)
}
if err := db.QueryRow("SELECT coalesce(session_id, '') FROM chat_steps WHERE id = ?", fix.ID).Scan(&s1); err != nil || s1 != s0 {
t.Fatalf("the fix round resumed session %q, the first round's was %q (%v)", s1, s0, err)
}
if kept := workerKept(t, worker, fix.ID); len(kept) != 1 || kept[0] != s0 {
t.Fatalf("the worker kept %v for the fix round, want [%s]", kept, s0)
}
dir0, dir1 := workedIn(first.Summary), workedIn(fix.Summary)
if dir0 == "" || dir1 == "" || dir0 == dir1 || !strings.Contains(dir0, "/worker-steps/") || !strings.Contains(dir1, "/worker-steps/") {
t.Fatalf("worktrees %q then %q (%q / %q)", dir0, dir1, first.Summary, fix.Summary)
}
if !strings.Contains(first.Summary, "Created build/leftover.txt.") || !strings.Contains(fix.Summary, "No build/leftover.txt.") {
t.Fatalf("the fix round's tree is not fresh: %q / %q", first.Summary, fix.Summary)
}
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, so the turn's
// record never gets its final note. On restart the worker ends what
// the launch left and, holding the Mac's turn, reads the runner
// user's processes (task 9's idle clearance, on the fake's scoped
// table): only the runner and what existed before the turn are left,
// and nothing the record names is alive, so the end is proven by
// process group. Retry runs Engineering again on the same worker, to
// done; nobody clears anything by hand.
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)
}
// The CLI also starts a child in a session of its own that ignores
// SIGTERM and SIGHUP and keeps the attempt's marker: it outlives
// the runner, and only the restart's recovery may end it.
linger := filepath.Join(t.TempDir(), "linger.pid")
sent := s.send(t, "tool:record_task:woodstar/panes|Killed mid Engineering|Name the app in About.\ntool:start_task:$task|linger:"+linger+" 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
defer func() {
if t.Failed() {
k, _ := env.Client.Task(context.Background(), id)
t.Logf("task %s needs %q: %s; the Mac's report: %+v", k.Stage, k.NeedsYou, stepKinds(k), macCaps(t, inst, worker.runnerID).Engineering)
}
}()
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: it has started its lingering child,
// which carries the attempt's marker.
child := lingering(t, linger)
t.Cleanup(func() {
// Whatever the assertions found: it never outlives the test.
if child.alive() {
_ = syscall.Kill(child.PID, syscall.SIGKILL)
}
})
worker.kill(t)
if !child.alive() {
t.Fatalf("the launch's lingering child %+v did not outlive the runner", child)
}
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 end proven", 2*time.Minute, func(c *thintest.Conversation) bool {
e := stepOf(c.Tasks[id], wire.SpecialistEngineering, 0)
return e.State == wire.StepFailed && e.Terminated
})
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.TerminationKind != wire.TerminationProcessGroup || e.RunnerID != worker.runnerID || k.NeedsYou != wire.NeedsRetry {
t.Fatalf("after the restart %+v (needs %q)", e, k.NeedsYou)
}
// Recovery ended it, by its identity, before the end was proven
// (and so before the clearance and any Retry).
if child.alive() {
t.Fatalf("the launch's lingering child %+v survived the restart, and the end was proven", child)
}
if left := engineeringProcs(worker); len(left) > 0 {
t.Fatalf("processes %v of the killed attempt survived the restart", left)
}
if _, err := os.Stat(filepath.Join(worker.cfg.StateDir, "mac-gate.lock.owed")); err == nil {
if raw, _ := os.ReadFile(filepath.Join(worker.cfg.StateDir, "mac-gate.lock.owed")); strings.Contains(string(raw), "engineering-") {
t.Fatalf("the killed attempt still owes after the clearance: %s", raw)
}
}
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)
}
})
}