# Slice 4c progress: the coordinator merges

Branch `thin-v1-slice4c` from `thin-v1-slice4b` (a0d418f). Spec:
`docs/superpowers/specs/2026-11-06-equipo-thin-v1.md` §§3, 4, 5, with
Paul's ruling of 2026-11-07 overruling "Equipo never merges": "'Open on
Amadan to merge' ... I'm not doing the merging. The co-ordinator should
be doing that, or tasking someone to do it." Equipo merges its own work
once it has earned Ready to merge. Conventions and scripts as in
`SLICE1-PROGRESS.md` to `SLICE4B-PROGRESS.md`.

## Amadan's merge API and the agent's permission

- API: `POST /api/v1/repos/{ns}/{repo}/branches/{name}/merge` (the
  `amadan branch merge` twin, hub `internal/hub/branch_merge_api.go`),
  bearer token, body `{expect_sha, message, keep_branch, strategy,
  agent: {session, harness, host}}`. Answers `200 {merged, sha, into,
  branch_closed}` or a refusal `{error, reason[, ci_state]}`: `moved`,
  `conflicts`, `ci_not_green`, `up_to_date`, `no_such_branch`,
  `archived`, `no_expect_sha`, 403/404. The hub's repository instance
  compares `expect_sha` with the branch under its git lock, so a branch
  that moved is refused, never merged.
- Strategy: the hub's default, `merge` (a real two-parent merge commit;
  the CLI sends it unless `-squash`, and the hub records a landing by
  ancestry). The branch is deleted after the merge (the hub's default,
  `keep_branch: false`); its page, tasks and discussions stay.
- Permission (no merge made): the route needs writer role on the
  repository (`discussAPIActionGate(roleWriter)`); an agent grant's role
  `agent` ranks with writer (hub `gitRoleRank`, repod `roleRank`). Live,
  with the runner's forge credential (`equipo-docs-t1~paul@keymail.dev`,
  namespaces oficina and woodstar): `GET /api/v1/repos` lists
  oficina/suite and woodstar/woodstar as writable, and a merge request
  with an empty `expect_sha` on a branch that does not exist passed the
  role gate and the agent-session check and was refused only with `400
  no_expect_sha` (the hub refuses that before contacting the instance)
  on both. The agent may merge in both namespaces; nothing is missing.
- A repository may require a green Amadan CI run on the commit
  (`require_green`, not readable through the API): the merge is then
  refused `ci_not_green` until Amadan's own CI passes. Amadan CI runs on
  Equipo's task branches (both suite branches show "CI passed").

## Done

1. Contracts (`internal/wire/tasks.go`, fixtures): stage `merging`
   (between `ready_to_merge` and `done`); specialist `merge`; strategies
   `merge` and `squash`; Needs you `merge_conflict`; `MaxRebaseRounds` 1;
   card kind `merge` with choices `merge` and `wait`; `Step` gained
   `rebase`, `merge_sha`, `into`, `strategy`, `without_checks`; `Task`
   gained `merged {sha, into, strategy, without_checks, at}` (null until
   Equipo merged it; a person's merge leaves it null) and `reports`;
   `DispatchCommand` gained `rebase`, `from_base`; `StepReport` gained
   `merge_sha`, `into`, `strategy`; step reasons `merge_conflict`,
   `branch_moved`, `amadan_ci_pending`, `amadan_ci_failed`,
   `merge_forbidden`, `merge_failed`; tool `add_report`; `ValidBranchName`.
   New fixtures `api/task-merged.json`, `api/card-merge.json`; task,
   step, dispatch and needs-you fixtures gained the fields. Events go to
   active members as before; the merge card and the merged line only to
   the creator's conversation.

2. Forge (`internal/runner/forge/merge.go`), the only holder of the
   Amadan credential: `HubMerge` (the request above, the agent's bearer,
   a 200 with a commit is the only success, an unreadable or 5xx answer
   is uncertain) and `MergeBranch`, record-then-reconcile like the push:
   validate (repository, task branch never the default, a full SHA, the
   person among the runner's owners); read the remote first (already on
   the default branch: done, never asked again; the head not at the
   judged SHA: `moved`, no request); record `requested`; confirm the
   lease right before the request; a lost answer, `up_to_date`, `moved`
   or `no_such_branch` is settled from the default branch; refusals map
   to conflict, CI pending, CI failed, forbidden, failed. One record per
   task and SHA, so a new attempt reconciles from it. Tests:
   `TestMergeBranch`, `TestMergeBranchReconcilesALostAnswer`,
   `TestMergeBranchRecoversACrash` (crashed after recording, landed or
   not), `TestMergeBranchNeverMergesAMovedBranch`,
   `TestMergeBranchRefusals`, `TestMergeBranchRefusesInvalid`,
   `TestHubMerge` (path, bearer, body, answers).

3. Runner (`internal/runner/thin/mergestep.go`): the merge step runs in
   the one step queue (never beside a write step): lease, then
   `MergeBranch` with the remote read through one `ls-remote` (fetching
   only when the tip is new) and the merge commit found on the default
   branch's first-parent line. Uncertain: three tries with backoff. The
   hub's CI still running: waited for (poll 15 s, up to 10 minutes). On
   success the merge watch for that SHA ends without a report, so only
   the step's report says it landed. A runner that dies mid-merge holds
   the attempt and runs it again (the record settles it), never fails it
   `runner_restarted`. Rebase round (`engineer.go`, `workspace.Rebase`):
   the default branch's tip checked out, then the three-way merge of the
   tip and the old candidate on the task's old base (`merge-tree
   --merge-base`) replaces the tree, conflicted files carrying markers
   and named in the prompt; Engineering resolves them; the runner commits
   on the tip and pushes over its own earlier candidate. The merge's
   agent block is `{session: equipo-<task>, harness: equipo, host:
   <machine label>}`. Tests: `TestMergeStep`,
   `TestMergeStepReconcilesALostAnswer`, `TestMergeStepRefusals`,
   `TestRecoverStepsRerunsAMerge`, `TestTaskTreeRebase`;
   `forgetest.Merge` is a hub-like local merge shared by the runner tests
   and the headless forge.

4. Instance (`internal/equipo/chat/merge.go`, migration 0046): the
   policy runs in `advance`, deterministic, never a model's call. Checks
   passed and an approving verdict on the newest candidate with the
   branch at it: Ready to merge (its own event), then a merge step for
   exactly that SHA (stage Merging). Done only on the runner's report of
   a confirmed merge of the dispatched SHA (merge commit, a plain branch
   name, a known strategy, termination); the task records it and the
   coordinator's line goes into the creator's conversation once
   ("Merged [title](/tasks/id) into <project>.", or "... without
   checks."). Checks `cannot_run` or `none`: no merge; one `merge` card
   per SHA in the creator's conversation; only the creator answers
   (another person's answer is 404, a stale revision 409); Merge
   dispatches the merge labelled without checks, Wait leaves the task at
   Ready to merge (a person may still merge on Amadan; slice 4's watch
   makes it Done). A new candidate or the task's end resolves an open
   card. A refused merge: `merge_conflict` sends Engineering one rebase
   round (the new candidate invalidates checks and review and is judged
   from the new base); a second conflict is Needs you `merge_conflict`;
   any other refusal (branch moved, Amadan CI, forbidden) leaves Ready to
   merge with the reason and Retry, which is refused unless the SHA is
   still the judged one as it stands. No automatic re-merge after the
   branch moves and comes back (Retry does it). Cancel is not offered
   while merging. Tests: `TestContractAutoMerge`,
   `TestContractMergeWithoutChecks`, `TestContractMergeConflictRebase`,
   `TestContractMergeRefusedAndRetry`, `TestContractDuplicateReports`;
   `TestContractReviewAndChecks`, `TestContractBranchMovedInvalidatesReadiness`
   and the pages tests now end in Equipo's merge (a person's merge while
   Merging still makes it Done).

5. Duplicates: `record_task` first looks for open tasks in the same
   project that read like the report (significant words of title and
   brief: title overlap at least 0.6 with two shared words, or title and
   brief overlap at least 0.5 with three) and returns up to three as
   `similar` without recording; `separate: true` records anyway.
   `add_report(task, text)` puts the report on an open team task's thread
   (`reports` counts them) and shows the task card in this turn. House
   rule 2026-11-07.9: Equipo merges once checks and review pass (the
   person is never asked to merge); never file the same problem twice.
   The launcher's own allowlist of conversation tools gained
   `add_report` (`TestConversePolicyCoversEveryTool`: it lagged once and
   every coordinator start failed `policy_rejected`).
   `TestOpeningReusesOpenTasks`.

6. UI (kept minimal, Fable is redesigning the inner screens): stage
   "Merging…"; done shows "Merged into main at abc1234" (", without
   checks") with the quiet "Open on Amadan" link to the repository (the
   branch link goes, the branch is deleted); "Open on Amadan to merge"
   and its copy are removed; the merge card (Merge, Wait for checks; then
   "Merging without checks." or "Waiting for checks.") stands in the
   conversation at its own time; Stopped lines for the merge reasons;
   the step list names Merge and "(rebase)".

7. Headless (fake CLI in real bwrap, local forge with `forgetest.Merge`):
   `4_review` now ends merged by Equipo (merge commit on main, second
   parent the candidate, branch gone, the line in chat);
   `4c_checks_card` (an iOS change: card; the branch moves and back;
   Wait, then the person merges on the forge; the next task Merge, merged
   without checks); `4c_rebase` (main changes the same line during
   review: conflict, one rebase round on the new tip, judged again,
   merged); `4c_duplicate`; `4b_ask` now asks while its task waits on a
   merge card (an iOS change), since a merged task forgets its sessions.
   `4c_witness` is staging only (`EQUIPO_STAGING_MERGE_WITNESS`).

8. Mutation checks (ten, each observed failing a test unless noted):
   auto-merge of unchecked work, a merge report for another SHA, Retry
   of a merge while the branch is away, unlimited rebase rounds, no
   duplicate check, forge without the landed check first, forge merging
   a moved head, the merge watch kept after a merge, a crash failing the
   merge. Survived, as defence in depth: the merge card's stale-SHA check
   (the Ready to merge stage check refuses first, and a new candidate
   resolves the card).

9. Merged `thin-v1-slice4b` round-1 fixes at 56a623b (ask output bounds,
   ask termination proof, ReportAnswer retry, git_show range): clean.

10. Review round 1 (Astra 4c, REQUEST CHANGES, three Important and one
    Minor), the 4b round 2 findings and Paul's request. Each fix has a
    test that failed without it (one mutation per fix, all observed
    failing):
    1. No cancel while merging: the API (409 `task_merging`), the page
       and the coordinator's `cancel_task` (refused `merging`) refuse it;
       the runner settles a merge from its record and the default branch
       whatever the step's context, so a lost answer ends Done.
       `TestContractCancelRefusedWhileMerging`,
       `TestMergeStepSettlesDespiteCancel`.
    2. Not retroactive: a candidate is eligible to merge on its own only
       if it first earned Ready under the policy with checks passed
       (`ready_sha`, `merge_eligible`, migration 0047; the migration marks
       candidates already Ready, or moved away from Ready, ineligible).
       Leaving Ready and coming back grants nothing. An ineligible
       candidate gets one card, "Merge <title>?" with Merge and Not now;
       Merge adopts it. `TestContractNoRetroactiveMerge` runs 0047's own
       statements on a Ready task.
    3. The hub's CI wait releases the queue: the merge step is deferred
       (`not_before`, `deferred_since` on the runner's steps) and due
       again after 15 s; other steps and questions run meanwhile; each
       resumption runs afresh (lease, owner, judged head). Past ten
       minutes it ends `amadan_ci_pending`. `TestMergeCIWaitReleasesTheQueue`
       (and the branch moving while it waits: `branch_moved`, no merge).
    4. The branch moving gives an open merge card a new revision; an
       answer from before the move is 409 once it is back.
       `TestContractMergeCardStaleAfterMove`; `4c_checks_card` answers
       with the refreshed revision.
    5. (4b) Nothing is dispatched while a step or question waits for its
       namespace's exit to be verified; the worker looks again every 5 s.
       `TestNothingRunsBesideAnUnverifiedExit`.
    6. (4b) The namespace is written before launch (containment's record
       callback); a record that cannot be written launches nothing. A held
       answer with no namespace is released only when no namespace of the
       runner remains. `TestNamespaceRecordedBeforeLaunch`,
       `TestHeldAnswerWithoutNamespaceNeedsVerification`.
    7. Paul: a done task's specialists can be asked for 14 days
       (`done_at`); `forget_task` carries `keep_until` and the runner keeps
       the sessions until then (`expires_at`), the sweep removes them
       after; a cancelled task forgets at once.
       `TestContractAskImplementer`, `TestContractCancelledTaskForgetsNow`,
       `TestForgetTaskKeepsMergedSessions`; headless `4b_ask` asks after
       the merge.
    New copy (accepted for now, in the inventory): `chat.card.merge_adopt`
    "Merge %s?", `chat.card.not_now` "Not now",
    `chat.card.merge_chose_not_now` "Not now.". Fixture
    `frames/forget_task.json` gained `keep_until`. No live run (the
    staging account's weekly limit).

11. Review round 2 (Astra 4c: the four findings resolved, three new),
    each with a test that failed first:
    1. Not now is not final: a task left at Ready to merge (Not now, or
       Wait for checks) offers its creator a quiet Merge (task card and
       page; `POST /api/v1/tasks/{id}/merge`, `Task.merge_offered`),
       validated afresh (Ready, the branch at the judged SHA, no merge yet,
       no card open); checks passed records eligibility at that moment.
       Teammates get 403; away from the SHA, 409 `not_mergeable`.
       `TestContractNoRetroactiveMerge`.
    2. A merge's explicit expiry overrides idle expiry: a session last
       used ten days before the merge lasts the 14 days from it.
       `TestMergedSessionOutlivesIdleExpiry`.
    3. The task page asks the implementer on a done task within its 14
       days, like the API (`Task.ask_open`). `TestContractAskImplementer`
       (page), browser `TestBrowserAskAfterMerge`;
       `TestBrowserTaskThread` now asks on the merged task.
    New copy: `work.merge_now` "Merge". Fixtures gained `ask_open` and
    `merge_offered`.

## Decisions

- The merge is a step (specialist `merge`) in the runner's one queue: it
  reuses dispatch, durable reports, sync, attempts and Retry, and never
  runs beside a write step. Nothing runs in a namespace, so its reports
  always carry termination.
- Strategy: the hub's default merge commit, recorded on the task and the
  step. The branch is deleted by the hub (its page stays).
- "Checks passed" means `passed`. `none` (no gate found) is treated like
  `cannot_run`: the person is asked with the card.
- Wait is final for that SHA's card: the task stays at Ready to merge
  (checks pending); the person may still merge on Amadan.
- After the branch moves away and back, Equipo does not merge again on
  its own: Retry does, after re-checking the SHA (avoids a merge loop
  while the watch and the merge race to report the head).
- The coordinator's merged line is written by the instance (no model
  turn), in the creator's conversation only, once per task.
- A person's report of the same problem goes on the open task's thread
  as a `report` entry (any team member may add one to an open task); an
  ended task is never offered as similar.

## Staging

Release d521a44 (built by `scripts/staging-thin.py build`, deployed with
`--swap hold` at 22:54:42, serving 22:55:48, both runner units installed
by 22:55:49, about a minute of change-over).

- Unapproved merges on the upgrade: the suite person's two earlier
  witness tasks were at Ready to merge with checks passed and approval
  (`tk2jhc6z46ar` from slice 4, `tkgzy4ioeoh7` from slice 4b). The new
  policy merged both on the suite runner's first sync, 22:55:49 and
  22:55:50, into oficina/suite main (c758267, then cebae9f; README only:
  the line break and the em dash fix, each judged on its SHA). Only the
  witness task was approved for merging. Not reverted: reverting means a
  push to suite's main, which needs Paul's or the controller's word.
  Woodstar is untouched (its main moved only by Paul's own commits): its
  three tasks' checks cannot run, so they wait at Ready to merge with a
  merge card (Paul's `tkf6dufnbzcg` in his conversation, the suite's
  `tklkbx5vid3y` in the suite's), or at Needs you retry (`tks6kwzzdngr`).
  Production starts from a fresh database, so the cutover has no such
  backlog; a deploy onto a database with ready tasks merges them.
- Witness (`4c_witness`, real Claude CLI 2.1.312, suite person, one
  message): "In the oficina/suite README, the `server/` bullet says "the
  producer half — the bearer check, the three routes, their wire shapes
  and cache headers, and the cursor reset — that an app mounts". Please
  replace those two em dashes with commas so it reads "...". Change
  nothing else." Task `tkeog27odnoo` "Replace em dashes in README
  server/ bullet": noted 5.4 s, in progress 12.0 s, Engineering 12.4 s
  (candidate 37e72437), checks `.amadan/ci.d` passed 9.8 s, review
  approved (`same_account`) 25.8 s, Ready to merge 60.96 s, Merging
  60.97 s, Done 61.62 s (the merge step 0.6 s). Merged into suite's main
  as 98380bce (a merge commit, second parent 37e72437), branch deleted.
  The coordinator: "Merged [Replace em dashes in README server/
  bullet](/tasks/tkeog27odnoo) into Suite." (no SHA, no path).
- Checks that could not run: the card flow ran headless with the fake
  CLI (`4c_checks_card`, both Wait and Merge). On staging the card is
  live on the Woodstar tasks (`c_z5fbtn2e5fbrnppubttv665eae`, "Merge iOS
  edge swipe to go back doesn't work on panes without checks?", options
  merge and wait); nobody answered it.

## Live runs (budget: 3 coordinator turns, 2 Engineering steps, 2 Review steps)

Used: 1 coordinator turn, 1 Engineering step, 1 Review step (task
`tkeog27odnoo`). The two unapproved merges spent no model run (merge
steps only).

## Open issues

- The two unapproved merges above: the controller decides whether to
  revert them on oficina/suite.
- Amadan's `require_green` is not readable through the API; a merge
  waiting for Amadan's CI is deferred for up to 10 minutes before it
  reports `amadan_ci_pending`.
- Version skew as before: an old runner refuses a `merge` dispatch;
  install runners right after the instance.
- The squash-merge detection of slice 4 still serves people's merges.

## Copy for review

Accepted for now with the existing marker in `copy.go` and listed in the
plan 3 inventory:
- `work.stage.merging` "Merging…"
- `work.merged` "Merged into %s at %s", `work.merged_without_checks`
  "Merged into %s at %s, without checks"
- `work.specialist.merge` "Merge", `work.rebase` "rebase"
- `work.needs.merge_conflict` "Needs you: it still conflicts with the
  default branch after a rebase"
- `work.reason.merge_conflict` "it conflicts with the default branch",
  `.branch_moved` "the branch moved on Amadan", `.amadan_ci_pending`
  "Amadan's own CI had not finished", `.amadan_ci_failed` "Amadan's own
  CI did not pass", `.merge_forbidden` "Equipo may not merge in this
  repository", `.merge_failed` "Amadan did not merge it"
- `chat.card.merge_question` "Merge %s without checks?",
  `chat.card.merge` "Merge", `chat.card.wait` "Wait for checks",
  `chat.card.merge_chose_merge` "Merging without checks.",
  `chat.card.merge_chose_wait` "Waiting for checks.",
  `chat.card.merge_resolved` "Nothing to decide any more."
- `chat.merged` "Merged [%s](%s) into %s.", `chat.merged_without_checks`
  "Merged [%s](%s) into %s without checks."
- `chat.activity.add_report` "Adding to the task…"
- Removed: `work.merge` "Open on Amadan to merge".

## Blockers

None.
