//go:build testbuild package thin import ( "context" "encoding/hex" "encoding/json" "os" "path/filepath" "slices" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/runner" "amadan.net/oficina/equipo/internal/wire" ) // Ask the implementer on a Mac worker (Mac runners slice F, task 13), on // Linux through the darwin launch of the pinned stand-in: a question is // bound to exactly the (step, attempt, account, session) the instance // froze, resumes that kept session with the read-only answer settings, // and reads the change with git over the worker's store. // askedRound runs one Engineering round on the worker to its publication // and returns its final report (its kept session named). func askedRound(t *testing.T, x *engRig) wire.StepReport { t.Helper() x.note("edit:Swipe.swift|false|true") rep := x.round(t) if rep.SessionID == "" || !rep.Askable || rep.Account == "" { t.Fatalf("no kept session reported: %+v", rep) } // Questions confirm the runner's lease, as the link does once welcomed. x.w.Engine.Authorize = func(context.Context) error { return nil } return rep } // askAbout is the instance's ask for the round rep, pinned to it. func askAbout(x *engRig, rep wire.StepReport, id, text string) askRow { return askRow{AskCommand: wire.AskCommand{Person: connPerson, TaskID: rep.TaskID, StepID: rep.StepID, QuestionID: id, Attempt: 1, Specialist: wire.SpecialistEngineering, Repo: x.r.Repo, Branch: x.r.Branch, BaseSHA: rep.BaseSHA, CandidateSHA: rep.CandidateSHA, Title: "Swipe back", Text: text, EngAttempt: rep.Attempt, EngAccount: rep.Account, EngSession: rep.SessionID}} } // asked runs a on the worker as the step engine does: accepted, started, // answered; it returns the final report and the running reports said. func (x *engRig) asked(t *testing.T, a askRow) (wire.AnswerReport, []wire.AnswerReport) { t.Helper() ctx := context.Background() if err := x.state.AcceptAsk(ctx, "f-"+a.QuestionID, a.AskCommand); err != nil { t.Fatal(err) } if err := x.state.startAsk(ctx, a); err != nil { t.Fatal(err) } var said []wire.AnswerReport res := x.w.ask(ctx, a, func(p wire.AnswerReport) { said = append(said, p) }) if !res.Terminated { t.Fatalf("the answer's end was not proven: %+v", res.Report) } if !x.turnFree() { t.Fatal("the Mac's turn is still held") } return res.Report, said } // newest is the newest step-shaped launch of the pinned CLI (-p; auth // status reads are not). func (x *engRig) newest(t *testing.T) launched { t.Helper() var best launched var at time.Time for _, l := range x.launches() { info, err := os.Stat(filepath.Join(x.dir, "bin", "launch."+itoa(int64(l.pid))+".argv")) if err == nil && strings.HasPrefix(l.argv, "-p ") && info.ModTime().After(at) { best, at = l, info.ModTime() } } if at.IsZero() { t.Fatal("no launch") } return best } // keepAnother records a kept session for another attempt of rep's step, // on the same candidate, whose transcript's last reply is said. func (x *engRig) keepAnother(t *testing.T, rep wire.StepReport, attempt int64, account, session, said string) { t.Helper() r := stepRow{DispatchCommand: wire.DispatchCommand{Person: connPerson, TaskID: rep.TaskID, StepID: rep.StepID, Attempt: attempt, Specialist: wire.SpecialistEngineering}} dir := x.w.Engine.keepDir(r) line, _ := json.Marshal(map[string]string{"type": "assistant", "text": said}) if err := os.MkdirAll(filepath.Dir(keptTranscript(dir, session)), 0o700); err != nil { t.Fatal(err) } if err := os.WriteFile(keptTranscript(dir, session), append(line, '\n'), 0o600); err != nil { t.Fatal(err) } if err := x.state.keepSession(context.Background(), r, wire.SpecialistEngineering, account, "", "", session, dir, rep.CandidateSHA, int64(len(line))); err != nil { t.Fatal(err) } // Its candidate pinned in the store, as its commit would be. if out, err := x.store(t, "update-ref", candidateRef(r), rep.CandidateSHA); err != nil { t.Fatalf("pin %v %s", err, out) } } // The answer comes from exactly the bound kept session: a newer attempt // of the same step with the same candidate kept on the worker is not the // one asked about. It resumes that session read-only, streams, and its // git_diff reads the change from the worker's store. func TestWorkerAskAnswersFromKeptSession(t *testing.T) { x := newEngRig(t) rep := askedRound(t, x) const later = "00000000-0000-4000-8000-0000000000a2" x.keepAnother(t, rep, rep.Attempt+1, rep.Account, later, "Attempt two's own words.") var deltas []wire.DeltaReport x.w.Engine.Delta = func(d wire.DeltaReport) { deltas = append(deltas, d) } launched := x.steps() got, said := x.asked(t, askAbout(x, rep, "q1", "What did you change? ask:git")) if got.State != wire.QuestionAnswered || !strings.HasPrefix(got.Text, "From my session: ") || strings.Contains(got.Text, "Attempt two") || !strings.Contains(got.Text, "The change: +let back = true") { t.Fatalf("answer %+v\n%s", got, x.logs.String()) } if len(said) != 1 || said[0].State != wire.QuestionRunning { t.Fatalf("running reports %+v", said) } if len(deltas) == 0 || deltas[0].TurnID != "q1" { t.Fatalf("nothing streamed: %+v", deltas) } if x.steps() != launched+1 { t.Fatalf("%d launches for one question", x.steps()-launched) } l := x.newest(t) if !strings.Contains(l.argv, "--resume "+rep.SessionID) || strings.Contains(l.argv, later) { t.Fatalf("not the bound session (%s): %s", rep.SessionID, l.argv) } // Asked about the later attempt, the later session answers. a := askAbout(x, rep, "q2", "And then?") a.EngAttempt, a.EngSession = rep.Attempt+1, later if got, _ := x.asked(t, a); got.State != wire.QuestionAnswered || !strings.Contains(got.Text, "Attempt two's own words.") { t.Fatalf("later attempt's answer %+v", got) } if l := x.newest(t); !strings.Contains(l.argv, "--resume "+later) { t.Fatalf("not the later session: %s", l.argv) } } // A question that does not match a kept session exactly is refused // before anything runs: another account, another session, an attempt // this worker kept nothing for, another step, another candidate, no // pinning at all, or a specialist a worker never runs. func TestWorkerAskRefusesMismatch(t *testing.T) { x := newEngRig(t) rep := askedRound(t, x) cases := map[string]struct { edit func(*askRow) reason string }{ "another account": {func(a *askRow) { a.EngAccount = "c9" }, "policy_rejected"}, "another session": {func(a *askRow) { a.EngSession = "00000000-0000-4000-8000-0000000000ff" }, "policy_rejected"}, "another attempt": {func(a *askRow) { a.EngAttempt = rep.Attempt + 5 }, "session_gone"}, "another step": {func(a *askRow) { a.StepID = "s9" }, "session_gone"}, "another candidate": {func(a *askRow) { a.CandidateSHA = strings.Repeat("a", 40) }, "policy_rejected"}, "not pinned": {func(a *askRow) { a.EngAttempt, a.EngAccount, a.EngSession = 0, "", "" }, "policy_rejected"}, "no session": {func(a *askRow) { a.EngSession = "" }, "policy_rejected"}, "review": {func(a *askRow) { a.Specialist = wire.SpecialistReview }, "policy_rejected"}, } n := 0 for name, c := range cases { n++ a := askAbout(x, rep, "q"+itoa(int64(n)), "Why?") c.edit(&a) before := x.steps() got, said := x.asked(t, a) if got.State != wire.QuestionFailed || got.Reason != c.reason || len(said) != 0 || x.steps() != before { t.Errorf("%s: %+v, said %+v, %d launches", name, got, said, x.steps()-before) } } // The exact pinning still answers. if got, _ := x.asked(t, askAbout(x, rep, "q-ok", "Why?")); got.State != wire.QuestionAnswered { t.Fatalf("pinned answer %+v\n%s", got, x.logs.String()) } // With the attempt's candidate no longer pinned in the store (its keep // ended), nothing runs. ref := candidateRef(stepRow{DispatchCommand: wire.DispatchCommand{TaskID: rep.TaskID, StepID: rep.StepID, Attempt: rep.Attempt}}) if out, err := x.store(t, "update-ref", "-d", ref); err != nil { t.Fatalf("drop %v %s", err, out) } before := x.steps() if got, _ := x.asked(t, askAbout(x, rep, "q-gone", "Why?")); got.State != wire.QuestionFailed || got.Reason != "candidate_unavailable" || x.steps() != before { t.Fatalf("without its candidate: %+v", got) } } // A known secret in what the session says (here, its own transcript // quoting the connection's token) never leaves the Mac: the answer and // its streamed text are redacted. func TestWorkerAskRedactsKnownSecrets(t *testing.T) { x := newEngRig(t) rep := askedRound(t, x) const later = "00000000-0000-4000-8000-0000000000b2" x.keepAnother(t, rep, rep.Attempt+1, rep.Account, later, "I saw "+x.tokens[0]+" there.") var deltas []string x.w.Engine.Delta = func(d wire.DeltaReport) { deltas = append(deltas, d.Text) } a := askAbout(x, rep, "q1", "What did you see?") a.EngAttempt, a.EngSession = rep.Attempt+1, later got, _ := x.asked(t, a) if got.State != wire.QuestionAnswered || !strings.HasPrefix(got.Text, "From my session: I saw ") || strings.Contains(got.Text, x.tokens[0]) { t.Fatalf("answer %+v", got) } if len(deltas) == 0 || strings.Contains(strings.Join(deltas, ""), x.tokens[0]) { t.Fatalf("streamed %q", deltas) } } // The answer runs with the read-only darwin settings: Read, Glob and // Grep only, the worktree denied to writes and not writable, partial // messages on; a Write is refused, and nothing reaches the store. func TestWorkerAskCannotWrite(t *testing.T) { x := newEngRig(t) rep := askedRound(t, x) ref := candidateRef(stepRow{DispatchCommand: wire.DispatchCommand{TaskID: rep.TaskID, StepID: rep.StepID, Attempt: rep.Attempt}}) got, _ := x.asked(t, askAbout(x, rep, "q1", "Fix it? ask:write:Swipe.swift")) if got.State != wire.QuestionAnswered || !strings.Contains(got.Text, "Write to Swipe.swift was denied") { t.Fatalf("answer %+v\n%s", got, x.logs.String()) } l := x.newest(t) if !strings.Contains(l.argv, "--tools Read,Glob,Grep ") || !strings.Contains(l.argv, "--include-partial-messages") { t.Fatalf("not the answer profile: %s", l.argv) } raw, err := os.ReadFile(filepath.Join(x.dir, "bin", "launch."+itoa(int64(l.pid))+".settings")) if err != nil { t.Fatal(err) } var s struct { Sandbox struct { Filesystem struct { AllowWrite, DenyWrite []string } } Permissions struct{ Allow []string } } if err := json.Unmarshal(raw, &s); err != nil { t.Fatal(err) } for _, tool := range s.Permissions.Allow { if strings.HasPrefix(tool, "Write") || strings.HasPrefix(tool, "Edit") || strings.HasPrefix(tool, "Bash") { t.Fatalf("the ask settings allow %s: %s", tool, raw) } } if slices.Contains(s.Sandbox.Filesystem.AllowWrite, l.cwd) || !slices.Contains(s.Sandbox.Filesystem.DenyWrite, l.cwd) { t.Fatalf("the worktree %s is writable: %s", l.cwd, raw) } if tip, err := x.store(t, "rev-parse", ref); err != nil || tip != rep.CandidateSHA { t.Fatalf("the candidate's ref moved: %q %v", tip, err) } if body, err := x.store(t, "show", rep.CandidateSHA+":Swipe.swift"); err != nil || body != "let back = true" { t.Fatalf("the candidate changed: %q %v", body, err) } } // The worker as it runs answers the asks it is sent: one about a session // it does not hold ends at once, failed, with nothing launched (an ask // the step engine had no answerer for would wait for ever). The person it // is enrolled for is one of its owners before their first connection // here, as on the primary: nothing waits for a restart. func TestWorkerRunAnswersAsks(t *testing.T) { r := newDarwinRig(t) r.machineKey() r.workerCredential() inst := newWorkerInstance(t) stop := r.runWorker(inst, 0) defer stop() inst.welcome(wire.ProtocolMacEngineering) launches := len(r.launches()) inst.send(wire.FrameAsk, wire.AskCommand{Person: connPerson, TaskID: "tk1", StepID: "s1", QuestionID: "q1", Attempt: 1, Specialist: wire.SpecialistEngineering, Repo: "amadan.net/oficina/sample", Branch: relayBranch, BaseSHA: strings.Repeat("1", 40), CandidateSHA: strings.Repeat("2", 40), Title: "Swipe back", Text: "Why?", EngAttempt: 1, EngAccount: "c1", EngSession: "00000000-0000-4000-8000-000000000001"}) a := inst.next(wire.FrameAnswer, func(b any) bool { v := b.(*wire.AnswerReport) return v.QuestionID == "q1" && wire.QuestionTerminal(v.State) }).(*wire.AnswerReport) if a.State != wire.QuestionFailed || a.Reason != "session_gone" || len(r.launches()) != launches { t.Fatalf("answer %+v, %d launches", a, len(r.launches())-launches) } } // The answer is redacted whole before it is cut to its bound: a known // secret's hex form that crosses the bound leaves nothing of itself. func TestWorkerAskRedactsBeforeTheBound(t *testing.T) { x := newEngRig(t) rep := askedRound(t, x) hexed := hex.EncodeToString([]byte(x.tokens[0])) prefix := "From my session: " pad := strings.Repeat("x", wire.MaxAnswerText-len(prefix)-len(hexed)/2) const later = "00000000-0000-4000-8000-0000000000c2" x.keepAnother(t, rep, rep.Attempt+1, rep.Account, later, pad+hexed+" and more.") a := askAbout(x, rep, "q1", "What did you see?") a.EngAttempt, a.EngSession = rep.Attempt+1, later got, _ := x.asked(t, a) if got.State != wire.QuestionAnswered || len(got.Text) > wire.MaxAnswerText || !strings.HasPrefix(got.Text, prefix+pad) { t.Fatalf("answer %s... (%d bytes) %s", got.Text[:min(len(got.Text), 40)], len(got.Text), got.Reason) } if strings.Contains(got.Text, hexed[:minSecret]) { t.Fatalf("the secret's hex form survived the cut: %q", got.Text[len(prefix+pad):]) } } // A question on a Mac confirms the runner's current lease (as a question, // not a step) before anything of it is prepared, and needs protocol 37: // a refusal, a lease that cannot be had, a lease never asked for or an // older instance launch nothing. func TestWorkerAskConfirmsTheLease(t *testing.T) { x := newEngRig(t) rep := askedRound(t, x) stepLease := false x.w.Engine.AuthorizeStep = func(context.Context, string, int64) error { stepLease = true; return nil } asked := 0 cases := []struct { name string authorize func(context.Context) error spoken int reason string }{ {"refused", func(context.Context) error { asked++; return ErrWithdrawn }, wire.ProtocolMacEngineering, "superseded"}, {"no lease", nil, wire.ProtocolMacEngineering, "policy_rejected"}, {"older instance", func(context.Context) error { asked++; return nil }, wire.ProtocolMacEngineering - 1, "policy_rejected"}, } for i, c := range cases { x.w.Engine.Authorize = c.authorize x.w.Engine.Spoken = func() int { return c.spoken } before := x.steps() got, said := x.asked(t, askAbout(x, rep, "q"+itoa(int64(i+1)), "Why?")) if got.State != wire.QuestionFailed || got.Reason != c.reason || len(said) != 0 || x.steps() != before { t.Errorf("%s: %+v, said %+v, %d launches", c.name, got, said, x.steps()-before) } if entries, _ := os.ReadDir(x.w.stepsDir()); slices.ContainsFunc(entries, func(e os.DirEntry) bool { return strings.HasPrefix(e.Name(), "ask-") }) { t.Errorf("%s: a tree was prepared", c.name) } } if asked != 1 { t.Fatalf("the refused lease was asked %d times", asked) } // Unavailable (the link is down): the question waits for it, and a // cancel ends it with nothing launched. x.w.Engine.Spoken = func() int { return wire.ProtocolMacEngineering } x.w.Engine.Authorize = func(context.Context) error { return ErrNoAuthority } ctx, cancel := context.WithTimeout(context.Background(), 1500*time.Millisecond) defer cancel() a := askAbout(x, rep, "q-down", "Why?") if err := x.state.AcceptAsk(ctx, "f-q-down", a.AskCommand); err != nil { t.Fatal(err) } before := x.steps() res := x.w.ask(ctx, a, func(wire.AnswerReport) { t.Error("running without a lease") }) if res.Report.State != wire.QuestionCancelled || x.steps() != before { t.Fatalf("without a lease: %+v, %d launches", res.Report, x.steps()-before) } // Granted: it runs, and only ever as a question. x.w.Engine.Authorize = func(context.Context) error { return nil } if got, _ := x.asked(t, askAbout(x, rep, "q-ok", "Why?")); got.State != wire.QuestionAnswered || stepLease { t.Fatalf("granted: %+v, step lease asked %v", got, stepLease) } } // The connection is chosen from one reading of the bindings: a // connection removed while the question chooses can neither shift // another into the kept one's place nor end the runner. func TestWorkerAskOneBindingsSnapshot(t *testing.T) { x := newEngRig(t, "a@example.com", "b@example.com") rep := askedRound(t, x) all := x.w.Engine.Conns.Mine(connPerson) kept := slices.IndexFunc(all, func(b runner.AccountBinding) bool { return b.LocalID == rep.Account }) if len(all) != 2 || kept < 0 { t.Fatalf("bindings %+v, kept %s", all, rep.Account) } other := all[1-kept] for _, order := range [][]runner.AccountBinding{{other, all[kept]}, {all[kept], other}} { reads := 0 x.w.mine = func(string) []runner.AccountBinding { reads++ if reads == 1 { return order } // Signed out meanwhile: the list is shorter and shifted. return []runner.AccountBinding{other} } got, _ := x.asked(t, askAbout(x, rep, "q-"+order[0].LocalID, "Why?")) if got.State != wire.QuestionAnswered || len(got.Usage) == 0 || got.Usage[0].Connection != rep.Account || reads != 1 { t.Fatalf("order %s first: %+v (read %d times)", order[0].LocalID, got, reads) } } }