oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1//go:build testbuild
2
3package thin
4
5import (
6 "context"
7 "encoding/hex"
8 "encoding/json"
9 "os"
10 "path/filepath"
11 "slices"
12 "strings"
13 "testing"
14 "time"
15
16 "amadan.net/oficina/equipo/internal/runner"
17 "amadan.net/oficina/equipo/internal/wire"
18)
19
20// Ask the implementer on a Mac worker (Mac runners slice F, task 13), on
21// Linux through the darwin launch of the pinned stand-in: a question is
22// bound to exactly the (step, attempt, account, session) the instance
23// froze, resumes that kept session with the read-only answer settings,
24// and reads the change with git over the worker's store.
25
26// askedRound runs one Engineering round on the worker to its publication
27// and returns its final report (its kept session named).
28func askedRound(t *testing.T, x *engRig) wire.StepReport {
29 t.Helper()
30 x.note("edit:Swipe.swift|false|true")
31 rep := x.round(t)
32 if rep.SessionID == "" || !rep.Askable || rep.Account == "" {
33 t.Fatalf("no kept session reported: %+v", rep)
34 }
35 // Questions confirm the runner's lease, as the link does once welcomed.
36 x.w.Engine.Authorize = func(context.Context) error { return nil }
37 return rep
38}
39
40// askAbout is the instance's ask for the round rep, pinned to it.
41func askAbout(x *engRig, rep wire.StepReport, id, text string) askRow {
42 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,
43 EngAttempt: rep.Attempt, EngAccount: rep.Account, EngSession: rep.SessionID}}
44}
45
46// asked runs a on the worker as the step engine does: accepted, started,
47// answered; it returns the final report and the running reports said.
48func (x *engRig) asked(t *testing.T, a askRow) (wire.AnswerReport, []wire.AnswerReport) {
49 t.Helper()
50 ctx := context.Background()
51 if err := x.state.AcceptAsk(ctx, "f-"+a.QuestionID, a.AskCommand); err != nil {
52 t.Fatal(err)
53 }
54 if err := x.state.startAsk(ctx, a); err != nil {
55 t.Fatal(err)
56 }
57 var said []wire.AnswerReport
58 res := x.w.ask(ctx, a, func(p wire.AnswerReport) { said = append(said, p) })
59 if !res.Terminated {
60 t.Fatalf("the answer's end was not proven: %+v", res.Report)
61 }
62 if !x.turnFree() {
63 t.Fatal("the Mac's turn is still held")
64 }
65 return res.Report, said
66}
67
68// newest is the newest step-shaped launch of the pinned CLI (-p; auth
69// status reads are not).
70func (x *engRig) newest(t *testing.T) launched {
71 t.Helper()
72 var best launched
73 var at time.Time
74 for _, l := range x.launches() {
75 info, err := os.Stat(filepath.Join(x.dir, "bin", "launch."+itoa(int64(l.pid))+".argv"))
76 if err == nil && strings.HasPrefix(l.argv, "-p ") && info.ModTime().After(at) {
77 best, at = l, info.ModTime()
78 }
79 }
80 if at.IsZero() {
81 t.Fatal("no launch")
82 }
83 return best
84}
85
86// keepAnother records a kept session for another attempt of rep's step,
87// on the same candidate, whose transcript's last reply is said.
88func (x *engRig) keepAnother(t *testing.T, rep wire.StepReport, attempt int64, account, session, said string) {
89 t.Helper()
90 r := stepRow{DispatchCommand: wire.DispatchCommand{Person: connPerson, TaskID: rep.TaskID, StepID: rep.StepID, Attempt: attempt, Specialist: wire.SpecialistEngineering}}
91 dir := x.w.Engine.keepDir(r)
92 line, _ := json.Marshal(map[string]string{"type": "assistant", "text": said})
93 if err := os.MkdirAll(filepath.Dir(keptTranscript(dir, session)), 0o700); err != nil {
94 t.Fatal(err)
95 }
96 if err := os.WriteFile(keptTranscript(dir, session), append(line, '\n'), 0o600); err != nil {
97 t.Fatal(err)
98 }
99 if err := x.state.keepSession(context.Background(), r, wire.SpecialistEngineering, account, "", "", session, dir, rep.CandidateSHA, int64(len(line))); err != nil {
100 t.Fatal(err)
101 }
102 // Its candidate pinned in the store, as its commit would be.
103 if out, err := x.store(t, "update-ref", candidateRef(r), rep.CandidateSHA); err != nil {
104 t.Fatalf("pin %v %s", err, out)
105 }
106}
107
108// The answer comes from exactly the bound kept session: a newer attempt
109// of the same step with the same candidate kept on the worker is not the
110// one asked about. It resumes that session read-only, streams, and its
111// git_diff reads the change from the worker's store.
112func TestWorkerAskAnswersFromKeptSession(t *testing.T) {
113 x := newEngRig(t)
114 rep := askedRound(t, x)
115 const later = "00000000-0000-4000-8000-0000000000a2"
116 x.keepAnother(t, rep, rep.Attempt+1, rep.Account, later, "Attempt two's own words.")
117 var deltas []wire.DeltaReport
118 x.w.Engine.Delta = func(d wire.DeltaReport) { deltas = append(deltas, d) }
119 launched := x.steps()
120 got, said := x.asked(t, askAbout(x, rep, "q1", "What did you change? ask:git"))
121 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") {
122 t.Fatalf("answer %+v\n%s", got, x.logs.String())
123 }
124 if len(said) != 1 || said[0].State != wire.QuestionRunning {
125 t.Fatalf("running reports %+v", said)
126 }
127 if len(deltas) == 0 || deltas[0].TurnID != "q1" {
128 t.Fatalf("nothing streamed: %+v", deltas)
129 }
130 if x.steps() != launched+1 {
131 t.Fatalf("%d launches for one question", x.steps()-launched)
132 }
133 l := x.newest(t)
134 if !strings.Contains(l.argv, "--resume "+rep.SessionID) || strings.Contains(l.argv, later) {
135 t.Fatalf("not the bound session (%s): %s", rep.SessionID, l.argv)
136 }
137 // Asked about the later attempt, the later session answers.
138 a := askAbout(x, rep, "q2", "And then?")
139 a.EngAttempt, a.EngSession = rep.Attempt+1, later
140 if got, _ := x.asked(t, a); got.State != wire.QuestionAnswered || !strings.Contains(got.Text, "Attempt two's own words.") {
141 t.Fatalf("later attempt's answer %+v", got)
142 }
143 if l := x.newest(t); !strings.Contains(l.argv, "--resume "+later) {
144 t.Fatalf("not the later session: %s", l.argv)
145 }
146}
147
148// A question that does not match a kept session exactly is refused
149// before anything runs: another account, another session, an attempt
150// this worker kept nothing for, another step, another candidate, no
151// pinning at all, or a specialist a worker never runs.
152func TestWorkerAskRefusesMismatch(t *testing.T) {
153 x := newEngRig(t)
154 rep := askedRound(t, x)
155 cases := map[string]struct {
156 edit func(*askRow)
157 reason string
158 }{
159 "another account": {func(a *askRow) { a.EngAccount = "c9" }, "policy_rejected"},
160 "another session": {func(a *askRow) { a.EngSession = "00000000-0000-4000-8000-0000000000ff" }, "policy_rejected"},
161 "another attempt": {func(a *askRow) { a.EngAttempt = rep.Attempt + 5 }, "session_gone"},
162 "another step": {func(a *askRow) { a.StepID = "s9" }, "session_gone"},
163 "another candidate": {func(a *askRow) { a.CandidateSHA = strings.Repeat("a", 40) }, "policy_rejected"},
164 "not pinned": {func(a *askRow) { a.EngAttempt, a.EngAccount, a.EngSession = 0, "", "" }, "policy_rejected"},
165 "no session": {func(a *askRow) { a.EngSession = "" }, "policy_rejected"},
166 "review": {func(a *askRow) { a.Specialist = wire.SpecialistReview }, "policy_rejected"},
167 }
168 n := 0
169 for name, c := range cases {
170 n++
171 a := askAbout(x, rep, "q"+itoa(int64(n)), "Why?")
172 c.edit(&a)
173 before := x.steps()
174 got, said := x.asked(t, a)
175 if got.State != wire.QuestionFailed || got.Reason != c.reason || len(said) != 0 || x.steps() != before {
176 t.Errorf("%s: %+v, said %+v, %d launches", name, got, said, x.steps()-before)
177 }
178 }
179 // The exact pinning still answers.
180 if got, _ := x.asked(t, askAbout(x, rep, "q-ok", "Why?")); got.State != wire.QuestionAnswered {
181 t.Fatalf("pinned answer %+v\n%s", got, x.logs.String())
182 }
183 // With the attempt's candidate no longer pinned in the store (its keep
184 // ended), nothing runs.
185 ref := candidateRef(stepRow{DispatchCommand: wire.DispatchCommand{TaskID: rep.TaskID, StepID: rep.StepID, Attempt: rep.Attempt}})
186 if out, err := x.store(t, "update-ref", "-d", ref); err != nil {
187 t.Fatalf("drop %v %s", err, out)
188 }
189 before := x.steps()
190 if got, _ := x.asked(t, askAbout(x, rep, "q-gone", "Why?")); got.State != wire.QuestionFailed || got.Reason != "candidate_unavailable" || x.steps() != before {
191 t.Fatalf("without its candidate: %+v", got)
192 }
193}
194
195// A known secret in what the session says (here, its own transcript
196// quoting the connection's token) never leaves the Mac: the answer and
197// its streamed text are redacted.
198func TestWorkerAskRedactsKnownSecrets(t *testing.T) {
199 x := newEngRig(t)
200 rep := askedRound(t, x)
201 const later = "00000000-0000-4000-8000-0000000000b2"
202 x.keepAnother(t, rep, rep.Attempt+1, rep.Account, later, "I saw "+x.tokens[0]+" there.")
203 var deltas []string
204 x.w.Engine.Delta = func(d wire.DeltaReport) { deltas = append(deltas, d.Text) }
205 a := askAbout(x, rep, "q1", "What did you see?")
206 a.EngAttempt, a.EngSession = rep.Attempt+1, later
207 got, _ := x.asked(t, a)
208 if got.State != wire.QuestionAnswered || !strings.HasPrefix(got.Text, "From my session: I saw ") || strings.Contains(got.Text, x.tokens[0]) {
209 t.Fatalf("answer %+v", got)
210 }
211 if len(deltas) == 0 || strings.Contains(strings.Join(deltas, ""), x.tokens[0]) {
212 t.Fatalf("streamed %q", deltas)
213 }
214}
215
216// The answer runs with the read-only darwin settings: Read, Glob and
217// Grep only, the worktree denied to writes and not writable, partial
218// messages on; a Write is refused, and nothing reaches the store.
219func TestWorkerAskCannotWrite(t *testing.T) {
220 x := newEngRig(t)
221 rep := askedRound(t, x)
222 ref := candidateRef(stepRow{DispatchCommand: wire.DispatchCommand{TaskID: rep.TaskID, StepID: rep.StepID, Attempt: rep.Attempt}})
223 got, _ := x.asked(t, askAbout(x, rep, "q1", "Fix it? ask:write:Swipe.swift"))
224 if got.State != wire.QuestionAnswered || !strings.Contains(got.Text, "Write to Swipe.swift was denied") {
225 t.Fatalf("answer %+v\n%s", got, x.logs.String())
226 }
227 l := x.newest(t)
228 if !strings.Contains(l.argv, "--tools Read,Glob,Grep ") || !strings.Contains(l.argv, "--include-partial-messages") {
229 t.Fatalf("not the answer profile: %s", l.argv)
230 }
231 raw, err := os.ReadFile(filepath.Join(x.dir, "bin", "launch."+itoa(int64(l.pid))+".settings"))
232 if err != nil {
233 t.Fatal(err)
234 }
235 var s struct {
236 Sandbox struct {
237 Filesystem struct {
238 AllowWrite, DenyWrite []string
239 }
240 }
241 Permissions struct{ Allow []string }
242 }
243 if err := json.Unmarshal(raw, &s); err != nil {
244 t.Fatal(err)
245 }
246 for _, tool := range s.Permissions.Allow {
247 if strings.HasPrefix(tool, "Write") || strings.HasPrefix(tool, "Edit") || strings.HasPrefix(tool, "Bash") {
248 t.Fatalf("the ask settings allow %s: %s", tool, raw)
249 }
250 }
251 if slices.Contains(s.Sandbox.Filesystem.AllowWrite, l.cwd) || !slices.Contains(s.Sandbox.Filesystem.DenyWrite, l.cwd) {
252 t.Fatalf("the worktree %s is writable: %s", l.cwd, raw)
253 }
254 if tip, err := x.store(t, "rev-parse", ref); err != nil || tip != rep.CandidateSHA {
255 t.Fatalf("the candidate's ref moved: %q %v", tip, err)
256 }
257 if body, err := x.store(t, "show", rep.CandidateSHA+":Swipe.swift"); err != nil || body != "let back = true" {
258 t.Fatalf("the candidate changed: %q %v", body, err)
259 }
260}
261
262// The worker as it runs answers the asks it is sent: one about a session
263// it does not hold ends at once, failed, with nothing launched (an ask
264// the step engine had no answerer for would wait for ever). The person it
265// is enrolled for is one of its owners before their first connection
266// here, as on the primary: nothing waits for a restart.
267func TestWorkerRunAnswersAsks(t *testing.T) {
268 r := newDarwinRig(t)
269 r.machineKey()
270 r.workerCredential()
271 inst := newWorkerInstance(t)
272 stop := r.runWorker(inst, 0)
273 defer stop()
274 inst.welcome(wire.ProtocolMacEngineering)
275 launches := len(r.launches())
276 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?",
277 EngAttempt: 1, EngAccount: "c1", EngSession: "00000000-0000-4000-8000-000000000001"})
278 a := inst.next(wire.FrameAnswer, func(b any) bool {
279 v := b.(*wire.AnswerReport)
280 return v.QuestionID == "q1" && wire.QuestionTerminal(v.State)
281 }).(*wire.AnswerReport)
282 if a.State != wire.QuestionFailed || a.Reason != "session_gone" || len(r.launches()) != launches {
283 t.Fatalf("answer %+v, %d launches", a, len(r.launches())-launches)
284 }
285}
286
287// The answer is redacted whole before it is cut to its bound: a known
288// secret's hex form that crosses the bound leaves nothing of itself.
289func TestWorkerAskRedactsBeforeTheBound(t *testing.T) {
290 x := newEngRig(t)
291 rep := askedRound(t, x)
292 hexed := hex.EncodeToString([]byte(x.tokens[0]))
293 prefix := "From my session: "
294 pad := strings.Repeat("x", wire.MaxAnswerText-len(prefix)-len(hexed)/2)
295 const later = "00000000-0000-4000-8000-0000000000c2"
296 x.keepAnother(t, rep, rep.Attempt+1, rep.Account, later, pad+hexed+" and more.")
297 a := askAbout(x, rep, "q1", "What did you see?")
298 a.EngAttempt, a.EngSession = rep.Attempt+1, later
299 got, _ := x.asked(t, a)
300 if got.State != wire.QuestionAnswered || len(got.Text) > wire.MaxAnswerText || !strings.HasPrefix(got.Text, prefix+pad) {
301 t.Fatalf("answer %s... (%d bytes) %s", got.Text[:min(len(got.Text), 40)], len(got.Text), got.Reason)
302 }
303 if strings.Contains(got.Text, hexed[:minSecret]) {
304 t.Fatalf("the secret's hex form survived the cut: %q", got.Text[len(prefix+pad):])
305 }
306}
307
308// A question on a Mac confirms the runner's current lease (as a question,
309// not a step) before anything of it is prepared, and needs protocol 37:
310// a refusal, a lease that cannot be had, a lease never asked for or an
311// older instance launch nothing.
312func TestWorkerAskConfirmsTheLease(t *testing.T) {
313 x := newEngRig(t)
314 rep := askedRound(t, x)
315 stepLease := false
316 x.w.Engine.AuthorizeStep = func(context.Context, string, int64) error { stepLease = true; return nil }
317 asked := 0
318 cases := []struct {
319 name string
320 authorize func(context.Context) error
321 spoken int
322 reason string
323 }{
324 {"refused", func(context.Context) error { asked++; return ErrWithdrawn }, wire.ProtocolMacEngineering, "superseded"},
325 {"no lease", nil, wire.ProtocolMacEngineering, "policy_rejected"},
326 {"older instance", func(context.Context) error { asked++; return nil }, wire.ProtocolMacEngineering - 1, "policy_rejected"},
327 }
328 for i, c := range cases {
329 x.w.Engine.Authorize = c.authorize
330 x.w.Engine.Spoken = func() int { return c.spoken }
331 before := x.steps()
332 got, said := x.asked(t, askAbout(x, rep, "q"+itoa(int64(i+1)), "Why?"))
333 if got.State != wire.QuestionFailed || got.Reason != c.reason || len(said) != 0 || x.steps() != before {
334 t.Errorf("%s: %+v, said %+v, %d launches", c.name, got, said, x.steps()-before)
335 }
336 if entries, _ := os.ReadDir(x.w.stepsDir()); slices.ContainsFunc(entries, func(e os.DirEntry) bool { return strings.HasPrefix(e.Name(), "ask-") }) {
337 t.Errorf("%s: a tree was prepared", c.name)
338 }
339 }
340 if asked != 1 {
341 t.Fatalf("the refused lease was asked %d times", asked)
342 }
343 // Unavailable (the link is down): the question waits for it, and a
344 // cancel ends it with nothing launched.
345 x.w.Engine.Spoken = func() int { return wire.ProtocolMacEngineering }
346 x.w.Engine.Authorize = func(context.Context) error { return ErrNoAuthority }
347 ctx, cancel := context.WithTimeout(context.Background(), 1500*time.Millisecond)
348 defer cancel()
349 a := askAbout(x, rep, "q-down", "Why?")
350 if err := x.state.AcceptAsk(ctx, "f-q-down", a.AskCommand); err != nil {
351 t.Fatal(err)
352 }
353 before := x.steps()
354 res := x.w.ask(ctx, a, func(wire.AnswerReport) { t.Error("running without a lease") })
355 if res.Report.State != wire.QuestionCancelled || x.steps() != before {
356 t.Fatalf("without a lease: %+v, %d launches", res.Report, x.steps()-before)
357 }
358 // Granted: it runs, and only ever as a question.
359 x.w.Engine.Authorize = func(context.Context) error { return nil }
360 if got, _ := x.asked(t, askAbout(x, rep, "q-ok", "Why?")); got.State != wire.QuestionAnswered || stepLease {
361 t.Fatalf("granted: %+v, step lease asked %v", got, stepLease)
362 }
363}
364
365// The connection is chosen from one reading of the bindings: a
366// connection removed while the question chooses can neither shift
367// another into the kept one's place nor end the runner.
368func TestWorkerAskOneBindingsSnapshot(t *testing.T) {
369 x := newEngRig(t, "a@example.com", "b@example.com")
370 rep := askedRound(t, x)
371 all := x.w.Engine.Conns.Mine(connPerson)
372 kept := slices.IndexFunc(all, func(b runner.AccountBinding) bool { return b.LocalID == rep.Account })
373 if len(all) != 2 || kept < 0 {
374 t.Fatalf("bindings %+v, kept %s", all, rep.Account)
375 }
376 other := all[1-kept]
377 for _, order := range [][]runner.AccountBinding{{other, all[kept]}, {all[kept], other}} {
378 reads := 0
379 x.w.mine = func(string) []runner.AccountBinding {
380 reads++
381 if reads == 1 {
382 return order
383 }
384 // Signed out meanwhile: the list is shorter and shifted.
385 return []runner.AccountBinding{other}
386 }
387 got, _ := x.asked(t, askAbout(x, rep, "q-"+order[0].LocalID, "Why?"))
388 if got.State != wire.QuestionAnswered || len(got.Usage) == 0 || got.Usage[0].Connection != rep.Account || reads != 1 {
389 t.Fatalf("order %s first: %+v (read %d times)", order[0].LocalID, got, reads)
390 }
391 }
392}
393