| 1 | package wire |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "regexp" |
| 6 | "slices" |
| 7 | ) |
| 8 | |
| 9 | // Mac Engineering (Mac runners spec §8, slice F): Engineering placed on a |
| 10 | // Mac worker. Everything here is protocol 37 (ProtocolMacEngineering); |
| 11 | // Encode drops each field and refuses each frame and Engineering |
| 12 | // transfer below it (downgradeMacEngineering). |
| 13 | |
| 14 | // Frames. prepare_base asks the primary to resolve the base of an |
| 15 | // Engineering attempt placed on a worker (instance to primary); base is |
| 16 | // its answer (primary to instance). Both durable. |
| 17 | const ( |
| 18 | FramePrepareBase = "prepare_base" |
| 19 | FrameBase = "base" |
| 20 | ) |
| 21 | |
| 22 | // macEngineeringOnly are the frame types below ProtocolMacEngineering |
| 23 | // never carries (Speaks). |
| 24 | var macEngineeringOnly = map[string]bool{FramePrepareBase: true, FrameBase: true} |
| 25 | |
| 26 | // PrepareBaseCommand asks the primary to fetch and resolve the base an |
| 27 | // Engineering attempt on a worker starts from, exactly as it would for |
| 28 | // its own Engineering: the default branch's tip, or, for a rebase round |
| 29 | // (Rebase), the new tip that CandidateSHA (made on FromBase) goes on top |
| 30 | // of. The instance binds the reported SHA to the attempt before it |
| 31 | // dispatches to the worker. |
| 32 | type PrepareBaseCommand struct { |
| 33 | TaskID string `json:"task_id"` |
| 34 | StepID string `json:"step_id"` |
| 35 | Attempt int64 `json:"attempt"` |
| 36 | Repo string `json:"repo"` |
| 37 | Rebase bool `json:"rebase"` |
| 38 | FromBase string `json:"from_base"` |
| 39 | CandidateSHA string `json:"candidate_sha"` |
| 40 | } |
| 41 | |
| 42 | // Valid: a named attempt of a repository; a rebase names the commit it |
| 43 | // moves and the base it was made on, and a first step names neither. |
| 44 | func (c PrepareBaseCommand) Valid() bool { |
| 45 | if c.TaskID == "" || c.StepID == "" || c.Attempt < 1 || c.Repo == "" { |
| 46 | return false |
| 47 | } |
| 48 | if !c.Rebase { |
| 49 | return c.FromBase == "" && c.CandidateSHA == "" |
| 50 | } |
| 51 | return ValidCommitSHA(c.FromBase) && ValidCommitSHA(c.CandidateSHA) && c.FromBase != c.CandidateSHA |
| 52 | } |
| 53 | |
| 54 | // BaseReport is the primary's answer to prepare_base: the base it |
| 55 | // resolved, or ReasonBaseUnavailable (the fetch failed, or the default |
| 56 | // branch is unborn, which a worker never takes). |
| 57 | type BaseReport struct { |
| 58 | TaskID string `json:"task_id"` |
| 59 | StepID string `json:"step_id"` |
| 60 | Attempt int64 `json:"attempt"` |
| 61 | BaseSHA string `json:"base_sha"` |
| 62 | Reason string `json:"reason"` |
| 63 | } |
| 64 | |
| 65 | // Valid: exactly one of a commit SHA and base_unavailable. |
| 66 | func (r BaseReport) Valid() bool { |
| 67 | if r.TaskID == "" || r.StepID == "" || r.Attempt < 1 { |
| 68 | return false |
| 69 | } |
| 70 | if r.Reason == "" { |
| 71 | return ValidCommitSHA(r.BaseSHA) |
| 72 | } |
| 73 | return r.Reason == ReasonBaseUnavailable && r.BaseSHA == "" |
| 74 | } |
| 75 | |
| 76 | // Step reasons slice F adds. secret_in_candidate: the worker found one |
| 77 | // of its known secrets (or gitleaks did) in the candidate, so nothing |
| 78 | // was uploaded. workspace_too_large: the base's pack is over |
| 79 | // MaxTransferBytes, so Engineering cannot go to the Mac. engineering_ |
| 80 | // unavailable: the worker could not launch Engineering as certified (a |
| 81 | // settings check, the pinned CLI, the tool proxy). base_unavailable: the |
| 82 | // primary could not resolve the attempt's base. |
| 83 | // |
| 84 | // Each is in StepReasons, with its work.reason words pending copy review |
| 85 | // (plan task 15). |
| 86 | const ( |
| 87 | ReasonSecretInCandidate = "secret_in_candidate" |
| 88 | ReasonWorkspaceTooLarge = "workspace_too_large" |
| 89 | ReasonEngineeringUnavailable = "engineering_unavailable" |
| 90 | ReasonBaseUnavailable = "base_unavailable" |
| 91 | ) |
| 92 | |
| 93 | // XcodeAccessSandboxed (DispatchCommand.XcodeAccess, StepReport.XcodeAccess) |
| 94 | // gives Engineering's Bash sandbox the Mach services Xcode needs. "" is |
| 95 | // no Xcode access: the change is built and tested by Checks. |
| 96 | const XcodeAccessSandboxed = "sandboxed" |
| 97 | |
| 98 | // Outcome phases (StepReport.OutcomePhase, PublishCommand.OutcomePhase, |
| 99 | // PublishedReport.OutcomePhase): what a worker's commit is, kept apart |
| 100 | // from progress phases (StepReport.Phase): an ordinary candidate, work |
| 101 | // kept on step_timeout, or a fix round whose shell never worked. |
| 102 | const ( |
| 103 | OutcomeCommitted = "committed" |
| 104 | OutcomeUnfinished = "unfinished" |
| 105 | OutcomeNoShell = "no_shell" |
| 106 | ) |
| 107 | |
| 108 | // TransferKindEngineering is an inbound transfer carrying the commits an |
| 109 | // Engineering attempt on a worker starts from. "" is a checks transfer |
| 110 | // (or a worker's outbound commit) as before slice F. |
| 111 | const TransferKindEngineering = "engineering" |
| 112 | |
| 113 | // MaxTransferCommits bounds TransferHeader.Commits: base, old base and |
| 114 | // candidate. |
| 115 | const MaxTransferCommits = 3 |
| 116 | |
| 117 | var commitSHA = regexp.MustCompile(`^(?:[0-9a-f]{40}|[0-9a-f]{64})$`) |
| 118 | |
| 119 | // ValidCommitSHA is a full lowercase SHA-1 or SHA-256 object name. |
| 120 | func ValidCommitSHA(s string) bool { return commitSHA.MatchString(s) } |
| 121 | |
| 122 | // Commits is the list of commits the transfer's pack must yield, in |
| 123 | // order, de-duplicated and bounded by MaxTransferCommits: the candidate |
| 124 | // for a checks transfer or an outbound commit; for an Engineering |
| 125 | // transfer the base, then (a rebase round) the old base and the |
| 126 | // candidate. Empty fields are left out. |
| 127 | func (h TransferHeader) Commits() []string { |
| 128 | named := []string{h.CandidateSHA} |
| 129 | if h.Kind != "" { |
| 130 | named = []string{h.BaseSHA, h.OldBaseSHA, h.CandidateSHA} |
| 131 | } |
| 132 | out := make([]string, 0, MaxTransferCommits) |
| 133 | for _, c := range named { |
| 134 | if c != "" && !slices.Contains(out, c) { |
| 135 | out = append(out, c) |
| 136 | } |
| 137 | } |
| 138 | return out[:min(len(out), MaxTransferCommits)] |
| 139 | } |
| 140 | |
| 141 | // Valid checks the header's kind rules and every SHA it names. A checks |
| 142 | // transfer has a candidate (and its base, when known) and no old base. |
| 143 | // An Engineering transfer is inbound and has a base, and either nothing |
| 144 | // else (a first step or a fix round) or both an old base and a candidate |
| 145 | // (a rebase round). |
| 146 | func (h TransferHeader) Valid() bool { |
| 147 | switch h.Kind { |
| 148 | case "": |
| 149 | if h.OldBaseSHA != "" || h.CandidateSHA == "" || h.BaseSHA != "" && !ValidCommitSHA(h.BaseSHA) { |
| 150 | return false |
| 151 | } |
| 152 | case TransferKindEngineering: |
| 153 | if h.Direction != TransferInbound || h.BaseSHA == "" || (h.OldBaseSHA == "") != (h.CandidateSHA == "") { |
| 154 | return false |
| 155 | } |
| 156 | default: |
| 157 | return false |
| 158 | } |
| 159 | commits := h.Commits() |
| 160 | if len(commits) > MaxTransferCommits { |
| 161 | return false |
| 162 | } |
| 163 | for _, c := range commits { |
| 164 | if !ValidCommitSHA(c) { |
| 165 | return false |
| 166 | } |
| 167 | } |
| 168 | return true |
| 169 | } |
| 170 | |
| 171 | // engineeringTransfer: a header an older peer has no words for. |
| 172 | func (h TransferHeader) engineeringTransfer() bool { return h.Kind != "" || h.OldBaseSHA != "" } |
| 173 | |
| 174 | // EngineeringStatus is a Mac worker's word on whether it can take |
| 175 | // Engineering, beside its claude tag: ready, or the first thing missing. |
| 176 | // Reason is a short detail in the capability string rules ("" when |
| 177 | // ready). Busy is not a state: placement counts running steps. |
| 178 | type EngineeringStatus struct { |
| 179 | State string `json:"state"` |
| 180 | Reason string `json:"reason"` |
| 181 | } |
| 182 | |
| 183 | // Engineering states. |
| 184 | const ( |
| 185 | EngineeringReady = "ready" |
| 186 | EngineeringNoConnection = "no_connection" |
| 187 | EngineeringSignedOut = "signed_out" |
| 188 | EngineeringLimited = "limited" |
| 189 | EngineeringProbesPending = "probes_pending" |
| 190 | EngineeringProbesFailed = "probes_failed" |
| 191 | EngineeringCLIUnpinned = "cli_unpinned" |
| 192 | EngineeringHomeOpen = "home_open" |
| 193 | EngineeringTainted = "tainted" |
| 194 | ) |
| 195 | |
| 196 | // EngineeringStates is every Engineering state, ready first. |
| 197 | var EngineeringStates = []string{EngineeringReady, EngineeringNoConnection, EngineeringSignedOut, EngineeringLimited, EngineeringProbesPending, EngineeringProbesFailed, EngineeringCLIUnpinned, EngineeringHomeOpen, EngineeringTainted} |
| 198 | |
| 199 | // EngineeringProbeIDs are the shipped Engineering probes (plan task 14), |
| 200 | // reported in Capabilities.Probes beside P1 to P7. |
| 201 | var EngineeringProbeIDs = []string{"F1", "F2", "F3", "F4", "F5", "F6", "F7"} |
| 202 | |
| 203 | // engineeringProbeSuccess is each F probe's one success verdict. F4 (the |
| 204 | // process group ends and the proof holds) passes; the others prove that |
| 205 | // something was denied (network, reads, the token, Xcode's services, |
| 206 | // native tools, Xcode without access), so they report denied. |
| 207 | var engineeringProbeSuccess = map[string]string{ |
| 208 | "F1": ProbeDenied, |
| 209 | "F2": ProbeDenied, |
| 210 | "F3": ProbeDenied, |
| 211 | "F4": ProbePassed, |
| 212 | "F5": ProbeDenied, |
| 213 | "F6": ProbeDenied, |
| 214 | "F7": ProbeDenied, |
| 215 | } |
| 216 | |
| 217 | // EngineeringProbeSuccess is an F probe's success verdict, "" for any |
| 218 | // other ID. |
| 219 | func EngineeringProbeSuccess(id string) string { return engineeringProbeSuccess[id] } |
| 220 | |
| 221 | // validProbeVerdict: P probes as before (only P2 says denied); an F probe |
| 222 | // says its own success verdict or failed, skipped or unavailable. |
| 223 | func validProbeVerdict(id, verdict string) bool { |
| 224 | if !slices.Contains(probeVerdicts, verdict) { |
| 225 | return false |
| 226 | } |
| 227 | if success, ok := engineeringProbeSuccess[id]; ok { |
| 228 | return verdict == success || verdict != ProbePassed && verdict != ProbeDenied |
| 229 | } |
| 230 | return slices.Contains(ProbeIDs, id) && (verdict != ProbeDenied || id == "P2") |
| 231 | } |
| 232 | |
| 233 | // A checks step's SandboxChoice while it waits for a Mac's sandbox |
| 234 | // (Step.SandboxChoice): the creator may choose to run it outside, or may |
| 235 | // not because the Mac holds a model credential (D1, Paul 2026-11-28: |
| 236 | // once a Mac holds one, its checks run sandboxed or not at all). |
| 237 | const ( |
| 238 | SandboxChoiceOffered = "offered" |
| 239 | SandboxChoiceHeld = "credential_held" |
| 240 | ) |
| 241 | |
| 242 | // runnerUser is a macOS short name: what a Mac worker's runner user may |
| 243 | // be called. |
| 244 | var runnerUser = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_.-]{0,31}$`) |
| 245 | |
| 246 | // ValidRunnerUser reports whether name may be a Mac's runner user. |
| 247 | func ValidRunnerUser(name string) bool { return runnerUser.MatchString(name) } |
| 248 | |
| 249 | func validEngineeringStatus(s EngineeringStatus) bool { |
| 250 | return slices.Contains(EngineeringStates, s.State) && (s.State != EngineeringReady || s.Reason == "") |
| 251 | } |
| 252 | |
| 253 | // Placements slice F adds: waiting_mac_connection while a Mac fits all |
| 254 | // but claude (its EngineeringStatus says why); waiting_mac_update while |
| 255 | // the Mac or the primary speaks below ProtocolMacEngineering; |
| 256 | // waiting_base while the primary resolves the attempt's base. |
| 257 | const ( |
| 258 | PlacementMacConnection = "waiting_mac_connection" |
| 259 | PlacementMacUpdate = "waiting_mac_update" |
| 260 | PlacementBase = "waiting_base" |
| 261 | ) |
| 262 | |
| 263 | // Needs-you kinds slice F adds: a Mac fits Mac Engineering but has no |
| 264 | // usable Claude connection (mac_connection), or it or the primary needs |
| 265 | // an update (mac_update). |
| 266 | const ( |
| 267 | NeedsMacConnection = "mac_connection" |
| 268 | NeedsMacUpdate = "mac_update" |
| 269 | ) |
| 270 | |
| 271 | // WithoutMacEngineering drops a hello's Engineering status, Unproven, the |
| 272 | // credential hold, the runner user, the inventory mark, F probes and a Mac's claude tag |
| 273 | // (in new values; the caller's are untouched). The runner's first hello |
| 274 | // on a connection goes out before the welcome names the protocol, and an |
| 275 | // older instance's ValidCapabilities refuses an F probe; the runner sends |
| 276 | // them once the welcome says 37. It reports whether anything changed. |
| 277 | func WithoutMacEngineering(h *Hello) bool { |
| 278 | inventory := h.Inventory |
| 279 | h.Inventory = false |
| 280 | c := h.Capabilities |
| 281 | if c == nil { |
| 282 | return inventory |
| 283 | } |
| 284 | isF := func(p Probe) bool { _, ok := engineeringProbeSuccess[p.ID]; return ok } |
| 285 | // A slice F Mac (it says its Engineering status) says claude only at |
| 286 | // 37: an older instance would take it for a Mac that can run Claude. |
| 287 | macClaude := h.Platform != nil && h.Platform.OS == "darwin" && c.Engineering != nil && slices.Contains(c.Tags, TagClaude) |
| 288 | if c.Engineering == nil && c.Unproven == "" && c.UnprovenCount == 0 && !c.ModelHold && c.HoldingItems == nil && c.RunnerUser == "" && !slices.ContainsFunc(c.Probes, isF) && !macClaude { |
| 289 | return inventory |
| 290 | } |
| 291 | out := *c |
| 292 | out.Engineering, out.Unproven, out.UnprovenCount, out.ModelHold, out.HoldingItems, out.RunnerUser = nil, "", 0, false, nil, "" |
| 293 | if macClaude { |
| 294 | out.Tags = slices.DeleteFunc(slices.Clone(c.Tags), func(t string) bool { return t == TagClaude }) |
| 295 | } |
| 296 | if slices.ContainsFunc(c.Probes, isF) { |
| 297 | out.Probes = slices.DeleteFunc(slices.Clone(c.Probes), isF) |
| 298 | } |
| 299 | h.Capabilities = &out |
| 300 | return true |
| 301 | } |
| 302 | |
| 303 | // WithoutWorkerConnections is the instance's reading of a worker's |
| 304 | // hello: below ProtocolMacEngineering a worker holds no connections and |
| 305 | // no seal key, so any it sends are ignored (cleared in new values). A |
| 306 | // primary's hello is never passed here. It reports whether anything |
| 307 | // changed. |
| 308 | func WithoutWorkerConnections(h *Hello, protocol int) bool { |
| 309 | if protocol >= ProtocolMacEngineering || len(h.Connections) == 0 && h.SealKey == "" { |
| 310 | return false |
| 311 | } |
| 312 | h.Connections, h.SealKey = []HeldConnection{}, "" |
| 313 | return true |
| 314 | } |
| 315 | |
| 316 | // downgradeMacEngineering takes slice F out of what a peer below |
| 317 | // ProtocolMacEngineering is sent (the new frames never get this far: |
| 318 | // Speaks refuses them): an Engineering transfer and a diff upload bound |
| 319 | // to a publication are refused; every new field is dropped. A body that |
| 320 | // can carry a slice F key is always re-encoded (it reports true), so the |
| 321 | // key goes even when its value is empty, zero or null: every new field is |
| 322 | // omitempty, and an older peer's strict decoder refuses the key itself. |
| 323 | func downgradeMacEngineering(body any, protocol int) (bool, error) { |
| 324 | refuse := func(what string) (bool, error) { |
| 325 | return false, fmt.Errorf("%w: %s at protocol %d", ErrProtocol, what, protocol) |
| 326 | } |
| 327 | switch v := body.(type) { |
| 328 | case *Blob: |
| 329 | if v.Transfer.engineeringTransfer() { |
| 330 | return refuse("an Engineering transfer") |
| 331 | } |
| 332 | case *SendPackCommand: |
| 333 | if v.Transfer.engineeringTransfer() { |
| 334 | return refuse("an Engineering transfer") |
| 335 | } |
| 336 | case *ChangeDiffUpload: |
| 337 | if v.Publication != "" { |
| 338 | return refuse("a publication's diff") |
| 339 | } |
| 340 | case *Hello: |
| 341 | WithoutMacEngineering(v) |
| 342 | case *DispatchCommand: |
| 343 | v.XcodeAccess = "" |
| 344 | case *StepReport: |
| 345 | v.XcodeAccess, v.SessionID, v.OutcomePhase = "", "", "" |
| 346 | case *PublishCommand: |
| 347 | v.OutcomePhase = "" |
| 348 | case *PublishedReport: |
| 349 | v.ChangeFiles, v.DiffCollection, v.OutcomePhase = nil, "", "" |
| 350 | case *AskCommand: |
| 351 | v.EngAttempt, v.EngAccount, v.EngSession = 0, "", "" |
| 352 | case *DisconnectCommand: |
| 353 | v.RunnerID = "" |
| 354 | default: |
| 355 | return false, nil |
| 356 | } |
| 357 | return true, nil |
| 358 | } |
| 359 | |