package api
import (
"os/exec"
"path/filepath"
"slices"
"testing"
"craftdesign.group/quarry/internal/events"
"craftdesign.group/quarry/internal/index"
"craftdesign.group/quarry/internal/ingest"
"craftdesign.group/quarry/internal/oltp"
"craftdesign.group/quarry/internal/ops"
"craftdesign.group/quarry/internal/zitcli"
)
// A 5-rung strata auto-restack updates ALL rungs including the depth-5
// top rung, coalesces CI enqueues until the cascade finishes (zero
// intermediate runs), enqueues strictly bottom-up, and keeps the top
// rung's arm intact across its clean target merge (#507).
func TestFiveRungRestackUpdatesTopAndCoalescesBottomUp(t *testing.T) {
if _, err := exec.LookPath("zit"); err != nil {
t.Skip("zit not on PATH")
}
dir := t.TempDir()
zrun(t, dir, "init", ".")
zwrite(t, dir, "base.txt", "root\n")
zrun(t, dir, "add", "base.txt")
zrun(t, dir, "commit", "-m", "root", "--user", "u")
rungs := []struct{ branch, target string }{
{"r1", "trunk"},
{"r2", "r1"},
{"r3", "r2"},
{"r4", "r3"},
{"r5", "r4"},
}
ids := map[string]string{}
for _, r := range rungs {
zrun(t, dir, "update", r.target)
zwrite(t, dir, r.branch+".txt", r.branch+"\n")
zrun(t, dir, "add", r.branch+".txt")
zrun(t, dir, "commit", "-m", r.branch, "--branch", r.branch, "--user", "u")
id, err := zitcli.New(dir).LandingOpen(testToken, "dan", r.branch, r.target, "land "+r.branch, "")
if err != nil {
t.Fatal(err)
}
ids[r.branch] = id
}
// Trunk moves cleanly; r1..r5 are now behind.
zrun(t, dir, "update", "trunk")
zwrite(t, dir, "trunk2.txt", "trunk2\n")
zrun(t, dir, "add", "trunk2.txt")
zrun(t, dir, "commit", "-m", "trunk moves", "--user", "u")
ev, err := events.Start(filepath.Join(t.TempDir(), "nats"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(ev.Close)
lastStoreEvents = ev
ix, err := index.Open(filepath.Join(t.TempDir(), "index.db"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { ix.Close() })
pipe := ingest.NewPipeline(zitcli.New(dir), ev, ix, "test", "n1")
if _, err := pipe.Sync(); err != nil {
t.Fatal(err)
}
db, err := oltp.Open(filepath.Join(t.TempDir(), "o.db"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { db.Close() })
if err := db.AddAccount("dan", "a-long-enough-password", false); err != nil {
t.Fatal(err)
}
r5TipBefore := ztip(t, dir, "r5")
if err := db.SetAutoAccept("test", ids["r5"], "dan", r5TipBefore); err != nil {
t.Fatal(err)
}
ci := &mergeRuns{pairRuns: &pairRuns{runs: map[string][]CIRun{}}}
var enqueued []string
var sawRestacking bool
d := Deps{
Version: "v",
ZitVersion: zitcli.MinVersion,
Checks: mergeChecks{},
CI: ci,
Auto: db,
CIRunPair: func(_, branch, tip, target string) error {
if Restacking("test") {
sawRestacking = true
}
enqueued = append(enqueued, branch)
pair := "pair:" + tip + ":" + target
ci.pairRuns.runs[pair] = append(ci.pairRuns.runs[pair], CIRun{
Checkin: pair, Pair: pair, Workflow: "ci", Pipeline: "ci", Status: "running",
})
return nil
},
Repos: NewRepos(map[string]*Repo{"test": {Chat: "test", Index: ix, Zit: zitcli.New(dir), Sync: pipe.Sync}}),
}
r := ops.NewRegistry()
if err := RegisterAll(r, d); err != nil {
t.Fatal(err)
}
d.AutoAcceptSweep(db)
if sawRestacking {
t.Errorf("FAIL: CIRunPair fired while Restacking was still active")
}
if Restacking("test") {
t.Errorf("FAIL: Restacking was not released after cascade")
}
if ztip(t, dir, "r5") == r5TipBefore {
t.Errorf("FAIL: depth-5 top rung r5 was skipped by auto-restack")
}
testRepo, _ := d.Repos.Get("test")
for _, rg := range rungs {
n, err := ix.BehindWork(rg.branch, rg.target, cleanMergeOf(testRepo))
if err != nil {
t.Fatalf("BehindWork(%s, %s): %v", rg.branch, rg.target, err)
}
if n != 0 {
t.Errorf("FAIL: %s still %d behind %s after cascade", rg.branch, n, rg.target)
}
}
wantOrder := []string{"r1", "r2", "r3", "r4", "r5"}
if !slices.Equal(enqueued, wantOrder) {
t.Errorf("FAIL: enqueued = %v; want %v (coalesced once per rung, strictly bottom-up)", enqueued, wantOrder)
}
// Top rung arm must survive the clean auto-restack merge (not lapse).
d.AutoAcceptSweep(db)
arms, err := db.AutoAccepts()
if err != nil {
t.Fatal(err)
}
if len(arms) != 1 || arms[0].Landing != ids["r5"] {
t.Errorf("FAIL: top rung arm lapsed after clean restack: %+v", arms)
}
t.Log("ok: 5-rung restack updated r1..r5 including top, coalesced bottom-up, and preserved arm")
}