oficina / equipo Public

Spec: merge authority revision 2 (Astra round 1 findings)

One door (authorizeMerge) for every merge path, re-checked before every
hub request; change facts from raw plus numstat bound to the review
run; size limits in every mode; main ships unknown until an owner
answers; verification as its own record; Undo as a normal revert task
with an exact patch-id check; no tip fallback for the merge SHA; trust
generations with unique credits; durable fix-task intents; protocol 3
optional fields; upgrade and safety tests listed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 4ab106fa2408597ea750f65f4228c67d3f477672 parent 7eba9c8
1 file changed, +624 −411
  • docs/superpowers/specs/2026-11-11-equipo-merge-authority.md +624 −411
diff --git a/docs/superpowers/specs/2026-11-11-equipo-merge-authority.md b/docs/superpowers/specs/2026-11-11-equipo-merge-authority.md
index baa0375d..e3de36b1 100644
--- a/docs/superpowers/specs/2026-11-11-equipo-merge-authority.md
+++ b/docs/superpowers/specs/2026-11-11-equipo-merge-authority.md
@@ -1,9 +1,10 @@
# Equipo merge authority: when the coordinator merges without asking
-Status: spec addendum for review, 2026-11-11, revision 1. Drafted by
-Claude (Opus 5.5) on `merge-authority` from main ac4a809. Builds on
+Status: spec addendum for review, 2026-11-11, revision 2 after Astra
+round 1 (REQUEST CHANGES at 7eba9c8, 13 findings; §13 maps each). Drafted
+by Claude (Opus 5.5) on `merge-authority` from main ac4a809. Builds on
slice 4c (`docs/superpowers/plans/SLICE4C-PROGRESS.md`: the merge step,
-the merge card, `ready_sha` and `merge_eligible`), Mac runners
+the merge card, `ready_sha`, `merge_eligible`), Mac runners
(`2026-11-07-equipo-mac-runners.md` §4.3, ruling 2) and housekeeping
(`2026-11-08-equipo-housekeeping.md` §3, decision classes). Not
implemented.
@@ -17,481 +18,693 @@ able to make a decision ... we can give it heuristics and best
practice." This replaces his slice 4c ruling "ask once when checks
can't run": Equipo decides, and asks only when its policy says so.
-Today (`internal/equipo/chat/merge.go`): a candidate whose checks
-`passed`, approved on the same SHA, first Ready under the policy
-(`merge_eligible`) and not checked outside the sandbox is merged at
-once. Anything else that is approved gets one merge card per SHA. This
-addendum adds a third outcome for approved work whose checks could not
-run: merge and tell, with Undo, then check afterwards.
+Today (`internal/equipo/chat/merge.go`) a candidate whose checks
+`passed`, approved on the same SHA, first Ready under the policy and not
+checked outside the sandbox is merged at once; anything else approved
+gets one merge card per SHA. This addendum adds a third outcome for
+approved work whose checks could not run: merge and tell, with Undo,
+then verify on the merged commit.
-Three invariants, each tested as such:
+Invariants, each tested as such:
-1. **The gate is code.** One pure function decides; no model output is
- an input that can make it merge.
-2. **Never looser.** The coordinator can only make a decision stricter
- (a hold, a tighter policy). Loosening needs a person who is an owner,
- by a tap or a form, never a tool call alone.
-3. **Every decision is recorded with its reasons**, in the transaction
- that acts on it.
+1. **The gate is code, on the instance.** One pure function decides.
+ No model output and no runner can make it merge; a runner only
+ supplies measured facts, and missing facts mean ask.
+2. **Never looser.** The coordinator can only make a decision stricter.
+ Loosening needs an owner's tap or form.
+3. **One door.** Every merge dispatch and every hub request goes through
+ `authorizeMerge`, which writes one audit row per decision.
## 1. Decision classes
-The housekeeping classes, reused by name (`housekeeping.ClassAct`,
-`ClassAsk`, and the spec's Never):
+The housekeeping classes, reused by name:
| Class | When | What happens |
|---|---|---|
-| `act` (merge and tell) | every criterion of §2 holds | merge step dispatched; receipt card with Undo (§5); checks afterwards (§4) |
-| `ask` (with a recommendation) | approved, but a criterion fails, or the project says always ask | one merge card per SHA, worded as Equipo's call (§3) |
-| `never` | checks failed, review asked for changes, no verdict yet, branch moved, a merge in flight, task ended or cancelled | no merge, no card (fix rounds and Needs you as today) |
+| `act` (merge and tell) | every criterion of §2.2 holds | merge step dispatched; receipt card with Undo (§6); verification afterwards (§5) |
+| `ask` (with a recommendation) | approved, but a criterion fails | one merge card per SHA, worded as Equipo's call (§4) |
+| `never` | checks failed or still running, review asked for changes or has not finished, branch moved, task ended or cancelled, a merge in flight | no merge, no card (fix rounds and Needs you as today) |
The housekeeping principal still may never merge, open a merge card or
change a merge policy (`hkForbid`, unchanged).
## 2. The gate
-New package `internal/equipo/mergegate`, pure (no store, no clock
-beyond the input). `chat` builds the inputs inside the `advance`
-transaction and calls it at the moment a candidate first earns Ready
-(the existing `k.ReadySHA != p.candidate` branch), and again only on a
-person's Merge or Wait answer.
+### 2.1 Package and inputs
+
+New package `internal/equipo/mergegate`, pure: no store, no clock, no
+I/O. `chat` builds `Inputs` inside the write transaction.
```go
type Inputs struct {
- Candidate string // newest pushed candidate, branch at it (not moved)
- Verdict string // review verdict on Candidate ("" if none)
- Checks string // passed | failed | none | cannot_run | ""
- ChecksReason string // e.g. needs_macos, runner_offline
- OutsideSandbox bool // checks ran with checks_sandbox none
- CanCheckLater bool // §2.2
- Change *ChangeFacts // §2.3; nil when missing
- Policy Policy // §6; defaults when the project has none
- Repo RepoFacts // §2.5, from the primary's catalog
- AsksLeft int // §7 trust counter
- Hold string // coordinator hold (§3.2); "" when none
- FirstReady bool // this candidate earns Ready now
+ Candidate string // newest pushed candidate; "" when the branch moved
+ Verdict string // newest review verdict on Candidate, finished
+ Checks string // passed | failed | none | cannot_run | "" (running)
+ ChecksReason string
+ OutsideSandbox bool // checks_sandbox none
+ CanCheckLater bool // §2.3
+ Change *ChangeFacts // §3; nil when missing, refused or from an old runner
+ Policy Policy // §7; defaults when no row
+ AsksLeft int // §8
+ Hold string // §4.3
+ Consent *Consent // §2.4; nil for Equipo's own decision
+ Revert *RevertFacts // §6; set only for a revert task
+ Eligible bool // k.MergeEligible == Candidate (slice 4c)
}
-type Criterion struct{ Name string; OK bool; Value, Limit string }
+type Criterion struct {
+ Name string
+ OK bool
+ Value string
+ Limit string
+}
type Decision struct {
- Class string // act | ask | never
- Stance string // merge | wait (for ask)
- Checks bool // true: merges with checks passed
- Reasons []Criterion // every criterion evaluated, in a fixed order
+ Class string // act | ask | never
+ Stance string // merge | wait, for ask
+ Checks bool // act with checks passed
+ Reasons []Criterion // every criterion evaluated, fixed order
}
func Decide(in Inputs) Decision
```
-### 2.1 Order of evaluation
+### 2.2 Order of evaluation
-1. **Never**: `Verdict != approve`, `Checks == failed`, `Checks == ""`
- (still running), `Candidate == ""`. Class `never`.
-2. **Checks passed** (`Checks == passed`, not outside the sandbox,
- `FirstReady`): `act` with `Checks: true` unless `Policy.Mode ==
- always_ask`, `AsksLeft > 0` or `Hold != ""`, which make it `ask`
- (options Merge, Not now). Size, sensitivity and shipping do not apply
- to judged work: slice 4c behaviour is unchanged for these.
-3. **Without checks**: `act` only when ALL of these hold, else `ask`:
+1. **Never** when `Candidate == ""`, `Verdict != approve`, `Checks ==
+ failed` or `Checks == ""`.
+2. **Consent** (§2.4) present and valid: `act` (the person decided).
+3. **Checks passed** and not outside the sandbox: `act` with `Checks:
+ true` only when `Eligible` (slice 4c's `merge_eligible`: the
+ candidate first earned Ready under the policy with checks passed), and
+ not `Policy.Mode == always_ask`, `AsksLeft > 0` or `Hold != ""`;
+ otherwise `ask` (options Merge, Not now; the adopt card when not
+ eligible). Size, sensitivity and shipping are not applied to checked
+ work: slice 4c is unchanged for it.
+4. **Without checks**: `act` only when ALL of these hold, else `ask`.
| Criterion | Holds when |
|---|---|
| `approved_exact_sha` | `Verdict == approve` on `Candidate`, branch at it |
-| `environment_reason` | `Checks == cannot_run` and `ChecksReason` in `{needs_macos, runner_offline}` |
-| `can_check_later` | `CanCheckLater` (§2.2) |
-| `small` | `Change != nil`, `Change.Lines <= Policy.MaxLines`, `Change.Files <= Policy.MaxFiles`, no binary file; skipped when `Policy.Mode == review_enough` |
-| `not_sensitive` | `Change != nil`, `!Change.Truncated`, no path matches §2.4, `!Change.Signing` |
-| `not_shipping` | §2.5 says main is not a release |
+| `environment_reason` | `Checks == cannot_run`, `ChecksReason` in `{needs_macos, runner_offline}` |
+| `can_check_later` | `CanCheckLater` |
+| `facts_present` | `Change != nil` (§3 accepted it) |
+| `small` | `Change.Lines <= Policy.MaxLines`, `Change.Files <= Policy.MaxFiles`, `Change.Binary == 0`, in every mode |
+| `not_sensitive` | no path (old or new side) matches §3.3, `!Change.Special`, `!Change.Signing` |
+| `not_shipping` | `Policy.MainShips == no` (§7.3); `unknown` and `yes` fail |
| `trusted` | `AsksLeft == 0` |
| `no_hold` | `Hold == ""` |
| `policy_allows` | `Policy.Mode != always_ask` |
-| `first_ready` | `FirstReady` (never retroactive, as slice 4c) |
+| `revert_exact` | only when `Revert != nil`: §6 |
`none` (no gate found), `checks_timeout`, `checks_unavailable` and
-`needs_network` are not environment reasons: the gate ran partly, or
-there is nothing to run afterwards. They always ask.
-`OutsideSandbox` with checks passed asks, as today (Mac runners ruling
-2 is not widened here).
+`needs_network` are not environment reasons: they always ask. Checks
+passed outside the sandbox ask, as today. Without checks, nothing
+retroactive can pass: a review finished before the upgrade carries no
+change facts, so `facts_present` fails and it asks (§12 tests the
+upgrade).
+
+### 2.3 Can check later
+
+`CanCheckLater` uses the same predicate placement uses, extracted as
+`runnerFits(runner, needs, refusedBy)` (protocol 2, not removing, tags
+cover the needs, not in `refused_by`), over the person's enrolled
+runners, online or not, with the needs the task's checks step stored
+(`chat_steps.needs`). False when no enrolled runner fits.
+
+### 2.4 Consent
+
+A person's Merge (card, task page `POST /tasks/{id}/merge`, Retry of a
+refused merge, or the merge that follows a Wait) records consent on the
+task: `{person, sha, policy_revision, trust_generation, hold_revision,
+at}`. Consent is valid for `authorizeMerge` only while the person is
+still the task's creator and an owner (current roster, inside the
+transaction), the SHA is the candidate, the branch is at it, and the
+policy revision, trust generation and hold revision are unchanged.
+Anything else voids it and the task asks again (a new card revision).
+
+### 2.5 `authorizeMerge(task, candidateSHA)`: the one door
+
+`func (t *txn) authorizeMerge(k *taskRecord, sha string, at string)
+(Decision, error)`, `at` naming the caller. It loads the inputs, calls
+`Decide`, writes one audit row (§9) and returns the decision. Callers:
+
+| Caller | On `act` | Otherwise |
+|---|---|---|
+| `advance` at Ready (Equipo's own) | `startMerge` | `ask`: card once per SHA; `never`: nothing |
+| `answerMerge` (Merge), `MergeTask`, merge Retry | record consent, then `startMerge` | 409 with the failing reason; card refreshed |
+| Wait's checks passing (§4.2) | `startMerge` | card again |
+| `Store.Authorize` for a merge step attempt (§2.6) | grant | refuse |
+
+`startMerge` is unexported and has no other callers (a test lists the
+call sites with `go/ast`). The merge guards that exist today (ended,
+cancelled, moved, merge in flight, `hkForbid`) stay in `startMerge` too.
+
+### 2.6 Re-check before every hub request
+
+The runner's forge calls `Confirm` (the step's lease, `Store.Authorize`)
+immediately before every hub merge request, including a re-request
+after an uncertain answer and every resumption of a step deferred for
+the hub's own CI (`internal/runner/forge/merge.go`, `MergeBranch`).
+For merge steps, `Authorize` changes:
+
+- it runs `authorizeMerge` on **every** call, not only the first
+ (today it returns early once `started_at` is set);
+- on anything but `act` it marks the attempt withdrawn
+ (`reason = merge_not_authorized`), refuses the lease with
+ `withdrawn`, and returns the task to Ready to merge, where the ask
+ card is raised. Both old and new runners already end an attempt whose
+ lease is refused as withdrawn, so no wire change is needed.
+
+The irreversible boundary is therefore the hub request itself. A
+request already sent when policy changes is reconciled by the forge
+record from the default branch, as today; a merge that lands that way
+is audited as `landed_after_change`. Queued merges (offline runner,
+deferred for CI) are re-decided before they can send anything.
-### 2.2 Can check later
+Policy, trust and hold changes bump their revisions, which void consent
+(§2.4) and touch open merge cards of the project (a new card revision),
+so an answer given under the old rules is refused 409.
-True when the task's person has an enrolled runner, not being removed,
-whose tags cover the checks' needs (`checksNeeds`, the same tags that
-placed them), online or not. False when no such runner was ever enrolled
-(nobody could check it afterwards, so Equipo asks).
+## 3. Change facts
-### 2.3 Change facts: what the change is, measured by the runner
+### 3.1 What the runner measures
-New `wire.ChangeFacts`, carried on the **Review** step's report (Review
-always runs on the primary until slice F, always before approval, on
-exactly the candidate):
+New optional `wire.ChangeFacts` on the **Review** step's report
+(Review runs on the primary, on exactly the candidate, before approval):
```go
type ChangeFacts struct {
- Base string `json:"base"` // merge-base(task base, candidate)
- SHA string `json:"sha"` // == candidate
- Files int `json:"files"`
- Lines int `json:"lines"` // added + deleted, text files
- Binary int `json:"binary"` // files numstat reports as "-"
- Special bool `json:"special"` // a submodule or symlink changed
- Signing bool `json:"signing"` // §2.4 content rule
- Paths []string `json:"paths"` // up to MaxChangePaths (200), each <= 300 bytes
- Truncated bool `json:"truncated"` // more paths than were sent
+ ReviewStep string `json:"review_step"` // the review step's ID
+ Attempt int64 `json:"attempt"`
+ Repo string `json:"repo"`
+ Base string `json:"base"` // merge-base(task base, candidate)
+ SHA string `json:"sha"` // the candidate
+ Files int `json:"files"`
+ Lines int `json:"lines"` // added + deleted, text files
+ Binary int `json:"binary"`
+ Special bool `json:"special"` // §3.2
+ Signing bool `json:"signing"` // §3.3 content rule
+ Paths []Path `json:"paths"` // every changed entry, old and new
+ Complete bool `json:"complete"`
}
+type Path struct{ Old, New string; OldMode, NewMode string }
```
-The runner computes it deterministically (no model) from
-`git diff --numstat -z -M <base> <candidate>` in the review tree. The
-instance keeps it only from the person's primary runner, only when
-`SHA == candidate` and the step's `CandidateSHA` matches, stored as JSON
-on the review step (`change_facts`). Anything missing, malformed or from
-a worker leaves `Change` nil, which fails `small` and `not_sensitive`
-(ask). An old runner sends nothing, so it asks, as today. `Special`
-counts as sensitive (dependency or infrastructure).
+Computed deterministically (no model) in the review tree from the exact
+pair: `git diff --raw -z -M --no-abbrev <base> <sha>` (modes, both
+paths of a rename or copy, status) and `git diff --numstat -z -M <base>
+<sha>` (lines, binary as `-`), plus `git diff -U0 <base> <sha> --` over
+the `.pbxproj`, `.xcconfig` and `Info.plist` files only, for the
+signing rule. The two listings must name the same entries; any
+disagreement, error, or more than `MaxChangePaths` (200) entries sets
+`Complete: false`.
-### 2.4 Sensitive areas
+### 3.2 Special entries
-Defaults are a table in `mergegate/sensitive.go`, matched on the path,
-case-insensitive. A path's **tokens** are its segments split on `/`,
-`.`, `-`, `_` and lower-to-upper case changes; token rules match whole
-tokens only (so `keyboard` is not `key`).
+`Special` is true when any entry has mode `120000` (symlink) or `160000`
+(gitlink, a submodule) on either side, or the old and new modes differ
+(including a new file created executable, `100755`).
-| Class | Paths (glob) | Tokens |
+### 3.3 Sensitive areas
+
+Defaults are a table in `mergegate/sensitive.go`, matched against both
+the old and the new path of every entry, case-insensitive. A path's
+**tokens** are its segments split on `/`, `.`, `-`, `_` and
+lower-to-upper case changes; token rules match whole tokens (so
+`keyboard` is not `key`). Every glob without a leading directory
+matches at any depth.
+
+| Class | Globs | Tokens |
|---|---|---|
-| `migrations` | `**/migrations/**`, `**/migrate/**`, `**/*.sql`, `**/schema.*`, `**/*.prisma`, `**/db/schema*` | `migration`, `migrations`, `schema` |
-| `auth_secrets` | `**/.env*`, `**/*.pem`, `**/*.key`, `**/*.p12`, `**/*.p8`, `**/*.keystore`, `**/*.jks`, `**/*.keychain*` | `auth`, `authn`, `authz`, `oauth`, `oidc`, `saml`, `jwt`, `login`, `logout`, `signin`, `signup`, `session`, `sessions`, `password`, `passwords`, `passwd`, `credential`, `credentials`, `secret`, `secrets`, `token`, `tokens`, `key`, `keys`, `keychain`, `crypto`, `cipher`, `encrypt`, `decrypt`, `cert`, `certs`, `certificate`, `tls`, `ssl`, `permission`, `permissions`, `acl`, `rbac` |
+| `migrations` | `**/migrations/**`, `**/migrate/**`, `**/*.sql`, `**/schema.*`, `**/*.prisma` | `migration`, `migrations`, `schema` |
+| `auth_secrets` | `**/.env*`, `**/*.pem`, `**/*.key`, `**/*.p12`, `**/*.p8`, `**/*.keystore`, `**/*.jks` | `auth`, `authn`, `authz`, `oauth`, `oidc`, `saml`, `jwt`, `login`, `logout`, `signin`, `signup`, `session`, `sessions`, `password`, `passwords`, `passwd`, `credential`, `credentials`, `secret`, `secrets`, `token`, `tokens`, `key`, `keys`, `keychain`, `crypto`, `cipher`, `encrypt`, `decrypt`, `cert`, `certs`, `certificate`, `tls`, `ssl`, `permission`, `permissions`, `acl`, `rbac` |
| `payments` | | `payment`, `payments`, `billing`, `stripe`, `checkout`, `invoice`, `invoices`, `subscription`, `subscriptions`, `purchase`, `purchases`, `storekit`, `iap`, `paywall`, `refund`, `refunds` |
-| `ci_config` | `.amadan/**`, `.github/**`, `.gitlab-ci.yml`, `.circleci/**`, `.buildkite/**`, `Makefile`, `GNUmakefile`, `makefile`, `**/*.mk` | |
-| `dependencies` | `go.mod`, `go.sum`, `**/package.json`, `**/package-lock.json`, `**/yarn.lock`, `**/pnpm-lock.yaml`, `**/Cargo.toml`, `**/Cargo.lock`, `**/Gemfile*`, `**/requirements*.txt`, `**/pyproject.toml`, `**/poetry.lock`, `**/Pipfile*`, `**/uv.lock`, `**/Package.swift`, `**/Package.resolved`, `**/Podfile*`, `**/Cartfile*`, `**/*.gradle*`, `**/gradle.lockfile`, `**/composer.*`, `**/mix.exs`, `**/mix.lock`, `.gitmodules`, `vendor/**` | |
-| `release_signing` | `**/*.entitlements`, `**/*.mobileprovision`, `**/ExportOptions*.plist`, `fastlane/**`, `**/*.xcconfig`, `.goreleaser*`, `**/VERSION`, `release/**`, `releases/**` | `release`, `signing`, `entitlements`, `provisioning` |
-| `infrastructure` | `**/*.tf`, `**/*.tfvars`, `**/*.hcl`, `terraform/**`, `infra/**`, `infrastructure/**`, `deploy/**`, `k8s/**`, `helm/**`, `**/Dockerfile*`, `**/docker-compose*`, `**/*.service`, `fly.toml`, `vercel.json`, `netlify.toml`, `render.yaml`, `Procfile`, `app.yaml`, `carlos.toml` | `terraform`, `ansible`, `pulumi`, `cloudformation`, `deploy` |
-
-**Content rule** (`Signing`, computed by the runner): an `.pbxproj`,
-`.xcconfig` or `Info.plist` change whose added or removed lines name
-`CODE_SIGN`, `DEVELOPMENT_TEAM`, `PROVISIONING_PROFILE`,
-`ENTITLEMENTS`, `PRODUCT_BUNDLE_IDENTIFIER`, `MARKETING_VERSION`,
-`CURRENT_PROJECT_VERSION`, `CFBundleVersion` or
-`CFBundleShortVersionString`. A plain `.pbxproj` change (Xcode adding a
-file) is not sensitive by itself.
-
-**Per project**, the policy may add globs (`extra_sensitive`, at most
-20, each <= 200 bytes, validated with `path.Match` syntax plus `**`).
-Nobody can remove a default: the table is code. The receipt and the
-card name the class and the first matching path.
-
-### 2.5 "Merging ships to users"
-
-`not_shipping` is decided from three inputs, in this order:
-
-1. **Deploy signal on the default branch** (stricter wins): the
- primary's index of the repository (`wire.RepoInfo`, protocol bump)
- gains `deploy_signals []string`, the paths at `head_sha` that suggest
- main deploys: any of the `infrastructure` hosting files above
- (`fly.toml`, `vercel.json`, `netlify.toml`, `render.yaml`, `Procfile`,
- `app.yaml`, `carlos.toml`), `.amadan/deploy*`, an `.amadan/ci.d/*`
- file or a `.github/workflows/*` or `.gitlab-ci.yml` that names
- `deploy`, `release` or `publish` together with the default branch or
- `push`. Any signal: **ships**, whatever the policy says (the card
- names the file).
-2. **Policy** `main_ships`: `yes` ships; `no` does not.
-3. **Default** (`main_ships: auto`): an Xcode app (`RepoInfo.NeedsMacOS`
- from its project files, the index's existing flag) does not ship from
- main: it ships through a store release (Woodstar). Anything else is
- **unknown, which counts as ships** and asks; the card's
- recommendation says so and the project page offers "Main is not a
- release".
-
-A repository missing from the catalog, or an index older than 24 hours,
-is unknown (ships).
-
-## 3. Asking, with a recommendation
-
-### 3.1 The card
+| `ci_config` | `**/.amadan/**`, `**/.github/**`, `**/.gitlab-ci.yml`, `**/.circleci/**`, `**/.buildkite/**`, `**/Makefile`, `**/GNUmakefile`, `**/makefile`, `**/*.mk` | |
+| `dependencies` | `**/go.mod`, `**/go.sum`, `**/go.work*`, `**/package.json`, `**/package-lock.json`, `**/npm-shrinkwrap.json`, `**/yarn.lock`, `**/pnpm-lock.yaml`, `**/bun.lock*`, `**/Cargo.toml`, `**/Cargo.lock`, `**/Gemfile*`, `**/requirements*.txt`, `**/pyproject.toml`, `**/poetry.lock`, `**/Pipfile*`, `**/uv.lock`, `**/Package.swift`, `**/Package.resolved`, `**/Podfile*`, `**/Cartfile*`, `**/*.gradle*`, `**/gradle.lockfile`, `**/composer.json`, `**/composer.lock`, `**/mix.exs`, `**/mix.lock`, `**/.gitmodules`, `**/vendor/**` | |
+| `release_signing` | `**/*.entitlements`, `**/*.mobileprovision`, `**/ExportOptions*.plist`, `**/fastlane/**`, `**/*.xcconfig`, `**/.goreleaser*`, `**/VERSION` | `release`, `releases`, `signing`, `entitlements`, `provisioning` |
+| `infrastructure` | `**/*.tf`, `**/*.tfvars`, `**/*.hcl`, `**/Dockerfile*`, `**/docker-compose*`, `**/*.service`, `**/fly.toml`, `**/vercel.json`, `**/netlify.toml`, `**/render.yaml`, `**/Procfile`, `**/app.yaml`, `**/carlos.toml` | `terraform`, `ansible`, `pulumi`, `cloudformation`, `infra`, `infrastructure`, `deploy`, `k8s`, `helm` |
-The existing `merge` card, one per SHA (`merge_asked`), in the
-creator's conversation only. Its question becomes Equipo's call,
-composed by the instance from the decision (no model turn):
-
-- `Stance: merge` when the only failing criteria are `small`,
- `not_shipping` with an unknown default (not a signal, not `yes`), and
- `policy_allows`: "I'd merge: %s. [Merge] [Wait ...]".
-- `Stance: wait` otherwise: "I'd wait: %s. [Merge] [Wait ...]".
-
-`%s` joins at most three phrases, from the criteria in order: what
-passed for merge ("approved by Review", "a small change, %d lines in %d
-files", "nothing ships until a release"), what failed for wait ("it
-touches payments (%s)", "Woodstar ships from main (%s)", "checks failed
-on main after a recent merge", the coordinator's hold text).
-
-Options by case: checks could not run for `needs_macos` or
-`runner_offline` with a Mac-tagged need: **Merge**, **Wait for a Mac**;
-other cannot-run reasons and `none`: **Merge**, **Wait for checks**;
-checks passed but asked (always ask, trust, hold): **Merge**, **Not
-now**.
-
-**Wait for a Mac / Wait for checks** now means something: the checks
-step for the same SHA is queued again (attempt n+1) with no
-`OfflineLimit` (it waits for a runner that fits), and the person's
-answer is recorded as consent: when those checks pass the candidate is
-merged under the checks-passed rule (`merge_eligible` set by the
-answer); when they fail, the fix round runs as usual. A Wait on a task
-whose person has no runner that could ever run them (`can_check_later`
-false) is Wait for checks with today's meaning (stays at Ready to
-merge; Merge stays offered).
-
-The card is touched or withdrawn exactly as today when the branch moves
-or a new candidate arrives.
-
-### 3.2 The coordinator: stricter only
-
-- New tool `hold_merge{task, reason}` (own task, not final, not
- merging): sets `task.merge_hold` (plain text, <= 200 bytes). A held
- task never merges on its own; its card stance is wait with the reason
- as the coordinator's words. The coordinator has no tool to release a
- hold; the person's Merge on the card is the release for that SHA.
-- The coordinator's text reaches the gate only as `Hold`, which can only
- turn `act` into `ask`. The coordinator never supplies `Stance: merge`.
-- `read_task` shows the decision (class, stance, reasons) so the
- coordinator can explain it in conversation.
-
-## 4. Checks afterwards
-
-### 4.1 The post-merge step
-
-`mergeDone` for any merge labelled without checks (Equipo's own or a
-person's Merge on the card) creates, in the same transaction, a checks
-step on the done task: `post_merge: true`, `CandidateSHA` = the merge
-commit, `BaseSHA` = the task's base (so `needsMacOS` sees the change),
-the person and needs as the task's checks. Placement and the step
-report treat it as ordinary checks with three exceptions:
-
-- `placeWaiting`, `offline` and `Place` admit `post_merge` steps on a
- done task (today they skip final stages).
-- `offline` never resolves them `runner_offline`; they wait up to
- `PostMergeWait` (14 days), then end `cannot_run`
- `post_merge_expired`.
-- `progressOf` ignores them (their SHA is not the candidate), and
- `advance` stays a no-op on a done task; the outcome is applied by
- `postMergeResult` after the report is saved.
-
-The worker's pack relay serves the merge commit as it serves a
-candidate: the primary fetches the default branch before packing a SHA
-it does not have (a test proves a merge commit reaches a Mac worker).
-
-### 4.2 Outcomes
-
-- **Passed**: the receipt card gains "Checks passed on main afterwards."
- (new revision; no new message); trust counts down (§7); audit row.
-- **Failed**: at once, in the same transaction: trust lowered (§7); a
- **fix task** recorded and started under the task's creator, title
- `Fix checks after merging %s` (clipped to the task title bound), brief
- with the merge SHA, the gate, the exit code and the last 60 lines of
- output, base the default branch's tip at dispatch, through the same
- store functions as `record_task` and `start_task` (owner check,
- execution enabled; if either fails it is recorded and not started, and
- the line says so); one coordinator line in the creator's conversation:
- "Checks failed on main after I merged [%s](%s). I opened [%s](%s) to
- fix it." Idempotent per post-merge step. At most one open fix task per
- project from this path: a later failure adds a report to it
- (`add_report`'s store path) instead of a second task.
-- **Could not run** (any cannot-run reason, or expired): audit row and
- one line: "Checks still could not run on main after merging [%s](%s)
- (%s)." Trust unchanged.
-
-The fix task itself goes through this gate with trust lowered, so it
-asks.
+**Signing** (content rule): an added or removed line in a `.pbxproj`,
+`.xcconfig` or `Info.plist` naming `CODE_SIGN`, `DEVELOPMENT_TEAM`,
+`PROVISIONING_PROFILE`, `ENTITLEMENTS`, `PRODUCT_BUNDLE_IDENTIFIER`,
+`MARKETING_VERSION`, `CURRENT_PROJECT_VERSION`, `CFBundleVersion` or
+`CFBundleShortVersionString`. A `.pbxproj` change that only adds a file
+reference is not sensitive by itself.
-## 5. Receipt and Undo
-
-An `act` merge without checks gets a receipt card (new kind
-`merge_receipt`) in the creator's conversation instead of the
-`chat.merged_without_checks` line: "Merged [%s](%s) into %s without
-checks: %s. Checks run on main when a Mac is online. [Undo]" (`%s` =
-the passing phrases of §3.1; the second sentence names "a runner" when
-the need is not a Mac). Receipts follow housekeeping's act-and-tell
-rules: visible at once on the task page, in the conversation at
-`visible_at` (the person's quiet hours), Undo for `UndoWindow` (7 days).
-A checks-passed merge keeps today's plain line and no Undo.
-
-**Undo is a revert through the same merge path.** The creator's Undo
-(card or `POST /api/v1/tasks/{id}/undo-merge`; owner, the creator, the
-receipt's revision; 409 when already undone, outside the window, or the
-task is not Equipo's merge) does, in one transaction:
-
-1. records a **revert task** (`revert_of` = the task; title "Undo %s";
- creator the undoing person) and sets `reverted_by` on the original;
-2. dispatches its first step, a new deterministic specialist `revert`
- (no model): the primary fetches, checks out the default branch's
- tip, runs `git revert --no-edit -m 1 <merge sha>` (plain revert for a
- squash), commits as Equipo's agent identity, pushes the revert task's
- branch with `PushBranch` (record then reconcile) and reports the
- candidate. A conflict ends it `revert_conflict`: Needs you on the
- revert task, with Start to let Engineering resolve it like any task;
-3. on the revert's candidate, the instance dispatches the ordinary merge
- step (`forge.MergeBranch`, expect_sha, the hub's own CI rule),
- labelled without checks, decided by the person (audit);
-4. lowers trust (§7).
-
-The revert merge gets its own post-merge checks (§4). Undo is offered
-only when the person's primary runner advertises the `revert`
-capability in hello (an older runner would refuse the dispatch).
-
-## 6. Policy per project, in words
-
-### 6.1 Storage
-
-Migration **0058** (next free on main ac4a809; other open branches may
-also claim 0058, so whichever lands second renumbers) adds:
+A project's policy may add globs (`extra_sensitive`, at most 20, each
+<= 200 bytes, `path.Match` syntax plus `**`). No one can remove a
+default: the table is code.
-`chat_merge_policies` (team record, one row per project):
-`project_id` primary key, `mode` (`rules` | `review_enough` |
-`always_ask`), `max_lines` (default 300, 0 to 2000), `max_files`
-(default 15, 0 to 100), `main_ships` (`auto` | `no` | `yes`),
-`extra_sensitive` (JSON list), `words` (the person's sentence, <= 300
-bytes, display only), `asks_left`, `trust_reason`, `trust_since`,
-`revision`, `updated_by`, `updated_at`. No row means defaults (`rules`,
-300, 15, `auto`, none, 0).
-
-`chat_merge_audit` (append only, §8).
-
-Columns: `chat_steps.post_merge`, `chat_steps.change_facts`;
-`chat_tasks.merge_hold`, `chat_tasks.revert_of`,
-`chat_tasks.reverted_by`, `chat_tasks.merge_decision` (the newest audit
-row's id). All additive; existing Ready tasks keep their open cards
-(no backfill makes anything eligible).
-
-The instance never parses the words. They are what the person said;
-the structured fields are what the gate reads.
-
-### 6.2 Setting it
-
-- **In conversation**: new tool `set_merge_policy{project, words, mode?,
- max_lines?, max_files?, main_ships?, add_sensitive?}`. The instance
- compares each field with the stored policy. Fields that are tighter
- (mode towards `always_ask`, smaller numbers, `main_ships: yes`, added
- globs) are applied at once with a receipt and Undo (the home card's
- revision pattern). If any field is looser, nothing is applied: a
- confirm card "Change how Equipo merges %s: %s? [Save] [Cancel]" goes to
- the person, and Save (an owner's tap, current revision) applies the
- whole change. "for Woodstar, merge when Review approves" maps to
- `review_enough`; "always ask me about Suite" to `always_ask`.
-- **On the project page**: a section "How Equipo merges" (a partial
- template `merge_policy.html` included with one line in
- `work_project.html`, to stay clear of the Projects and Tasks redesign)
- shows the current policy in plain sentences, the words, the trust
- state ("Asking for the next %d merges: checks failed on main after
- %s."), and the last five decisions with their reasons; an owner's
- form edits the fields directly (a person's action, so it may loosen),
- CSRF and revision checked; teammates see it read only.
-- `GET/PUT /api/v1/projects/{id}/merge-policy` mirror the form.
+### 3.4 Acceptance by the instance
-Hard limits are code: `review_enough` waives only `small`; no policy
-waives `approved_exact_sha`, `environment_reason`, `can_check_later`,
-`not_sensitive` defaults, a deploy signal, `trusted` or `no_hold`.
+The instance stores facts as JSON on the review step (`change_facts`)
+only when all hold, else drops them (the verdict still counts; the gate
+then asks on `facts_present`):
-## 7. Trust per project
+- the report is from the person's primary runner and the runner the
+ review step is placed on;
+- `ReviewStep` and `Attempt` are this step and its current attempt;
+- `Repo` is the task's project, `SHA` the step's `CandidateSHA`, `Base`
+ a valid SHA;
+- `Complete` is true, the counts match the entries, every path is clean
+ (`cleanPath`) and every mode is one of git's six.
-`asks_left` on the policy row:
+`facts_present` reads only the facts on the review step whose verdict
+the gate is using.
-- set to **5** (with `trust_reason`) when post-merge checks fail or an
- Undo merges a revert; a second failure while lowered resets it to 5;
-- counts down by one for each later **clean** merge into the project:
- a merge with checks passed (at `mergeDone`), or a merge without checks
- whose post-merge checks passed (at that result);
-- `asks_left > 0` fails `trusted`: every merge in the project asks,
- including checks passed (§2.1 step 2). At 0 trust is restored and
- the project page says so.
+## 4. Asking, with a recommendation
-Changes to `asks_left` are audit rows.
+### 4.1 The card
-## 8. Audit
+The existing `merge` card, one per SHA (`merge_asked`), in the
+creator's conversation only, its question composed by the instance from
+the decision (no model turn):
+
+- `Stance: merge` when the only failing criteria are `small` and
+ `policy_allows`: "I'd merge: %s." with up to three passing phrases
+ ("approved by Review", "a small change, %d lines in %d files",
+ "nothing ships until a release").
+- `Stance: wait` otherwise: "I'd wait: %s." with up to two failing
+ phrases ("it touches payments (%s)", "I don't know whether %s's main
+ ships to users", "checks failed on main after a recent merge", "the
+ runner didn't say what changed", the coordinator's hold text).
+
+Options: cannot run for `needs_macos`, or `runner_offline` with a macOS
+need: **Merge**, **Wait for a Mac**; other cannot-run reasons and
+`none`: **Merge**, **Wait for checks**; checks passed but asked:
+**Merge**, **Not now**.
+
+### 4.2 Wait
+
+Wait for a Mac or Wait for checks queues the checks step for the same
+SHA again (attempt n+1) without the `OfflineLimit` (it waits for a
+runner that fits) and records consent (§2.4). When those checks pass,
+`advance` calls `authorizeMerge` (the consent makes it `act` if still
+valid); when they fail, the fix round runs as usual. When
+`can_check_later` is false, Wait keeps today's meaning (stays at Ready
+to merge; Merge stays offered).
+
+### 4.3 The coordinator: stricter only
+
+- Tool `hold_merge{task, reason}` (own task, not final, not merging):
+ sets `merge_hold` (plain text, <= 200 bytes) and bumps
+ `hold_revision`. A held task never merges without a person's consent
+ given after the hold. No tool releases a hold; the person's Merge is
+ the release for that SHA.
+- The coordinator's text reaches the gate only as `Hold`, which can only
+ turn `act` into `ask`.
+- `read_task` shows the newest decision (class, stance, reasons).
+
+## 5. Verification after the merge
+
+### 5.1 Its own record
+
+A merge labelled without checks (any path) writes, in `mergeDone`'s
+transaction, a row in `chat_merge_verifications`; the done task is not
+touched again:
+
+`id` (`v_...`), `task_id`, `project_id`, `person`, `repo`, `merge_sha`
+(verified, §5.4), `base_sha` (the merge commit's first parent),
+`needs` (JSON, copied from the task's checks step), `state` (`waiting`,
+`placed`, `running`, `passed`, `failed`, `not_run`, `expired`),
+`attempt`, `runner_id`, `refused_by`, `placed_at`, `expires_at`
+(absolute, 14 days after the merge, never reset), `trust_generation`
+(§8), `gate`, `exit_code`, `reason`, `log_tail`, `output`, `revision`,
+timestamps.
+
+### 5.2 Lifecycle
+
+All in `Store.Place` (every minute) and the report path, one
+transaction each:
+
+- **waiting → placed**: a runner with `runnerFits(needs)` is online;
+ a `dispatch` command is queued with `TaskID` = the task, `StepID` =
+ the verification's ID, `Attempt`, specialist `checks`,
+ `CandidateSHA` = `merge_sha`, `BaseSHA` = `base_sha`, the task's
+ branch name (the runner only fetches and checks out the SHA). Inbound
+ pack transfers for a worker key on the verification ID the same way.
+- **placed or running → waiting** (attempt n+1, cancel sent): the
+ runner is offline for `WithdrawAfter`, refuses it
+ (`placement_refused` adds to `refused_by`), or no report arrived for
+ an hour.
+- **→ passed / failed / not_run**: the runner's report (§5.3).
+- **→ expired**: `expires_at` passed in any non-final state.
+
+Code that keys on step IDs routes `v_` IDs to the verification instead
+of a step: `stepReport`, `Store.Authorize`, the transfer handlers
+(`transfers.go`, which today refuse a done task's steps) and `syncSteps`
+(a held verification attempt the instance does not know is cancelled;
+one it knows is reconciled like a step). `progressOf`, `advance`,
+`RetryTask`, `withdrawnSettle` and `offline` never see verifications.
+One handler, `verificationEnded(v, outcome)`, applies every final
+state, idempotent on `(id, attempt)`.
+
+### 5.3 Outcomes
+
+- **passed**: the receipt card gains "Checks passed on main afterwards."
+ (new revision, no new message); trust credit (§8); audit row.
+- **failed**: in one transaction: trust lowered (§8); a fix-task intent
+ (§5.5); one coordinator line in the creator's conversation, "Checks
+ failed on main after I merged [%s](%s). I opened [%s](%s) to fix it."
+ (or, when the intent could not start a task, "... I couldn't start a
+ fix: %s."); audit row.
+- **not_run** or **expired**: audit row and one line, "Checks still
+ couldn't run on main after merging [%s](%s) (%s)." Trust unchanged.
+
+### 5.4 Verified landing
+
+`mergeDone` records `merged_verified` only when the merge SHA is
+established, never guessed:
+
+- the hub's `200 {merged, sha}` answer gives it; or
+- reconciliation finds, on the default branch's first-parent line, the
+ commit that brought the candidate in (a merge whose second parent is
+ the candidate, or the candidate itself for a fast-forward or squash
+ recorded as such).
+
+`inspectMerge` (`internal/runner/thin/mergestep.go`) today falls back to
+the tip when the bounded search misses. Revised: it reports `MergeSHA`
+empty and the new optional `landing_verified: false`. The instance then
+marks the task done with `merged_sha` unknown, writes no verification
+and offers no Undo, and tells the creator: "Merged [%s](%s), but I
+couldn't tell which commit on main it is, so I can't check it or undo
+it." An old runner's report (no `landing_verified`) is treated the same
+for verification and Undo.
+
+### 5.5 Fix-task intent
+
+`chat_fix_intents`: `id`, `verification_id` (unique), `project_id`,
+`creator`, `title` ("Fix checks after merging %s", clipped), `brief`
+(merge SHA, gate, exit code, last 60 lines), `state` (`pending`,
+`created`, `started`, `reported`, `blocked`), `task_id`, `reason`.
+
+Written with the failure. `realizeIntent(id)` runs in the same
+transaction and again from `Place` while `pending` or `created`:
+
+- If the project has an open task created from an intent, the failure
+ is added to it as a report entry (`reported`); no new task.
+- Else it creates the task directly with the store's task insert (not
+ `recordTask`: no similarity check, no project card, no tool result),
+ `fix_intent` set on the task, then starts it with the internal start
+ (the creator is a current owner, execution is enabled, Engineering
+ dispatched as `startTask` does). A refusal leaves `created` or
+ `blocked` with the reason; the failure, trust change and line are
+ kept either way.
+
+The fix task goes through the gate like any task; with trust lowered it
+asks.
+
+## 6. Undo is a revert task
+
+The creator's Undo on a receipt (card, or `POST
+/api/v1/tasks/{id}/undo-merge`) within 7 days (`housekeeping.UndoWindow`)
+creates a **normal task** in the same project: title "Undo %s", brief
+"Revert merge commit <sha> on <branch> with `git revert -m 1 <sha>`
+(plain `git revert <sha>` for a squash). Change nothing else.",
+`revert_of` = the task, `revert_sha` = the recorded merge SHA; it is
+started at once (owner, execution enabled). It then runs Engineering,
+checks and Review like any task, and reaches the gate like any task.
+
+- Refused (409) with a line to the creator when the merge SHA is not
+ verified (§5.4), when the task already has an open or merged revert
+ task, outside the window, or for a teammate (404) or a non-owner
+ (403). Never falls back to main's tip.
+- **`revert_exact`** (only for a revert task): the review report's
+ change facts carry the optional `revert_of: {sha, exact}`, where the
+ runner compares `git patch-id --stable` of `git diff <sha> <sha>^1`
+ with that of `git diff <base> <candidate>`. Only `exact: true` for the
+ task's `revert_sha` passes. A revert that conflicted or did more is
+ asked about.
+- Trust is lowered when the revert task's merge is done (`mergeDone`
+ for a task with `revert_of`), once, keyed by the original merge SHA.
+
+No special runner step and no new specialist.
+
+## 7. Policy per project
+
+### 7.1 Storage
+
+Migration **0058** (next free on main ac4a809; another open branch may
+also claim 0058, and whichever lands second renumbers) adds tables
+`chat_merge_policies`, `chat_merge_audit`, `chat_merge_verifications`,
+`chat_fix_intents`, `chat_trust_credits`, and columns
+`chat_steps.change_facts`, `chat_tasks.merge_hold`,
+`chat_tasks.hold_revision`, `chat_tasks.merge_consent`,
+`chat_tasks.merged_verified`, `chat_tasks.revert_of`,
+`chat_tasks.revert_sha`, `chat_tasks.fix_intent`,
+`chat_tasks.merge_decision`. All additive; each table is registered in
+`chat.Models` and `Schema`, and the migration check covers them.
+
+`chat_merge_policies` (team record, one row per project):
+`project_id`, `mode` (`rules` | `always_ask`), `max_lines` (default
+300, 0 to 2000), `max_files` (default 15, 0 to 100), `main_ships`
+(`unknown` | `yes` | `no`), `ships_asked` (bool), `extra_sensitive`
+(JSON), `words` (<= 300 bytes, display only), `asks_left`,
+`trust_generation`, `trust_reason`, `revision`, `updated_by`,
+`updated_at`. No row means the defaults (`rules`, 300, 15, `unknown`).
+
+### 7.2 Setting it
+
+- **In conversation**: tool `set_merge_policy{project, words, mode?,
+ max_lines?, max_files?, main_ships?, add_sensitive?}`. Each field is
+ compared with the stored one. Only tighter fields (towards
+ `always_ask`, smaller numbers, `main_ships: yes`, added globs): applied
+ at once with a receipt and Undo (the home card's revision pattern;
+ Undo applies only if the revision is still the one it made, and never
+ restores trust fields). Any looser field: nothing applied; a confirm
+ card "Change how Equipo merges %s: %s? [Save] [Cancel]" for the
+ person, and Save (an owner, current revision) applies all of it. The
+ instance never parses words; they are stored for display.
+- **On the project page**: a section "How Equipo merges" (a partial
+ `merge_policy.html` included with one line in `work_project.html`, to
+ stay clear of the Projects and Tasks work) shows the policy in plain
+ sentences, the words, the trust state ("Asking for the next %d merges:
+ checks failed on main after %s.") and the last five decisions with
+ their reasons. An owner's form edits the fields (CSRF, revision,
+ current roster); teammates see it read only.
+- `GET/PUT /api/v1/projects/{id}/merge-policy` mirror the form.
-`chat_merge_audit`: `id`, `project_id`, `task_id`, `kind` (`decision`,
-`answer`, `merged`, `post_merge`, `fix_task`, `undo`, `trust`,
-`policy`), `candidate_sha`, `merge_sha`, `class`, `stance`,
-`decided_by` (`policy`, `person:<id>`, `coordinator:<id>`), `reasons`
-(JSON: every `Criterion`), `inputs` (JSON: the facts used, without
-paths beyond the first ten, policy revision, index head and signals,
-checks reason, review label, `asks_left`), `created_at`. Written in the
-same transaction as the effect; the transaction also appends the
-instance's audit event as every write does. No credentials, no model
-prose except the hold text. Read by the project page and `read_task`.
+No policy waives `approved_exact_sha`, `environment_reason`,
+`can_check_later`, `facts_present`, `small`, the default sensitive
+table, `trusted` or `no_hold`.
+
+### 7.3 Does main ship to users?
+
+`main_ships` starts `unknown`, and unknown fails `not_shipping`. The
+first time a decision fails only or partly on it, and `ships_asked` is
+false, the instance (in the same transaction) sends one card to the
+task's creator if they are an owner: "Does merging to %s's main ship to
+users? [It ships] [It doesn't]". The answer, by an owner on the current
+policy revision, sets `main_ships` (`yes` or `no`) as owner policy with
+an audit row; `ships_asked` stops a second card. The project page edits
+it too. Nothing in the repository (the checks script, the index, CI
+files) is evidence either way. The answer does not re-decide the task
+whose card is open; that card stays the person's to answer.
+
+## 8. Trust per project
+
+State on the policy row: `trust_generation` (starts 0), `asks_left`
+(starts 0, trusted). Table `chat_trust_credits`: `project_id`,
+`merge_sha`, `kind` (`credit` | `debit`), `generation`, unique on
+`(project_id, merge_sha, kind)`.
+
+Every merge done by Equipo records the `trust_generation` current at
+its `mergeDone` (on the verification row, or on the audit row for a
+checked merge).
+
+Transitions, each in the transaction of the event, each an audit row:
+
+- **Lower** (debit), on a verification `failed`, or a revert task's
+ merge done (keyed by the original merge SHA): if no debit row exists
+ for that key: `trust_generation += 1`, `asks_left = 5`,
+ `trust_reason` set, debit row written. A second, different failure
+ while lowered lowers again (new generation, 5 again).
+- **Credit**, on a clean merge: a merge with checks passed (at
+ `mergeDone`), or a verification `passed` from the primary or a
+ sandboxed worker (not `checks_sandbox: none`): if `asks_left > 0`, the
+ merge's recorded generation equals the current one, and no credit row
+ exists for its SHA: `asks_left -= 1`, credit row written. Merges from
+ an earlier generation never credit.
+- **Restored** when `asks_left` reaches 0; the project page says so.
+
+While `asks_left > 0`, `trusted` fails: every merge asks, including
+checks passed (§2.2 step 3). So a lowered project needs five clean
+merges, each of which a person approved, to be trusted again.
+
+## 9. Audit
+
+`chat_merge_audit`, append only: `id`, `project_id`, `task_id`,
+`kind` (`decision`, `authorize`, `answer`, `merged`,
+`landed_after_change`, `verification`, `fix_intent`, `undo`, `trust`,
+`policy`, `ships`), `at` (the `authorizeMerge` caller), `candidate_sha`,
+`merge_sha`, `class`, `stance`, `decided_by` (`policy`, `person:<id>`,
+`coordinator:<id>`), `reasons` (every `Criterion`), `inputs` (counts,
+the first ten matched paths, policy revision, trust generation and
+`asks_left`, hold revision, checks reason, review label, consent),
+`created_at`. Written in the transaction of the effect, which also
+appends the instance's audit event as every write does; a rolled-back
+effect leaves no row. No credentials and no model prose except the hold
+text.
+
+## 10. Wire and versions
+
+The gate and all decisions live on the instance. New wire fields are
+optional and `omitempty`: `StepReport.change`,
+`StepReport.landing_verified`, `ChangeFacts.revert_of`. They belong to a
+new **protocol 3**: the runner sends them only when the welcome says 3,
+and `wire.Encode` clears them for a protocol 2 connection (the existing
+`downgrade` pattern), so an old instance never receives a field its
+strict decoder refuses. Rollout order is instance first, then runners,
+as today.
+
+| Combination | Behaviour |
+|---|---|
+| New instance, old runner | no change facts: every merge without checks asks; no `landing_verified`: no verification, no Undo; consent and re-checks still apply (lease refusal is protocol 2) |
+| Old instance, new runner | protocol 2 welcome: the runner omits the new fields |
+| New both | as specified |
+| Runner downgraded after a receipt | Undo is a normal task (no capability needed); verification placement needs nothing new |
-## 9. Failure modes
+## 11. Failure modes
| What goes wrong | What happens |
|---|---|
-| Runner sends no or bad change facts | `Change` nil: asks |
-| A worker reports change facts | ignored (primary only): asks |
-| Index stale or missing | ships unknown: asks |
-| Branch moves after the decision | the runner's expect_sha refuses (`branch_moved`), as today |
-| Policy tightened while a merge step is in flight | the merge completes (merging cannot be cancelled); the next decision uses the new policy |
-| Mac never comes back | post-merge checks expire after 14 days with one line; `can_check_later` stays true only while the Mac is enrolled |
-| Post-merge checks fail repeatedly | one open fix task per project; later failures are reports on it |
-| Fix task cannot start (not an owner, execution off) | recorded, not started; the line says so |
-| Revert conflicts | Needs you on the revert task; nothing merged |
-| Old runner, no `revert` capability | no Undo offered; the receipt says how to revert on Amadan |
-| Deploy on upgrade with Ready tasks | only candidates first Ready after the deploy are decided; open cards stay |
+| Facts missing, incomplete, mismatched or from a worker | dropped: asks |
+| Policy, trust or hold changes with a merge queued | `Authorize` re-decides before the request; withdrawn, asks |
+| Change after the hub request was sent | reconciled from the default branch; audited `landed_after_change` |
+| Branch moves | expect_sha refuses (`branch_moved`), as today |
+| Merge SHA not established | done, no verification, no Undo, one line |
+| Mac never returns | verification expires after 14 days, one line |
+| Relay primary offline during a worker verification | no report within the hour: back to waiting, attempt n+1 |
+| Repeated failures | one open fix task per project; later failures are reports on it |
+| Fix task cannot start | intent `blocked` with the reason; the line says so |
+| Revert conflicts or does more | `revert_exact` fails: asks |
| The coordinator tries to loosen | confirm card; nothing changes without a tap |
-| Hub refuses (`ci_not_green`, forbidden) | today's reasons and Retry |
-
-## 10. Test plan
-
-Write each test first and watch it fail; break each guard and watch a
-test fail (mutations recorded in the progress log).
-
-- `mergegate`: `TestDecideEachCriterion` (all pass: act; each failing
- alone: ask with that criterion named); `TestDecideNever`;
- `TestDecideChecksPassedPath`; `TestDecideNeverLooser`, an invariant
- simulation over random inputs: `act` without checks implies every row
- of §2.1 holds (an independent oracle), a hold never yields `act`,
- no `Hold` text yields `Stance: merge` on its own;
- `TestSensitivePaths` (each class, token boundaries, `keyboard`,
- `monkey`, signing content rule, extra globs only add);
- `TestShipsToUsers` (signal beats `no`, native default, unknown asks).
-- Runner: `TestReviewReportsChangeFacts` (numstat, renames, binary,
- submodule, symlink, truncation, signing lines); `TestRevertStep`
- (clean, conflict, crash after push reconciles, squash);
- `TestPostMergeChecksOnMergeCommit` (worker pack relay of a merge SHA).
-- Store contracts (`internal/equipo/chat`): `TestContractMergeAuthorityAct`
- (Woodstar-shaped needs_macos change merges, receipt, audit row,
- post-merge step waiting); `TestContractMergeAuthorityAsks` (each
- criterion yields the card with the stance and options of §3.1);
- `TestContractWaitForAMac` (requeue without the offline limit, pass
- merges, fail fixes); `TestContractPostMergePassed`,
- `TestContractPostMergeFailed` (fix task started, one line, trust 5,
- next merge asks, second failure is a report);
- `TestContractUndoMerge` (revert task, revert step, merge step, trust,
- window, 403/404/409); `TestContractTrustCountdown`;
- `TestContractMergePolicyTool` (tighter applies with Undo, looser makes
- a confirm card, Save by an owner applies, a teammate cannot);
- `TestContractHoldMerge`; `TestContractMergeAuthorityNotRetroactive`
- (0058 on a database with a Ready task and an open card).
-- Pages: `TestProjectPageMergePolicy` (section, form, read only for
+| Hub refuses (`ci_not_green`, forbidden) | today's reasons and Retry, Retry through `authorizeMerge` |
+
+## 12. Test plan
+
+Each test is written first and watched failing; each guard is broken
+and a test watched failing (recorded in the progress log).
+
+**Gate (`mergegate`)**
+- `TestDecideEachCriterion`: all pass gives `act`; each criterion
+ failing alone gives `ask` naming it.
+- `TestDecideNever`; `TestDecideChecksPassedPath`; `TestDecideConsent`
+ (valid, and each voiding change).
+- `TestDecideNeverLooser`, an invariant simulation over random inputs:
+ `act` without checks and without consent implies every row of §2.2
+ holds (independent oracle); a hold never yields `act` without later
+ consent; no policy value waives a fixed criterion; size applies in
+ every mode.
+- `TestSensitivePaths`: each class at the root and nested, old and new
+ rename paths, token boundaries (`keyboard`, `monkey`, `tokenizer`),
+ extra globs only add.
+
+**Runner**
+- `TestReviewReportsChangeFacts`: numstat and raw agree, rename both
+ paths, binary, symlink, gitlink, mode change, new executable,
+ signing lines, a plain pbxproj file add, truncation, protocol 2 omits
+ the field.
+- `TestRevertPatchIDExact`: exact revert true; revert plus another edit
+ false.
+- `TestInspectMergeNeverGuessesTip`: the landing commit beyond the
+ search window gives `landing_verified: false`, empty SHA.
+
+**Store contracts (`internal/equipo/chat`)**
+- `TestContractMergeAuthorityAct`: a Woodstar-shaped needs_macos change
+ with `main_ships: no` merges, receipt, audit row, verification waiting.
+- `TestContractMergeAuthorityAsks`: each criterion gives the card with
+ the stance and options of §4.1.
+- `TestContractOneDoor`: every caller of §2.5 goes through
+ `authorizeMerge` (a `go/ast` scan of `startMerge` callers) and each
+ writes one audit row.
+- `TestContractAuthorizeRechecks`: a merge step queued for an offline
+ runner, then policy to `always_ask` (and separately a hold, a trust
+ drop, a void consent): the lease is refused, nothing reaches the
+ forge, the task asks.
+- `TestContractDeferredMergeRechecked`: deferred for the hub's CI, a
+ hold arrives, the resumption is refused.
+- `TestContractShipsQuestion`: one card per project, owner only,
+ stale revision 409, answer is policy, no second card.
+- `TestContractWaitForAMac`: requeue without the offline limit, pass
+ merges through consent, fail runs the fix round, consent voided by a
+ policy change asks again.
+- `TestContractVerificationLifecycle`: placed when a Mac comes online,
+ worker offline back to waiting, `placement_refused`, no report in an
+ hour, expiry, transfer for a `v_` ID, `syncSteps` with an unknown and
+ a known verification, the done task untouched throughout.
+- `TestContractVerificationPassed`, `TestContractVerificationFailed`
+ (intent, fix task started bypassing similarity, one line, trust 5,
+ next merge asks, a second failure is a report on the open fix task,
+ start refused keeps the line and trust).
+- `TestContractFixIntentIdempotent`: `realizeIntent` run twice and
+ after a crash between create and start makes one task.
+- `TestContractUndoMerge`: revert task created and started, normal
+ path, `revert_exact` passes and fails, unverified SHA refused with a
+ line, window, 403/404/409, trust lowered once at the revert's merge.
+- `TestContractTrustTransitions`: lower, a second failure, five clean
+ credits restore, an older generation's success never credits, a
+ merge credited once, outside-sandbox pass never credits.
+- `TestContractMergePolicyTool`: tighter applies with Undo, looser
+ makes a confirm card, Save by an owner applies, a teammate cannot,
+ Undo after a later change 409, Undo never touches trust.
+- `TestContractHoldMerge`; `TestContractRosterDenial`: a removed
+ member's or demoted owner's consent, Save, ships answer and Undo are
+ refused inside the transaction.
+- `TestContractAuditRollback`: an effect that fails rolls back its audit
+ row; a replayed report adds none.
+
+**Upgrade (migration 0058 on fixtures built with 0057)**
+- `TestUpgradeReadyWithOpenCard`, `TestUpgradeReadyAnsweredWait`,
+ `TestUpgradeMovedAwayReady`, `TestUpgradeEligibleChecked` (a
+ `merge_eligible` task still merges, through `authorizeMerge`),
+ `TestUpgradeMergingInFlight` (the next `Authorize` re-decides): none
+ merges without checks on upgrade, because none has change facts.
+- `TestUpgradeReplay`: a protocol 2 runner reconnecting and replaying
+ held reports after the upgrade.
+- `TestWireProtocol3Downgrade`: both directions of §10.
+
+**Pages and end to end**
+- `TestProjectPageMergePolicy` (section, form, read only for
teammates); browser `TestBrowserMergePolicy` with `-run`.
-- Headless: `ma_act` (fake CLI, local forge: an iOS change merges and
- tells, a fake Mac worker comes online, post-merge checks pass) and
- `ma_fail` (they fail: fix task, line, the next merge asks).
+- Headless `ma_act` (fake CLI, local forge: an iOS change merges and
+ tells; a fake Mac worker comes online; verification passes) and
+ `ma_fail` (fails: fix task, line, the next merge asks).
- Gates kept green: `make budget`, gofmt, `go vet ./internal/...`,
- `scripts/runner-dead-references.py`, `TestPlan3ReleaseBoundaries`.
-
-## 11. Copy
-
-All new strings in `internal/equipo/copy.go` marked `COPY REVIEW
-REQUIRED` and listed in the Plan 3 copy inventory: the card stances
-and phrases (§3.1), Wait for a Mac, the receipt and its passed line
-(§5), the failure, fix-task and could-not-run lines (§4.2), Undo's
-refusals, the policy confirm card and receipts (§6.2), the project page
-section, the trust sentence, the tool descriptions of `hold_merge` and
-`set_merge_policy`.
-
-## 12. Choices to confirm with Paul
-
-1. Trust: "a clean run restores it" read as: five clean merges restore
- it, and a failure while lowered starts the five again.
+ `scripts/runner-dead-references.py`, `TestPlan3ReleaseBoundaries`,
+ the migration and model check.
+
+## 13. Round 1 findings and where they went
+
+1. Size waivable: `review_enough` removed; `small` in every mode (§2.2, §7.2).
+2. Facts underspecified: raw plus numstat, both paths, modes, any depth,
+ bound to the review run, acceptance rules (§3).
+3. Shipping inferred: removed; `unknown` asks; one owner question per
+ project; nothing in the repository is evidence (§7.3).
+4. Gate invocation incomplete: one door `authorizeMerge` for every path
+ (§2.5).
+5. Queued merges outlive authority: re-check before every hub request,
+ consent voided by changes (§2.4, §2.6).
+6. Done-task paths: verification is its own record and lifecycle (§5).
+7. Lost Mac need: needs copied at merge time, shared `runnerFits`,
+ absolute expiry, relay recovery (§2.3, §5).
+8. Undo state machine: a normal revert task, no special step (§6).
+9. Tip fallback: never guessed; unverified means no verification and no
+ Undo (§5.4).
+10. Trust ordering: generation, unique credits and debits, transitions
+ (§8).
+11. Fix task not guaranteed: durable intent, direct insert, idempotent
+ (§5.5).
+12. Mixed versions: protocol 3 optional fields, downgrade, table (§10).
+13. Tests: upgrade, roster, audit and lifecycle cases listed (§12).
+
+## 14. Choices to confirm with Paul
+
+1. Trust: lowered for five clean merges of the current generation; each
+ asks, so each is a person's call.
2. Lowered trust and `always_ask` also ask for checks-passed merges.
3. Any binary file (an image asset) asks.
-4. "merge when Review approves" waives only the size limit.
-5. Projects that are not Xcode apps and have no deploy signal ask until
- someone says "main is not a release".
+4. "for Woodstar, merge when Review approves" is the default `rules`
+ mode plus `main_ships: no`; it waives nothing else.
+5. Answering "Does main ship?" does not re-decide the card already open.