mergegate: the merge authority as a pure function; protocol 3 wire
Decide(Inputs) answers act, ask or never with every criterion and Equipo's stance; Sensitive matches both paths of every entry against the fixed table and a project's added globs; ValidPolicy and Tighter bound what a policy may hold and what the coordinator may apply alone. Wire protocol 3: optional change facts and merge provenance on step reports, the merge_request lease purpose, a revert's target on dispatch, and the merge_not_authorized reason; Encode drops protocol 3 fields for protocol 2 and 1.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
6 files changed,
+849
−8
internal/equipo/mergegate/gate.go+260 −0internal/equipo/mergegate/gate_test.go+342 −0internal/equipo/mergegate/sensitive.go+143 −0internal/wire/frames.go+8 −0internal/wire/runners.go+32 −8internal/wire/tasks.go+64 −0
Intent
diff --git a/internal/equipo/mergegate/gate.go b/internal/equipo/mergegate/gate.go| new file mode 100644 |
| index 00000000..1321d23c |
| --- /dev/null |
| +++ b/internal/equipo/mergegate/gate.go |
| @@ -0,0 +1,260 @@ |
| +// Package mergegate is Equipo's merge authority (spec |
| +// docs/superpowers/specs/2026-11-11-equipo-merge-authority.md): one pure |
| +// function decides whether Equipo may send a merge request on its own, |
| +// must ask its person, or must do nothing. No store, clock or I/O: the |
| +// instance builds the inputs inside its write transaction. No model's |
| +// words can make it merge; a hold (the coordinator's) can only stop it. |
| +package mergegate |
| + |
| +import ( |
| + "path" |
| + "slices" |
| + "strings" |
| + |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +// Decision classes, the housekeeping classes by name. |
| +const ( |
| + ClassAct = "act" |
| + ClassAsk = "ask" |
| + ClassNever = "never" |
| +) |
| + |
| +// Stances: Equipo's own call on an ask card. |
| +const ( |
| + StanceMerge = "merge" |
| + StanceWait = "wait" |
| +) |
| + |
| +// Who decided an act. |
| +const ( |
| + DecidedPolicy = "policy" |
| + DecidedPerson = "person" |
| +) |
| + |
| +// Policy modes and the answers to "does main ship to users?". |
| +const ( |
| + ModeRules = "rules" |
| + ModeAsk = "ask" |
| + ShipsUnknown = "unknown" |
| + ShipsYes = "yes" |
| + ShipsNo = "no" |
| +) |
| + |
| +// Policy bounds (spec §7.1). |
| +const ( |
| + DefaultMaxLines = 300 |
| + DefaultMaxFiles = 15 |
| + MaxLinesCeiling = 2000 |
| + MaxFilesCeiling = 100 |
| + MaxExtraGlobs = 20 |
| + MaxGlobBytes = 200 |
| + // MinProtocol is the runner protocol that measures change facts and |
| + // confirms each merge request (wire.Protocol3). |
| + MinProtocol = wire.Protocol3 |
| +) |
| + |
| +// Criteria, in the order Decide evaluates and reports them. |
| +const ( |
| + CritApproved = "approved_exact_sha" |
| + CritEnvironment = "environment_reason" |
| + CritProtocol = "runner_protocol" |
| + CritFacts = "facts_present" |
| + CritSmall = "small" |
| + CritSensitive = "not_sensitive" |
| + CritShips = "main_does_not_ship" |
| + CritPolicy = "policy_allows" |
| + CritHold = "no_hold" |
| + CritRevert = "revert_exact" |
| + CritEligible = "first_ready_checked" |
| + CritSandbox = "checked_in_sandbox" |
| +) |
| + |
| +// environment are the reasons checks could not run that say nothing |
| +// about the change: no Mac, or the runner that could run them offline. |
| +var environment = []string{"needs_macos", "runner_offline"} |
| + |
| +// Policy is a project's merge policy. |
| +type Policy struct { |
| + Mode string |
| + MaxLines int |
| + MaxFiles int |
| + MainShips string |
| + ExtraSensitive []string |
| +} |
| + |
| +// DefaultPolicy applies to a project without a row. |
| +func DefaultPolicy() Policy { |
| + return Policy{Mode: ModeRules, MaxLines: DefaultMaxLines, MaxFiles: DefaultMaxFiles, MainShips: ShipsUnknown} |
| +} |
| + |
| +// ValidPolicy reports whether every field is inside its bounds. |
| +func ValidPolicy(p Policy) bool { |
| + if p.Mode != ModeRules && p.Mode != ModeAsk || !slices.Contains([]string{ShipsUnknown, ShipsYes, ShipsNo}, p.MainShips) { |
| + return false |
| + } |
| + if p.MaxLines < 0 || p.MaxLines > MaxLinesCeiling || p.MaxFiles < 0 || p.MaxFiles > MaxFilesCeiling || len(p.ExtraSensitive) > MaxExtraGlobs { |
| + return false |
| + } |
| + for _, g := range p.ExtraSensitive { |
| + if !ValidGlob(g) { |
| + return false |
| + } |
| + } |
| + return true |
| +} |
| + |
| +// ValidGlob reports whether g is a usable project glob: relative, clean, |
| +// at most MaxGlobBytes, path.Match syntax per segment plus "**". |
| +func ValidGlob(g string) bool { |
| + if g == "" || len(g) > MaxGlobBytes || strings.HasPrefix(g, "/") || strings.ContainsAny(g, "\x00\\") { |
| + return false |
| + } |
| + for _, seg := range strings.Split(g, "/") { |
| + if seg == "" || seg == "." || seg == ".." { |
| + return false |
| + } |
| + if _, err := path.Match(seg, ""); err != nil { |
| + return false |
| + } |
| + } |
| + return true |
| +} |
| + |
| +// Tighter reports whether next allows nothing that old did not: what |
| +// the coordinator may apply without a person's tap. |
| +func Tighter(old, next Policy) bool { |
| + if old.Mode == ModeAsk && next.Mode != ModeAsk || next.MaxLines > old.MaxLines || next.MaxFiles > old.MaxFiles { |
| + return false |
| + } |
| + if next.MainShips != old.MainShips && next.MainShips != ShipsYes { |
| + return false |
| + } |
| + for _, g := range old.ExtraSensitive { |
| + if !slices.Contains(next.ExtraSensitive, g) { |
| + return false |
| + } |
| + } |
| + return true |
| +} |
| + |
| +// Inputs are the facts of one decision, built by the instance. |
| +type Inputs struct { |
| + // Candidate is the newest pushed candidate, "" when the branch moved. |
| + Candidate string |
| + // Verdict, Checks and ChecksReason are the finished judgements of |
| + // Candidate ("" while one runs). |
| + Verdict, Checks, ChecksReason string |
| + // OutsideSandbox: the checks ran with checks_sandbox none. |
| + OutsideSandbox bool |
| + // Eligible: Candidate first earned Ready with checks passed (slice 4c's |
| + // merge_eligible). |
| + Eligible bool |
| + // Person: the task's creator, a current owner, chose Merge for this |
| + // SHA. |
| + Person bool |
| + // Change is the review's measured change, nil when missing or refused. |
| + Change *wire.ChangeFacts |
| + // Protocol is the primary runner's protocol on the connection that |
| + // will send (or is sending) the request. |
| + Protocol int |
| + Policy Policy |
| + // Hold is the coordinator's hold on the task, "" when none. |
| + Hold string |
| + // RevertSHA is set for a revert task: the merge commit it undoes. |
| + RevertSHA string |
| +} |
| + |
| +// Criterion is one rule's outcome, for the card and the audit. |
| +type Criterion struct { |
| + Name string `json:"name"` |
| + OK bool `json:"ok"` |
| + Value string `json:"value,omitempty"` |
| +} |
| + |
| +// Decision is the gate's answer. |
| +type Decision struct { |
| + Class string `json:"class"` |
| + Stance string `json:"stance,omitempty"` |
| + Checks bool `json:"checks"` |
| + DecidedBy string `json:"decided_by,omitempty"` |
| + Reasons []Criterion `json:"reasons"` |
| + // Sensitive are the matches that failed not_sensitive. |
| + Sensitive []Match `json:"sensitive,omitempty"` |
| +} |
| + |
| +// Failing names the criteria that did not hold. |
| +func (d Decision) Failing() []string { |
| + var out []string |
| + for _, c := range d.Reasons { |
| + if !c.OK { |
| + out = append(out, c.Name) |
| + } |
| + } |
| + return out |
| +} |
| + |
| +// Decide is the merge authority. Never: nothing to merge. A person's |
| +// Merge acts on approved work. Checked work acts as slice 4c did, on a |
| +// protocol 3 runner, unless the project asks or a hold stops it. |
| +// Unchecked work acts only when every criterion holds. |
| +func Decide(in Inputs) Decision { |
| + if in.Candidate == "" || in.Verdict != wire.VerdictApprove { |
| + return Decision{Class: ClassNever, Reasons: []Criterion{{Name: CritApproved}}} |
| + } |
| + switch in.Checks { |
| + case wire.ChecksPassed, wire.ChecksCannotRun, wire.ChecksNone: |
| + default: |
| + return Decision{Class: ClassNever, Reasons: []Criterion{{Name: CritApproved, OK: true}, {Name: CritEnvironment, Value: in.Checks}}} |
| + } |
| + approved := Criterion{Name: CritApproved, OK: true} |
| + if in.Person { |
| + return Decision{Class: ClassAct, Checks: in.Checks == wire.ChecksPassed, DecidedBy: DecidedPerson, Reasons: []Criterion{approved}} |
| + } |
| + validPolicy := ValidPolicy(in.Policy) |
| + protocol := Criterion{Name: CritProtocol, OK: in.Protocol >= MinProtocol} |
| + policy := Criterion{Name: CritPolicy, OK: validPolicy && in.Policy.Mode == ModeRules, Value: in.Policy.Mode} |
| + hold := Criterion{Name: CritHold, OK: in.Hold == ""} |
| + if in.Checks == wire.ChecksPassed { |
| + rs := []Criterion{approved, {Name: CritEligible, OK: in.Eligible}, {Name: CritSandbox, OK: !in.OutsideSandbox}, protocol, policy, hold} |
| + return decided(rs, true, nil, []string{CritEligible, CritProtocol, CritPolicy}) |
| + } |
| + c := in.Change |
| + facts := Criterion{Name: CritFacts, OK: c != nil && c.Complete} |
| + rs := []Criterion{approved, {Name: CritEnvironment, OK: in.Checks == wire.ChecksCannotRun && slices.Contains(environment, in.ChecksReason), Value: in.ChecksReason}, protocol, facts} |
| + var matches []Match |
| + if facts.OK { |
| + small := validPolicy && c.Lines <= in.Policy.MaxLines && c.Files <= in.Policy.MaxFiles && c.Binary == 0 |
| + matches = Sensitive(c.Entries, in.Policy.ExtraSensitive) |
| + rs = append(rs, Criterion{Name: CritSmall, OK: small}, Criterion{Name: CritSensitive, OK: len(matches) == 0 && !c.Special && !c.Signing}) |
| + } else { |
| + rs = append(rs, Criterion{Name: CritSmall}, Criterion{Name: CritSensitive}) |
| + } |
| + rs = append(rs, Criterion{Name: CritShips, OK: validPolicy && in.Policy.MainShips == ShipsNo, Value: in.Policy.MainShips}, policy, hold) |
| + if in.RevertSHA != "" { |
| + ok := facts.OK && c.Revert != nil && c.Revert.SHA == in.RevertSHA && c.Revert.OnTop && c.Revert.Exact |
| + rs = append(rs, Criterion{Name: CritRevert, OK: ok}) |
| + } |
| + return decided(rs, false, matches, []string{CritSmall, CritPolicy}) |
| +} |
| + |
| +// decided is act when every criterion holds, else ask; the stance is |
| +// merge only when every failing criterion is one of soft. |
| +func decided(rs []Criterion, checks bool, matches []Match, soft []string) Decision { |
| + d := Decision{Class: ClassAct, Checks: checks, DecidedBy: DecidedPolicy, Reasons: rs, Sensitive: matches} |
| + stance := StanceMerge |
| + for _, c := range rs { |
| + if c.OK { |
| + continue |
| + } |
| + d.Class, d.DecidedBy = ClassAsk, "" |
| + if !slices.Contains(soft, c.Name) { |
| + stance = StanceWait |
| + } |
| + } |
| + if d.Class == ClassAsk { |
| + d.Stance = stance |
| + } |
| + return d |
| +} |
diff --git a/internal/equipo/mergegate/gate_test.go b/internal/equipo/mergegate/gate_test.go| new file mode 100644 |
| index 00000000..69768d27 |
| --- /dev/null |
| +++ b/internal/equipo/mergegate/gate_test.go |
| @@ -0,0 +1,342 @@ |
| +package mergegate |
| + |
| +import ( |
| + "math/rand/v2" |
| + "slices" |
| + "strings" |
| + "testing" |
| + |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +var ( |
| + cand = strings.Repeat("2", 40) |
| + base = strings.Repeat("1", 40) |
| +) |
| + |
| +func smallChange() *wire.ChangeFacts { |
| + return &wire.ChangeFacts{ReviewStep: "s_r", Attempt: 1, Repo: "amadan.net/woodstar/woodstar", Base: base, SHA: cand, Files: 2, Lines: 40, Complete: true, |
| + Entries: []wire.ChangeEntry{ |
| + {Status: "M", New: "Woodstar/Views/PaneView.swift", OldMode: "100644", NewMode: "100644"}, |
| + {Status: "M", New: "Woodstar/Views/EdgeSwipe.swift", OldMode: "100644", NewMode: "100644"}, |
| + }} |
| +} |
| + |
| +// passing is a merge without checks that every criterion allows. |
| +func passing() Inputs { |
| + p := DefaultPolicy() |
| + p.MainShips = ShipsNo |
| + return Inputs{Candidate: cand, Verdict: wire.VerdictApprove, Checks: wire.ChecksCannotRun, ChecksReason: "needs_macos", Change: smallChange(), Protocol: wire.Protocol3, Policy: p} |
| +} |
| + |
| +func failing(d Decision) []string { |
| + var out []string |
| + for _, c := range d.Reasons { |
| + if !c.OK { |
| + out = append(out, c.Name) |
| + } |
| + } |
| + return out |
| +} |
| + |
| +// TestDecideEachCriterion: every criterion holding merges; each one |
| +// failing alone asks, and names that criterion. |
| +func TestDecideEachCriterion(t *testing.T) { |
| + if d := Decide(passing()); d.Class != ClassAct || d.Checks || len(failing(d)) != 0 { |
| + t.Fatalf("all pass: %+v", d) |
| + } |
| + cases := map[string]func(*Inputs){ |
| + CritEnvironment: func(in *Inputs) { in.ChecksReason = "checks_timeout" }, |
| + CritProtocol: func(in *Inputs) { in.Protocol = wire.Protocol2 }, |
| + CritFacts: func(in *Inputs) { in.Change = nil }, |
| + CritSmall: func(in *Inputs) { in.Change.Lines = 301 }, |
| + CritSensitive: func(in *Inputs) { in.Change.Entries[0].New = "Woodstar/Billing/Checkout.swift" }, |
| + CritShips: func(in *Inputs) { in.Policy.MainShips = ShipsUnknown }, |
| + CritPolicy: func(in *Inputs) { in.Policy.Mode = ModeAsk }, |
| + CritHold: func(in *Inputs) { in.Hold = "this touches the pane stack" }, |
| + } |
| + for name, change := range cases { |
| + in := passing() |
| + change(&in) |
| + d := Decide(in) |
| + if d.Class != ClassAsk || !slices.Contains(failing(d), name) { |
| + t.Errorf("%s failing: %+v", name, d) |
| + } |
| + } |
| + more := map[string]func(*Inputs){ |
| + "files": func(in *Inputs) { in.Change.Files = 16 }, |
| + "incomplete": func(in *Inputs) { in.Change.Complete = false }, |
| + "binary": func(in *Inputs) { in.Change.Binary = 1 }, |
| + "special": func(in *Inputs) { in.Change.Special = true }, |
| + "signing": func(in *Inputs) { in.Change.Signing = true }, |
| + "rename from": func(in *Inputs) { in.Change.Entries[0].Old = "Woodstar/Auth/Login.swift" }, |
| + "ships yes": func(in *Inputs) { in.Policy.MainShips = ShipsYes }, |
| + "checks none": func(in *Inputs) { in.Checks, in.ChecksReason = wire.ChecksNone, "" }, |
| + "needs network": func(in *Inputs) { in.ChecksReason = "needs_network" }, |
| + "unavailable": func(in *Inputs) { in.ChecksReason = "checks_unavailable" }, |
| + "protocol 1": func(in *Inputs) { in.Protocol = wire.Protocol1 }, |
| + "extra sensitive": func(in *Inputs) { in.Policy.ExtraSensitive = []string{"Woodstar/Views/**"} }, |
| + "limit lines zero": func(in *Inputs) { in.Policy.MaxLines = 0 }, |
| + "revert inexact": func(in *Inputs) { |
| + in.RevertSHA = strings.Repeat("e", 40) |
| + in.Change.Revert = &wire.RevertCheck{SHA: in.RevertSHA, OnTop: true} |
| + }, |
| + } |
| + for name, change := range more { |
| + in := passing() |
| + change(&in) |
| + if d := Decide(in); d.Class != ClassAsk { |
| + t.Errorf("%s: %+v", name, d) |
| + } |
| + } |
| + in := passing() |
| + in.RevertSHA = strings.Repeat("e", 40) |
| + in.Change.Revert = &wire.RevertCheck{SHA: in.RevertSHA, OnTop: true, Exact: true} |
| + if d := Decide(in); d.Class != ClassAct { |
| + t.Fatalf("an exact revert: %+v", d) |
| + } |
| +} |
| + |
| +// TestDecideNever: not approved, checks failed or still running, or no |
| +// candidate: nothing at all, even for a person. |
| +func TestDecideNever(t *testing.T) { |
| + cases := []func(*Inputs){ |
| + func(in *Inputs) { in.Candidate = "" }, |
| + func(in *Inputs) { in.Verdict = wire.VerdictChanges }, |
| + func(in *Inputs) { in.Verdict = "" }, |
| + func(in *Inputs) { in.Checks = wire.ChecksFailed }, |
| + func(in *Inputs) { in.Checks = "" }, |
| + func(in *Inputs) { in.Checks = "maybe" }, |
| + } |
| + for i, change := range cases { |
| + in := passing() |
| + change(&in) |
| + in.Person = true |
| + if d := Decide(in); d.Class != ClassNever { |
| + t.Errorf("case %d: %+v", i, d) |
| + } |
| + } |
| +} |
| + |
| +// TestDecideChecksPassedPath: checked work merges on its own only when it |
| +// first earned Ready with checks passed, inside the sandbox, on a |
| +// protocol 3 runner, with no hold and the project not asking. Size, |
| +// sensitivity and shipping do not apply to it. |
| +func TestDecideChecksPassedPath(t *testing.T) { |
| + ok := Inputs{Candidate: cand, Verdict: wire.VerdictApprove, Checks: wire.ChecksPassed, Eligible: true, Protocol: wire.Protocol3, Policy: DefaultPolicy()} |
| + if d := Decide(ok); d.Class != ClassAct || !d.Checks { |
| + t.Fatalf("checked: %+v", d) |
| + } |
| + for name, change := range map[string]func(*Inputs){ |
| + CritEligible: func(in *Inputs) { in.Eligible = false }, |
| + CritSandbox: func(in *Inputs) { in.OutsideSandbox = true }, |
| + CritProtocol: func(in *Inputs) { in.Protocol = wire.Protocol2 }, |
| + CritPolicy: func(in *Inputs) { in.Policy.Mode = ModeAsk }, |
| + CritHold: func(in *Inputs) { in.Hold = "wait" }, |
| + "no protocol": func(in *Inputs) { in.Protocol = 0 }, |
| + } { |
| + in := ok |
| + change(&in) |
| + if d := Decide(in); d.Class != ClassAsk { |
| + t.Errorf("%s: %+v", name, d) |
| + } |
| + } |
| +} |
| + |
| +// TestDecidePersonMerge: a person's Merge acts on approved work whatever |
| +// the policy, the hold or the runner say; never on unapproved work. |
| +func TestDecidePersonMerge(t *testing.T) { |
| + in := passing() |
| + in.Person, in.Change, in.Protocol, in.Hold, in.Policy.Mode = true, nil, wire.Protocol1, "hold", ModeAsk |
| + if d := Decide(in); d.Class != ClassAct || d.DecidedBy != DecidedPerson { |
| + t.Fatalf("person: %+v", d) |
| + } |
| +} |
| + |
| +// TestDecideStance: Equipo's call on an ask card. Only size or the |
| +// project's ask mode leave it recommending the merge. |
| +func TestDecideStance(t *testing.T) { |
| + in := passing() |
| + in.Change.Lines = 900 |
| + if d := Decide(in); d.Stance != StanceMerge { |
| + t.Fatalf("big: %+v", d) |
| + } |
| + in = passing() |
| + in.Policy.Mode = ModeAsk |
| + if d := Decide(in); d.Stance != StanceMerge { |
| + t.Fatalf("ask mode: %+v", d) |
| + } |
| + for name, change := range map[string]func(*Inputs){ |
| + "sensitive": func(in *Inputs) { in.Change.Entries[0].New = "go.mod" }, |
| + "ships": func(in *Inputs) { in.Policy.MainShips = ShipsUnknown }, |
| + "hold": func(in *Inputs) { in.Hold = "no" }, |
| + "facts": func(in *Inputs) { in.Change = nil }, |
| + } { |
| + in := passing() |
| + change(&in) |
| + if d := Decide(in); d.Stance != StanceWait { |
| + t.Errorf("%s: %+v", name, d) |
| + } |
| + } |
| +} |
| + |
| +// oracle is the rule written out once more, independently: Equipo may |
| +// merge on its own without checks only when every criterion holds. |
| +func oracle(in Inputs) bool { |
| + if in.Candidate == "" || in.Verdict != wire.VerdictApprove || in.Checks != wire.ChecksCannotRun { |
| + return false |
| + } |
| + if in.ChecksReason != "needs_macos" && in.ChecksReason != "runner_offline" { |
| + return false |
| + } |
| + if in.Protocol < 3 || in.Change == nil || !in.Change.Complete || in.Hold != "" || in.Policy.Mode != ModeRules || in.Policy.MainShips != ShipsNo { |
| + return false |
| + } |
| + if in.Policy.MaxLines < 0 || in.Policy.MaxLines > 2000 || in.Policy.MaxFiles < 0 || in.Policy.MaxFiles > 100 { |
| + return false |
| + } |
| + c := in.Change |
| + if c.Lines > in.Policy.MaxLines || c.Files > in.Policy.MaxFiles || c.Binary > 0 || c.Special || c.Signing { |
| + return false |
| + } |
| + if len(Sensitive(c.Entries, in.Policy.ExtraSensitive)) > 0 { |
| + return false |
| + } |
| + if in.RevertSHA != "" && (c.Revert == nil || c.Revert.SHA != in.RevertSHA || !c.Revert.OnTop || !c.Revert.Exact) { |
| + return false |
| + } |
| + return true |
| +} |
| + |
| +// TestDecideNeverLooser: over random inputs, Decide merges unchecked work |
| +// on its own only when the oracle does, a hold never yields a merge |
| +// without a person, and no policy value waives a criterion. |
| +func TestDecideNeverLooser(t *testing.T) { |
| + rng := rand.New(rand.NewPCG(1, 2)) |
| + pick := func(xs ...string) string { return xs[rng.IntN(len(xs))] } |
| + paths := []string{"Woodstar/Views/Pane.swift", "README.md", "go.mod", "app/payments/x.go", "db/migrations/1.sql", ".amadan/ci", "Sources/Keyboard.swift", "infra/main.tf", "lib/tokenizer.go"} |
| + for i := 0; i < 20000; i++ { |
| + in := Inputs{ |
| + Candidate: pick(cand, ""), |
| + Verdict: pick(wire.VerdictApprove, wire.VerdictApprove, wire.VerdictChanges, ""), |
| + Checks: pick(wire.ChecksCannotRun, wire.ChecksCannotRun, wire.ChecksPassed, wire.ChecksNone, wire.ChecksFailed, ""), |
| + ChecksReason: pick("needs_macos", "runner_offline", "checks_timeout", "needs_network", ""), |
| + OutsideSandbox: rng.IntN(4) == 0, |
| + Eligible: rng.IntN(2) == 0, |
| + Protocol: rng.IntN(4), |
| + Hold: pick("", "", "", "careful"), |
| + Policy: Policy{Mode: pick(ModeRules, ModeRules, ModeAsk, "loose"), MaxLines: rng.IntN(3000) - 500, MaxFiles: rng.IntN(200) - 20, MainShips: pick(ShipsNo, ShipsNo, ShipsYes, ShipsUnknown, "maybe")}, |
| + RevertSHA: pick("", "", strings.Repeat("e", 40)), |
| + } |
| + if rng.IntN(5) > 0 { |
| + c := &wire.ChangeFacts{Complete: rng.IntN(6) > 0, Files: rng.IntN(30), Lines: rng.IntN(800), Binary: rng.IntN(3) / 2, Special: rng.IntN(8) == 0, Signing: rng.IntN(8) == 0} |
| + for j := 0; j < 1+rng.IntN(3); j++ { |
| + c.Entries = append(c.Entries, wire.ChangeEntry{Status: "M", New: paths[rng.IntN(len(paths))], Old: pick("", "", paths[rng.IntN(len(paths))])}) |
| + } |
| + if rng.IntN(2) == 0 { |
| + c.Revert = &wire.RevertCheck{SHA: pick(strings.Repeat("e", 40), cand), OnTop: rng.IntN(2) == 0, Exact: rng.IntN(2) == 0} |
| + } |
| + in.Change = c |
| + } |
| + d := Decide(in) |
| + if d.Class == ClassAct && !d.Checks && !oracle(in) { |
| + t.Fatalf("merged without checks against the rule: %+v -> %+v", in, d) |
| + } |
| + if oracle(in) && d.Class != ClassAct { |
| + t.Fatalf("refused what the rule allows: %+v -> %+v", in, d) |
| + } |
| + if in.Hold != "" && d.Class == ClassAct { |
| + t.Fatalf("a hold merged: %+v", in) |
| + } |
| + if d.Class == ClassAct && d.Checks && (in.Checks != wire.ChecksPassed || !in.Eligible || in.OutsideSandbox || in.Protocol < 3 || in.Policy.Mode != ModeRules) { |
| + t.Fatalf("checked merge against the rule: %+v", in) |
| + } |
| + } |
| +} |
| + |
| +// TestSensitivePaths: each class, at the root and nested, on either side |
| +// of a rename; whole tokens only; a project's globs only add. |
| +func TestSensitivePaths(t *testing.T) { |
| + yes := []string{ |
| + "db/migrations/0001_init.sql", "internal/equipo/migrations/0058_x.sql", "schema.prisma", "app/db/schema.rb", |
| + ".env", "config/.env.production", "certs/server.pem", "ios/AuthKey.p8", |
| + "Sources/Auth/LoginView.swift", "lib/session_store.go", "pkg/crypto/aes.go", "api/tokens.go", "OAuthClient.swift", "keys/README.md", |
| + "Woodstar/Billing/Checkout.swift", "server/stripe_webhook.go", "StoreKit/Purchase.swift", |
| + ".amadan/ci", ".amadan/ci.d/10-test", ".github/workflows/ci.yml", "Makefile", "tools/Makefile", "build/rules.mk", |
| + "go.mod", "go.sum", "server/go.mod", "web/package.json", "web/package-lock.json", "app/yarn.lock", "Cargo.lock", "Package.swift", "Woodstar.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved", "Podfile.lock", "app/build.gradle.kts", ".gitmodules", "vendor/x/y.go", |
| + "Woodstar/Woodstar.entitlements", "fastlane/Fastfile", "Config/Release.xcconfig", "VERSION", "scripts/release.sh", |
| + "infra/main.tf", "Dockerfile", "deploy/k8s/app.yaml", "docker-compose.yml", "fly.toml", "systemd/equipo.service", |
| + } |
| + for _, p := range yes { |
| + if len(Sensitive([]wire.ChangeEntry{{Status: "M", New: p}}, nil)) == 0 { |
| + t.Errorf("not sensitive: %s", p) |
| + } |
| + if len(Sensitive([]wire.ChangeEntry{{Status: "R100", Old: p, New: "docs/moved.txt"}}, nil)) == 0 { |
| + t.Errorf("rename from %s not sensitive", p) |
| + } |
| + } |
| + no := []string{"Sources/Keyboard.swift", "lib/tokenizer.go", "Woodstar/Views/PaneView.swift", "README.md", "docs/monkey.md", "Sources/KeyboardShortcuts.swift", "Woodstar.xcodeproj/project.pbxproj", "Sources/SessionlessView.swift", "app/Authorship.swift"} |
| + for _, p := range no { |
| + if m := Sensitive([]wire.ChangeEntry{{Status: "M", New: p}}, nil); len(m) != 0 { |
| + t.Errorf("sensitive: %s %+v", p, m) |
| + } |
| + } |
| + if len(Sensitive([]wire.ChangeEntry{{Status: "M", New: "Woodstar/Views/PaneView.swift"}}, []string{"Woodstar/Views/*.swift"})) == 0 { |
| + t.Error("a project's glob did not add") |
| + } |
| + if len(Sensitive([]wire.ChangeEntry{{Status: "M", New: "a/b/Woodstar/Views/PaneView.swift"}}, []string{"Woodstar/Views/*.swift"})) == 0 { |
| + t.Error("a project's glob does not match at depth") |
| + } |
| +} |
| + |
| +// TestValidPolicy: numbers inside their bounds, known modes, at most 20 |
| +// clean globs. |
| +func TestValidPolicy(t *testing.T) { |
| + p := DefaultPolicy() |
| + if !ValidPolicy(p) { |
| + t.Fatal("defaults invalid") |
| + } |
| + for name, change := range map[string]func(*Policy){ |
| + "lines": func(p *Policy) { p.MaxLines = MaxLinesCeiling + 1 }, |
| + "files": func(p *Policy) { p.MaxFiles = -1 }, |
| + "mode": func(p *Policy) { p.Mode = "loose" }, |
| + "ships": func(p *Policy) { p.MainShips = "maybe" }, |
| + "globs": func(p *Policy) { p.ExtraSensitive = make([]string, 21) }, |
| + "glob": func(p *Policy) { p.ExtraSensitive = []string{"[bad"} }, |
| + "abs": func(p *Policy) { p.ExtraSensitive = []string{"/etc/**"} }, |
| + "length": func(p *Policy) { p.ExtraSensitive = []string{strings.Repeat("a", 201)} }, |
| + } { |
| + q := DefaultPolicy() |
| + change(&q) |
| + if ValidPolicy(q) { |
| + t.Errorf("%s accepted", name) |
| + } |
| + } |
| +} |
| + |
| +// TestTighter: what the coordinator may apply on its own. |
| +func TestTighter(t *testing.T) { |
| + old := DefaultPolicy() |
| + for name, p := range map[string]Policy{ |
| + "ask": {Mode: ModeAsk, MaxLines: 300, MaxFiles: 15, MainShips: ShipsUnknown}, |
| + "lines": {Mode: ModeRules, MaxLines: 100, MaxFiles: 15, MainShips: ShipsUnknown}, |
| + "ships": {Mode: ModeRules, MaxLines: 300, MaxFiles: 15, MainShips: ShipsYes}, |
| + "globs": {Mode: ModeRules, MaxLines: 300, MaxFiles: 15, MainShips: ShipsUnknown, ExtraSensitive: []string{"x/**"}}, |
| + } { |
| + if !Tighter(old, p) { |
| + t.Errorf("%s not tighter", name) |
| + } |
| + } |
| + strict := Policy{Mode: ModeAsk, MaxLines: 100, MaxFiles: 5, MainShips: ShipsYes, ExtraSensitive: []string{"x/**"}} |
| + for name, p := range map[string]Policy{ |
| + "rules": {Mode: ModeRules, MaxLines: 100, MaxFiles: 5, MainShips: ShipsYes, ExtraSensitive: []string{"x/**"}}, |
| + "lines": {Mode: ModeAsk, MaxLines: 101, MaxFiles: 5, MainShips: ShipsYes, ExtraSensitive: []string{"x/**"}}, |
| + "ships no": {Mode: ModeAsk, MaxLines: 100, MaxFiles: 5, MainShips: ShipsNo, ExtraSensitive: []string{"x/**"}}, |
| + "unknown": {Mode: ModeAsk, MaxLines: 100, MaxFiles: 5, MainShips: ShipsUnknown, ExtraSensitive: []string{"x/**"}}, |
| + "globs": {Mode: ModeAsk, MaxLines: 100, MaxFiles: 5, MainShips: ShipsYes}, |
| + } { |
| + if Tighter(strict, p) { |
| + t.Errorf("%s counted as tighter", name) |
| + } |
| + } |
| +} |
diff --git a/internal/equipo/mergegate/sensitive.go b/internal/equipo/mergegate/sensitive.go| new file mode 100644 |
| index 00000000..0252b4d4 |
| --- /dev/null |
| +++ b/internal/equipo/mergegate/sensitive.go |
| @@ -0,0 +1,143 @@ |
| +package mergegate |
| + |
| +import ( |
| + "path" |
| + "strings" |
| + "unicode" |
| + |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +// Sensitive classes (spec §3.3). The table is code: a project may add |
| +// globs, nobody can remove one. |
| +const ( |
| + ClassMigrations = "migrations" |
| + ClassAuthSecrets = "auth_secrets" |
| + ClassPayments = "payments" |
| + ClassCIConfig = "ci_config" |
| + ClassDependencies = "dependencies" |
| + ClassRelease = "release_signing" |
| + ClassInfra = "infrastructure" |
| + ClassProject = "project" |
| +) |
| + |
| +type area struct { |
| + class string |
| + globs []string |
| + tokens []string |
| +} |
| + |
| +var areas = []area{ |
| + {ClassMigrations, []string{"**/migrations/**", "**/migrate/**", "**/*.sql", "**/schema.*", "**/*.prisma"}, []string{"migration", "migrations", "schema"}}, |
| + {ClassAuthSecrets, []string{"**/.env*", "**/*.pem", "**/*.key", "**/*.p12", "**/*.p8", "**/*.keystore", "**/*.jks"}, []string{"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"}}, |
| + {ClassPayments, nil, []string{"payment", "payments", "billing", "stripe", "checkout", "invoice", "invoices", "subscription", "subscriptions", "purchase", "purchases", "storekit", "iap", "paywall", "refund", "refunds"}}, |
| + {ClassCIConfig, []string{"**/.amadan/**", "**/.github/**", "**/.gitlab-ci.yml", "**/.circleci/**", "**/.buildkite/**", "**/Makefile", "**/GNUmakefile", "**/makefile", "**/*.mk"}, nil}, |
| + {ClassDependencies, []string{"**/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/**"}, nil}, |
| + {ClassRelease, []string{"**/*.entitlements", "**/*.mobileprovision", "**/ExportOptions*.plist", "**/fastlane/**", "**/*.xcconfig", "**/.goreleaser*", "**/VERSION"}, []string{"release", "releases", "signing", "entitlements", "provisioning"}}, |
| + {ClassInfra, []string{"**/*.tf", "**/*.tfvars", "**/*.hcl", "**/Dockerfile*", "**/docker-compose*", "**/*.service", "**/fly.toml", "**/vercel.json", "**/netlify.toml", "**/render.yaml", "**/Procfile", "**/app.yaml", "**/carlos.toml"}, []string{"terraform", "ansible", "pulumi", "cloudformation", "infra", "infrastructure", "deploy", "k8s", "helm"}}, |
| +} |
| + |
| +// Match is one sensitive path and the class it falls in. |
| +type Match struct { |
| + Class string `json:"class"` |
| + Path string `json:"path"` |
| +} |
| + |
| +// Sensitive lists the entries' paths (old and new) that fall in a |
| +// sensitive class or match one of the project's extra globs. |
| +func Sensitive(entries []wire.ChangeEntry, extra []string) []Match { |
| + var out []Match |
| + for _, e := range entries { |
| + for _, p := range []string{e.Old, e.New} { |
| + if p == "" { |
| + continue |
| + } |
| + if class := classOf(p, extra); class != "" { |
| + out = append(out, Match{Class: class, Path: p}) |
| + } |
| + } |
| + } |
| + return out |
| +} |
| + |
| +func classOf(p string, extra []string) string { |
| + lower := strings.ToLower(p) |
| + toks := tokens(p) |
| + for _, a := range areas { |
| + for _, g := range a.globs { |
| + if glob(strings.ToLower(g), lower) { |
| + return a.class |
| + } |
| + } |
| + for _, t := range toks { |
| + for _, want := range a.tokens { |
| + if t == want { |
| + return a.class |
| + } |
| + } |
| + } |
| + } |
| + for _, g := range extra { |
| + g = strings.ToLower(g) |
| + if !strings.HasPrefix(g, "**/") { |
| + g = "**/" + g |
| + } |
| + if glob(g, lower) { |
| + return ClassProject |
| + } |
| + } |
| + return "" |
| +} |
| + |
| +// tokens splits a path into lower-case words: on "/", ".", "-", "_" and |
| +// where a lower-case letter or digit is followed by an upper-case one. |
| +func tokens(p string) []string { |
| + var out []string |
| + var cur []rune |
| + flush := func() { |
| + if len(cur) > 0 { |
| + out = append(out, strings.ToLower(string(cur))) |
| + cur = cur[:0] |
| + } |
| + } |
| + rs := []rune(p) |
| + for i, r := range rs { |
| + switch { |
| + case r == '/' || r == '.' || r == '-' || r == '_' || r == ' ': |
| + flush() |
| + continue |
| + case i > 0 && unicode.IsUpper(r) && (unicode.IsLower(rs[i-1]) || unicode.IsDigit(rs[i-1])): |
| + flush() |
| + } |
| + cur = append(cur, r) |
| + } |
| + flush() |
| + return out |
| +} |
| + |
| +// glob matches a slash path against a pattern whose segments are |
| +// path.Match patterns, "**" standing for any number of segments. |
| +func glob(pattern, name string) bool { |
| + return segments(strings.Split(pattern, "/"), strings.Split(name, "/")) |
| +} |
| + |
| +func segments(ps, ns []string) bool { |
| + for len(ps) > 0 { |
| + if ps[0] == "**" { |
| + for i := 0; i <= len(ns); i++ { |
| + if segments(ps[1:], ns[i:]) { |
| + return true |
| + } |
| + } |
| + return false |
| + } |
| + if len(ns) == 0 { |
| + return false |
| + } |
| + if ok, err := path.Match(ps[0], ns[0]); err != nil || !ok { |
| + return false |
| + } |
| + ps, ns = ps[1:], ns[1:] |
| + } |
| + return len(ns) == 0 |
| +} |
diff --git a/internal/wire/frames.go b/internal/wire/frames.go| index b3c51332..91bcddba 100644 |
| --- a/internal/wire/frames.go |
| +++ b/internal/wire/frames.go |
| @@ -363,8 +363,16 @@ type LeaseCheck struct { |
| // Publication: the primary confirms, right before it pushes a worker's |
| // commit, that this publication is still pending. |
| Publication string `json:"publication,omitempty"` |
| + // Protocol 3: Purpose merge_request is the confirmation right before |
| + // a hub merge request for the step attempt: the instance decides the |
| + // merge again (merge authority) and acks only if it may go now. |
| + Purpose string `json:"purpose,omitempty"` |
| } |
| +// LeasePurposeMerge is a LeaseCheck's Purpose right before a hub merge |
| +// request. |
| +const LeasePurposeMerge = "merge_request" |
| + |
| // Sync is sent on every connect, after hello. |
| type Sync struct { |
| Sessions []SessionState `json:"sessions"` |
diff --git a/internal/wire/runners.go b/internal/wire/runners.go| index f3fcea12..e6c78a26 100644 |
| --- a/internal/wire/runners.go |
| +++ b/internal/wire/runners.go |
| @@ -13,13 +13,16 @@ import ( |
| // Runner stream protocols. 1 is the slice 4 wire: a hello without |
| // protocol. 2 adds roles, capabilities, placement, the attempt-specific |
| // start authorization, pack transfers and publication (Mac runners spec |
| -// §3.3). The instance speaks the lower of the two on each connection and |
| -// encodes every frame for it with Encode; nothing a protocol 1 runner |
| -// does not know ever reaches it. |
| +// §3.3). 3 adds what merge authority needs (spec 2026-11-11): the |
| +// review's change facts, the merge's provenance, the merge request's own |
| +// confirmation and a revert's target. The instance speaks the lower of |
| +// the two on each connection and encodes every frame for it with Encode; |
| +// nothing a runner does not know ever reaches it. |
| const ( |
| Protocol1 = 1 |
| Protocol2 = 2 |
| - ProtocolCurrent = Protocol2 |
| + Protocol3 = 3 |
| + ProtocolCurrent = Protocol3 |
| ) |
| // Runner roles. A person's first runner is the primary: the coordinator, |
| @@ -344,10 +347,11 @@ func Speaks(protocol int, kind string) bool { return protocol >= Protocol2 || !p |
| var ErrProtocol = errors.New("wire: frame not in this protocol") |
| // Encode returns f as the given protocol speaks it. At protocol 1 it is |
| -// exactly the slice 4 frame and field set: protocol 2 fields are dropped |
| -// and a protocol 2 frame type is refused (ErrProtocol). |
| +// exactly the slice 4 frame and field set: protocol 2 and 3 fields are |
| +// dropped and a protocol 2 frame type is refused (ErrProtocol). At |
| +// protocol 2 the protocol 3 fields are dropped. |
| func Encode(f Frame, protocol int) (Frame, error) { |
| - if protocol >= Protocol2 { |
| + if protocol >= ProtocolCurrent { |
| return f, nil |
| } |
| if !Speaks(protocol, f.Type) { |
| @@ -357,7 +361,11 @@ func Encode(f Frame, protocol int) (Frame, error) { |
| if err != nil { |
| return Frame{}, err |
| } |
| - if !downgrade(body) { |
| + changed := downgrade3(body) |
| + if protocol < Protocol2 && downgrade(body) { |
| + changed = true |
| + } |
| + if !changed { |
| return f, nil |
| } |
| raw, err := json.Marshal(body) |
| @@ -368,6 +376,22 @@ func Encode(f Frame, protocol int) (Frame, error) { |
| return f, nil |
| } |
| +// downgrade3 clears a body's protocol 3 fields (all omitempty). It |
| +// reports whether the body has any. |
| +func downgrade3(body any) bool { |
| + switch v := body.(type) { |
| + case *DispatchCommand: |
| + v.RevertSHA = "" |
| + case *LeaseCheck: |
| + v.Purpose = "" |
| + case *StepReport: |
| + v.Change, v.MergeSource, v.MergeParents = nil, "", nil |
| + default: |
| + return false |
| + } |
| + return true |
| +} |
| + |
| // downgrade clears a body's protocol 2 fields (all omitempty, so they |
| // are absent once zero). It reports whether the body has any. |
| func downgrade(body any) bool { |
diff --git a/internal/wire/tasks.go b/internal/wire/tasks.go| index 15a5bdd5..a158e60d 100644 |
| --- a/internal/wire/tasks.go |
| +++ b/internal/wire/tasks.go |
| @@ -615,6 +615,9 @@ type DispatchCommand struct { |
| // a runner lacking a need refuses it (placement_refused). |
| Needs []string `json:"needs,omitempty"` |
| RunnerID string `json:"runner_id,omitempty"` |
| + // Protocol 3: RevertSHA is the merge commit a revert task undoes; the |
| + // review measures whether the candidate reverts exactly that. |
| + RevertSHA string `json:"revert_sha,omitempty"` |
| } |
| // WatchMergeCommand watches a task's branch for its candidate landing on |
| @@ -702,8 +705,66 @@ type StepReport struct { |
| // (srt, P2 denied every hostile attempt) or none (they ran outside |
| // the sandbox, Paul's ruling 2). |
| ChecksSandbox string `json:"checks_sandbox,omitempty"` |
| + // Protocol 3. Change is what the reviewed change is, measured by the |
| + // runner on exactly the reviewed pair (review steps). MergeSource says |
| + // where a merge's SHA came from (MergeSourceHub: this request's answer) |
| + // and MergeParents are that commit's parents, read after the merge. |
| + Change *ChangeFacts `json:"change,omitempty"` |
| + MergeSource string `json:"merge_source,omitempty"` |
| + MergeParents []string `json:"merge_parents,omitempty"` |
| } |
| +// Merge sources: the hub's answer to this request, the default branch |
| +// read after an uncertain answer, or the runner's earlier record. |
| +const ( |
| + MergeSourceHub = "hub" |
| + MergeSourceReconciled = "reconciled" |
| + MergeSourceCached = "cached" |
| +) |
| + |
| +// ChangeFacts is a reviewed change as the runner measured it, with no |
| +// model: git diff --raw and --numstat of Base..SHA, both paths of every |
| +// entry, and the signing lines of Xcode project files. Complete is false |
| +// when the listings disagree, an error occurred or there were more than |
| +// MaxChangeEntries entries. |
| +type ChangeFacts struct { |
| + ReviewStep string `json:"review_step"` |
| + Attempt int64 `json:"attempt"` |
| + Repo string `json:"repo"` |
| + Base string `json:"base"` |
| + SHA string `json:"sha"` |
| + Files int `json:"files"` |
| + Lines int `json:"lines"` |
| + Binary int `json:"binary"` |
| + Special bool `json:"special"` |
| + Signing bool `json:"signing"` |
| + Entries []ChangeEntry `json:"entries"` |
| + Complete bool `json:"complete"` |
| + Revert *RevertCheck `json:"revert,omitempty"` |
| +} |
| + |
| +// ChangeEntry is one changed path: its status letter, both paths (Old |
| +// is "" unless renamed or copied) and both modes. |
| +type ChangeEntry struct { |
| + Status string `json:"status"` |
| + Old string `json:"old"` |
| + New string `json:"new"` |
| + OldMode string `json:"old_mode"` |
| + NewMode string `json:"new_mode"` |
| +} |
| + |
| +// RevertCheck says whether a revert task's candidate exactly reverts SHA: |
| +// OnTop when its parent is SHA itself, Exact when its tree is SHA's first |
| +// parent's tree. |
| +type RevertCheck struct { |
| + SHA string `json:"sha"` |
| + OnTop bool `json:"on_top"` |
| + Exact bool `json:"exact"` |
| +} |
| + |
| +// MaxChangeEntries bounds a ChangeFacts listing. |
| +const MaxChangeEntries = 200 |
| + |
| // RecheckCommand asks the runner to check now what its agent reaches. |
| type RecheckCommand struct { |
| Person string `json:"person"` |
| @@ -753,6 +814,9 @@ var StepReasons = map[string]bool{ |
| "amadan_ci_failed": true, |
| "merge_forbidden": true, |
| "merge_failed": true, |
| + // merge_not_authorized: the instance refused the merge request's |
| + // confirmation (merge authority); nothing was sent to the hub. |
| + "merge_not_authorized": true, |
| // Connections: the provider refused on quota and no other connection |
| // could take the attempt over (limited); nothing the person connected |
| // can run this specialist (no_connection). |