diff --git a/pkgs/fleet/crates/fleet-queue/src/client.rs b/pkgs/fleet/crates/fleet-queue/src/client.rs index d373a82263..04d3e32852 100644 --- a/pkgs/fleet/crates/fleet-queue/src/client.rs +++ b/pkgs/fleet/crates/fleet-queue/src/client.rs @@ -3463,9 +3463,10 @@ fn cmd_outbox_drain(rest: &[String]) -> i32 { 0 } -/// Merge-intent stack verbs (#8582 increment 3): the client surface -/// for the broker's /stack-record and /stack-list routes (increment -/// 2). Recording a finished branch names its authoring lane/worker +/// Merge-intent stack verbs (#8582 increments 3-4): the client +/// surface for the broker's /stack-record and /stack-list routes +/// (increment 2), the /stack-transition route, and the replay +/// executor (increment 4, `stack replay` below). Recording a finished branch names its authoring lane/worker /// pair; the broker validates that pair against the lane registry /// (the validation deferred from the CodeRabbit round on PR #8660, /// where the pair originates — here, at the client verbs). @@ -3582,9 +3583,936 @@ fn cmd_stack_list(rest: &[String]) -> i32 { 0 } + +/// Body for the broker's /stack-transition route (#8582 increment +/// 4), shaped and fail-fast validated here: the target state must +/// parse in the pure core, and a move to `conflicted` must carry +/// the detail the authoring lane will resolve against — a +/// conflict recorded without context strands its owner. +pub(crate) fn stack_transition_body( + stack_id: &str, + position: i64, + to_state: &str, + pr_number: Option, + conflict_detail: Option<&str>, +) -> Result { + if stack_id.trim().is_empty() { + return Err("stack transition requires a non-empty stack_id".to_string()); + } + let Some(to) = crate::merge_intent::IntentState::parse(to_state) else { + return Err(format!( + "stack transition: unknown target state {to_state:?}" + )); + }; + if to == crate::merge_intent::IntentState::Conflicted { + match conflict_detail { + Some(d) if !d.trim().is_empty() => {} + _ => { + return Err( + "stack transition: a move to conflicted requires --conflict-detail \ + naming what the authoring lane must resolve" + .to_string(), + ) + } + } + } + Ok(json!({ + "stack_id": stack_id, + "position": position, + "to_state": to.as_str(), + "pr_number": pr_number, + "conflict_detail": conflict_detail, + })) +} + +fn stack_transition( + stack_id: &str, + position: i64, + to_state: &str, + pr_number: Option, + conflict_detail: Option<&str>, +) -> Value { + let body = match stack_transition_body(stack_id, position, to_state, pr_number, conflict_detail) + { + Ok(b) => b, + Err(e) => die(2, &e), + }; + let resp = unwrap_ok(call("/stack-transition", &body)); + require_row(&resp, "stack_transition") +} + +/// The replay executor's transition helper: like +/// [`stack_transition`] but it returns the broker's verdict instead +/// of exiting on it (CodeRabbit finding, PR #8849, comment +/// 4547592887). The broker's store/transport failures carry exit 4, +/// which inside `stack replay` is reserved for a conflict routed to +/// its authoring lane — a helper that dies with the envelope's code +/// makes a store failure indistinguishable from a routed conflict, +/// and prints no replay JSON at all. Replay maps an Err onto its +/// transient path (exit 3, intent left `replaying`, resumable). +fn stack_transition_result( + stack_id: &str, + position: i64, + to_state: &str, + pr_number: Option, + conflict_detail: Option<&str>, +) -> Result { + let body = stack_transition_body(stack_id, position, to_state, pr_number, conflict_detail)?; + let resp = call("/stack-transition", &body); + if resp.get("ok").and_then(|o| o.as_bool()) == Some(false) { + let msg = resp + .get("error") + .and_then(|e| e.as_str()) + .unwrap_or("queue-broker error"); + return Err(format!("stack transition to {to_state} failed: {msg}")); + } + Ok(resp.get("row").cloned().unwrap_or(Value::Null)) +} + +fn cmd_stack_transition(rest: &[String]) -> i32 { + let args = parse_args( + rest, + &["stack", "position", "to", "pr", "conflict-detail", "worker"], + &[], + ); + reject_extra_pos("stack transition", &args, 0); + let stack_id = args + .get("stack") + .unwrap_or_else(|| die(2, "stack transition: --stack is required")); + let position = args + .get_i64("position") + .unwrap_or_else(|| die(2, "stack transition: --position is required")); + let to = args + .get("to") + .unwrap_or_else(|| die(2, "stack transition: --to is required")); + let row = stack_transition( + &stack_id, + position, + &to, + args.get_i64("pr"), + args.get("conflict-detail").as_deref(), + ); + print_json(&row); + 0 +} + +/// Body for the broker's /stack-restack route (#8582; Codex P2, +/// PR #8849, comment 4547537340): the acknowledgement that an +/// intent's author restacked its branch off a withdrawn base, so +/// the recorded base_branch can be refreshed. Fail-fast validated +/// here for shape; the broker re-plans with the pure core's +/// `plan_restack` against the stored rows, which is where the +/// taint rules bind. +pub(crate) fn stack_restack_body( + stack_id: &str, + position: i64, + new_base_branch: &str, + new_head_sha: Option<&str>, +) -> Result { + if stack_id.trim().is_empty() { + return Err("stack restack requires a non-empty stack_id".to_string()); + } + if new_base_branch.trim().is_empty() { + return Err( + "stack restack requires a non-empty --base (the branch's new base)".to_string(), + ); + } + if let Some(sha) = new_head_sha { + if sha.trim().is_empty() { + return Err( + "stack restack requires a non-empty --head-sha when one is given".to_string(), + ); + } + } + Ok(json!({ + "stack_id": stack_id, + "position": position, + "new_base_branch": new_base_branch, + "head_sha": new_head_sha, + })) +} + +fn cmd_stack_restack(rest: &[String]) -> i32 { + let args = parse_args( + rest, + &["stack", "position", "base", "head-sha", "worker"], + &[], + ); + reject_extra_pos("stack restack", &args, 0); + let stack_id = args + .get("stack") + .unwrap_or_else(|| die(2, "stack restack: --stack is required")); + let position = args + .get_i64("position") + .unwrap_or_else(|| die(2, "stack restack: --position is required")); + let base = args.get("base").unwrap_or_else(|| { + die(2, "stack restack: --base is required (the branch's new base after restacking)") + }); + let body = match stack_restack_body( + &stack_id, + position, + &base, + args.get("head-sha").as_deref(), + ) { + Ok(b) => b, + Err(e) => die(2, &e), + }; + let resp = unwrap_ok(call("/stack-restack", &body)); + print_json(&require_row(&resp, "stack_restack")); + 0 +} + +/// One recorded intent, parsed back from a /stack-list row for the +/// replay executor (the broker's row shape is the storage shape). +fn stack_intent_from_row(row: &Value) -> Option { + Some(crate::merge_intent::MergeIntent { + stack_id: row.get("stack_id")?.as_str()?.to_string(), + position: row.get("position")?.as_i64()?, + repo: row.get("repo")?.as_str()?.to_string(), + branch: row.get("branch")?.as_str()?.to_string(), + base_branch: row.get("base_branch")?.as_str()?.to_string(), + head_sha: row + .get("head_sha") + .and_then(|v| v.as_str()) + .map(|s| s.to_string()), + base_head_sha: row + .get("base_head_sha") + .and_then(|v| v.as_str()) + .map(|s| s.to_string()), + issue_number: row.get("issue_number").and_then(|v| v.as_i64()), + pr_number: row.get("pr_number").and_then(|v| v.as_i64()), + owner_lane: row.get("owner_lane")?.as_str()?.to_string(), + owner_worker: row.get("owner_worker")?.as_str()?.to_string(), + owner_session: row + .get("owner_session") + .and_then(|v| v.as_str()) + .map(|s| s.to_string()), + state: crate::merge_intent::IntentState::parse(row.get("state")?.as_str()?)?, + }) +} + +fn replay_snippet(s: &str) -> String { + s.chars().take(300).collect() +} + +/// Run one external step of a replay (git/gh) in the repo +/// checkout: Ok(trimmed stdout) on success, Err(a bounded +/// stderr/stdout summary) otherwise. +fn replay_run(dir: &str, program: &str, argv: &[String]) -> Result { + match std::process::Command::new(program) + .args(argv) + .current_dir(dir) + .output() + { + Ok(o) if o.status.success() => Ok(String::from_utf8_lossy(&o.stdout).trim().to_string()), + Ok(o) => { + let err = String::from_utf8_lossy(&o.stderr).trim().to_string(); + let out = String::from_utf8_lossy(&o.stdout).trim().to_string(); + Err(replay_snippet(if err.is_empty() { &out } else { &err })) + } + Err(e) => Err(format!("{program}: {e}")), + } +} + +/// Whether the checkout at `dir` already has a rebase in progress +/// that this replay did NOT start (Codex P2, PR #8849). Replay must +/// refuse that checkout state up front: `git rebase --abort` on a +/// rebase somebody else is mid-way through would discard their +/// conflict-resolution progress. +fn rebase_in_progress(dir: &str) -> bool { + for kind in ["rebase-merge", "rebase-apply"] { + if let Ok(p) = replay_run(dir, "git", &replay_args(&["rev-parse", "--git-path", kind])) { + let path = std::path::Path::new(&p); + let full = if path.is_absolute() { + path.to_path_buf() + } else { + std::path::Path::new(dir).join(path) + }; + if full.exists() { + return true; + } + } + } + false +} + +fn replay_args(parts: &[&str]) -> Vec { + parts.iter().map(|s| s.to_string()).collect() +} + +/// The replay executor (#8582 increment 4): walk one stack's +/// recorded merge order bottom-up and land it — rebase onto the +/// new main, push, open the PR, merge, mark landed, post the +/// outcome note — one intent at a time, in the recorded order. +/// The plan is the pure core's (`plan_for_walk` over the +/// `resumable_walk`), so `--dry-run` prints exactly what a live +/// pass would do. A rebase or merge conflict is never resolved +/// here: the intent is marked `conflicted` with the detail, the +/// walk stops, and the summary routes the conflict to the +/// authoring lane recorded on the intent (exit 4). Any other step +/// failure stops the pass with the intent left `replaying` — a +/// later `stack replay` resumes it (exit 3). +fn cmd_stack_replay(rest: &[String]) -> i32 { + let args = parse_args(rest, &["stack", "worker", "repo-dir"], &["dry-run"]); + reject_extra_pos("stack replay", &args, 0); + let stack_id = args + .get("stack") + .unwrap_or_else(|| die(2, "stack replay: --stack is required")); + let dir = args.get("repo-dir").unwrap_or_else(|| ".".to_string()); + let resp = unwrap_ok(call("/stack-list", &json!({"stack_id": stack_id}))); + let state = require_row(&resp, "stack_list"); + let rows = state + .get("intents") + .and_then(|v| v.as_array()) + .cloned() + .unwrap_or_default(); + let intents: Vec = + rows.iter().filter_map(stack_intent_from_row).collect(); + let walk = crate::merge_intent::resumable_walk(&intents, &stack_id); + let plan = crate::merge_intent::plan_for_walk(&walk); + if args.has("dry-run") { + let steps: Vec = plan + .iter() + .map(|s| { + json!({ + "position": s.position, + "branch": s.branch, + "action": s.action.as_str(), + }) + }) + .collect(); + print_json(&json!({"stack_id": stack_id, "dry_run": true, "plan": steps})); + return 0; + } + if plan.is_empty() { + print_json(&json!({ + "stack_id": stack_id, + "landed": [], + "note": "no replayable prefix: the stack is empty, finished, or blocked at a conflicted head (see stack state)", + "stack": state, + })); + return 0; + } + let by_position: std::collections::HashMap = + intents.iter().map(|i| (i.position, i)).collect(); + let mut pr_numbers: std::collections::HashMap> = + intents.iter().map(|i| (i.position, i.pr_number)).collect(); + let mut landed: Vec = Vec::new(); + let mut warnings: Vec = Vec::new(); + // The verified pre-rebase tip of every branch this pass rebases + // (position -> sha recorded immediately before its rebase ran): + // the Push step pins its force-with-lease to this tip and refuses + // to rewrite a branch whose remote moved past it (Codex P1, + // PR #8849, comment 4547537332). + // Persisted across attempts (Codex P2, PR #8849, comment + // 4548246124): a pass that rebases a published branch and then + // stops transiently at Push must not lose the verified tip -- + // on the next invocation the intent can look like the walk's + // bottom and never rebase again, so the tip is stored in the + // checkout's git dir, keyed by stack, and cleared as intents + // land. A stale entry is only ever used as a force-with-lease + // pin after a live ls-remote confirms the remote is still + // exactly at that tip. + let tips_path = replay_run(&dir, "git", &replay_args(&["rev-parse", "--git-path", "fleet-replay-pre-rebase-tips.json"])).ok().map(|rel| { + let path = std::path::Path::new(&rel); + if path.is_absolute() { path.to_path_buf() } else { std::path::Path::new(&dir).join(path) } + }); + let mut pre_rebase_tips: std::collections::HashMap = + std::collections::HashMap::new(); + if let Some(path) = &tips_path { + if let Ok(text) = std::fs::read_to_string(path) { + if let Ok(saved) = serde_json::from_str::>(&text) { + if let Some(entry) = saved.get(&stack_id) { + if let Some(obj) = entry.as_object() { + for (pos, sha) in obj { + if let (Ok(pos), Some(sha)) = (pos.parse::(), sha.as_str()) { + pre_rebase_tips.insert(pos, sha.to_string()); + } + } + } + } + } + } + } + if let Err(e) = replay_run(&dir, "git", &replay_args(&["fetch", "origin", "main"])) { + print_json(&json!({ + "stack_id": stack_id, + "landed": landed, + "stopped_at": {"step": "fetch", "error": e}, + })); + return 3; + } + // Preflight (Codex P2, PR #8849): a checkout with somebody + // else's rebase already in progress is not replay's to abort + // or build on — refuse before any step runs. + if rebase_in_progress(&dir) { + print_json(&json!({ + "stack_id": stack_id, + "landed": landed, + "stopped_at": {"step": "preflight", "error": "checkout already has a rebase in progress that this replay did not start; finish or abort it outside replay first"}, + })); + return 3; + } + // Shared conflict exit: mark the intent conflicted (it is + // `replaying` by then — Begin precedes every other step in the + // plan), name the route to its authoring lane, and stop. + let conflict_exit = |position: i64, detail: String, landed: &[i64]| -> i32 { + // Exit 4 is earned only once the conflicted transition is + // recorded (CodeRabbit, PR #8849): if the store refuses it, + // the conflict is not routed yet — report a resumable stop + // (exit 3) with the conflict named, never a bare 4. + if let Err(e) = + stack_transition_result(&stack_id, position, "conflicted", None, Some(&detail)) + { + print_json(&json!({ + "stack_id": stack_id, + "landed": landed, + "stopped_at": {"position": position, "step": "conflict_transition", "error": e}, + "conflict": {"position": position, "detail": detail}, + "note": "the conflict could not be recorded; the intent is left replaying and a later pass resumes it", + })); + return 3; + } + let route = crate::merge_intent::route_replay_conflict(&intents, &stack_id, position); + print_json(&json!({ + "stack_id": stack_id, + "landed": landed, + "conflict": { + "position": position, + "detail": detail, + "route": route.map(|r| json!({ + "owner_lane": r.owner_lane, + "owner_worker": r.owner_worker, + "owner_session": r.owner_session, + "repo": r.repo, + "branch": r.branch, + "base_branch": r.base_branch, + "issue_number": r.issue_number, + })), + }, + })); + 4 + }; + let transient_exit = |step: &crate::merge_intent::PlannedStep, + e: String, + landed: &[i64]| + -> i32 { + print_json(&json!({ + "stack_id": stack_id, + "landed": landed, + "stopped_at": { + "position": step.position, + "action": step.action.as_str(), + "error": e, + }, + "note": "the intent is left replaying; fix the cause and re-run stack replay to resume", + })); + 3 + }; + for step in &plan { + let intent = by_position[&step.position]; + let repo = intent.repo.clone(); + let branch = intent.branch.clone(); + match step.action { + crate::merge_intent::ReplayAction::Begin => { + if intent.state != crate::merge_intent::IntentState::Replaying { + if let Err(e) = stack_transition_result( + &stack_id, + step.position, + "replaying", + None, + None, + ) { + return transient_exit(step, e, &landed); + } + } + } + crate::merge_intent::ReplayAction::RebaseOntoMain => { + if rebase_in_progress(&dir) { + return transient_exit( + step, + "checkout already has a rebase in progress that this replay did not start; finish or abort it outside replay first".to_string(), + &landed, + ); + } + if let Ok(tip) = replay_run(&dir, "git", &replay_args(&["rev-parse", &branch])) { + pre_rebase_tips.insert(step.position, tip); + if let Some(path) = &tips_path { + let mut saved: serde_json::Map = + std::fs::read_to_string(path) + .ok() + .and_then(|t| serde_json::from_str(&t).ok()) + .unwrap_or_default(); + let entry = saved + .entry(stack_id.clone()) + .or_insert_with(|| json!({})); + if let Some(obj) = entry.as_object_mut() { + for (pos, sha) in &pre_rebase_tips { + obj.insert(pos.to_string(), json!(sha)); + } + } + let _ = std::fs::write(path, serde_json::to_string(&saved).unwrap_or_default()); + } + } + // Merge-bearing histories are refused, never + // flattened (Codex P1, PR #8849, comment + // 4549335625): a plain rebase skips merge commits, + // so a merge commit carrying merge-only changes (a + // fixup or new file added while merging the base) + // would be silently discarded and the altered tree + // published as success. If the range replay would + // rebase contains any merge commit, route it to + // the authoring lane as a conflict: the author + // restacks preserving the merges (or merges main + // in) and replay resumes afterwards. + match replay_run( + &dir, + "git", + &replay_args(&[ + "rev-list", + "--merges", + &format!("origin/main..{branch}"), + ]), + ) { + Ok(list) if !list.is_empty() => { + return conflict_exit( + step.position, + format!( + "branch {branch} contains merge commits ({}) in the range replay would rebase onto main; a plain rebase would discard their merge-only changes, so replay refuses to flatten this history -- the authoring lane restacks it preserving the merges and re-runs replay", + list.lines().take(5).collect::>().join(", ") + ), + &landed, + ); + } + Ok(_) => {} + Err(e) => { + return transient_exit( + step, + format!( + "checking {branch} for merge commits before its rebase failed: {e}" + ), + &landed, + ); + } + } + if let Err(e) = replay_run( + &dir, + "git", + &replay_args(&["rebase", "origin/main", &branch]), + ) { + // Distinguish a rebase conflict from a rebase + // that never started (Codex P2, PR #8849, + // comment 4547537349): git refuses to START a + // rebase — dirty checkout, missing branch, + // spawn failure — without leaving any rebase + // state behind, and that failure is transient: + // the intent stays `replaying` and a later pass + // resumes it once the cause is fixed. Only a + // rebase this step actually started can be a + // conflict — the guard above proved none was in + // progress before, so state present now is ours + // to abort before routing the conflict to the + // authoring lane. + if rebase_in_progress(&dir) { + let _ = replay_run(&dir, "git", &replay_args(&["rebase", "--abort"])); + return conflict_exit( + step.position, + format!( + "rebase of {branch} onto origin/main failed at replay: {e}" + ), + &landed, + ); + } + return transient_exit( + step, + format!("rebase of {branch} onto origin/main never started: {e}"), + &landed, + ); + } + } + crate::merge_intent::ReplayAction::Push => { + // Publishing a branch must never delete commits this + // pass has not accounted for (Codex P1, PR #8849, + // comment 4547537332). The earlier fix for + // already-published branches (comment 4546983376) + // used a bare --force-with-lease, whose expected + // value is the mutable remote-tracking ref: an + // ordinary fetch can move that ref to a tip carrying + // remote-only commits the local branch lacks, and + // the lease then passes while the push deletes them. + // So decide from the LIVE remote tip, read with + // ls-remote at push time: + // - no remote branch yet: plain first push; + // - remote tip == local tip, or an ancestor of the + // local branch: a no-op or a fast-forward (the + // untouched bottom branch's case) — plain push; + // - this pass rebased the branch and the remote tip + // is still the verified pre-rebase tip: the + // rewrite is this pass's alone — publish with the + // lease PINNED to that tip; + // - anything else (the remote moved past what this + // pass verified): refuse. The intent stays + // `replaying`; its author reconciles the + // remote-only commits and a later pass resumes. + let remote_tip = replay_run( + &dir, + "git", + &replay_args(&["ls-remote", "origin", &format!("refs/heads/{branch}")]), + ) + .ok() + .and_then(|out| out.split_whitespace().next().map(|s| s.to_string())); + let push = match remote_tip { + None => replay_run(&dir, "git", &replay_args(&["push", "origin", &branch])), + Some(remote_sha) => { + // Make the remote tip's object available for + // the ancestry check below. + let _ = + replay_run(&dir, "git", &replay_args(&["fetch", "origin", &branch])); + let local_tip = + replay_run(&dir, "git", &replay_args(&["rev-parse", &branch])) + .unwrap_or_default(); + let remote_is_ancestor = replay_run( + &dir, + "git", + &replay_args(&[ + "merge-base", + "--is-ancestor", + &remote_sha, + &branch, + ]), + ) + .is_ok(); + if remote_sha == local_tip || remote_is_ancestor { + replay_run(&dir, "git", &replay_args(&["push", "origin", &branch])) + } else if pre_rebase_tips.get(&step.position) == Some(&remote_sha) { + replay_run( + &dir, + "git", + &replay_args(&[ + "push", + &format!( + "--force-with-lease=refs/heads/{branch}:{remote_sha}" + ), + "origin", + &branch, + ]), + ) + } else { + return transient_exit( + step, + format!( + "remote branch {branch} is at {remote_sha}, which is \ + neither contained in the local branch nor the verified \ + pre-rebase tip of this pass; refusing to force-push \ + over possible remote-only commits — the authoring \ + lane reconciles the remote branch first" + ), + &landed, + ); + } + } + }; + if let Err(e) = push { + return transient_exit(step, e, &landed); + } + } + crate::merge_intent::ReplayAction::OpenPr => { + if pr_numbers.get(&step.position).copied().flatten().is_none() { + let title = format!("stack replay {} #{}: {}", stack_id, step.position, branch); + let body = format!( + "Replayed from merge-intent stack {stack_id} position {} (#8582). \ + Recorded author: lane {} / worker {}.", + step.position, intent.owner_lane, intent.owner_worker + ); + let created = replay_run( + &dir, + "gh", + &replay_args(&[ + "pr", "create", "--repo", &repo, "--base", "main", "--head", &branch, + "--title", &title, "--body", &body, + ]), + ); + let found = match &created { + Ok(url) => url + .rsplit('/') + .next() + .and_then(|n| n.trim().parse::().ok()), + Err(_) => replay_run( + &dir, + "gh", + &replay_args(&[ + "pr", "list", "--repo", &repo, "--head", &branch, "--state", "all", + "--json", "number", "--limit", "1", + ]), + ) + .ok() + .and_then(|out| serde_json::from_str::(&out).ok()) + .and_then(|v| { + v.as_array() + .and_then(|a| a.first()) + .and_then(|r| r.get("number")) + .and_then(|n| n.as_i64()) + }), + }; + match found { + Some(n) => { + pr_numbers.insert(step.position, Some(n)); + } + None => { + return transient_exit( + step, + created.err().unwrap_or_else(|| { + "PR number not parseable from gh output".to_string() + }), + &landed, + ); + } + } + } + } + crate::merge_intent::ReplayAction::Merge => { + let pr = pr_numbers + .get(&step.position) + .copied() + .flatten() + .unwrap_or_else(|| die(2, "stack replay: merge step without a PR number")); + let pr_s = pr.to_string(); + // Resume reconciliation (Codex P1, PR #8849): if an + // earlier pass merged this PR but stopped before the + // landed transition recorded it, the intent is still + // `replaying` with no persisted number — the OpenPr + // fallback above recovered the number across all PR + // states, and an already-MERGED PR here is success, + // not a merge to re-attempt (re-attempting fails and + // would block the rest of the stack forever). + let pr_view = replay_run( + &dir, + "gh", + &replay_args(&[ + "pr", + "view", + &pr_s, + "--repo", + &repo, + "--json", + "state,baseRefName", + ]), + ) + .ok() + .and_then(|out| serde_json::from_str::(&out).ok()); + let pr_field = |name: &str| { + pr_view + .as_ref() + .and_then(|v| v.get(name)) + .and_then(|f| f.as_str()) + .map(|f| f.to_string()) + }; + let pr_state = pr_field("state"); + // Base validation (Codex P1, PR #8849, comment + // 4546983383): a reused PR recorded from the stack + // may still target its parent branch; merging it + // would land the changes into that branch, not + // main, while Land records success. Retarget to + // main before merging. + if pr_state.as_deref() != Some("MERGED") + && pr_field("baseRefName").as_deref() != Some("main") + { + if let Err(e) = replay_run( + &dir, + "gh", + &replay_args(&["pr", "edit", &pr_s, "--repo", &repo, "--base", "main"]), + ) { + return transient_exit( + step, + format!("retargeting reused PR #{pr} to base main failed: {e}"), + &landed, + ); + } + } + // Abandon coordination (Codex P1, PR #8849, + // comment 4549335594): the plan executes a stack + // snapshot taken at pass start, but an author may + // withdraw this intent (replaying -> abandoned is a + // legal transition) while the pass works. Merging + // on the stale snapshot would land withdrawn + // changes on main; the Land transition afterwards + // would refuse, but only after the irreversible + // step. So re-read the intent's live state + // immediately before merging and honor a + // withdrawal: stop the pass without merging. Any + // state other than replaying, or a state that + // cannot be read at all, also stops the pass -- + // never merge blind. + let mut abandon_stop: Option = None; + if pr_state.as_deref() != Some("MERGED") { + let resp = call("/stack-list", &json!({"stack_id": stack_id})); + if resp.get("ok").and_then(|o| o.as_bool()) == Some(false) { + abandon_stop = Some( + "could not re-read the stack state before merging; refusing to merge on a stale snapshot".to_string(), + ); + } else { + let fresh_rows = resp + .get("row") + .and_then(|r| r.get("intents")) + .and_then(|v| v.as_array()) + .cloned() + .unwrap_or_default(); + let fresh_state = fresh_rows + .iter() + .filter_map(stack_intent_from_row) + .find(|i| i.position == step.position) + .map(|i| i.state); + match fresh_state { + Some(crate::merge_intent::IntentState::Replaying) => {} + Some(crate::merge_intent::IntentState::Abandoned) => { + abandon_stop = Some(format!( + "intent at position {} was abandoned by its author during this replay pass; PR #{pr} was NOT merged", + step.position + )); + } + Some(other) => { + abandon_stop = Some(format!( + "intent at position {} is {} in the live stack state, not replaying; refusing to merge on a stale snapshot", + step.position, + other.as_str() + )); + } + None => { + abandon_stop = Some(format!( + "intent at position {} is missing from the live stack state; refusing to merge on a stale snapshot", + step.position + )); + } + } + } + } + if let Some(stop) = abandon_stop { + return transient_exit(step, stop, &landed); + } + if pr_state.as_deref() == Some("MERGED") { + // Fall through to Land: the merge already + // happened; recording it is the remaining step. + } else if let Err(e) = replay_run( + &dir, + "gh", + &replay_args(&["pr", "merge", &pr_s, "--repo", &repo, "--merge"]), + ) { + let mergeable = replay_run( + &dir, + "gh", + &replay_args(&[ + "pr", + "view", + &pr_s, + "--repo", + &repo, + "--json", + "mergeable", + ]), + ) + .ok() + .and_then(|out| serde_json::from_str::(&out).ok()) + .and_then(|v| { + v.get("mergeable") + .and_then(|m| m.as_str()) + .map(|s| s.to_string()) + }); + if mergeable.as_deref() == Some("CONFLICTING") { + return conflict_exit( + step.position, + format!( + "PR #{pr} ({branch}) is conflicting against main at replay: {e}" + ), + &landed, + ); + } + return transient_exit(step, e, &landed); + } + // Refresh main after each merge (Codex P2, PR + // #8849, comment 4546983362): the next intent + // rebases onto origin/main, which must already + // contain this just-landed parent — rebasing onto + // the pre-replay tip replays the parent's commits + // and can conflict falsely. A fetch failure here is + // resumable: the PR is merged, the intent is still + // replaying, and the Merge arm's already-MERGED + // reconciliation lands it on the next pass. + if let Err(e) = + replay_run(&dir, "git", &replay_args(&["fetch", "origin", "main"])) + { + return transient_exit( + step, + format!( + "PR #{pr} merged but refreshing origin/main before the next intent failed: {e}" + ), + &landed, + ); + } + } + crate::merge_intent::ReplayAction::Land => { + let pr = pr_numbers.get(&step.position).copied().flatten(); + // A refused landing is a resumable stop, not a + // landed intent: the PR is merged, the intent stays + // `replaying`, and the Merge arm's already-MERGED + // reconciliation records the landing on the next + // pass (CodeRabbit, PR #8849). + if let Err(e) = + stack_transition_result(&stack_id, step.position, "landed", pr, None) + { + return transient_exit(step, e, &landed); + } + landed.push(step.position); + pre_rebase_tips.remove(&step.position); + if let Some(path) = &tips_path { + if let Ok(text) = std::fs::read_to_string(path) { + if let Ok(mut saved) = serde_json::from_str::>(&text) { + if let Some(obj) = saved.get_mut(&stack_id).and_then(|e| e.as_object_mut()) { + obj.remove(&step.position.to_string()); + } + let _ = std::fs::write(path, serde_json::to_string(&saved).unwrap_or_default()); + } + } + } + // The outcome note replays in the same pass: the + // intent's issue hears that its branch landed, in + // the recorded order, as soon as it lands. + if let (Some(issue), Some(pr)) = (intent.issue_number, pr) { + let issue_s = issue.to_string(); + let note = format!( + "stack replay: position {} of stack {stack_id} landed via PR #{pr} \ + (branch {branch}), in the recorded merge order (#8582).", + step.position + ); + if let Err(e) = replay_run( + &dir, + "gh", + &replay_args(&[ + "issue", "comment", &issue_s, "--repo", &repo, "--body", ¬e, + ]), + ) { + warnings.push(format!( + "position {}: outcome note on issue #{issue} failed: {e}", + step.position + )); + } + } + } + } + } + let resp = unwrap_ok(call("/stack-list", &json!({"stack_id": stack_id}))); + let state = require_row(&resp, "stack_list"); + print_json(&json!({ + "stack_id": stack_id, + "landed": landed, + "warnings": warnings, + "stack": state, + })); + 0 +} + fn cmd_stack(rest: &[String]) -> i32 { if rest.is_empty() { - eprint("usage: repo-queue stack ..."); + eprint("usage: repo-queue stack ..."); return 2; } let sub = rest[0].as_str(); @@ -3592,6 +4520,9 @@ fn cmd_stack(rest: &[String]) -> i32 { match sub { "record" => cmd_stack_record(tail), "list" => cmd_stack_list(tail), + "transition" => cmd_stack_transition(tail), + "restack" => cmd_stack_restack(tail), + "replay" => cmd_stack_replay(tail), _ => { eprint(&format!("repo-queue: unknown stack command {sub:?}")); 2 @@ -3724,6 +4655,64 @@ mod tests { assert!(batch_count_flag(Some(crate::turso_queue::BATCH_CLAIM_MAX + 1)).is_err()); } + + #[test] + fn stack_transition_body_carries_the_transition_shape_8582() { + // #8582 increment 4 oracle: the client transition body is + // exactly the broker's transition shape (stack, position, + // target state in the core's spelling, optional landing PR + // number and conflict detail). + let body = stack_transition_body("outage-2026-11-11", 2, "landed", Some(8810), None) + .expect("a landing transition is well-formed"); + assert_eq!(body["stack_id"], json!("outage-2026-11-11")); + assert_eq!(body["position"], json!(2)); + assert_eq!(body["to_state"], json!("landed")); + assert_eq!(body["pr_number"], json!(8810)); + assert_eq!(body["conflict_detail"], Value::Null); + let body = stack_transition_body( + "outage-2026-11-11", + 1, + "conflicted", + None, + Some("rebase onto main conflicts in client.rs"), + ) + .expect("a conflicted transition with detail is well-formed"); + assert_eq!(body["to_state"], json!("conflicted")); + assert_eq!( + body["conflict_detail"], + json!("rebase onto main conflicts in client.rs") + ); + } + + #[test] + fn stack_transition_body_rejects_unknown_state_and_bare_conflict_8582() { + // A state the core cannot parse, and a conflict recorded + // without the detail its authoring lane needs, are usage + // errors here — they never reach the broker. + assert!(stack_transition_body("s1", 0, "bogus", None, None).is_err()); + assert!(stack_transition_body("s1", 0, "conflicted", None, None).is_err()); + assert!(stack_transition_body("s1", 0, "conflicted", None, Some(" ")).is_err()); + assert!(stack_transition_body(" ", 0, "replaying", None, None).is_err()); + assert!(stack_transition_body("s1", 0, "replaying", None, None).is_ok()); + } + + #[test] + fn stack_restack_body_carries_the_refresh_shape_8582() { + // Oracle: the restack acknowledgement carries exactly the + // fields the broker's plan_restack consumes (#8582) — stack, + // position, the new base, and the restacked head when given. + let body = stack_restack_body("outage-2026-11-11", 2, "main", Some("deadbeef")) + .expect("valid restack body"); + assert_eq!(body["stack_id"], "outage-2026-11-11"); + assert_eq!(body["position"], 2); + assert_eq!(body["new_base_branch"], "main"); + assert_eq!(body["head_sha"], "deadbeef"); + assert!(stack_restack_body("s1", 2, "main", None).is_ok()); + assert!(stack_restack_body(" ", 2, "main", None).is_err()); + assert!(stack_restack_body("s1", 2, " ", None).is_err()); + assert!(stack_restack_body("s1", 2, "main", Some(" ")).is_err()); + } + #[test] fn stack_record_body_carries_the_append_shape_8582() { // #8582 increment 3 oracle: the client record body is diff --git a/pkgs/fleet/crates/fleet-queue/src/merge_intent.rs b/pkgs/fleet/crates/fleet-queue/src/merge_intent.rs index ca3fda8318..18c37942c5 100644 --- a/pkgs/fleet/crates/fleet-queue/src/merge_intent.rs +++ b/pkgs/fleet/crates/fleet-queue/src/merge_intent.rs @@ -35,6 +35,7 @@ CREATE TABLE IF NOT EXISTS merge_intents ( branch TEXT NOT NULL, base_branch TEXT NOT NULL, head_sha TEXT, + base_head_sha TEXT, issue_number INTEGER, pr_number INTEGER, owner_lane TEXT NOT NULL, @@ -118,6 +119,16 @@ pub struct MergeIntent { pub branch: String, pub base_branch: String, pub head_sha: Option, + /// The recorded head of the base branch's intent at the moment + /// this branch was stacked (or last restacked) onto it: the + /// base-tip linkage. None when the base is main or no head was + /// recorded for the base. If the base intent's head later moves + /// (a restack rebuilds it), this intent's linkage goes stale + /// and the intent stays taint-blocked until it is itself + /// restacked -- refreshing the base alone cannot establish that + /// an unchanged descendant is clean (Codex P1, PR #8849, + /// comment 4548246107). + pub base_head_sha: Option, pub issue_number: Option, pub pr_number: Option, pub owner_lane: String, @@ -255,16 +266,25 @@ pub fn validate_append_against_stack( /// branch was built on a different base passes that real base /// explicitly (see [`AppendRequest::base_branch`]). pub fn plan_append(existing: &[MergeIntent], req: &AppendRequest) -> MergeIntent { + let base_branch = req + .base_branch + .clone() + .unwrap_or_else(|| next_base_branch(existing, &req.stack_id)); + // Base-tip linkage: record the base intent's head as of this + // append, so a later rebuild of the base is detectable from + // the recorded stack alone. + let base_head_sha = existing + .iter() + .find(|i| i.stack_id == req.stack_id && i.branch == base_branch) + .and_then(|base| base.head_sha.clone()); MergeIntent { stack_id: req.stack_id.clone(), position: next_position(existing, &req.stack_id), repo: req.repo.clone(), branch: req.branch.clone(), - base_branch: req - .base_branch - .clone() - .unwrap_or_else(|| next_base_branch(existing, &req.stack_id)), + base_branch, head_sha: req.head_sha.clone(), + base_head_sha, issue_number: req.issue_number, pr_number: req.pr_number, owner_lane: req.owner_lane.clone(), @@ -274,6 +294,129 @@ pub fn plan_append(existing: &[MergeIntent], req: &AppendRequest) -> MergeIntent } } +/// A request to re-record one intent's base after its author has +/// restacked the branch onto a new base (#8582; Codex P2, PR #8849, +/// comment 4547537340). Recording a branch again is impossible — the +/// append path INSERTs and `UNIQUE (repo, branch)` refuses the +/// second row — and the transition verb moves only lifecycle state, +/// so without this refresh a descendant restacked off a withdrawn +/// branch stayed blocked by its stale recorded ancestry forever: +/// [`abandoned_tainted_branches`] derives the taint from the +/// recorded `base_branch` chain, and nothing could update it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RestackRequest { + pub stack_id: String, + pub position: i64, + pub new_base_branch: String, + /// The restacked branch's new head, when the author recorded it: + /// a restack rewrites the branch, so the recorded head moves + /// with the base. `None` keeps the recorded head. + pub new_head_sha: Option, +} + +/// Plan the metadata refresh a restack acknowledgement applies: the +/// intent at `req.position` in `req.stack_id`, with its recorded +/// base (and head, when given) replaced. The rules keep the refresh +/// from becoming a laundering path for withdrawn changes: +/// +/// - terminal intents (`landed`, `abandoned`) are sealed — their +/// recorded base is history, never refreshed; +/// - the new base is `main`, or the branch of another intent in the +/// same stack that is neither abandoned nor itself tainted by an +/// abandoned ancestor (restacking onto a still-tainted branch +/// would keep the withdrawn commits in the ancestry); +/// - an intent cannot be based on its own branch. +/// +/// Taint is derived from the recorded chain on every walk. This +/// refresh unblocks the restacked intent only: its descendants +/// keep the base-tip linkage they recorded when they were stacked +/// on this branch's OLD head, so they stay blocked until each is +/// itself restacked onto the new tip (Codex P1, PR #8849, comment +/// 4548246107). The refresh also re-records this intent's own +/// linkage to its new base's current head. +pub fn plan_restack( + intents: &[MergeIntent], + req: &RestackRequest, +) -> Result { + if req.new_base_branch.trim().is_empty() { + return Err("merge-intent restack requires a non-empty new base_branch".to_string()); + } + if let Some(sha) = &req.new_head_sha { + if sha.trim().is_empty() { + return Err( + "merge-intent restack requires a non-empty head_sha when one is given" + .to_string(), + ); + } + } + let Some(intent) = intents + .iter() + .find(|i| i.stack_id == req.stack_id && i.position == req.position) + else { + return Err(format!( + "merge-intent restack: no intent at stack {} position {}", + req.stack_id, req.position + )); + }; + match intent.state { + IntentState::Landed | IntentState::Abandoned => { + return Err(format!( + "merge-intent restack: intent at stack {} position {} is {} (terminal); \ + its recorded base is sealed", + req.stack_id, + req.position, + intent.state.as_str() + )); + } + _ => {} + } + if req.new_base_branch == intent.branch { + return Err( + "merge-intent restack: an intent cannot be based on its own branch".to_string(), + ); + } + if req.new_base_branch != "main" { + let Some(base) = intents + .iter() + .find(|i| i.stack_id == req.stack_id && i.branch == req.new_base_branch) + else { + return Err(format!( + "merge-intent restack: new base {:?} is not \"main\" and no intent in \ + stack {} records it", + req.new_base_branch, req.stack_id + )); + }; + if base.position > intent.position { + return Err(format!( + "merge-intent restack: new base {:?} is recorded ABOVE the intent at stack {} position {} (base at position {}); restacking onto a descendant would cycle the stack -- restack onto main or a branch recorded below it", + req.new_base_branch, req.stack_id, req.position, base.position + )); + } + let tainted = abandoned_tainted_branches(intents, &req.stack_id); + if base.state == IntentState::Abandoned || tainted.contains(base.branch.as_str()) { + return Err(format!( + "merge-intent restack: new base {:?} still carries an abandoned \ + intent's changes; restack onto a live base or main", + req.new_base_branch + )); + } + } + let mut updated = intent.clone(); + updated.base_branch = req.new_base_branch.clone(); + if let Some(sha) = &req.new_head_sha { + updated.head_sha = Some(sha.clone()); + } + updated.base_head_sha = if req.new_base_branch == "main" { + None + } else { + intents + .iter() + .find(|i| i.stack_id == req.stack_id && i.branch == req.new_base_branch) + .and_then(|base| base.head_sha.clone()) + }; + Ok(updated) +} + /// The replay walk for one stack: the `intended` intents in recorded /// order, bottom first. Finished entries — `landed` (already merged /// by an earlier replay pass) and `abandoned` (withdrawn) — are @@ -282,7 +425,72 @@ pub fn plan_append(existing: &[MergeIntent], req: &AppendRequest) -> MergeIntent /// at the first live non-intended entry — a `conflicted` or /// `replaying` intent blocks everything stacked above it — so only /// the intended prefix is returned. +/// Branches in `stack_id` that still carry an abandoned intent's +/// changes: the abandoned intents' own branches, plus -- transitively -- +/// every branch stacked on one of them (its base_branch names a +/// tainted branch). An abandoned intent is its author withdrawing +/// the change; a descendant replayed without restacking would merge +/// the withdrawn commits along with its own (Codex P1, PR #8849), so +/// both walks stop before the first tainted intent: replay refuses +/// descendants that still contain abandoned changes until their +/// author restacks them off the withdrawn branch. +/// +/// A restack acknowledgement for one intent does NOT clear its +/// descendants (Codex P1, PR #8849, comment 4548246107): rebuilding +/// branch B on main says nothing about branch C stacked on B's old +/// tip -- C's history still contains the original commits. So when +/// the stack holds an abandoned intent, an intent whose recorded +/// base-tip linkage (base_head_sha) no longer matches its base +/// intent's current head is tainted as well, until that intent is +/// itself restacked (which re-records its linkage). Stacks with +/// no abandoned intent are unaffected: a stale linkage there has +/// no withdrawn changes to launder. +fn abandoned_tainted_branches<'a>( + intents: &'a [MergeIntent], + stack_id: &str, +) -> std::collections::HashSet<&'a str> { + let mut tainted: std::collections::HashSet<&'a str> = intents + .iter() + .filter(|i| i.stack_id == stack_id && i.state == IntentState::Abandoned) + .map(|i| i.branch.as_str()) + .collect(); + let has_abandoned = !tainted.is_empty(); + loop { + let mut grew = false; + for i in intents.iter().filter(|i| i.stack_id == stack_id) { + if tainted.contains(i.branch.as_str()) { + continue; + } + if tainted.contains(i.base_branch.as_str()) { + tainted.insert(i.branch.as_str()); + grew = true; + continue; + } + // Stale base-tip linkage: this intent was stacked on a + // tip of its base that the base no longer records -- + // the base was rebuilt (restacked) and this intent was + // not. Its ancestry is unverified against the new base. + if has_abandoned { + if let Some(base) = intents + .iter() + .find(|b| b.stack_id == stack_id && b.branch == i.base_branch) + { + if i.base_head_sha != base.head_sha { + tainted.insert(i.branch.as_str()); + grew = true; + } + } + } + } + if !grew { + break; + } + } + tainted +} + pub fn replay_prefix<'a>(intents: &'a [MergeIntent], stack_id: &str) -> Vec<&'a MergeIntent> { + let tainted = abandoned_tainted_branches(intents, stack_id); let mut ordered: Vec<&MergeIntent> = intents .iter() .filter(|i| { @@ -294,10 +502,140 @@ pub fn replay_prefix<'a>(intents: &'a [MergeIntent], stack_id: &str) -> Vec<&'a ordered.sort_by_key(|i| i.position); ordered .into_iter() - .take_while(|i| i.state == IntentState::Intended) + .take_while(|i| i.state == IntentState::Intended && !tainted.contains(i.branch.as_str())) .collect() } + +/// One step of a replay pass, planned by [`replay_plan`] from the +/// recorded stack state alone (#8582 increment 4). The executor +/// (client `stack replay`) performs the steps in plan order; the +/// plan itself is pure, so a `--dry-run` prints exactly what a live +/// pass would do, and the drill (increment 5) can assert on it. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ReplayAction { + /// Mark the intent `replaying` (intended -> replaying). An + /// intent a previous interrupted pass already left `replaying` + /// is resumed: the executor skips the transition for it. + Begin, + /// Rebase the intent's branch onto the current main tip. Every + /// intent above the walk's bottom was stacked on the previous + /// branch; once that branch lands, this one is rebased onto the + /// new main before it is pushed. The step is planned under the + /// REBASED intent's own position: a conflict here belongs to + /// that intent's author, never to the landed intent below it. + RebaseOntoMain, + /// Push the branch (its first push, after the outage). + Push, + /// Open the PR against `main`, or reuse the recorded PR number. + OpenPr, + /// Merge the PR, in recorded order. + Merge, + /// Mark the intent `landed` (recording the PR number) and post + /// its outcome note in the same pass. + Land, +} + +impl ReplayAction { + pub fn as_str(&self) -> &'static str { + match self { + ReplayAction::Begin => "begin", + ReplayAction::RebaseOntoMain => "rebase_onto_main", + ReplayAction::Push => "push", + ReplayAction::OpenPr => "open_pr", + ReplayAction::Merge => "merge", + ReplayAction::Land => "land", + } + } +} + +/// One planned replay step: the intent it serves (by stack +/// position), that intent's branch, and the action. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PlannedStep { + pub position: i64, + pub branch: String, + pub action: ReplayAction, +} + +/// The replay plan for a walk (see [`replay_prefix`]): each intent, +/// bottom first, is begun, rebased onto main when it is not the +/// walk's bottom, pushed, PR-opened, merged, and landed — then the +/// next intent up the stack. Order is the contract: a step for a +/// higher position never precedes the `Land` step below it. +pub fn plan_for_walk(walk: &[&MergeIntent]) -> Vec { + let mut steps = Vec::new(); + for (idx, intent) in walk.iter().enumerate() { + let mut step = |action| { + steps.push(PlannedStep { + position: intent.position, + branch: intent.branch.clone(), + action, + }) + }; + step(ReplayAction::Begin); + if idx > 0 { + step(ReplayAction::RebaseOntoMain); + } + step(ReplayAction::Push); + step(ReplayAction::OpenPr); + step(ReplayAction::Merge); + step(ReplayAction::Land); + } + steps +} + +/// The replay plan for a stack's recorded state: the plan for its +/// [`replay_prefix`] walk. +pub fn replay_plan(intents: &[MergeIntent], stack_id: &str) -> Vec { + plan_for_walk(&replay_prefix(intents, stack_id)) +} + +/// The walk a resumed replay pass serves: like [`replay_prefix`], +/// except a head intent left `replaying` by an interrupted pass is +/// resumed (included, with the intended intents above it) instead +/// of blocking its own resume. A `conflicted` head still blocks: +/// only its authoring lane clears it, by resolving the conflict +/// and moving it back to `replaying`. +pub fn resumable_walk<'a>(intents: &'a [MergeIntent], stack_id: &str) -> Vec<&'a MergeIntent> { + let mut ordered: Vec<&MergeIntent> = intents + .iter() + .filter(|i| { + i.stack_id == stack_id + && i.state != IntentState::Abandoned + && i.state != IntentState::Landed + }) + .collect(); + ordered.sort_by_key(|i| i.position); + let tainted = abandoned_tainted_branches(intents, stack_id); + let mut out = Vec::new(); + for (idx, i) in ordered.iter().enumerate() { + if tainted.contains(i.branch.as_str()) { + break; + } + match i.state { + IntentState::Intended => out.push(*i), + IntentState::Replaying if idx == 0 => out.push(*i), + _ => break, + } + } + out +} + +/// Route a replay conflict at `position` in `stack_id` to the +/// authoring lane recorded on that intent — never to the lane +/// running the replay (#8582). `None` when no such intent exists. +pub fn route_replay_conflict( + intents: &[MergeIntent], + stack_id: &str, + position: i64, +) -> Option { + intents + .iter() + .find(|i| i.stack_id == stack_id && i.position == position) + .map(|i| i.conflict_route()) +} + #[cfg(test)] mod tests { use super::*; @@ -310,6 +648,7 @@ mod tests { branch: branch.to_string(), base_branch: "main".to_string(), head_sha: None, + base_head_sha: None, issue_number: Some(8582), pr_number: None, owner_lane: "any-b".to_string(), @@ -614,6 +953,345 @@ mod tests { assert!(err.contains("already records repo"), "{err}"); } + + #[test] + fn replay_plan_walks_bottom_up_with_rebase_only_above_the_bottom() { + // Oracle: the module doc's replay walk — push, PR, merge, + // rebase the next branch onto the new main — stated as a + // per-intent step order (begin/land are the state marks at + // the ends of each intent's turn). + let stack = vec![ + intent("s1", 1, "queue/b", IntentState::Intended), + intent("s1", 0, "queue/a", IntentState::Intended), + intent("s1", 2, "queue/c", IntentState::Intended), + ]; + let plan: Vec<(i64, ReplayAction)> = replay_plan(&stack, "s1") + .iter() + .map(|s| (s.position, s.action)) + .collect(); + use ReplayAction::*; + assert_eq!( + plan, + vec![ + (0, Begin), + (0, Push), + (0, OpenPr), + (0, Merge), + (0, Land), + (1, Begin), + (1, RebaseOntoMain), + (1, Push), + (1, OpenPr), + (1, Merge), + (1, Land), + (2, Begin), + (2, RebaseOntoMain), + (2, Push), + (2, OpenPr), + (2, Merge), + (2, Land), + ] + ); + } + + #[test] + fn replay_plan_stops_at_the_conflicted_prefix_boundary() { + let stack = vec![ + intent("s1", 0, "queue/a", IntentState::Intended), + intent("s1", 1, "queue/b", IntentState::Conflicted), + intent("s1", 2, "queue/c", IntentState::Intended), + ]; + let plan = replay_plan(&stack, "s1"); + assert!(plan.iter().all(|s| s.position == 0), "{plan:?}"); + assert_eq!(plan.len(), 5); + // A conflicted head means no plan at all. + let stack = vec![ + intent("s1", 0, "queue/a", IntentState::Conflicted), + intent("s1", 1, "queue/b", IntentState::Intended), + ]; + assert!(replay_plan(&stack, "s1").is_empty()); + assert!(replay_plan(&stack, "unknown-stack").is_empty()); + } + + #[test] + fn resumable_walk_resumes_a_replaying_head_only() { + // An interrupted pass left the head replaying: resume serves + // it and the intended intents above it. + let stack = vec![ + intent("s1", 0, "queue/a", IntentState::Replaying), + intent("s1", 1, "queue/b", IntentState::Intended), + ]; + let walk: Vec<&str> = resumable_walk(&stack, "s1") + .iter() + .map(|i| i.branch.as_str()) + .collect(); + assert_eq!(walk, vec!["queue/a", "queue/b"]); + // A replaying intent that is NOT the head still blocks the + // intended intent below it is served, nothing above moves. + let stack = vec![ + intent("s1", 0, "queue/a", IntentState::Intended), + intent("s1", 1, "queue/b", IntentState::Replaying), + intent("s1", 2, "queue/c", IntentState::Intended), + ]; + let walk: Vec<&str> = resumable_walk(&stack, "s1") + .iter() + .map(|i| i.branch.as_str()) + .collect(); + assert_eq!(walk, vec!["queue/a"]); + // A conflicted head blocks its own resume too. + let stack = vec![ + intent("s1", 0, "queue/a", IntentState::Conflicted), + intent("s1", 1, "queue/b", IntentState::Intended), + ]; + assert!(resumable_walk(&stack, "s1").is_empty()); + } + + fn stacked( + stack: &str, + position: i64, + branch: &str, + base: &str, + state: IntentState, + ) -> MergeIntent { + let mut i = intent(stack, position, branch, state); + i.base_branch = base.to_string(); + i + } + + #[test] + fn replay_refuses_descendants_of_an_abandoned_intent() { + // Oracle: `abandoned` is the author withdrawing the change + // (#8582 lifecycle). A branch stacked on the withdrawn branch + // still contains its commits; replaying it would merge the + // withdrawn changes, so the walk stops before it — and before + // everything stacked on it, transitively (Codex P1, PR #8849). + let stack = vec![ + stacked("s1", 0, "queue/a", "main", IntentState::Abandoned), + stacked("s1", 1, "queue/b", "queue/a", IntentState::Intended), + stacked("s1", 2, "queue/c", "queue/b", IntentState::Intended), + ]; + assert!(replay_prefix(&stack, "s1").is_empty()); + assert!(resumable_walk(&stack, "s1").is_empty()); + assert!(replay_plan(&stack, "s1").is_empty()); + } + + #[test] + fn replay_still_walks_the_clean_prefix_below_an_abandoned_tip() { + // An abandoned entry higher in the stack does not taint the + // intents below it: their bases never contained its changes. + let stack = vec![ + stacked("s1", 0, "queue/a", "main", IntentState::Intended), + stacked("s1", 1, "queue/b", "queue/a", IntentState::Abandoned), + ]; + let walk: Vec<&str> = replay_prefix(&stack, "s1") + .iter() + .map(|i| i.branch.as_str()) + .collect(); + assert_eq!(walk, vec!["queue/a"]); + } + + #[test] + fn replay_conflict_routes_to_the_recording_author() { + // The intent() fixture records owner any-b / repo-worker-code + // / ses_test: the route names that author, at the position + // the conflict surfaced, with the branch context to resolve. + let stack = vec![ + intent("s1", 0, "queue/a", IntentState::Landed), + intent("s1", 1, "queue/b", IntentState::Conflicted), + ]; + let route = route_replay_conflict(&stack, "s1", 1).expect("intent exists"); + assert_eq!(route.owner_lane, "any-b"); + assert_eq!(route.owner_worker, "repo-worker-code"); + assert_eq!(route.branch, "queue/b"); + assert_eq!(route.issue_number, Some(8582)); + assert!(route_replay_conflict(&stack, "s1", 9).is_none()); + assert!(route_replay_conflict(&stack, "other", 1).is_none()); + } + + proptest! { + #![proptest_config(ProptestConfig::with_cases(256))] + + /// Model-based property (oracle: the #8582 replay semantics, + /// stated independently of the planner): for ANY mix of + /// lifecycle states, the plan serves exactly the walk the + /// model derives (skip finished, collect intended, stop at + /// the first live non-intended), and each served intent's + /// steps are begin, [rebase if not the walk's bottom], push, + /// open-pr, merge, land, in that order, grouped by ascending + /// position with no interleaving. + #[test] + fn replay_plan_matches_the_model_for_any_state_mix( + states in prop::collection::vec(0u8..5, 0..6), + ) { + let to_state = |c: u8| match c { + 0 => IntentState::Intended, + 1 => IntentState::Replaying, + 2 => IntentState::Landed, + 3 => IntentState::Conflicted, + _ => IntentState::Abandoned, + }; + let stack: Vec = states + .iter() + .enumerate() + .map(|(idx, c)| { + intent("s1", idx as i64, &format!("queue/{idx}"), to_state(*c)) + }) + .collect(); + // The model walk, from the semantics. + let mut walk_positions: Vec = Vec::new(); + for i in &stack { + match i.state { + IntentState::Landed | IntentState::Abandoned => continue, + IntentState::Intended => walk_positions.push(i.position), + IntentState::Replaying | IntentState::Conflicted => break, + } + } + let mut expected: Vec<(i64, ReplayAction)> = Vec::new(); + for (idx, pos) in walk_positions.iter().enumerate() { + expected.push((*pos, ReplayAction::Begin)); + if idx > 0 { + expected.push((*pos, ReplayAction::RebaseOntoMain)); + } + expected.push((*pos, ReplayAction::Push)); + expected.push((*pos, ReplayAction::OpenPr)); + expected.push((*pos, ReplayAction::Merge)); + expected.push((*pos, ReplayAction::Land)); + } + let plan: Vec<(i64, ReplayAction)> = replay_plan(&stack, "s1") + .iter() + .map(|s| (s.position, s.action)) + .collect(); + prop_assert_eq!(plan, expected); + } + } + + #[test] + fn restack_onto_a_branch_recorded_above_is_refused() { + // Oracle: a restack base recorded ABOVE the intent is its + // descendant; basing an intent on its own descendant cycles + // the recorded stack (CodeRabbit, PR #8849, comment + // 4548301698). plan_restack refuses it; main and bases + // recorded below remain legal. + let stack = vec![ + stacked("s1", 0, "queue/a", "main", IntentState::Intended), + stacked("s1", 1, "queue/b", "queue/a", IntentState::Intended), + stacked("s1", 2, "queue/c", "queue/b", IntentState::Intended), + ]; + let onto_c = RestackRequest { + stack_id: "s1".to_string(), + position: 1, + new_base_branch: "queue/c".to_string(), + new_head_sha: None, + }; + assert!(plan_restack(&stack, &onto_c).is_err()); + let onto_a = RestackRequest { + new_base_branch: "queue/a".to_string(), + ..onto_c.clone() + }; + assert!(plan_restack(&stack, &onto_a).is_ok()); + } + + #[test] + fn restack_acknowledgement_unblocks_a_restacked_descendant() { + // Oracle: the documented recovery for a descendant of an + // abandoned intent is its author restacking it off the + // withdrawn branch (#8582). Recording that restack + // (plan_restack) must unblock the descendant and everything + // stacked on it, because the taint is derived from the + // recorded base chain (Codex P2, PR #8849). + let stack = vec![ + stacked("s1", 0, "queue/a", "main", IntentState::Abandoned), + stacked("s1", 1, "queue/b", "queue/a", IntentState::Intended), + stacked("s1", 2, "queue/c", "queue/b", IntentState::Intended), + ]; + assert!(replay_prefix(&stack, "s1").is_empty(), "tainted stack is blocked"); + // Restacking onto a still-tainted (or the abandoned) base + // is refused: the withdrawn commits would remain. + let onto_a = RestackRequest { + stack_id: "s1".to_string(), + position: 1, + new_base_branch: "queue/a".to_string(), + new_head_sha: None, + }; + assert!(plan_restack(&stack, &onto_a).is_err()); + // Restacking onto an unrecorded base is refused. + let onto_nowhere = RestackRequest { + new_base_branch: "release/x".to_string(), + ..onto_a.clone() + }; + assert!(plan_restack(&stack, &onto_nowhere).is_err()); + // The real restack: queue/b rebuilt on main, new head noted. + let req = RestackRequest { + stack_id: "s1".to_string(), + position: 1, + new_base_branch: "main".to_string(), + new_head_sha: Some("deadbeef".to_string()), + }; + let updated = plan_restack(&stack, &req).expect("restack onto main is legal"); + assert_eq!(updated.base_branch, "main"); + assert_eq!(updated.head_sha.as_deref(), Some("deadbeef")); + assert_eq!(updated.state, IntentState::Intended); + let stack: Vec = stack + .into_iter() + .map(|i| if i.position == 1 { updated.clone() } else { i }) + .collect(); + // Only the restacked intent unblocks (Codex P1, PR #8849, + // comment 4548246107): queue/c was stacked on queue/b's old + // tip and was NOT rebuilt, so its recorded base-tip linkage + // (None) no longer matches queue/b's new head (deadbeef) -- + // its history still contains the original queue/a commits + // and it stays blocked until its own author restacks it. + let walk: Vec<&str> = replay_prefix(&stack, "s1") + .iter() + .map(|i| i.branch.as_str()) + .collect(); + assert_eq!(walk, vec!["queue/b"], "unchanged descendants stay blocked"); + // Restacking queue/c onto the rebuilt queue/b re-records + // its linkage to the new tip and unblocks it. + let c_req = RestackRequest { + stack_id: "s1".to_string(), + position: 2, + new_base_branch: "queue/b".to_string(), + new_head_sha: Some("cafef00d".to_string()), + }; + let c_updated = plan_restack(&stack, &c_req).expect("restack onto rebuilt base is legal"); + assert_eq!(c_updated.base_head_sha.as_deref(), Some("deadbeef")); + let stack: Vec = stack + .into_iter() + .map(|i| { + if i.position == 2 { + c_updated.clone() + } else { + i + } + }) + .collect(); + let walk: Vec<&str> = replay_prefix(&stack, "s1") + .iter() + .map(|i| i.branch.as_str()) + .collect(); + assert_eq!( + walk, + vec!["queue/b", "queue/c"], + "restacked descendant unblocks" + ); + // Terminal intents are sealed against a refresh. + let sealed = RestackRequest { + stack_id: "s1".to_string(), + position: 0, + new_base_branch: "main".to_string(), + new_head_sha: None, + }; + assert!(plan_restack(&stack, &sealed).is_err(), "abandoned is terminal"); + // An intent cannot be based on itself. + let self_based = RestackRequest { + position: 1, + new_base_branch: "queue/b".to_string(), + ..sealed + }; + assert!(plan_restack(&stack, &self_based).is_err()); + } + #[test] fn ddl_names_the_table_and_order_key() { assert!(MERGE_INTENT_DDL.contains("CREATE TABLE IF NOT EXISTS merge_intents")); diff --git a/pkgs/fleet/crates/fleet-queue/src/queue_broker.rs b/pkgs/fleet/crates/fleet-queue/src/queue_broker.rs index e36f19e3f5..e8f2c880b8 100644 --- a/pkgs/fleet/crates/fleet-queue/src/queue_broker.rs +++ b/pkgs/fleet/crates/fleet-queue/src/queue_broker.rs @@ -1283,7 +1283,7 @@ fn dispatch(st: &State, path: &str, req: &Value) -> Value { Err(e) => fail(e.exit, e.msg), } } - "/stack-record" | "/stack-list" => fail( + "/stack-record" | "/stack-list" | "/stack-restack" => fail( 2, "merge-intent stack verbs require the turso queue backend (#8582)".to_string(), ), diff --git a/pkgs/fleet/crates/fleet-queue/src/turso_queue.rs b/pkgs/fleet/crates/fleet-queue/src/turso_queue.rs index 81c23c3ecd..0fe1449fcc 100644 --- a/pkgs/fleet/crates/fleet-queue/src/turso_queue.rs +++ b/pkgs/fleet/crates/fleet-queue/src/turso_queue.rs @@ -831,6 +831,28 @@ impl TursoBackend { &[], )?; } + // #8582: the merge_intents base-tip linkage column + // (base_head_sha -- the recorded head of an intent's base + // at stack/restack time) lands the same additive way for + // merge_intents tables created before it. No backfill: + // existing rows read NULL (no linkage recorded), which the + // taint derivation reads as unverified only inside stacks + // that hold an abandoned intent. + let micols = self.query_objs( + "SELECT name FROM pragma_table_info('merge_intents')", + &[], + &[], + )?; + if !micols.is_empty() + && !micols + .iter() + .any(|c| c.get("name").and_then(|v| v.as_str()) == Some("base_head_sha")) + { + self.exec( + "ALTER TABLE merge_intents ADD COLUMN base_head_sha TEXT", + &[], + )?; + } // #8210: the ledger's platform-limitation columns (a // task may be limited to one platform family, but only // with a good reason recorded beside it) land the same @@ -6434,7 +6456,8 @@ fn verb_health(t: &TursoBackend, req: &Value) -> Value { // Merge-intent stack storage (#8582 increment 2) — broker endpoints // over the merge_intents table (DDL of record: // crate::merge_intent::MERGE_INTENT_DDL, applied via SCHEMA above). -// Record/list only: the replay executor is a later increment. The +// Record/list came first; the transition verb (increment 4) moves +// intents through the core's lifecycle for the replay executor. The // append rules themselves (position, base tip) are the pure core's // (plan_append), so storage cannot drift from replay semantics, and // a stack's full state — branches, order, owners — reads back from @@ -6442,7 +6465,7 @@ fn verb_health(t: &TursoBackend, req: &Value) -> Value { // --------------------------------------------------------------------------- const MERGE_INTENT_COLS: &str = "id, stack_id, position, repo, branch, base_branch, \ - head_sha, issue_number, pr_number, owner_lane, owner_worker, owner_session, \ + head_sha, base_head_sha, issue_number, pr_number, owner_lane, owner_worker, owner_session, \ state, conflict_detail, created_at, updated_at"; fn merge_intent_core(row: &Value) -> Option { @@ -6456,6 +6479,10 @@ fn merge_intent_core(row: &Value) -> Option { .get("head_sha") .and_then(|v| v.as_str()) .map(|s| s.to_string()), + base_head_sha: row + .get("base_head_sha") + .and_then(|v| v.as_str()) + .map(|s| s.to_string()), issue_number: row.get("issue_number").and_then(|v| v.as_i64()), pr_number: row.get("pr_number").and_then(|v| v.as_i64()), owner_lane: row.get("owner_lane")?.as_str()?.to_string(), @@ -6595,8 +6622,8 @@ fn verb_stack_record(t: &TursoBackend, req: &Value) -> Value { let now = now_iso(); let res = t.exec( "INSERT INTO merge_intents (stack_id, position, repo, branch, base_branch, \ - head_sha, issue_number, pr_number, owner_lane, owner_worker, owner_session, \ - state, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + head_sha, base_head_sha, issue_number, pr_number, owner_lane, owner_worker, owner_session, \ + state, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", &[ Arg::Text(planned.stack_id.clone()), Arg::Int(planned.position), @@ -6604,6 +6631,7 @@ fn verb_stack_record(t: &TursoBackend, req: &Value) -> Value { Arg::Text(planned.branch.clone()), Arg::Text(planned.base_branch.clone()), arg_str(planned.head_sha.as_deref()), + arg_str(planned.base_head_sha.as_deref()), planned.issue_number.map(Arg::Int).unwrap_or(Arg::Null), planned.pr_number.map(Arg::Int).unwrap_or(Arg::Null), Arg::Text(planned.owner_lane.clone()), @@ -6658,6 +6686,219 @@ fn verb_stack_list(t: &TursoBackend, req: &Value) -> Value { } } + +/// Move one recorded intent through its lifecycle (#8582 +/// increment 4): the storage half of the replay executor. The +/// transition rules are the pure core's (`IntentState:: +/// can_transition`) — this verb only reads the current row, +/// refuses an illegal move, and writes the new state (plus the PR +/// number a landing records, and the conflict detail a conflict +/// routing carries). It performs no GitHub work: the client +/// executor drives git/gh and reports each state change here, so +/// the stack state stays fully visible from the database alone +/// even mid-replay. +fn verb_stack_transition(t: &TursoBackend, req: &Value) -> Value { + let Some(stack_id) = req_str(req, "stack_id") else { + return fail(2, "stack_id is required".to_string()); + }; + let stack_id = stack_id.to_string(); + let Some(position) = req_i64(req, "position") else { + return fail(2, "position is required".to_string()); + }; + let Some(to) = req_str(req, "to_state").and_then(crate::merge_intent::IntentState::parse) + else { + return fail( + 2, + format!( + "stack_transition: unknown to_state {:?}", + req_str(req, "to_state") + ), + ); + }; + let rows = match stack_rows(t, &stack_id) { + Ok(r) => r, + Err(e) => return terr(e), + }; + let Some(row) = rows + .iter() + .find(|r| r.get("position").and_then(|v| v.as_i64()) == Some(position)) + else { + return fail( + 2, + format!("stack_transition: no intent at stack {stack_id} position {position}"), + ); + }; + let Some(current) = merge_intent_core(row) else { + return fail( + 2, + "stack_transition: stored intent row is unparseable".to_string(), + ); + }; + if !current.state.can_transition(to) { + return fail( + 2, + format!( + "stack_transition: illegal move {} -> {} for stack {} position {}", + current.state.as_str(), + to.as_str(), + stack_id, + position + ), + ); + } + // A landing records the PR that landed it; an explicit number + // wins, otherwise the recorded one (if any) is kept. + let pr_number = req_i64(req, "pr_number").or(current.pr_number); + // The conflict detail lives only while the intent is + // conflicted: a fresh detail replaces it, a move out of + // conflicted clears it. + let conflict_detail: Option = if to == crate::merge_intent::IntentState::Conflicted { + req_str(req, "conflict_detail") + .map(|s| s.to_string()) + .or_else(|| { + row.get("conflict_detail") + .and_then(|v| v.as_str()) + .map(|s| s.to_string()) + }) + } else { + None + }; + let now = now_iso(); + // Condition the write on the state that was validated above + // (Codex P2, PR #8849): the broker serves connections + // concurrently, so a second transition can land between this + // verb's read and its UPDATE — an unconditional write would let + // it overwrite a terminal state the core has already sealed. + // With the validated state in the predicate, a lost race + // affects 0 rows and is refused as a concurrent change. + let upd = match t.exec( + "UPDATE merge_intents SET state = ?, pr_number = ?, conflict_detail = ?, \ + updated_at = ? WHERE stack_id = ? AND position = ? AND state = ?", + &[ + Arg::Text(to.as_str().to_string()), + pr_number.map(Arg::Int).unwrap_or(Arg::Null), + arg_str(conflict_detail.as_deref()), + Arg::Text(now), + Arg::Text(stack_id.clone()), + Arg::Int(position), + Arg::Text(current.state.as_str().to_string()), + ], + ) { + Ok(r) => r, + Err(e) => return terr(e), + }; + if upd.affected == 0 { + return fail( + 2, + format!( + "stack_transition: intent at stack {stack_id} position {position} changed \ + concurrently (validated state {} is no longer current); re-read the stack \ + and retry", + current.state.as_str() + ), + ); + } + let rows = match stack_rows(t, &stack_id) { + Ok(r) => r, + Err(e) => return terr(e), + }; + let updated = rows + .iter() + .find(|r| r.get("position").and_then(|v| v.as_i64()) == Some(position)) + .cloned() + .unwrap_or(Value::Null); + ok(json!({"row": {"intent": updated, "stack": stack_state(&stack_id, &rows)}})) +} + +/// Re-record one intent's base after its author restacked the +/// branch off a withdrawn base (#8582; Codex P2, PR #8849): the +/// storage half of the `stack restack` acknowledgement. The +/// refresh rules are the pure core's (`plan_restack`) — this verb +/// only reads the stack, refuses what the core refuses, and +/// writes the new base (plus the restacked head, when the author +/// recorded one), conditioned on the base that was validated so a +/// concurrent change is refused rather than overwritten (the +/// transition verb's CAS discipline). +fn verb_stack_restack(t: &TursoBackend, req: &Value) -> Value { + let Some(stack_id) = req_str(req, "stack_id") else { + return fail(2, "stack_id is required".to_string()); + }; + let stack_id = stack_id.to_string(); + let Some(position) = req_i64(req, "position") else { + return fail(2, "position is required".to_string()); + }; + let Some(new_base) = req_str(req, "new_base_branch") else { + return fail(2, "new_base_branch is required".to_string()); + }; + let rows = match stack_rows(t, &stack_id) { + Ok(r) => r, + Err(e) => return terr(e), + }; + let core: Vec = + rows.iter().filter_map(merge_intent_core).collect(); + let restack = crate::merge_intent::RestackRequest { + stack_id: stack_id.clone(), + position, + new_base_branch: new_base.to_string(), + new_head_sha: req_str(req, "head_sha").map(|s| s.to_string()), + }; + let planned = match crate::merge_intent::plan_restack(&core, &restack) { + Ok(pl) => pl, + Err(e) => return fail(2, e), + }; + // plan_restack found the intent; its validated base AND its + // validated lifecycle state are the CAS predicates for the + // write below. The state predicate matters (Codex P2, PR + // #8849, comment 4549335606): transitions do not change + // base_branch, so a base-only predicate would let a restack + // acknowledgement rewrite the recorded base/head of an intent + // that a concurrent transition just landed or abandoned -- + // terminal records are sealed. + let (current_base, current_state) = core + .iter() + .find(|i| i.position == position) + .map(|i| (i.base_branch.clone(), i.state.as_str().to_string())) + .unwrap_or_default(); + let now = now_iso(); + let upd = match t.exec( + "UPDATE merge_intents SET base_branch = ?, head_sha = ?, base_head_sha = ?, updated_at = ? \ + WHERE stack_id = ? AND position = ? AND base_branch = ? AND state = ?", + &[ + Arg::Text(planned.base_branch.clone()), + arg_str(planned.head_sha.as_deref()), + arg_str(planned.base_head_sha.as_deref()), + Arg::Text(now), + Arg::Text(stack_id.clone()), + Arg::Int(position), + Arg::Text(current_base), + Arg::Text(current_state), + ], + ) { + Ok(r) => r, + Err(e) => return terr(e), + }; + if upd.affected == 0 { + return fail( + 2, + format!( + "stack_restack: intent at stack {stack_id} position {position} changed \ + concurrently (validated base or lifecycle state is no longer current); \ + re-read the stack and retry" + ), + ); + } + let rows = match stack_rows(t, &stack_id) { + Ok(r) => r, + Err(e) => return terr(e), + }; + let updated = rows + .iter() + .find(|r| r.get("position").and_then(|v| v.as_i64()) == Some(position)) + .cloned() + .unwrap_or(Value::Null); + ok(json!({"row": {"intent": updated, "stack": stack_state(&stack_id, &rows)}})) +} + fn verb_signal_count(t: &TursoBackend, req: &Value) -> Value { let queue = req_str(req, "queue").unwrap_or("").to_string(); let work = (|| -> Result { @@ -7249,6 +7490,8 @@ pub fn dispatch(t: &TursoBackend, path: &str, req: &Value) -> Value { "/signal-count" => verb_signal_count(t, req), "/stack-record" => verb_stack_record(t, req), "/stack-list" => verb_stack_list(t, req), + "/stack-transition" => verb_stack_transition(t, req), + "/stack-restack" => verb_stack_restack(t, req), "/events-append" => verb_events_append(t, req), "/events-seen" => verb_events_seen(t, req), "/events-count" => verb_events_count(t, req), @@ -7310,6 +7553,61 @@ mod tests { assert!(list.contains("stack_state("), "list answers the derived stack state"); } + + #[test] + fn stack_transition_wiring_8582() { + // Source oracle for increment 4 of #8582: dispatch routes + // the transition verb, and the verb decides legality in the + // pure core's transition table (never in SQL), recording + // the landing PR number and the conflict detail. + let src = include_str!("turso_queue.rs"); + let dispatch_seg = seg8217(src, "pub fn dispatch(", "\n#[cfg(test)]"); + assert!( + dispatch_seg.contains("\"/stack-transition\" => verb_stack_transition(t, req)"), + "dispatch routes /stack-transition" + ); + let seg = seg8217(src, "fn verb_stack_transition(", "\nfn verb_signal_count("); + assert!( + seg.contains("can_transition("), + "transition legality comes from the core table" + ); + assert!( + seg.contains("illegal move"), + "an illegal move is a refusal, not a write" + ); + assert!(seg.contains("pr_number"), "a landing records its PR number"); + assert!( + seg.contains("conflict_detail"), + "a conflict records its routing detail" + ); + assert!( + seg.contains("stack_state("), + "transition answers the derived stack state" + ); + } + + #[test] + fn stack_restack_wiring_8582() { + // Source oracle for the restack acknowledgement (#8582; + // Codex P2, PR #8849): dispatch routes the restack verb, + // and the verb decides the refresh in the pure core + // (plan_restack) — never in SQL — and answers the derived + // stack state. + let src = include_str!("turso_queue.rs"); + let dispatch_seg = seg8217(src, "pub fn dispatch(", "\n#[cfg(test)]"); + assert!( + dispatch_seg.contains("\"/stack-restack\" => verb_stack_restack(t, req)"), + "dispatch routes /stack-restack" + ); + let seg = seg8217(src, "fn verb_stack_restack(", "\nfn verb_signal_count("); + assert!(seg.contains("plan_restack("), "restack planning comes from the core"); + assert!(seg.contains("base_branch = ?"), "restack writes the refreshed base"); + assert!( + seg.contains("stack_state("), + "restack answers the derived stack state" + ); + } + #[test] fn canonical_lanes_are_exactly_the_post_rename_universe_8097() { // #8097 oracle: after the 2026-11-11 lane rename + trims,