oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package thin
2
3import (
4 "context"
5 "crypto/sha256"
6 "encoding/hex"
7 "encoding/json"
8 "errors"
9 "os"
10 "path/filepath"
11 "regexp"
12 "slices"
13
14 "amadan.net/oficina/equipo/internal/runner"
15 "amadan.net/oficina/equipo/internal/runner/checks"
16 "amadan.net/oficina/equipo/internal/runner/mac"
17 "amadan.net/oficina/equipo/internal/runner/provider"
18 "amadan.net/oficina/equipo/internal/runner/provider/claude"
19 "amadan.net/oficina/equipo/internal/runner/workspace"
20 "amadan.net/oficina/equipo/internal/wire"
21 "amadan.net/oficina/equipo/internal/wire/forgekey"
22)
23
24// Engineering on a Mac worker (Mac runners spec §8; slice F task 12):
25// one attempt from the inbound pack to the outbound thin pack. The
26// primary relays the commits the attempt starts from (the base and, for
27// a rebase round, the old base and the candidate); the worker keeps them
28// in its store as shallow boundaries, checks out the tree under its
29// scratch root, runs the pinned CLI through the darwin launch on one of
30// its own connections (failing over among them as the primary does),
31// commits as Equipo, retains the candidate in its store under a ref, and
32// scans every new object for its known secrets and with gitleaks before
33// anything leaves. Only then is the attempt committed, durably, and its
34// report names the candidate and its outcome; the instance opens the
35// outbound transfer and the worker's relay answers it from the store.
36// The primary publishes the commit; a worker never pushes.
37
38// WorkerEngineering is what a Mac worker needs to take Engineering.
39type WorkerEngineering struct {
40 // Creds is the Mac's credential operations: its turns, executor, the
41 // pinned CLI, the §4.2 paths and the guards (maccreds.go).
42 Creds *macCreds
43 // XcodeExec starts an attempt with sandboxed Xcode access (the user's
44 // T cleaned once its end is proven, the simulators quieted first);
45 // nil: Creds' executor.
46 XcodeExec *mac.Executor
47 // DeveloperDir is xcode-select -p ("" for none).
48 DeveloperDir string
49 // Status is the Mac's Engineering status now (nil: not known).
50 Status func(context.Context) *wire.EngineeringStatus
51 // Xcode: this Mac's own trusted probe report allows sandboxed Xcode
52 // access now.
53 Xcode func() bool
54 // Secrets are the worker's known secrets now: every connection's
55 // token, its runner credential, the seal key's private half.
56 Secrets func(context.Context) ([]string, error)
57 // Leaks runs the pinned gitleaks over a directory of changed files,
58 // offline and confined (on a Mac, the checks gate: srt under the
59 // profile P2 proves), recording its process as marker: whether it
60 // found a secret, or an error when it could not tell
61 // (errScanUnproven when its end is not proven).
62 Leaks func(ctx context.Context, dir, marker string, record func(string) error) (bool, error)
63 // refresh, in tests, stands in for the runtime copy's auth status.
64 refresh func(context.Context, provider.Binding) (provider.Identity, error)
65}
66
67// workerFault, in tests, stops an attempt at a named point ("retained",
68// "committed") as a crash there would.
69var workerFault func(point string) bool
70
71// refName is a task or step id a ref may carry whole.
72var refName = regexp.MustCompile(`^[A-Za-z0-9_-]{1,64}$`)
73
74// candidateRef pins an attempt's candidate in the worker's store, so an
75// upload, a restart, a second send_pack and a question never depend on
76// the attempt's directory.
77func candidateRef(r stepRow) string {
78 return "refs/equipo/" + r.TaskID + "/" + r.StepID + "/" + itoa(r.Attempt)
79}
80
81// engineeringMarker is the EQUIPO_ATTEMPT value of a worker's
82// Engineering attempt: a word the darwin policy takes (no "/"). It is on
83// the attempt's row before anything of the attempt runs, so a restart
84// never settles it as unrecorded.
85func engineeringMarker(key string) string {
86 sum := sha256.Sum256([]byte(key))
87 return "engineering-" + hex.EncodeToString(sum[:8])
88}
89
90// refuseEngineering is why an Engineering dispatch is not run here
91// ("" when it may be): the dispatch's own fields (policy_rejected), or
92// what this worker can do now (engineering_unavailable). Protocol is
93// checked once the lease confirms the attempt (the link is up then).
94func (w *Worker) refuseEngineering(ctx context.Context, r stepRow) string {
95 e := w.Engine
96 switch {
97 case !slices.Contains(e.Owners, r.Person), !forgekey.ValidHub(r.Repo), !wire.ValidTaskBranch(r.Branch), !refName.MatchString(r.TaskID), !refName.MatchString(r.StepID),
98 !wire.ValidCommitSHA(r.BaseSHA), r.Republish,
99 r.Rebase && (!wire.ValidCommitSHA(r.FromBase) || !wire.ValidCommitSHA(r.CandidateSHA)),
100 r.XcodeAccess != "" && r.XcodeAccess != wire.XcodeAccessSandboxed,
101 specialistBound(r):
102 // A worker's commit is published again by a new outbound
103 // transfer (Retry of its publication), never by a republish. A
104 // specialist's step (Design) never runs on a Mac worker: it needs
105 // the page renderer, and would otherwise run as plain Engineering.
106 return "policy_rejected"
107 case w.Eng == nil || w.Eng.Creds == nil || w.Eng.Status == nil || w.Eng.Secrets == nil || w.Eng.Leaks == nil:
108 return wire.ReasonEngineeringUnavailable
109 }
110 if s := w.Eng.Status(ctx); s == nil || s.State != wire.EngineeringReady {
111 return wire.ReasonEngineeringUnavailable
112 }
113 if r.XcodeAccess != "" && (w.Eng.Xcode == nil || !w.Eng.Xcode()) {
114 // No stronger than this Mac's own trusted report allows.
115 return wire.ReasonEngineeringUnavailable
116 }
117 return ""
118}
119
120// engineering runs one Engineering attempt placed on this worker. Every
121// report it says or returns passes the known-secret redaction first.
122func (w *Worker) engineering(ctx context.Context, r stepRow, progress func(wire.StepReport)) (rep wire.StepReport) {
123 e := w.Engine
124 rep = wire.StepReport{TaskID: r.TaskID, StepID: r.StepID, Attempt: r.Attempt, BaseSHA: r.BaseSHA, XcodeAccess: r.XcodeAccess, Findings: []wire.Finding{}}
125 var known [][]byte
126 defer func() { rep = redactReport(rep, known) }()
127 say := func(p wire.StepReport) { progress(redactReport(p, known)) }
128 fail := func(reason string, terminated bool) wire.StepReport {
129 rep.State, rep.Reason, rep.Termination = wire.StepFailed, reason, terminated
130 return rep
131 }
132 cancelled := func() wire.StepReport {
133 rep.State, rep.Reason, rep.Termination = wire.StepCancelled, "cancelled", true
134 return rep
135 }
136 if committed(r.Phase) {
137 // Only the upload was left: it is answered from the store; the
138 // CLI never runs again for this attempt.
139 return w.committedEngineering(ctx, r, rep, say)
140 }
141 if reason := w.refuseEngineering(ctx, r); reason != "" {
142 return fail(reason, true)
143 }
144 if w.Ready != nil {
145 if err := w.Ready(ctx); err != nil {
146 return cancelled()
147 }
148 }
149 w.mu.Lock()
150 defer w.mu.Unlock()
151 if ctx.Err() != nil {
152 return cancelled()
153 }
154 // The Mac's one turn for the whole attempt: preparing, every launch
155 // (failover included), the commit, the retain and the scan.
156 m := w.Eng.Creds
157 if m.turns != nil {
158 u, err := m.turns.Take(ctx, mac.OpEngineering)
159 if err != nil {
160 if ctx.Err() != nil {
161 return cancelled()
162 }
163 e.log("worker engineering turn", err)
164 return fail(wire.ReasonEngineeringUnavailable, true)
165 }
166 defer u.Give()
167 ctx = u.Context(ctx)
168 }
169 secrets, err := w.Eng.Secrets(ctx)
170 if err != nil {
171 // What it cannot name it cannot keep from leaving: nothing runs.
172 e.log("worker secrets", err)
173 return fail(wire.ReasonEngineeringUnavailable, true)
174 }
175 known = secretForms(secrets)
176 marker := engineeringMarker(r.key())
177 w.marker = marker
178 defer func() { w.marker = "" }()
179 if err := w.State.setStepNamespace(ctx, r, mac.RecordID(0, marker)); err != nil {
180 e.log("worker record", err)
181 return fail("workspace_refused", true)
182 }
183 if err := e.lease(ctx, r); err != nil {
184 rep.State, rep.Reason, rep.Termination = wire.StepCancelled, leaseReason(err), true
185 return rep
186 }
187 if e.Spoken == nil || e.Spoken() < wire.ProtocolMacEngineering {
188 return fail(wire.ReasonEngineeringUnavailable, true)
189 }
190 defer func(step string, attempt int64) {
191 _ = w.State.dropStepChunks(context.WithoutCancel(ctx), step, attempt)
192 }(r.StepID, r.Attempt)
193 want := wire.TransferHeader{Direction: wire.TransferInbound, Kind: wire.TransferKindEngineering, Repo: r.Repo, TaskID: r.TaskID, StepID: r.StepID, Attempt: r.Attempt, BaseSHA: r.BaseSHA}
194 if r.Rebase {
195 want.OldBaseSHA, want.CandidateSHA = r.FromBase, r.CandidateSHA
196 }
197 pack, err := w.awaitPack(ctx, r, want)
198 switch {
199 case ctx.Err() != nil:
200 return cancelled()
201 case err != nil:
202 e.log("worker pack", err)
203 return fail("candidate_unavailable", true)
204 }
205 store := w.objects(r.Repo)
206 var dirs []string
207 defer func() {
208 for _, d := range dirs {
209 os.RemoveAll(d)
210 }
211 }()
212 // keys are the attempts this run went through (a failover moves on).
213 var keys []stepRow
214 attemptDir := func() string {
215 d := filepath.Join(w.stepsDir(), stepKey(r))
216 dirs, keys = append(dirs, d), append(keys, r)
217 return d
218 }
219 if err := w.indexEngineering(ctx, store, attemptDir(), pack, want); err != nil {
220 e.log("worker index", err)
221 return fail("candidate_unavailable", true)
222 }
223 base := r.BaseSHA
224 // The Research findings, quoted; kept images stay on the main runner.
225 handoff := e.researchHandoffOn(ctx, r, false)
226 defer handoff.close()
227 // prepare checks the tree out afresh from the store, for the attempt
228 // and after every refusal: the refused attempt's work is discarded.
229 var tree workspace.TaskTree
230 prepare := func() (string, string) {
231 for _, d := range dirs {
232 os.RemoveAll(filepath.Join(d, "tree"))
233 os.RemoveAll(filepath.Join(d, "git"))
234 }
235 d := attemptDir()
236 var err error
237 if tree, err = workspace.PrepareTaskTree(ctx, e.O.Runner.GitPath, store, base, r.Branch, filepath.Join(d, "tree"), filepath.Join(d, "git")); err != nil {
238 e.log("worker tree", err)
239 return "", "workspace_refused"
240 }
241 prompt := handoff.with(e.stepPrompt(r, false, tree.Dir), e.Note)
242 if r.Rebase {
243 conflicts, err := tree.Rebase(ctx, r.FromBase, r.CandidateSHA)
244 if err != nil {
245 e.log("worker rebase", err)
246 return "", "candidate_unavailable"
247 }
248 prompt = handoff.with(e.rebasePrompt(r, conflicts, tree.Dir), e.Note)
249 }
250 return prompt, ""
251 }
252 prompt, reason := prepare()
253 if reason != "" {
254 return fail(reason, true)
255 }
256 if err := w.State.setStepPhase(ctx, r, phaseRunning, base, ""); err != nil {
257 return fail("provider_failed", true)
258 }
259 say(rep)
260 var avoid []string
261 var b runner.AccountBinding
262 var res stepResult
263 // A fix round may go on in the session that made its commit (kept on
264 // this worker).
265 prior, resumable := e.fixSession(ctx, r, base)
266 for {
267 var resume bool
268 var hold *wire.StepHold
269 if b, resume, hold, _, err = e.fixPlan(ctx, r, avoid, prior, resumable); err != nil {
270 if errors.Is(err, ErrNoConnection) {
271 rep.State = stepDeferred
272 return rep
273 }
274 return fail("account_unavailable", true)
275 }
276 if hold != nil {
277 return heldReport(rep, hold)
278 }
279 rep.Family, rep.Account = b.Family, b.LocalID
280 spec := specialistRun{action: "implement", binding: b, tools: stepTools, names: []string{"submit_candidate", "ask_person", "submit_render"}, permission: claude.StepPermission, call: func(context.Context, string, string, json.RawMessage) (string, bool) { return stepToolText, false }, prompt: prompt, keep: e.keepDir(r), activity: e.stepActivity(r)}
281 if resume {
282 spec.prompt, spec.resume, spec.from = handoff.with(e.fixPrompt(r, tree.Dir), e.Note), prior.SessionID, prior.Dir
283 }
284 res = w.launch(ctx, r, tree, spec, marker, known)
285 if resume && res.reason == "session_gone" && res.terminated {
286 resumable = false
287 continue
288 }
289 e.observe(b.ID, res)
290 if res.limit == nil && !res.auth || !res.terminated || ctx.Err() != nil || e.Conns == nil {
291 break
292 }
293 if !e.refused(ctx, &r, &rep, b, res) {
294 return fail("provider_failed", true)
295 }
296 avoid = append(avoid, b.ID)
297 // The next attempt's marker is on record before anything of it runs.
298 marker = engineeringMarker(r.key())
299 w.marker = marker
300 if err := w.State.setStepNamespace(ctx, r, mac.RecordID(0, marker)); err != nil {
301 e.log("worker record", err)
302 return fail("workspace_refused", true)
303 }
304 if prompt, reason = prepare(); reason != "" {
305 return fail(reason, true)
306 }
307 say(rep)
308 }
309 if rep.Switched != nil && res.reason == "" {
310 rep.Switched.To = b.Provider
311 }
312 rep.Usage = append(rep.Usage, res.usage(b, r.Attempt)...)
313 // Screened whole before any of it is clipped (the frames were too):
314 // a secret cut by a bound would match nothing afterwards.
315 headline, summary := splitHeadline(redactText(res.summary, known))
316 rep.Headline, rep.Summary, rep.LogTail = headline, clip(summary, wire.MaxStepSummary), redactText(res.tail, known)
317 kept := e.recordKept(ctx, r, b, res, "")
318 if kept {
319 rep.SessionID = res.session
320 }
321 if !res.terminated {
322 // Its end is not proven: no Retry until a restarted runner proves it.
323 return fail(firstNonEmpty(res.reason, "provider_failed"), false)
324 }
325 if ctx.Err() != nil {
326 return cancelled()
327 }
328 unfinished := res.reason == "step_timeout" && !r.Rebase && e.keepsUnfinished()
329 if res.reason != "" && !unfinished {
330 return fail(res.reason, true)
331 }
332 message, outcome := commitMessage(r, summary), wire.OutcomeCommitted
333 switch {
334 case unfinished:
335 message, outcome = unfinishedMessage(r), wire.OutcomeUnfinished
336 case res.noShell && r.Round >= 1 && !r.Rebase:
337 outcome = wire.OutcomeNoShell
338 }
339 // The clipped message is screened again (the object scan reads it
340 // too, whole).
341 sha, err := tree.Commit(ctx, redactText(message, known), commitName, commitEmail)
342 switch {
343 case unfinished && err != nil:
344 if !errors.Is(err, workspace.ErrNoChanges) {
345 e.log("worker commit", err)
346 }
347 return fail(res.reason, true)
348 case errors.Is(err, workspace.ErrNoChanges):
349 return fail(emptyStepReason(res), true)
350 case err != nil:
351 e.log("worker commit", err)
352 return fail("workspace_refused", true)
353 }
354 if files, err := tree.ChangedFiles(ctx, sha); err == nil && len(files) > 0 {
355 rep.Apple = checks.NeedsMacOS(files, "")
356 }
357 // Retained before anything else: the store holds it under its ref.
358 ref := candidateRef(r)
359 if err := w.retain(ctx, tree, store, filepath.Join(w.stepsDir(), stepKey(r)), r, base, sha); err != nil {
360 e.log("worker retain", err)
361 return fail("workspace_refused", true)
362 }
363 if workerFault != nil && workerFault("retained") {
364 return wire.StepReport{}
365 }
366 // The scan, before anything leaves. A hit, a scanner that could not
367 // tell, an object past the bound or a list that cannot be read: the
368 // step ends secret_in_candidate, the ref goes, and nothing names the
369 // object but its id and kind (a file name can be the secret).
370 if hit := w.scan(ctx, store, filepath.Join(w.stepsDir(), stepKey(r)), base, sha, known, func(id string) error {
371 return w.State.setStepNamespace(context.WithoutCancel(ctx), r, id)
372 }); hit != nil {
373 if e.O.Logger != nil {
374 e.O.Logger.Warn("secret in candidate: nothing uploaded", "object", hit.object, "kind", hit.kind)
375 }
376 e.log("worker candidate ref", w.dropCandidate(context.WithoutCancel(ctx), r.Repo, ref))
377 // What names its files goes too: the step logs and the session
378 // of the attempts that made it.
379 w.discard(context.WithoutCancel(ctx), keys)
380 rep.Headline, rep.Summary, rep.LogTail, rep.Apple, rep.SessionID = "", "", "", false, ""
381 return fail(wire.ReasonSecretInCandidate, !hit.unproven)
382 }
383 // The pack that leaves, measured before anything is committed: a
384 // candidate past the transfer bound can never reach the primary, so
385 // the step ends now, workspace_too_large, with Retry.
386 if size, err := w.packSize(ctx, store, base, sha); err != nil || size > workerPackBound {
387 e.log("worker candidate ref", w.dropCandidate(context.WithoutCancel(ctx), r.Repo, ref))
388 if err != nil {
389 e.log("worker pack", err)
390 return fail("workspace_refused", true)
391 }
392 return fail(wire.ReasonWorkspaceTooLarge, true)
393 }
394 rep.CandidateSHA, rep.Phase, rep.OutcomePhase, rep.Askable = sha, wire.OutcomeCommitted, outcome, kept
395 final := redactReport(workerDone(rep, outcome), known)
396 // One transition: committed, the outcome, the final report a restart
397 // sends, and the kept session's binding to the candidate.
398 if err := w.State.setWorkerCommitted(ctx, r, base, sha, outcome, final, kept); err != nil {
399 return fail("provider_failed", true)
400 }
401 if workerFault != nil && workerFault("committed") {
402 return wire.StepReport{}
403 }
404 rep.Askable = false
405 say(rep)
406 return final
407}
408
409// discard removes the step logs of the attempts keys name and their kept
410// sessions (a refused candidate's: they name its files).
411func (w *Worker) discard(ctx context.Context, rows []stepRow) {
412 e := w.Engine
413 for _, r := range rows {
414 e.log("worker step log", os.RemoveAll(filepath.Join(e.root(), stepKey(r))))
415 dir, err := w.State.dropKept(ctx, r)
416 e.log("kept sessions", err)
417 if dir != "" {
418 e.log("kept sessions", e.removeKept(dir))
419 }
420 }
421}
422
423// workerDone is a committed attempt's final report: done, never pushed
424// (only the primary publishes), with the reason its outcome carries. The
425// instance reads the outcome from the committed report; an unfinished
426// one is queued failed step_timeout and sent as unfinished work
427// (unfinishedReport).
428func workerDone(rep wire.StepReport, outcome string) wire.StepReport {
429 rep.State, rep.Pushed, rep.Termination, rep.Phase, rep.Reason = wire.StepDone, false, true, "", ""
430 switch outcome {
431 case wire.OutcomeUnfinished:
432 rep.Reason = "step_timeout"
433 case wire.OutcomeNoShell:
434 rep.Reason = wire.ReasonShellUnavailable
435 }
436 return rep
437}
438
439// committedEngineering resumes an attempt a restart found committed: the
440// committed report again (a crash may have lost it) and done; the relay
441// answers the upload from the store.
442func (w *Worker) committedEngineering(ctx context.Context, r stepRow, rep wire.StepReport, say func(wire.StepReport)) wire.StepReport {
443 outcome, final, err := w.State.workerCommitted(ctx, r.StepID, r.Attempt)
444 if err != nil || outcome == "" || !wire.ValidCommitSHA(r.Candidate) || final.CandidateSHA != r.Candidate {
445 w.Engine.log("worker resume", errors.Join(err, errors.New("no recorded outcome")))
446 rep.State, rep.Reason, rep.Termination = wire.StepFailed, "candidate_unavailable", true
447 return rep
448 }
449 // The committed report again (a crash may have lost it), then the
450 // final report as the attempt made it.
451 committed := final
452 committed.State, committed.Reason, committed.Phase, committed.OutcomePhase, committed.Askable = "", "", wire.OutcomeCommitted, outcome, false
453 say(committed)
454 return final
455}
456