package thin import ( "context" "crypto/sha256" "encoding/hex" "encoding/json" "errors" "os" "path/filepath" "regexp" "slices" "amadan.net/oficina/equipo/internal/runner" "amadan.net/oficina/equipo/internal/runner/checks" "amadan.net/oficina/equipo/internal/runner/mac" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/runner/provider/claude" "amadan.net/oficina/equipo/internal/runner/workspace" "amadan.net/oficina/equipo/internal/wire" "amadan.net/oficina/equipo/internal/wire/forgekey" ) // Engineering on a Mac worker (Mac runners spec §8; slice F task 12): // one attempt from the inbound pack to the outbound thin pack. The // primary relays the commits the attempt starts from (the base and, for // a rebase round, the old base and the candidate); the worker keeps them // in its store as shallow boundaries, checks out the tree under its // scratch root, runs the pinned CLI through the darwin launch on one of // its own connections (failing over among them as the primary does), // commits as Equipo, retains the candidate in its store under a ref, and // scans every new object for its known secrets and with gitleaks before // anything leaves. Only then is the attempt committed, durably, and its // report names the candidate and its outcome; the instance opens the // outbound transfer and the worker's relay answers it from the store. // The primary publishes the commit; a worker never pushes. // WorkerEngineering is what a Mac worker needs to take Engineering. type WorkerEngineering struct { // Creds is the Mac's credential operations: its turns, executor, the // pinned CLI, the §4.2 paths and the guards (maccreds.go). Creds *macCreds // XcodeExec starts an attempt with sandboxed Xcode access (the user's // T cleaned once its end is proven, the simulators quieted first); // nil: Creds' executor. XcodeExec *mac.Executor // DeveloperDir is xcode-select -p ("" for none). DeveloperDir string // Status is the Mac's Engineering status now (nil: not known). Status func(context.Context) *wire.EngineeringStatus // Xcode: this Mac's own trusted probe report allows sandboxed Xcode // access now. Xcode func() bool // Secrets are the worker's known secrets now: every connection's // token, its runner credential, the seal key's private half. Secrets func(context.Context) ([]string, error) // Leaks runs the pinned gitleaks over a directory of changed files, // offline and confined (on a Mac, the checks gate: srt under the // profile P2 proves), recording its process as marker: whether it // found a secret, or an error when it could not tell // (errScanUnproven when its end is not proven). Leaks func(ctx context.Context, dir, marker string, record func(string) error) (bool, error) // refresh, in tests, stands in for the runtime copy's auth status. refresh func(context.Context, provider.Binding) (provider.Identity, error) } // workerFault, in tests, stops an attempt at a named point ("retained", // "committed") as a crash there would. var workerFault func(point string) bool // refName is a task or step id a ref may carry whole. var refName = regexp.MustCompile(`^[A-Za-z0-9_-]{1,64}$`) // candidateRef pins an attempt's candidate in the worker's store, so an // upload, a restart, a second send_pack and a question never depend on // the attempt's directory. func candidateRef(r stepRow) string { return "refs/equipo/" + r.TaskID + "/" + r.StepID + "/" + itoa(r.Attempt) } // engineeringMarker is the EQUIPO_ATTEMPT value of a worker's // Engineering attempt: a word the darwin policy takes (no "/"). It is on // the attempt's row before anything of the attempt runs, so a restart // never settles it as unrecorded. func engineeringMarker(key string) string { sum := sha256.Sum256([]byte(key)) return "engineering-" + hex.EncodeToString(sum[:8]) } // refuseEngineering is why an Engineering dispatch is not run here // ("" when it may be): the dispatch's own fields (policy_rejected), or // what this worker can do now (engineering_unavailable). Protocol is // checked once the lease confirms the attempt (the link is up then). func (w *Worker) refuseEngineering(ctx context.Context, r stepRow) string { e := w.Engine switch { case !slices.Contains(e.Owners, r.Person), !forgekey.ValidHub(r.Repo), !wire.ValidTaskBranch(r.Branch), !refName.MatchString(r.TaskID), !refName.MatchString(r.StepID), !wire.ValidCommitSHA(r.BaseSHA), r.Republish, r.Rebase && (!wire.ValidCommitSHA(r.FromBase) || !wire.ValidCommitSHA(r.CandidateSHA)), r.XcodeAccess != "" && r.XcodeAccess != wire.XcodeAccessSandboxed, specialistBound(r): // A worker's commit is published again by a new outbound // transfer (Retry of its publication), never by a republish. A // specialist's step (Design) never runs on a Mac worker: it needs // the page renderer, and would otherwise run as plain Engineering. return "policy_rejected" case w.Eng == nil || w.Eng.Creds == nil || w.Eng.Status == nil || w.Eng.Secrets == nil || w.Eng.Leaks == nil: return wire.ReasonEngineeringUnavailable } if s := w.Eng.Status(ctx); s == nil || s.State != wire.EngineeringReady { return wire.ReasonEngineeringUnavailable } if r.XcodeAccess != "" && (w.Eng.Xcode == nil || !w.Eng.Xcode()) { // No stronger than this Mac's own trusted report allows. return wire.ReasonEngineeringUnavailable } return "" } // engineering runs one Engineering attempt placed on this worker. Every // report it says or returns passes the known-secret redaction first. func (w *Worker) engineering(ctx context.Context, r stepRow, progress func(wire.StepReport)) (rep wire.StepReport) { e := w.Engine rep = wire.StepReport{TaskID: r.TaskID, StepID: r.StepID, Attempt: r.Attempt, BaseSHA: r.BaseSHA, XcodeAccess: r.XcodeAccess, Findings: []wire.Finding{}} var known [][]byte defer func() { rep = redactReport(rep, known) }() say := func(p wire.StepReport) { progress(redactReport(p, known)) } fail := func(reason string, terminated bool) wire.StepReport { rep.State, rep.Reason, rep.Termination = wire.StepFailed, reason, terminated return rep } cancelled := func() wire.StepReport { rep.State, rep.Reason, rep.Termination = wire.StepCancelled, "cancelled", true return rep } if committed(r.Phase) { // Only the upload was left: it is answered from the store; the // CLI never runs again for this attempt. return w.committedEngineering(ctx, r, rep, say) } if reason := w.refuseEngineering(ctx, r); reason != "" { return fail(reason, true) } if w.Ready != nil { if err := w.Ready(ctx); err != nil { return cancelled() } } w.mu.Lock() defer w.mu.Unlock() if ctx.Err() != nil { return cancelled() } // The Mac's one turn for the whole attempt: preparing, every launch // (failover included), the commit, the retain and the scan. m := w.Eng.Creds if m.turns != nil { u, err := m.turns.Take(ctx, mac.OpEngineering) if err != nil { if ctx.Err() != nil { return cancelled() } e.log("worker engineering turn", err) return fail(wire.ReasonEngineeringUnavailable, true) } defer u.Give() ctx = u.Context(ctx) } secrets, err := w.Eng.Secrets(ctx) if err != nil { // What it cannot name it cannot keep from leaving: nothing runs. e.log("worker secrets", err) return fail(wire.ReasonEngineeringUnavailable, true) } known = secretForms(secrets) marker := engineeringMarker(r.key()) w.marker = marker defer func() { w.marker = "" }() if err := w.State.setStepNamespace(ctx, r, mac.RecordID(0, marker)); err != nil { e.log("worker record", err) return fail("workspace_refused", true) } if err := e.lease(ctx, r); err != nil { rep.State, rep.Reason, rep.Termination = wire.StepCancelled, leaseReason(err), true return rep } if e.Spoken == nil || e.Spoken() < wire.ProtocolMacEngineering { return fail(wire.ReasonEngineeringUnavailable, true) } defer func(step string, attempt int64) { _ = w.State.dropStepChunks(context.WithoutCancel(ctx), step, attempt) }(r.StepID, r.Attempt) want := wire.TransferHeader{Direction: wire.TransferInbound, Kind: wire.TransferKindEngineering, Repo: r.Repo, TaskID: r.TaskID, StepID: r.StepID, Attempt: r.Attempt, BaseSHA: r.BaseSHA} if r.Rebase { want.OldBaseSHA, want.CandidateSHA = r.FromBase, r.CandidateSHA } pack, err := w.awaitPack(ctx, r, want) switch { case ctx.Err() != nil: return cancelled() case err != nil: e.log("worker pack", err) return fail("candidate_unavailable", true) } store := w.objects(r.Repo) var dirs []string defer func() { for _, d := range dirs { os.RemoveAll(d) } }() // keys are the attempts this run went through (a failover moves on). var keys []stepRow attemptDir := func() string { d := filepath.Join(w.stepsDir(), stepKey(r)) dirs, keys = append(dirs, d), append(keys, r) return d } if err := w.indexEngineering(ctx, store, attemptDir(), pack, want); err != nil { e.log("worker index", err) return fail("candidate_unavailable", true) } base := r.BaseSHA // The Research findings, quoted; kept images stay on the main runner. handoff := e.researchHandoffOn(ctx, r, false) defer handoff.close() // prepare checks the tree out afresh from the store, for the attempt // and after every refusal: the refused attempt's work is discarded. var tree workspace.TaskTree prepare := func() (string, string) { for _, d := range dirs { os.RemoveAll(filepath.Join(d, "tree")) os.RemoveAll(filepath.Join(d, "git")) } d := attemptDir() var err error if tree, err = workspace.PrepareTaskTree(ctx, e.O.Runner.GitPath, store, base, r.Branch, filepath.Join(d, "tree"), filepath.Join(d, "git")); err != nil { e.log("worker tree", err) return "", "workspace_refused" } prompt := handoff.with(e.stepPrompt(r, false, tree.Dir), e.Note) if r.Rebase { conflicts, err := tree.Rebase(ctx, r.FromBase, r.CandidateSHA) if err != nil { e.log("worker rebase", err) return "", "candidate_unavailable" } prompt = handoff.with(e.rebasePrompt(r, conflicts, tree.Dir), e.Note) } return prompt, "" } prompt, reason := prepare() if reason != "" { return fail(reason, true) } if err := w.State.setStepPhase(ctx, r, phaseRunning, base, ""); err != nil { return fail("provider_failed", true) } say(rep) var avoid []string var b runner.AccountBinding var res stepResult // A fix round may go on in the session that made its commit (kept on // this worker). prior, resumable := e.fixSession(ctx, r, base) for { var resume bool var hold *wire.StepHold if b, resume, hold, _, err = e.fixPlan(ctx, r, avoid, prior, resumable); err != nil { if errors.Is(err, ErrNoConnection) { rep.State = stepDeferred return rep } return fail("account_unavailable", true) } if hold != nil { return heldReport(rep, hold) } rep.Family, rep.Account = b.Family, b.LocalID 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)} if resume { spec.prompt, spec.resume, spec.from = handoff.with(e.fixPrompt(r, tree.Dir), e.Note), prior.SessionID, prior.Dir } res = w.launch(ctx, r, tree, spec, marker, known) if resume && res.reason == "session_gone" && res.terminated { resumable = false continue } e.observe(b.ID, res) if res.limit == nil && !res.auth || !res.terminated || ctx.Err() != nil || e.Conns == nil { break } if !e.refused(ctx, &r, &rep, b, res) { return fail("provider_failed", true) } avoid = append(avoid, b.ID) // The next attempt's marker is on record before anything of it runs. marker = engineeringMarker(r.key()) w.marker = marker if err := w.State.setStepNamespace(ctx, r, mac.RecordID(0, marker)); err != nil { e.log("worker record", err) return fail("workspace_refused", true) } if prompt, reason = prepare(); reason != "" { return fail(reason, true) } say(rep) } if rep.Switched != nil && res.reason == "" { rep.Switched.To = b.Provider } rep.Usage = append(rep.Usage, res.usage(b, r.Attempt)...) // Screened whole before any of it is clipped (the frames were too): // a secret cut by a bound would match nothing afterwards. headline, summary := splitHeadline(redactText(res.summary, known)) rep.Headline, rep.Summary, rep.LogTail = headline, clip(summary, wire.MaxStepSummary), redactText(res.tail, known) kept := e.recordKept(ctx, r, b, res, "") if kept { rep.SessionID = res.session } if !res.terminated { // Its end is not proven: no Retry until a restarted runner proves it. return fail(firstNonEmpty(res.reason, "provider_failed"), false) } if ctx.Err() != nil { return cancelled() } unfinished := res.reason == "step_timeout" && !r.Rebase && e.keepsUnfinished() if res.reason != "" && !unfinished { return fail(res.reason, true) } message, outcome := commitMessage(r, summary), wire.OutcomeCommitted switch { case unfinished: message, outcome = unfinishedMessage(r), wire.OutcomeUnfinished case res.noShell && r.Round >= 1 && !r.Rebase: outcome = wire.OutcomeNoShell } // The clipped message is screened again (the object scan reads it // too, whole). sha, err := tree.Commit(ctx, redactText(message, known), commitName, commitEmail) switch { case unfinished && err != nil: if !errors.Is(err, workspace.ErrNoChanges) { e.log("worker commit", err) } return fail(res.reason, true) case errors.Is(err, workspace.ErrNoChanges): return fail(emptyStepReason(res), true) case err != nil: e.log("worker commit", err) return fail("workspace_refused", true) } if files, err := tree.ChangedFiles(ctx, sha); err == nil && len(files) > 0 { rep.Apple = checks.NeedsMacOS(files, "") } // Retained before anything else: the store holds it under its ref. ref := candidateRef(r) if err := w.retain(ctx, tree, store, filepath.Join(w.stepsDir(), stepKey(r)), r, base, sha); err != nil { e.log("worker retain", err) return fail("workspace_refused", true) } if workerFault != nil && workerFault("retained") { return wire.StepReport{} } // The scan, before anything leaves. A hit, a scanner that could not // tell, an object past the bound or a list that cannot be read: the // step ends secret_in_candidate, the ref goes, and nothing names the // object but its id and kind (a file name can be the secret). if hit := w.scan(ctx, store, filepath.Join(w.stepsDir(), stepKey(r)), base, sha, known, func(id string) error { return w.State.setStepNamespace(context.WithoutCancel(ctx), r, id) }); hit != nil { if e.O.Logger != nil { e.O.Logger.Warn("secret in candidate: nothing uploaded", "object", hit.object, "kind", hit.kind) } e.log("worker candidate ref", w.dropCandidate(context.WithoutCancel(ctx), r.Repo, ref)) // What names its files goes too: the step logs and the session // of the attempts that made it. w.discard(context.WithoutCancel(ctx), keys) rep.Headline, rep.Summary, rep.LogTail, rep.Apple, rep.SessionID = "", "", "", false, "" return fail(wire.ReasonSecretInCandidate, !hit.unproven) } // The pack that leaves, measured before anything is committed: a // candidate past the transfer bound can never reach the primary, so // the step ends now, workspace_too_large, with Retry. if size, err := w.packSize(ctx, store, base, sha); err != nil || size > workerPackBound { e.log("worker candidate ref", w.dropCandidate(context.WithoutCancel(ctx), r.Repo, ref)) if err != nil { e.log("worker pack", err) return fail("workspace_refused", true) } return fail(wire.ReasonWorkspaceTooLarge, true) } rep.CandidateSHA, rep.Phase, rep.OutcomePhase, rep.Askable = sha, wire.OutcomeCommitted, outcome, kept final := redactReport(workerDone(rep, outcome), known) // One transition: committed, the outcome, the final report a restart // sends, and the kept session's binding to the candidate. if err := w.State.setWorkerCommitted(ctx, r, base, sha, outcome, final, kept); err != nil { return fail("provider_failed", true) } if workerFault != nil && workerFault("committed") { return wire.StepReport{} } rep.Askable = false say(rep) return final } // discard removes the step logs of the attempts keys name and their kept // sessions (a refused candidate's: they name its files). func (w *Worker) discard(ctx context.Context, rows []stepRow) { e := w.Engine for _, r := range rows { e.log("worker step log", os.RemoveAll(filepath.Join(e.root(), stepKey(r)))) dir, err := w.State.dropKept(ctx, r) e.log("kept sessions", err) if dir != "" { e.log("kept sessions", e.removeKept(dir)) } } } // workerDone is a committed attempt's final report: done, never pushed // (only the primary publishes), with the reason its outcome carries. The // instance reads the outcome from the committed report; an unfinished // one is queued failed step_timeout and sent as unfinished work // (unfinishedReport). func workerDone(rep wire.StepReport, outcome string) wire.StepReport { rep.State, rep.Pushed, rep.Termination, rep.Phase, rep.Reason = wire.StepDone, false, true, "", "" switch outcome { case wire.OutcomeUnfinished: rep.Reason = "step_timeout" case wire.OutcomeNoShell: rep.Reason = wire.ReasonShellUnavailable } return rep } // committedEngineering resumes an attempt a restart found committed: the // committed report again (a crash may have lost it) and done; the relay // answers the upload from the store. func (w *Worker) committedEngineering(ctx context.Context, r stepRow, rep wire.StepReport, say func(wire.StepReport)) wire.StepReport { outcome, final, err := w.State.workerCommitted(ctx, r.StepID, r.Attempt) if err != nil || outcome == "" || !wire.ValidCommitSHA(r.Candidate) || final.CandidateSHA != r.Candidate { w.Engine.log("worker resume", errors.Join(err, errors.New("no recorded outcome"))) rep.State, rep.Reason, rep.Termination = wire.StepFailed, "candidate_unavailable", true return rep } // The committed report again (a crash may have lost it), then the // final report as the attempt made it. committed := final committed.State, committed.Reason, committed.Phase, committed.OutcomePhase, committed.Askable = "", "", wire.OutcomeCommitted, outcome, false say(committed) return final }