| 1 | package thin |
| 2 | |
| 3 | import ( |
| 4 | "amadan.net/oficina/equipo/internal/wire/forgekey" |
| 5 | "context" |
| 6 | "errors" |
| 7 | "os/exec" |
| 8 | "path/filepath" |
| 9 | "slices" |
| 10 | "strings" |
| 11 | "time" |
| 12 | |
| 13 | "amadan.net/oficina/equipo/internal/runner/forge" |
| 14 | "amadan.net/oficina/equipo/internal/runner/workspace" |
| 15 | "amadan.net/oficina/equipo/internal/runnerproto" |
| 16 | "amadan.net/oficina/equipo/internal/wire" |
| 17 | ) |
| 18 | |
| 19 | // The coordinator's side merges a task once it has earned it (Paul, |
| 20 | // 2026-11-07, overruling "Equipo never merges"): the instance dispatches a |
| 21 | // merge step for the judged SHA, and the person's runner, the only holder |
| 22 | // of the Amadan credential, merges it through forge. Forge reads the |
| 23 | // remote first (the branch must still be at the judged SHA; a SHA already |
| 24 | // on the default branch is done), records its intent, confirms the lease |
| 25 | // and asks the hub, whose instance compares the SHA again under its git |
| 26 | // lock. A lost answer or a crash is settled from the default branch, |
| 27 | // never by asking twice blind. |
| 28 | |
| 29 | // Merge step bounds: how often an uncertain outcome is tried again, and |
| 30 | // how long the hub's own CI on the commit is waited for (the repository |
| 31 | // may require it green before a merge), polled every mergeCIPoll with the |
| 32 | // attempt deferred in between, so other work runs meanwhile. |
| 33 | var ( |
| 34 | mergeAttempts = 3 |
| 35 | mergeBackoff = 3 * time.Second |
| 36 | mergeCIWait = 10 * time.Minute |
| 37 | mergeCIPoll = 15 * time.Second |
| 38 | // mergeHubWait: how long a merge waits, deferred, for the hub to |
| 39 | // confirm write access again (workspace.ErrHubUnavailable). |
| 40 | mergeHubWait = 10 * time.Minute |
| 41 | ) |
| 42 | |
| 43 | // MergeAgentHarness names the runner to the hub in the merge's agent block. |
| 44 | const MergeAgentHarness = "equipo" |
| 45 | |
| 46 | // mergeStep merges r.CandidateSHA into the default branch. |
| 47 | func (e *Engineer) mergeStep(ctx context.Context, r stepRow, progress func(wire.StepReport)) wire.StepReport { |
| 48 | rep := wire.StepReport{TaskID: r.TaskID, StepID: r.StepID, Attempt: r.Attempt, BaseSHA: r.BaseSHA, CandidateSHA: r.CandidateSHA, Findings: []wire.Finding{}, Termination: true} |
| 49 | fail := func(reason string) wire.StepReport { |
| 50 | rep.State, rep.Reason = wire.StepFailed, reason |
| 51 | return rep |
| 52 | } |
| 53 | if !slices.Contains(e.Owners, r.Person) || !forgekey.ValidHub(r.Repo) || !wire.ValidTaskBranch(r.Branch) || !shaPattern.MatchString(r.CandidateSHA) { |
| 54 | return fail("policy_rejected") |
| 55 | } |
| 56 | if err := e.lease(ctx, r); err != nil { |
| 57 | if errors.Is(err, ErrMergeNotAuthorized) { |
| 58 | return fail("merge_not_authorized") |
| 59 | } |
| 60 | rep.State, rep.Reason = wire.StepCancelled, leaseReason(err) |
| 61 | return rep |
| 62 | } |
| 63 | progress(rep) |
| 64 | // Merge authority: right before every hub request the instance decides |
| 65 | // again; a refusal means nothing is sent and the step ends. |
| 66 | confirm := e.confirmFor(r) |
| 67 | if e.ConfirmMerge != nil { |
| 68 | confirm = func(ctx context.Context) error { return e.ConfirmMerge(ctx, r.StepID, r.Attempt) } |
| 69 | } |
| 70 | var maskDetail string |
| 71 | notAuthorized := false |
| 72 | confirmMerge := func(ctx context.Context) error { |
| 73 | if maskDetail = e.mergeSandboxDetail(ctx, r); maskDetail != "" { |
| 74 | return forge.ErrMergeRefused |
| 75 | } |
| 76 | err := confirm(ctx) |
| 77 | if errors.Is(err, ErrMergeNotAuthorized) { |
| 78 | notAuthorized = true |
| 79 | } |
| 80 | return err |
| 81 | } |
| 82 | host := e.Host |
| 83 | if host == "" { |
| 84 | host = "runner" |
| 85 | } |
| 86 | m := forge.BranchMerge{Root: filepath.Join(e.root(), "merge"), Repo: r.Repo, Branch: r.Branch, Commit: r.CandidateSHA, Task: r.TaskID, Message: clip(r.Title, wire.MaxTaskTitle), Strategy: wire.MergeCommit, |
| 87 | Agent: forge.AgentMeta{Session: "equipo-" + r.TaskID, Harness: MergeAgentHarness, Host: clip(host, 120)}, |
| 88 | Person: r.Person, Owners: e.Owners, |
| 89 | Inspect: func(ctx context.Context) (forge.RemoteState, error) { |
| 90 | st, err := e.inspectMerge(ctx, r.Repo, r.Branch, r.CandidateSHA) |
| 91 | // Forge counts it as uncertain; the log says what failed. |
| 92 | e.log("merge inspect", err) |
| 93 | return st, err |
| 94 | }, |
| 95 | Request: func(ctx context.Context, req forge.MergeRequest) (forge.MergeResult, error) { |
| 96 | return e.Forge.Merge(ctx, r.Repo, r.Branch, req) |
| 97 | }, |
| 98 | Confirm: confirmMerge} |
| 99 | if p, ok := e.Forge.(mergePreflighter); ok { |
| 100 | // No credential for the repository (the inspection needs it too): |
| 101 | // refused here, before anything is read or sent. |
| 102 | m.Preflight = func(ctx context.Context) error { return p.MergePreflight(ctx, r.Repo) } |
| 103 | } |
| 104 | // Once the request may be with the hub, a cancel never stops the |
| 105 | // merge from being settled: the forge calls outlive the step's context |
| 106 | // (the instance refuses cancels while merging; shutdown keeps the |
| 107 | // attempt held and it runs again). |
| 108 | mctx := context.WithoutCancel(ctx) |
| 109 | var out forge.MergeOutcome |
| 110 | var err error |
| 111 | for uncertain := 0; ; uncertain++ { |
| 112 | cctx, cancel := context.WithTimeout(mctx, 3*time.Minute) |
| 113 | out, err = forge.MergeBranch(cctx, m) |
| 114 | cancel() |
| 115 | // Tried again: an outcome the hub may have acted on, and a hub that |
| 116 | // could not confirm write access. Any other refusal made here |
| 117 | // before contacting it (forge.NotSentError) ends the step. |
| 118 | again := errors.Is(err, forge.ErrMergeUncertain) || errors.Is(err, workspace.ErrHubUnavailable) |
| 119 | if maskDetail != "" || notAuthorized || !again || uncertain+1 >= mergeAttempts { |
| 120 | break |
| 121 | } |
| 122 | time.Sleep(time.Duration(uncertain+1) * mergeBackoff) |
| 123 | } |
| 124 | // Why it did not merge, for the person (the stopped step's log tail): |
| 125 | // the hub's status, code and message, or the error's words. |
| 126 | if maskDetail != "" { |
| 127 | rep.LogTail = runnerproto.RedactDetail(maskDetail, runnerproto.DetailLimit) |
| 128 | return fail("policy_rejected") |
| 129 | } |
| 130 | rep.LogTail = forge.MergeDetail(err) |
| 131 | if notAuthorized && err != nil { |
| 132 | return fail("merge_not_authorized") |
| 133 | } |
| 134 | if errors.Is(err, forge.ErrMergeCIPending) { |
| 135 | // The hub's own CI is still running: held for later, releasing |
| 136 | // the queue, and run afresh then (lease, owner, judged SHA). |
| 137 | since := e.O.State.deferredSince(mctx, r) |
| 138 | if since.IsZero() || time.Since(since) < mergeCIWait { |
| 139 | rep.State = stepDeferred |
| 140 | return rep |
| 141 | } |
| 142 | } |
| 143 | if errors.Is(err, workspace.ErrHubUnavailable) { |
| 144 | // Nothing was sent: held for later, releasing the queue, until the |
| 145 | // hub answers or the wait is over. |
| 146 | e.logDetail("merge", err) |
| 147 | since := e.O.State.deferredSince(mctx, r) |
| 148 | if since.IsZero() || time.Since(since) < mergeHubWait { |
| 149 | rep.State = stepDeferred |
| 150 | return rep |
| 151 | } |
| 152 | return fail(wire.ReasonAmadanUnreachable) |
| 153 | } |
| 154 | switch { |
| 155 | case err == nil: |
| 156 | // Done: the merge watch for this candidate ends here, so only this |
| 157 | // report says it landed (with the commit and how). |
| 158 | e.logDetail("merge watch", e.O.State.endWatch(context.WithoutCancel(ctx), r.TaskID, r.CandidateSHA)) |
| 159 | rep.State, rep.MergeSHA, rep.Into, rep.Strategy = wire.StepDone, out.SHA, out.Into, out.Strategy |
| 160 | // Where the SHA came from, and its parents when the hub said it: the |
| 161 | // instance offers Undo only for a merge commit the hub named whose |
| 162 | // second parent is the candidate. |
| 163 | rep.MergeSource = out.Source |
| 164 | if out.Source == forge.SourceHub { |
| 165 | rep.MergeParents = e.mergeParents(mctx, r.Repo, out.SHA) |
| 166 | } |
| 167 | if e.Merged != nil { |
| 168 | // The default branch moved (or was born): the index reads it |
| 169 | // again now, not at the hourly refresh. |
| 170 | e.Merged(r.Repo) |
| 171 | } |
| 172 | return rep |
| 173 | case errors.Is(err, forge.ErrMergeConflict): |
| 174 | return fail("merge_conflict") |
| 175 | case errors.Is(err, forge.ErrMergeMoved): |
| 176 | return fail("branch_moved") |
| 177 | case errors.Is(err, forge.ErrMergeCIPending): |
| 178 | return fail("amadan_ci_pending") |
| 179 | case errors.Is(err, forge.ErrMergeCIFailed): |
| 180 | return fail("amadan_ci_failed") |
| 181 | case errors.Is(err, forge.ErrMergeForbidden): |
| 182 | return fail("merge_forbidden") |
| 183 | case errors.Is(err, forge.ErrMergeUnbornDefault): |
| 184 | return fail(wire.ReasonMergeUnbornDefault) |
| 185 | case errors.Is(err, forge.ErrMergeNoCredential): |
| 186 | // Refused on this runner before the hub was contacted: no |
| 187 | // credential serves the repository. The log tail names it. |
| 188 | e.logDetail("merge", err) |
| 189 | return fail(wire.ReasonMergeCredential) |
| 190 | case errors.Is(err, forge.ErrMergeRefused): |
| 191 | return fail("policy_rejected") |
| 192 | } |
| 193 | e.logDetail("merge", err) |
| 194 | return fail("merge_failed") |
| 195 | } |
| 196 | |
| 197 | // mergeParents reads a merge commit's parents from the fetched clone, |
| 198 | // nil when it cannot. |
| 199 | func (e *Engineer) mergeParents(ctx context.Context, repo, sha string) []string { |
| 200 | if !shaPattern.MatchString(sha) { |
| 201 | return nil |
| 202 | } |
| 203 | cctx, cancel := context.WithTimeout(ctx, fetchTimeout) |
| 204 | defer cancel() |
| 205 | if err := e.fetch(cctx, repo); err != nil { |
| 206 | return nil |
| 207 | } |
| 208 | cmd := exec.CommandContext(cctx, e.O.Runner.GitPath, "--git-dir="+e.Clones.Path(repo), "rev-list", "--parents", "-n", "1", "--end-of-options", sha) |
| 209 | env := workspace.GitEnvironment() |
| 210 | env["HOME"] = "/nonexistent" |
| 211 | for k, v := range env { |
| 212 | cmd.Env = append(cmd.Env, k+"="+v) |
| 213 | } |
| 214 | out, clipped, err := boundedOutput(cmd, 4096) |
| 215 | if err != nil || clipped { |
| 216 | return nil |
| 217 | } |
| 218 | f := strings.Fields(string(out)) |
| 219 | if len(f) < 2 || f[0] != sha { |
| 220 | return nil |
| 221 | } |
| 222 | for _, p := range f[1:] { |
| 223 | if !shaPattern.MatchString(p) { |
| 224 | return nil |
| 225 | } |
| 226 | } |
| 227 | return f[1:] |
| 228 | } |
| 229 | |
| 230 | // inspectMerge reads the repository for a merge: the task branch's head |
| 231 | // and the default branch's tip (one ls-remote), and, fetching only when |
| 232 | // the tip is not here yet, whether commit is on the default branch and |
| 233 | // which commit there brought it in. |
| 234 | func (e *Engineer) inspectMerge(ctx context.Context, repo, branch, commit string) (forge.RemoteState, error) { |
| 235 | cctx, cancel := context.WithTimeout(ctx, fetchTimeout) |
| 236 | defer cancel() |
| 237 | def, tip, heads, err := e.Clones.Heads(cctx, repo, []string{branch}) |
| 238 | if errors.Is(err, ErrEmptyRepo) { |
| 239 | // The default branch is unborn: nothing has landed, and the first |
| 240 | // merge creates it. |
| 241 | return forge.RemoteState{Head: heads[branch], Default: def, Unborn: true}, nil |
| 242 | } |
| 243 | if err != nil { |
| 244 | return forge.RemoteState{}, err |
| 245 | } |
| 246 | st := forge.RemoteState{Head: heads[branch], Default: def, Tip: tip} |
| 247 | if tip == commit { |
| 248 | st.Landed, st.MergeSHA = true, commit |
| 249 | return st, nil |
| 250 | } |
| 251 | git := func(args ...string) (string, error) { |
| 252 | cmd := exec.CommandContext(cctx, e.O.Runner.GitPath, append([]string{"--git-dir=" + e.Clones.Path(repo)}, args...)...) |
| 253 | env := workspace.GitEnvironment() |
| 254 | env["HOME"] = "/nonexistent" |
| 255 | for k, v := range env { |
| 256 | cmd.Env = append(cmd.Env, k+"="+v) |
| 257 | } |
| 258 | out, clipped, err := boundedOutput(cmd, 1<<20) |
| 259 | if clipped { |
| 260 | return "", errors.New("output too large") |
| 261 | } |
| 262 | return strings.TrimSpace(string(out)), err |
| 263 | } |
| 264 | if _, err := git("cat-file", "-e", tip+"^{commit}"); err != nil { |
| 265 | if err := e.fetch(cctx, repo); err != nil { |
| 266 | return forge.RemoteState{}, err |
| 267 | } |
| 268 | } |
| 269 | if _, err := git("cat-file", "-e", commit+"^{commit}"); err != nil { |
| 270 | // Not here even after a fetch: not on the default branch. |
| 271 | if _, terr := git("cat-file", "-e", tip+"^{commit}"); terr != nil { |
| 272 | return forge.RemoteState{}, terr |
| 273 | } |
| 274 | return st, nil |
| 275 | } |
| 276 | if _, err := git("merge-base", "--is-ancestor", commit, tip); err != nil { |
| 277 | var exit *exec.ExitError |
| 278 | if errors.As(err, &exit) && exit.ExitCode() == 1 { |
| 279 | return st, nil |
| 280 | } |
| 281 | return forge.RemoteState{}, err |
| 282 | } |
| 283 | st.Landed, st.MergeSHA = true, tip |
| 284 | // The commit on the default branch that brought it in: a merge whose |
| 285 | // other parent it is, or the commit itself on the first-parent line. |
| 286 | if out, err := git("rev-list", "--first-parent", "--parents", "-n", "200", tip); err == nil { |
| 287 | for _, line := range strings.Split(out, "\n") { |
| 288 | f := strings.Fields(line) |
| 289 | if len(f) > 0 && (f[0] == commit || slices.Contains(f[min(len(f), 2):], commit)) { |
| 290 | st.MergeSHA = f[0] |
| 291 | break |
| 292 | } |
| 293 | } |
| 294 | } |
| 295 | return st, nil |
| 296 | } |
| 297 | |