package thin import ( "amadan.net/oficina/equipo/internal/wire/forgekey" "context" "errors" "os/exec" "path/filepath" "slices" "strings" "time" "amadan.net/oficina/equipo/internal/runner/forge" "amadan.net/oficina/equipo/internal/runner/workspace" "amadan.net/oficina/equipo/internal/runnerproto" "amadan.net/oficina/equipo/internal/wire" ) // The coordinator's side merges a task once it has earned it (Paul, // 2026-11-07, overruling "Equipo never merges"): the instance dispatches a // merge step for the judged SHA, and the person's runner, the only holder // of the Amadan credential, merges it through forge. Forge reads the // remote first (the branch must still be at the judged SHA; a SHA already // on the default branch is done), records its intent, confirms the lease // and asks the hub, whose instance compares the SHA again under its git // lock. A lost answer or a crash is settled from the default branch, // never by asking twice blind. // Merge step bounds: how often an uncertain outcome is tried again, and // how long the hub's own CI on the commit is waited for (the repository // may require it green before a merge), polled every mergeCIPoll with the // attempt deferred in between, so other work runs meanwhile. var ( mergeAttempts = 3 mergeBackoff = 3 * time.Second mergeCIWait = 10 * time.Minute mergeCIPoll = 15 * time.Second // mergeHubWait: how long a merge waits, deferred, for the hub to // confirm write access again (workspace.ErrHubUnavailable). mergeHubWait = 10 * time.Minute ) // MergeAgentHarness names the runner to the hub in the merge's agent block. const MergeAgentHarness = "equipo" // mergeStep merges r.CandidateSHA into the default branch. func (e *Engineer) mergeStep(ctx context.Context, r stepRow, progress func(wire.StepReport)) wire.StepReport { rep := wire.StepReport{TaskID: r.TaskID, StepID: r.StepID, Attempt: r.Attempt, BaseSHA: r.BaseSHA, CandidateSHA: r.CandidateSHA, Findings: []wire.Finding{}, Termination: true} fail := func(reason string) wire.StepReport { rep.State, rep.Reason = wire.StepFailed, reason return rep } if !slices.Contains(e.Owners, r.Person) || !forgekey.ValidHub(r.Repo) || !wire.ValidTaskBranch(r.Branch) || !shaPattern.MatchString(r.CandidateSHA) { return fail("policy_rejected") } if err := e.lease(ctx, r); err != nil { if errors.Is(err, ErrMergeNotAuthorized) { return fail("merge_not_authorized") } rep.State, rep.Reason = wire.StepCancelled, leaseReason(err) return rep } progress(rep) // Merge authority: right before every hub request the instance decides // again; a refusal means nothing is sent and the step ends. confirm := e.confirmFor(r) if e.ConfirmMerge != nil { confirm = func(ctx context.Context) error { return e.ConfirmMerge(ctx, r.StepID, r.Attempt) } } var maskDetail string notAuthorized := false confirmMerge := func(ctx context.Context) error { if maskDetail = e.mergeSandboxDetail(ctx, r); maskDetail != "" { return forge.ErrMergeRefused } err := confirm(ctx) if errors.Is(err, ErrMergeNotAuthorized) { notAuthorized = true } return err } host := e.Host if host == "" { host = "runner" } 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, Agent: forge.AgentMeta{Session: "equipo-" + r.TaskID, Harness: MergeAgentHarness, Host: clip(host, 120)}, Person: r.Person, Owners: e.Owners, Inspect: func(ctx context.Context) (forge.RemoteState, error) { st, err := e.inspectMerge(ctx, r.Repo, r.Branch, r.CandidateSHA) // Forge counts it as uncertain; the log says what failed. e.log("merge inspect", err) return st, err }, Request: func(ctx context.Context, req forge.MergeRequest) (forge.MergeResult, error) { return e.Forge.Merge(ctx, r.Repo, r.Branch, req) }, Confirm: confirmMerge} if p, ok := e.Forge.(mergePreflighter); ok { // No credential for the repository (the inspection needs it too): // refused here, before anything is read or sent. m.Preflight = func(ctx context.Context) error { return p.MergePreflight(ctx, r.Repo) } } // Once the request may be with the hub, a cancel never stops the // merge from being settled: the forge calls outlive the step's context // (the instance refuses cancels while merging; shutdown keeps the // attempt held and it runs again). mctx := context.WithoutCancel(ctx) var out forge.MergeOutcome var err error for uncertain := 0; ; uncertain++ { cctx, cancel := context.WithTimeout(mctx, 3*time.Minute) out, err = forge.MergeBranch(cctx, m) cancel() // Tried again: an outcome the hub may have acted on, and a hub that // could not confirm write access. Any other refusal made here // before contacting it (forge.NotSentError) ends the step. again := errors.Is(err, forge.ErrMergeUncertain) || errors.Is(err, workspace.ErrHubUnavailable) if maskDetail != "" || notAuthorized || !again || uncertain+1 >= mergeAttempts { break } time.Sleep(time.Duration(uncertain+1) * mergeBackoff) } // Why it did not merge, for the person (the stopped step's log tail): // the hub's status, code and message, or the error's words. if maskDetail != "" { rep.LogTail = runnerproto.RedactDetail(maskDetail, runnerproto.DetailLimit) return fail("policy_rejected") } rep.LogTail = forge.MergeDetail(err) if notAuthorized && err != nil { return fail("merge_not_authorized") } if errors.Is(err, forge.ErrMergeCIPending) { // The hub's own CI is still running: held for later, releasing // the queue, and run afresh then (lease, owner, judged SHA). since := e.O.State.deferredSince(mctx, r) if since.IsZero() || time.Since(since) < mergeCIWait { rep.State = stepDeferred return rep } } if errors.Is(err, workspace.ErrHubUnavailable) { // Nothing was sent: held for later, releasing the queue, until the // hub answers or the wait is over. e.logDetail("merge", err) since := e.O.State.deferredSince(mctx, r) if since.IsZero() || time.Since(since) < mergeHubWait { rep.State = stepDeferred return rep } return fail(wire.ReasonAmadanUnreachable) } switch { case err == nil: // Done: the merge watch for this candidate ends here, so only this // report says it landed (with the commit and how). e.logDetail("merge watch", e.O.State.endWatch(context.WithoutCancel(ctx), r.TaskID, r.CandidateSHA)) rep.State, rep.MergeSHA, rep.Into, rep.Strategy = wire.StepDone, out.SHA, out.Into, out.Strategy // Where the SHA came from, and its parents when the hub said it: the // instance offers Undo only for a merge commit the hub named whose // second parent is the candidate. rep.MergeSource = out.Source if out.Source == forge.SourceHub { rep.MergeParents = e.mergeParents(mctx, r.Repo, out.SHA) } if e.Merged != nil { // The default branch moved (or was born): the index reads it // again now, not at the hourly refresh. e.Merged(r.Repo) } return rep case errors.Is(err, forge.ErrMergeConflict): return fail("merge_conflict") case errors.Is(err, forge.ErrMergeMoved): return fail("branch_moved") case errors.Is(err, forge.ErrMergeCIPending): return fail("amadan_ci_pending") case errors.Is(err, forge.ErrMergeCIFailed): return fail("amadan_ci_failed") case errors.Is(err, forge.ErrMergeForbidden): return fail("merge_forbidden") case errors.Is(err, forge.ErrMergeUnbornDefault): return fail(wire.ReasonMergeUnbornDefault) case errors.Is(err, forge.ErrMergeNoCredential): // Refused on this runner before the hub was contacted: no // credential serves the repository. The log tail names it. e.logDetail("merge", err) return fail(wire.ReasonMergeCredential) case errors.Is(err, forge.ErrMergeRefused): return fail("policy_rejected") } e.logDetail("merge", err) return fail("merge_failed") } // mergeParents reads a merge commit's parents from the fetched clone, // nil when it cannot. func (e *Engineer) mergeParents(ctx context.Context, repo, sha string) []string { if !shaPattern.MatchString(sha) { return nil } cctx, cancel := context.WithTimeout(ctx, fetchTimeout) defer cancel() if err := e.fetch(cctx, repo); err != nil { return nil } cmd := exec.CommandContext(cctx, e.O.Runner.GitPath, "--git-dir="+e.Clones.Path(repo), "rev-list", "--parents", "-n", "1", "--end-of-options", sha) env := workspace.GitEnvironment() env["HOME"] = "/nonexistent" for k, v := range env { cmd.Env = append(cmd.Env, k+"="+v) } out, clipped, err := boundedOutput(cmd, 4096) if err != nil || clipped { return nil } f := strings.Fields(string(out)) if len(f) < 2 || f[0] != sha { return nil } for _, p := range f[1:] { if !shaPattern.MatchString(p) { return nil } } return f[1:] } // inspectMerge reads the repository for a merge: the task branch's head // and the default branch's tip (one ls-remote), and, fetching only when // the tip is not here yet, whether commit is on the default branch and // which commit there brought it in. func (e *Engineer) inspectMerge(ctx context.Context, repo, branch, commit string) (forge.RemoteState, error) { cctx, cancel := context.WithTimeout(ctx, fetchTimeout) defer cancel() def, tip, heads, err := e.Clones.Heads(cctx, repo, []string{branch}) if errors.Is(err, ErrEmptyRepo) { // The default branch is unborn: nothing has landed, and the first // merge creates it. return forge.RemoteState{Head: heads[branch], Default: def, Unborn: true}, nil } if err != nil { return forge.RemoteState{}, err } st := forge.RemoteState{Head: heads[branch], Default: def, Tip: tip} if tip == commit { st.Landed, st.MergeSHA = true, commit return st, nil } git := func(args ...string) (string, error) { cmd := exec.CommandContext(cctx, e.O.Runner.GitPath, append([]string{"--git-dir=" + e.Clones.Path(repo)}, args...)...) env := workspace.GitEnvironment() env["HOME"] = "/nonexistent" for k, v := range env { cmd.Env = append(cmd.Env, k+"="+v) } out, clipped, err := boundedOutput(cmd, 1<<20) if clipped { return "", errors.New("output too large") } return strings.TrimSpace(string(out)), err } if _, err := git("cat-file", "-e", tip+"^{commit}"); err != nil { if err := e.fetch(cctx, repo); err != nil { return forge.RemoteState{}, err } } if _, err := git("cat-file", "-e", commit+"^{commit}"); err != nil { // Not here even after a fetch: not on the default branch. if _, terr := git("cat-file", "-e", tip+"^{commit}"); terr != nil { return forge.RemoteState{}, terr } return st, nil } if _, err := git("merge-base", "--is-ancestor", commit, tip); err != nil { var exit *exec.ExitError if errors.As(err, &exit) && exit.ExitCode() == 1 { return st, nil } return forge.RemoteState{}, err } st.Landed, st.MergeSHA = true, tip // The commit on the default branch that brought it in: a merge whose // other parent it is, or the commit itself on the first-parent line. if out, err := git("rev-list", "--first-parent", "--parents", "-n", "200", tip); err == nil { for _, line := range strings.Split(out, "\n") { f := strings.Fields(line) if len(f) > 0 && (f[0] == commit || slices.Contains(f[min(len(f), 2):], commit)) { st.MergeSHA = f[0] break } } } return st, nil }