package wire import ( "fmt" "regexp" "slices" ) // Mac Engineering (Mac runners spec ยง8, slice F): Engineering placed on a // Mac worker. Everything here is protocol 37 (ProtocolMacEngineering); // Encode drops each field and refuses each frame and Engineering // transfer below it (downgradeMacEngineering). // Frames. prepare_base asks the primary to resolve the base of an // Engineering attempt placed on a worker (instance to primary); base is // its answer (primary to instance). Both durable. const ( FramePrepareBase = "prepare_base" FrameBase = "base" ) // macEngineeringOnly are the frame types below ProtocolMacEngineering // never carries (Speaks). var macEngineeringOnly = map[string]bool{FramePrepareBase: true, FrameBase: true} // PrepareBaseCommand asks the primary to fetch and resolve the base an // Engineering attempt on a worker starts from, exactly as it would for // its own Engineering: the default branch's tip, or, for a rebase round // (Rebase), the new tip that CandidateSHA (made on FromBase) goes on top // of. The instance binds the reported SHA to the attempt before it // dispatches to the worker. type PrepareBaseCommand struct { TaskID string `json:"task_id"` StepID string `json:"step_id"` Attempt int64 `json:"attempt"` Repo string `json:"repo"` Rebase bool `json:"rebase"` FromBase string `json:"from_base"` CandidateSHA string `json:"candidate_sha"` } // Valid: a named attempt of a repository; a rebase names the commit it // moves and the base it was made on, and a first step names neither. func (c PrepareBaseCommand) Valid() bool { if c.TaskID == "" || c.StepID == "" || c.Attempt < 1 || c.Repo == "" { return false } if !c.Rebase { return c.FromBase == "" && c.CandidateSHA == "" } return ValidCommitSHA(c.FromBase) && ValidCommitSHA(c.CandidateSHA) && c.FromBase != c.CandidateSHA } // BaseReport is the primary's answer to prepare_base: the base it // resolved, or ReasonBaseUnavailable (the fetch failed, or the default // branch is unborn, which a worker never takes). type BaseReport struct { TaskID string `json:"task_id"` StepID string `json:"step_id"` Attempt int64 `json:"attempt"` BaseSHA string `json:"base_sha"` Reason string `json:"reason"` } // Valid: exactly one of a commit SHA and base_unavailable. func (r BaseReport) Valid() bool { if r.TaskID == "" || r.StepID == "" || r.Attempt < 1 { return false } if r.Reason == "" { return ValidCommitSHA(r.BaseSHA) } return r.Reason == ReasonBaseUnavailable && r.BaseSHA == "" } // Step reasons slice F adds. secret_in_candidate: the worker found one // of its known secrets (or gitleaks did) in the candidate, so nothing // was uploaded. workspace_too_large: the base's pack is over // MaxTransferBytes, so Engineering cannot go to the Mac. engineering_ // unavailable: the worker could not launch Engineering as certified (a // settings check, the pinned CLI, the tool proxy). base_unavailable: the // primary could not resolve the attempt's base. // // Each is in StepReasons, with its work.reason words pending copy review // (plan task 15). const ( ReasonSecretInCandidate = "secret_in_candidate" ReasonWorkspaceTooLarge = "workspace_too_large" ReasonEngineeringUnavailable = "engineering_unavailable" ReasonBaseUnavailable = "base_unavailable" ) // XcodeAccessSandboxed (DispatchCommand.XcodeAccess, StepReport.XcodeAccess) // gives Engineering's Bash sandbox the Mach services Xcode needs. "" is // no Xcode access: the change is built and tested by Checks. const XcodeAccessSandboxed = "sandboxed" // Outcome phases (StepReport.OutcomePhase, PublishCommand.OutcomePhase, // PublishedReport.OutcomePhase): what a worker's commit is, kept apart // from progress phases (StepReport.Phase): an ordinary candidate, work // kept on step_timeout, or a fix round whose shell never worked. const ( OutcomeCommitted = "committed" OutcomeUnfinished = "unfinished" OutcomeNoShell = "no_shell" ) // TransferKindEngineering is an inbound transfer carrying the commits an // Engineering attempt on a worker starts from. "" is a checks transfer // (or a worker's outbound commit) as before slice F. const TransferKindEngineering = "engineering" // MaxTransferCommits bounds TransferHeader.Commits: base, old base and // candidate. const MaxTransferCommits = 3 var commitSHA = regexp.MustCompile(`^(?:[0-9a-f]{40}|[0-9a-f]{64})$`) // ValidCommitSHA is a full lowercase SHA-1 or SHA-256 object name. func ValidCommitSHA(s string) bool { return commitSHA.MatchString(s) } // Commits is the list of commits the transfer's pack must yield, in // order, de-duplicated and bounded by MaxTransferCommits: the candidate // for a checks transfer or an outbound commit; for an Engineering // transfer the base, then (a rebase round) the old base and the // candidate. Empty fields are left out. func (h TransferHeader) Commits() []string { named := []string{h.CandidateSHA} if h.Kind != "" { named = []string{h.BaseSHA, h.OldBaseSHA, h.CandidateSHA} } out := make([]string, 0, MaxTransferCommits) for _, c := range named { if c != "" && !slices.Contains(out, c) { out = append(out, c) } } return out[:min(len(out), MaxTransferCommits)] } // Valid checks the header's kind rules and every SHA it names. A checks // transfer has a candidate (and its base, when known) and no old base. // An Engineering transfer is inbound and has a base, and either nothing // else (a first step or a fix round) or both an old base and a candidate // (a rebase round). func (h TransferHeader) Valid() bool { switch h.Kind { case "": if h.OldBaseSHA != "" || h.CandidateSHA == "" || h.BaseSHA != "" && !ValidCommitSHA(h.BaseSHA) { return false } case TransferKindEngineering: if h.Direction != TransferInbound || h.BaseSHA == "" || (h.OldBaseSHA == "") != (h.CandidateSHA == "") { return false } default: return false } commits := h.Commits() if len(commits) > MaxTransferCommits { return false } for _, c := range commits { if !ValidCommitSHA(c) { return false } } return true } // engineeringTransfer: a header an older peer has no words for. func (h TransferHeader) engineeringTransfer() bool { return h.Kind != "" || h.OldBaseSHA != "" } // EngineeringStatus is a Mac worker's word on whether it can take // Engineering, beside its claude tag: ready, or the first thing missing. // Reason is a short detail in the capability string rules ("" when // ready). Busy is not a state: placement counts running steps. type EngineeringStatus struct { State string `json:"state"` Reason string `json:"reason"` } // Engineering states. const ( EngineeringReady = "ready" EngineeringNoConnection = "no_connection" EngineeringSignedOut = "signed_out" EngineeringLimited = "limited" EngineeringProbesPending = "probes_pending" EngineeringProbesFailed = "probes_failed" EngineeringCLIUnpinned = "cli_unpinned" EngineeringHomeOpen = "home_open" EngineeringTainted = "tainted" ) // EngineeringStates is every Engineering state, ready first. var EngineeringStates = []string{EngineeringReady, EngineeringNoConnection, EngineeringSignedOut, EngineeringLimited, EngineeringProbesPending, EngineeringProbesFailed, EngineeringCLIUnpinned, EngineeringHomeOpen, EngineeringTainted} // EngineeringProbeIDs are the shipped Engineering probes (plan task 14), // reported in Capabilities.Probes beside P1 to P7. var EngineeringProbeIDs = []string{"F1", "F2", "F3", "F4", "F5", "F6", "F7"} // engineeringProbeSuccess is each F probe's one success verdict. F4 (the // process group ends and the proof holds) passes; the others prove that // something was denied (network, reads, the token, Xcode's services, // native tools, Xcode without access), so they report denied. var engineeringProbeSuccess = map[string]string{ "F1": ProbeDenied, "F2": ProbeDenied, "F3": ProbeDenied, "F4": ProbePassed, "F5": ProbeDenied, "F6": ProbeDenied, "F7": ProbeDenied, } // EngineeringProbeSuccess is an F probe's success verdict, "" for any // other ID. func EngineeringProbeSuccess(id string) string { return engineeringProbeSuccess[id] } // validProbeVerdict: P probes as before (only P2 says denied); an F probe // says its own success verdict or failed, skipped or unavailable. func validProbeVerdict(id, verdict string) bool { if !slices.Contains(probeVerdicts, verdict) { return false } if success, ok := engineeringProbeSuccess[id]; ok { return verdict == success || verdict != ProbePassed && verdict != ProbeDenied } return slices.Contains(ProbeIDs, id) && (verdict != ProbeDenied || id == "P2") } // A checks step's SandboxChoice while it waits for a Mac's sandbox // (Step.SandboxChoice): the creator may choose to run it outside, or may // not because the Mac holds a model credential (D1, Paul 2026-11-28: // once a Mac holds one, its checks run sandboxed or not at all). const ( SandboxChoiceOffered = "offered" SandboxChoiceHeld = "credential_held" ) // runnerUser is a macOS short name: what a Mac worker's runner user may // be called. var runnerUser = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_.-]{0,31}$`) // ValidRunnerUser reports whether name may be a Mac's runner user. func ValidRunnerUser(name string) bool { return runnerUser.MatchString(name) } func validEngineeringStatus(s EngineeringStatus) bool { return slices.Contains(EngineeringStates, s.State) && (s.State != EngineeringReady || s.Reason == "") } // Placements slice F adds: waiting_mac_connection while a Mac fits all // but claude (its EngineeringStatus says why); waiting_mac_update while // the Mac or the primary speaks below ProtocolMacEngineering; // waiting_base while the primary resolves the attempt's base. const ( PlacementMacConnection = "waiting_mac_connection" PlacementMacUpdate = "waiting_mac_update" PlacementBase = "waiting_base" ) // Needs-you kinds slice F adds: a Mac fits Mac Engineering but has no // usable Claude connection (mac_connection), or it or the primary needs // an update (mac_update). const ( NeedsMacConnection = "mac_connection" NeedsMacUpdate = "mac_update" ) // WithoutMacEngineering drops a hello's Engineering status, Unproven, the // credential hold, the runner user, the inventory mark, F probes and a Mac's claude tag // (in new values; the caller's are untouched). The runner's first hello // on a connection goes out before the welcome names the protocol, and an // older instance's ValidCapabilities refuses an F probe; the runner sends // them once the welcome says 37. It reports whether anything changed. func WithoutMacEngineering(h *Hello) bool { inventory := h.Inventory h.Inventory = false c := h.Capabilities if c == nil { return inventory } isF := func(p Probe) bool { _, ok := engineeringProbeSuccess[p.ID]; return ok } // A slice F Mac (it says its Engineering status) says claude only at // 37: an older instance would take it for a Mac that can run Claude. macClaude := h.Platform != nil && h.Platform.OS == "darwin" && c.Engineering != nil && slices.Contains(c.Tags, TagClaude) if c.Engineering == nil && c.Unproven == "" && c.UnprovenCount == 0 && !c.ModelHold && c.HoldingItems == nil && c.RunnerUser == "" && !slices.ContainsFunc(c.Probes, isF) && !macClaude { return inventory } out := *c out.Engineering, out.Unproven, out.UnprovenCount, out.ModelHold, out.HoldingItems, out.RunnerUser = nil, "", 0, false, nil, "" if macClaude { out.Tags = slices.DeleteFunc(slices.Clone(c.Tags), func(t string) bool { return t == TagClaude }) } if slices.ContainsFunc(c.Probes, isF) { out.Probes = slices.DeleteFunc(slices.Clone(c.Probes), isF) } h.Capabilities = &out return true } // WithoutWorkerConnections is the instance's reading of a worker's // hello: below ProtocolMacEngineering a worker holds no connections and // no seal key, so any it sends are ignored (cleared in new values). A // primary's hello is never passed here. It reports whether anything // changed. func WithoutWorkerConnections(h *Hello, protocol int) bool { if protocol >= ProtocolMacEngineering || len(h.Connections) == 0 && h.SealKey == "" { return false } h.Connections, h.SealKey = []HeldConnection{}, "" return true } // downgradeMacEngineering takes slice F out of what a peer below // ProtocolMacEngineering is sent (the new frames never get this far: // Speaks refuses them): an Engineering transfer and a diff upload bound // to a publication are refused; every new field is dropped. A body that // can carry a slice F key is always re-encoded (it reports true), so the // key goes even when its value is empty, zero or null: every new field is // omitempty, and an older peer's strict decoder refuses the key itself. func downgradeMacEngineering(body any, protocol int) (bool, error) { refuse := func(what string) (bool, error) { return false, fmt.Errorf("%w: %s at protocol %d", ErrProtocol, what, protocol) } switch v := body.(type) { case *Blob: if v.Transfer.engineeringTransfer() { return refuse("an Engineering transfer") } case *SendPackCommand: if v.Transfer.engineeringTransfer() { return refuse("an Engineering transfer") } case *ChangeDiffUpload: if v.Publication != "" { return refuse("a publication's diff") } case *Hello: WithoutMacEngineering(v) case *DispatchCommand: v.XcodeAccess = "" case *StepReport: v.XcodeAccess, v.SessionID, v.OutcomePhase = "", "", "" case *PublishCommand: v.OutcomePhase = "" case *PublishedReport: v.ChangeFiles, v.DiffCollection, v.OutcomePhase = nil, "", "" case *AskCommand: v.EngAttempt, v.EngAccount, v.EngSession = 0, "", "" case *DisconnectCommand: v.RunnerID = "" default: return false, nil } return true, nil }