Skip to main content

release_kit/commands/
integrate.rs

1//! `rk integrate`: move one implementation onto the trunk through the
2//! authority the target recorded.
3//!
4//! The local path is a transaction. It creates the squash commit as an
5//! unreferenced object, so nothing is published until one compare-and-swap
6//! carries the trunk tip observed before the gate ran. Every refusal
7//! therefore leaves the trunk at the tip it started from, and there is no
8//! half-integrated trunk to undo.
9//!
10//! The forge path stops where this repository's boundary already sits.
11//! It runs the project's own pre-push stage by pushing the branch, and it
12//! names the request command for the detected forge. Opening a request is
13//! an operator-named action in the landed routing block, and no verb here
14//! authors a request body: `rk message --check --kind body` is what
15//! judges one.
16//!
17//! Under the `rebase` merge form the local path builds no commit at all:
18//! it publishes the rebased branch tip with the same compare-and-swap, so
19//! every commit of the branch reaches the trunk with its own message, and
20//! each of those messages is judged first.
21//!
22//! SATISFIES git:a-local-integration-is-a-transaction
23//! SATISFIES git:a-rebase-integration-publishes-the-branch-tip
24//! SATISFIES git:the-pre-merge-commit-hook-is-the-pre-integrate-contract
25//! SATISFIES git:a-local-integration-warns-of-an-uncounted-release
26
27use camino::{Utf8Path, Utf8PathBuf};
28use serde::Serialize;
29
30use crate::cli::integrate::IntegrateArgs;
31use crate::diagnostic::{Diagnostic, Reason};
32use crate::error::RkError;
33use crate::integrate::{self, Entry, Ledger};
34use crate::landing::{Integration, MergeForm};
35use crate::maintenance::{GIT_HOOK_VARS, last_line};
36use crate::output::Output;
37use crate::requirements::Tool;
38
39/// The machine form of a report.
40#[derive(Debug, Serialize)]
41struct Report {
42    /// The shape version of this document.
43    schema: &'static str,
44    /// `preview` or `apply`.
45    mode: &'static str,
46    /// The target this ran against.
47    target: String,
48    /// The authority this execution used.
49    integration: &'static str,
50    /// Where the authority came from: `record` or `flag`.
51    authority_source: &'static str,
52    /// The recorded merge form: `squash` or `rebase`.
53    merge_form: &'static str,
54    /// The branch integrated.
55    branch: String,
56    /// The trunk it integrated onto.
57    trunk: String,
58    /// The seat the gate ran in.
59    seat: String,
60    /// The trunk tip before this integration.
61    trunk_before: String,
62    /// The commit the trunk now carries, on an applied local integration
63    /// alone: the squash commit, or the branch tip under `rebase`.
64    #[serde(skip_serializing_if = "Option::is_none")]
65    trunk_commit: Option<String>,
66    /// The steps that ran, in order.
67    steps: Vec<String>,
68    /// What the operator does next.
69    next: Vec<String>,
70}
71
72/// Integrate one branch; preview unless `--apply`.
73///
74/// # Errors
75///
76/// Returns [`RkError::Refusal`] for every judgment that stops the
77/// transaction, [`RkError::Missing`] for a target that is not a
78/// repository, and [`RkError::Io`] where the ledger cannot be written.
79pub fn run(args: &IntegrateArgs) -> Result<(), RkError> {
80    let out = Output::new(args.json);
81    let target = &args.target;
82    // git always, at the floor that `git hook run` needs. cargo, where the
83    // record releases a rust crate, is checked in the seat, where the
84    // listing the uncounted release warning reads runs it. Where git cannot
85    // serve, no seat can be found, so cargo is judged from the target and
86    // one refusal names both.
87    let rust = rust_automatic(target);
88    let git_unmet = crate::requirements::unmet(&[Tool::Git], None);
89    if !git_unmet.is_empty() {
90        let mut found = git_unmet;
91        let mut tools = vec![Tool::Git];
92        if rust {
93            tools.push(Tool::Cargo);
94            found.extend(crate::requirements::check(
95                Tool::Cargo,
96                Some(target.as_std_path()),
97            ));
98        }
99        return Err(crate::requirements::refusal("rk integrate", &tools, &found));
100    }
101    let trunk = crate::config::trunk_of(target.as_std_path())?;
102
103    let (integration, authority_source) = authority(args, target)?;
104    let merge_form = recorded_merge_form(target)?;
105    let scope_required = recorded_scope_rule(target)?;
106    if let Some(reason) = integrate::refuse_branch_name(&args.branch, &trunk) {
107        return Err(refuse(Reason::Usage, reason));
108    }
109
110    let git_dir = common_git_dir(target)?;
111    let seats = seats(target)?;
112    let seat = match seat_for(&seats, &args.branch, target) {
113        Ok(seat) => seat,
114        Err(error) => {
115            return Err(left_detached(&seats, &args.branch, target, &trunk).unwrap_or(error));
116        }
117    };
118    if rust {
119        let unmet = crate::requirements::unmet(&[Tool::Git, Tool::Cargo], Some(seat.as_std_path()));
120        if !unmet.is_empty() {
121            return Err(crate::requirements::refusal(
122                "rk integrate",
123                &[Tool::Git, Tool::Cargo],
124                &unmet,
125            ));
126        }
127    }
128    let dirty = is_dirty(&seat)?;
129    if dirty {
130        return Err(refuse(
131            Reason::StateDrift,
132            format!(
133                "{seat} has uncommitted changes, so the gate would judge a tree nobody reviewed"
134            ),
135        ));
136    }
137
138    let run = LocalRun {
139        target,
140        git_dir: &git_dir,
141        seat: &seat,
142        seats: &seats,
143        trunk: &trunk,
144        authority_source,
145        merge_form,
146        scope_required,
147    };
148    match (integration, merge_form) {
149        (Integration::Forge, _) => forge_path(
150            args,
151            out,
152            &seat,
153            &trunk,
154            authority_source,
155            merge_form,
156            scope_required,
157        ),
158        (Integration::Local, MergeForm::Squash) => local_path(args, out, &run),
159        (Integration::Local, MergeForm::Rebase) => rebase_path(args, out, &run),
160    }
161}
162
163/// Everything the local transaction resolved before it acts.
164struct LocalRun<'a> {
165    target: &'a Utf8Path,
166    git_dir: &'a Utf8Path,
167    seat: &'a Utf8Path,
168    seats: &'a [crate::worktree::Worktree],
169    trunk: &'a str,
170    authority_source: &'static str,
171    merge_form: MergeForm,
172    /// Whether a trunk message must name a scope: wherever the record
173    /// names a release, because the changelog reads it.
174    scope_required: bool,
175}
176
177/// The authority this execution uses, and where it came from.
178///
179/// The record answers, because the record is what landed: the hook block
180/// that admits or refuses these writes, the routing block an agent reads,
181/// and the forge protections the setup installed all render from it. A
182/// configuration edit is pending input to the next landing, never a
183/// runtime override — taking it here would run a local integration in a
184/// target whose installed controls still say forge, which is the split
185/// authority `target-config:the-config-is-input-and-the-record-is-the-record`
186/// exists to prevent. `--local` and `--forge` override one execution and
187/// write nothing.
188fn authority(
189    args: &IntegrateArgs,
190    target: &Utf8Path,
191) -> Result<(Integration, &'static str), RkError> {
192    if args.local {
193        return Ok((Integration::Local, "flag"));
194    }
195    if args.forge {
196        return Ok((Integration::Forge, "flag"));
197    }
198    let recorded = crate::landing::manifest::load(target)?.map(|record| record.git.integration);
199    Ok(recorded.map_or(
200        (crate::landing::manifest::integration_forge(), "default"),
201        |mode| (mode, "record"),
202    ))
203}
204
205/// The merge form this execution uses: the record's, as for the authority,
206/// and `squash` where no record exists or the record predates the form.
207///
208/// No flag overrides it. The authority flags exist because the same
209/// branch can reach the trunk either way, and the form decides which
210/// messages the trunk keeps, which the landed forge settings and gates
211/// were rendered for.
212fn recorded_merge_form(target: &Utf8Path) -> Result<MergeForm, RkError> {
213    Ok(crate::landing::manifest::load(target)?
214        .map_or_else(crate::landing::manifest::merge_form_squash, |record| {
215            record.git.merge_form
216        }))
217}
218
219/// Whether a trunk message must name a scope, as the record says: a
220/// release reads the scope, so every mode but `none` requires one, and a
221/// target with no record keeps the requirement it always had.
222///
223/// SATISFIES project-profile:a-release-less-landing-carries-no-release-text
224fn recorded_scope_rule(target: &Utf8Path) -> Result<bool, RkError> {
225    Ok(crate::landing::manifest::load(target)?
226        .is_none_or(|record| record.profile.release.mode != crate::profile::ReleaseMode::None))
227}
228
229/// The forge path: gate through the push, then name the request command.
230fn forge_path(
231    args: &IntegrateArgs,
232    out: Output,
233    seat: &Utf8Path,
234    trunk: &str,
235    authority_source: &'static str,
236    merge_form: MergeForm,
237    scope_required: bool,
238) -> Result<(), RkError> {
239    let mut steps = Vec::new();
240    if args.apply {
241        // The push is the boundary under forge integration, and the
242        // project's own pre-push stage is what git fires on it. Nothing
243        // here passes --no-verify.
244        let pushed = git(seat, &["push", "--set-upstream", "origin", &args.branch])?;
245        if !pushed.status.success() {
246            return Err(refuse(
247                Reason::RemoteConflict,
248                format!(
249                    "pushing {} refused: {}",
250                    args.branch,
251                    last_line(&pushed.stderr)
252                ),
253            ));
254        }
255        steps.push(format!("pushed {} to origin", args.branch));
256    } else {
257        steps.push(format!("would push {} to origin", args.branch));
258    }
259    let next = request_commands(
260        &origin_url(seat),
261        trunk,
262        &args.branch,
263        merge_form,
264        scope_required,
265    );
266    for line in &steps {
267        out.result_line(line);
268    }
269    out.emit(&Report {
270        schema: "rk.integrate/1",
271        mode: if args.apply { "apply" } else { "preview" },
272        target: args.target.to_string(),
273        integration: Integration::Forge.as_str(),
274        authority_source,
275        merge_form: merge_form.as_str(),
276        branch: args.branch.clone(),
277        trunk: trunk.to_owned(),
278        seat: seat.to_string(),
279        trunk_before: String::new(),
280        trunk_commit: None,
281        steps,
282        next: next.clone(),
283    })?;
284    out.next(&next);
285    Ok(())
286}
287
288/// The URL of the seat's `origin`, or empty where none answers.
289fn origin_url(seat: &Utf8Path) -> String {
290    git(seat, &["remote", "get-url", "origin"])
291        .ok()
292        .filter(|answer| answer.status.success())
293        .map(|answer| String::from_utf8_lossy(&answer.stdout).trim().to_owned())
294        .unwrap_or_default()
295}
296
297/// The request command for the forge the remote names, and what reaches
298/// the trunk from the request under the recorded merge form.
299///
300/// Under `squash` the request's title becomes the trunk's one commit, and
301/// GitLab is asked to squash. Under `rebase` every commit of the branch
302/// reaches the trunk with its own message, so no squash is asked for and
303/// each message is the one the commit-msg judgment holds. Where the record
304/// names no release, the guidance asks for a Conventional Commit whose
305/// scope is preferred and not required, because no changelog reads it.
306///
307/// SATISFIES git:the-merge-form-is-a-landing-parameter
308/// SATISFIES project-profile:a-release-less-landing-carries-no-release-text
309fn request_commands(
310    remote: &str,
311    trunk: &str,
312    branch: &str,
313    form: MergeForm,
314    scope_required: bool,
315) -> Vec<String> {
316    let squash = form == MergeForm::Squash;
317    let create = if remote.contains("gitlab") {
318        format!(
319            "glab mr create --source-branch {branch} --target-branch {trunk}{}",
320            if squash { " --squash-before-merge" } else { "" }
321        )
322    } else {
323        format!("gh pr create --base {trunk} --head {branch}")
324    };
325    let reaches = match (squash, scope_required) {
326        (true, true) => {
327            "the title is the trunk's commit message, so it is a scoped Conventional Commit"
328        }
329        (true, false) => {
330            "the title is the trunk's commit message, so it is a Conventional Commit, whose scope is preferred and not required"
331        }
332        (false, true) => {
333            "every commit of the branch reaches the trunk with its own message, so each one passes the commit-msg judgment: a scoped Conventional Commit with no guarded content"
334        }
335        (false, false) => {
336            "every commit of the branch reaches the trunk with its own message, so each one passes the commit-msg judgment: a Conventional Commit, whose scope is preferred and not required, with no guarded content"
337        }
338    };
339    vec![
340        create,
341        reaches.to_owned(),
342        "the body is yours; rk message --check --kind body judges it before you post it".to_owned(),
343    ]
344}
345
346/// Rebase the branch in its seat onto `onto`, with the integration's own
347/// semantics rather than the clone's preferences.
348///
349/// Both local merge forms run this one rebase. A merge in the branch is
350/// flattened, never recreated, whatever `rebase.rebaseMerges` says. No
351/// other branch moves, whatever `rebase.updateRefs` says, because the
352/// trunk is the one ref an integration publishes. No `fixup!` commit is
353/// folded and nothing is stashed, so the commits the gate judges are the
354/// commits the branch carries. A conflict refuses and leaves every ref
355/// where it found it.
356///
357/// SATISFIES git:a-rebase-integration-publishes-the-branch-tip
358fn rebase_onto(run: &LocalRun<'_>, branch: &str, onto: &str) -> Result<(), RkError> {
359    let rebased = git(
360        run.seat,
361        &REBASE_ARGS
362            .iter()
363            .copied()
364            .chain([onto])
365            .collect::<Vec<_>>(),
366    )?;
367    if !rebased.status.success() {
368        let _ = git(run.seat, &["rebase", "--abort"]);
369        return Err(refuse(
370            Reason::StateDrift,
371            format!(
372                "{branch} does not rebase onto {} cleanly: {}",
373                integrate::short(onto),
374                last_line(&rebased.stderr)
375            ),
376        ));
377    }
378    Ok(())
379}
380
381/// The rebase every local integration runs, before the commit it rebases
382/// onto: each option overrides the clone's configured preference of the
383/// same name.
384const REBASE_ARGS: [&str; 5] = [
385    "rebase",
386    "--no-rebase-merges",
387    "--no-update-refs",
388    "--no-autosquash",
389    "--no-autostash",
390];
391
392/// Refuse a range to publish that holds a merge commit.
393///
394/// The rebase flattens merges, and this does not trust it to: the trunk
395/// takes no merge commit from any actor, so the range is read back before
396/// the publication, and a merge in it refuses with the trunk unmoved.
397///
398/// SATISFIES git:a-rebase-integration-publishes-the-branch-tip
399fn refuse_merges_in_range(run: &LocalRun<'_>, from: &str, tip: &str) -> Result<(), RkError> {
400    let listed = git(
401        run.seat,
402        &["rev-list", "--merges", &format!("{from}..{tip}")],
403    )?;
404    if !listed.status.success() {
405        return Err(refuse(
406            Reason::StateDrift,
407            format!(
408                "the range {}..{} could not be read for merge commits: {}",
409                integrate::short(from),
410                integrate::short(tip),
411                last_line(&listed.stderr)
412            ),
413        ));
414    }
415    let merges: Vec<String> = String::from_utf8_lossy(&listed.stdout)
416        .lines()
417        .filter(|line| !line.is_empty())
418        .map(integrate::short)
419        .collect();
420    if merges.is_empty() {
421        return Ok(());
422    }
423    Err(refuse(
424        Reason::StateDrift,
425        format!(
426            "the rebased range {}..{} still holds the merge commit {}, and the trunk takes no merge commit, so nothing was published",
427            integrate::short(from),
428            integrate::short(tip),
429            merges.join(", ")
430        ),
431    ))
432}
433
434/// The dry run, which refreshes nothing.
435///
436/// No lock and no fetch: a preview that moved remote-tracking refs and
437/// wrote `FETCH_HEAD` would make its own promise false, and it would
438/// also report a plan built on state it changed while reporting it.
439fn preview(args: &IntegrateArgs, out: Output, run: &LocalRun<'_>) -> Result<(), RkError> {
440    let mut steps = Vec::new();
441    let trunk_before = rev_parse(run.seat, run.trunk)?;
442    warn_if_uncounted(
443        out,
444        run,
445        args.message.as_deref().unwrap_or_default(),
446        &[&format!("{trunk_before}...{}", args.branch)],
447        true,
448    );
449    steps.push("no fetch and no lock: a preview refreshes nothing".to_owned());
450    steps.push(format!(
451        "would rebase {} onto {}, or onto whatever the fetch brings",
452        args.branch,
453        integrate::short(&trunk_before)
454    ));
455    steps.push("would run the pre-merge-commit hook in the seat".to_owned());
456    steps.push(format!("would write one squash commit onto {}", run.trunk));
457    report(
458        args,
459        out,
460        run,
461        &trunk_before,
462        None,
463        steps,
464        &[format!(
465            "rk integrate {} --target {} --apply performs it",
466            args.branch, run.target
467        )],
468    )
469}
470
471/// The local transaction.
472///
473/// It reads its evidence ledger before it builds anything, so a ledger
474/// this binary cannot parse refuses while the trunk still stands where it
475/// stood, and it stages the evidence before it publishes, so every
476/// fallible part of writing it happens with the trunk unmoved. The one
477/// ref this moves is the trunk, through [`trunk_move`]'s publication.
478fn local_path(args: &IntegrateArgs, out: Output, run: &LocalRun<'_>) -> Result<(), RkError> {
479    let message = args.message.as_deref().unwrap_or_default();
480    refuse_message(run.seat, message, run.scope_required)?;
481    let mut steps = Vec::new();
482
483    if !args.apply {
484        return preview(args, out, run);
485    }
486
487    // The lock is the common git directory, so two seats of one clone
488    // collide on it: they write one trunk ref.
489    let _held = crate::landing::lock::acquire(run.git_dir)?;
490
491    // The evidence ledger is read and judged before anything is built, so
492    // an unreadable one refuses with the trunk untouched rather than
493    // after the squash is published.
494    let ledger_path = run.git_dir.join(integrate::LEDGER_PATH);
495    let mut ledger = read_ledger(&ledger_path)?;
496
497    refresh_trunk(run, &mut steps)?;
498
499    let trunk_before = rev_parse(run.seat, run.trunk)?;
500
501    // Bring the branch onto the trunk. A conflict refuses and leaves both
502    // refs where it found them.
503    rebase_onto(run, &args.branch, &trunk_before)?;
504    steps.push(format!(
505        "rebased {} onto {}",
506        args.branch,
507        integrate::short(&trunk_before)
508    ));
509
510    // The authoritative observation of the branch, taken before the gate
511    // so the tree the gate judges is the tree that reaches the trunk. It
512    // is re-observed below: a commit landing in the seat under the gate
513    // would otherwise be squashed without having passed it.
514    let branch_tip = rev_parse(run.seat, &args.branch)?;
515
516    // Before the gate, so the operator reads it while the trunk still
517    // stands where it stood and can stop to retype the message.
518    warn_if_uncounted(out, run, message, &[&trunk_before, &branch_tip], false);
519
520    // The gate: the repository's pre-merge-commit hook, through git, on
521    // the squash staged in the seat. No hook identifier is read.
522    let answer = gate(run.seat, &args.branch, &trunk_before, &branch_tip)?;
523    judge_gate(out, run, &args.branch, answer)?;
524    steps.push("the pre-merge-commit hook passed".to_owned());
525
526    // The re-observation. One object feeds the tree that is integrated
527    // and the tip the evidence certifies, and that object is the one the
528    // gate judged. The lock bounds this binary's own runs and bounds no
529    // hand at the desk, so both directions are checked rather than
530    // assumed.
531    let now = rev_parse(run.seat, &args.branch)?;
532    if now != branch_tip {
533        return Err(refuse(
534            Reason::StateDrift,
535            format!(
536                "{} moved from {} to {} while the gate ran, so the gate judged a tree that is no longer the branch's",
537                args.branch,
538                integrate::short(&branch_tip),
539                integrate::short(&now)
540            ),
541        ));
542    }
543    let commit = build_squash(run, &branch_tip, &trunk_before, message)?;
544    // Publish it against the tip observed before the gate ran. A trunk
545    // that moved under the gate refuses here and nothing was written.
546    // The evidence is rendered and staged before the publication, so
547    // every fallible part of writing it happens while the trunk still
548    // stands where it stood. Evidence naming a commit no ref carries
549    // proves nothing: both prune verbs require the trunk to reach the
550    // recorded commit, so a staged entry whose publication then fails is
551    // inert rather than dangerous.
552    ledger.record(Entry {
553        branch: args.branch.clone(),
554        branch_tip,
555        trunk_commit: commit.clone(),
556        at: crate::landing::manifest::now(),
557    });
558    write_ledger(&ledger_path, &ledger)?;
559
560    let drift = publish(run, &commit, &trunk_before)?;
561    steps.push(format!(
562        "{} now carries {}",
563        run.trunk,
564        integrate::short(&commit)
565    ));
566    steps.push("recorded the integration".to_owned());
567    if let Some(drift) = &drift {
568        steps.push(drift.step(run.trunk));
569    }
570
571    report(
572        args,
573        out,
574        run,
575        &trunk_before,
576        Some(commit.clone()),
577        steps,
578        &[
579            format!(
580                "git -C {} push origin {} pushes the trunk; it is a fast-forward and never a force",
581                run.target, run.trunk
582            ),
583            format!(
584                "rk worktree prune --target {} retires the seat, then its branch",
585                run.target
586            ),
587        ],
588    )?;
589    drift.map_or(Ok(()), |drift| Err(drift.into_error(run.trunk, &commit)))
590}
591
592/// The local transaction under the `rebase` merge form.
593///
594/// It is the squash transaction with the build step removed: the same
595/// lock, ledger read, refresh, rebase, gate, and re-observation, and the
596/// same publication, which moves the trunk to the rebased branch tip
597/// itself once the range is read back with no merge commit in it.
598/// Every commit between the trunk and that tip becomes a trunk commit, so
599/// each message is judged before the gate, and none is written here.
600///
601/// SATISFIES git:a-rebase-integration-publishes-the-branch-tip
602fn rebase_path(args: &IntegrateArgs, out: Output, run: &LocalRun<'_>) -> Result<(), RkError> {
603    refuse_message_under_rebase(args)?;
604    if !args.apply {
605        return rebase_preview(args, out, run);
606    }
607    let mut steps = Vec::new();
608
609    let _held = crate::landing::lock::acquire(run.git_dir)?;
610    let ledger_path = run.git_dir.join(integrate::LEDGER_PATH);
611    let mut ledger = read_ledger(&ledger_path)?;
612
613    refresh_trunk(run, &mut steps)?;
614
615    let trunk_before = rev_parse(run.seat, run.trunk)?;
616
617    rebase_onto(run, &args.branch, &trunk_before)?;
618    steps.push(format!(
619        "rebased {} onto {}",
620        args.branch,
621        integrate::short(&trunk_before)
622    ));
623
624    // The one observation the judgment, the gate, the evidence, and the
625    // publication all rest on; it is re-observed after the gate.
626    let branch_tip = rev_parse(run.seat, &args.branch)?;
627    let commits = branch_commits(run.seat, &trunk_before, &branch_tip, &args.branch)?;
628    refuse_commit_messages(run.seat, &commits, run.scope_required)?;
629    steps.push(format!(
630        "judged the message of each of {} commit{}",
631        commits.len(),
632        if commits.len() == 1 { "" } else { "s" }
633    ));
634
635    let answer = gate(run.seat, &args.branch, &trunk_before, &branch_tip)?;
636    judge_gate(out, run, &args.branch, answer)?;
637    steps.push("the pre-merge-commit hook passed".to_owned());
638
639    let now = rev_parse(run.seat, &args.branch)?;
640    if now != branch_tip {
641        return Err(refuse(
642            Reason::StateDrift,
643            format!(
644                "{} moved from {} to {} while the gate ran, so the gate judged a tree that is no longer the branch's",
645                args.branch,
646                integrate::short(&branch_tip),
647                integrate::short(&now)
648            ),
649        ));
650    }
651
652    // The range to publish holds no merge commit, whatever the rebase
653    // above did with the clone's preferences.
654    refuse_merges_in_range(run, &trunk_before, &branch_tip)?;
655
656    // The evidence names the branch tip as the integrated commit, staged
657    // before the publication like the squash form's, and inert in the
658    // same way where the publication then refuses: no prune reads an
659    // entry whose commit the trunk does not reach.
660    ledger.record(Entry {
661        branch: args.branch.clone(),
662        branch_tip: branch_tip.clone(),
663        trunk_commit: branch_tip.clone(),
664        at: crate::landing::manifest::now(),
665    });
666    write_ledger(&ledger_path, &ledger)?;
667
668    let drift = publish(run, &branch_tip, &trunk_before)?;
669    steps.push(format!(
670        "{} now carries {} at {}, with no new commit",
671        run.trunk,
672        args.branch,
673        integrate::short(&branch_tip)
674    ));
675    steps.push("recorded the integration".to_owned());
676    if let Some(drift) = &drift {
677        steps.push(drift.step(run.trunk));
678    }
679
680    report(
681        args,
682        out,
683        run,
684        &trunk_before,
685        Some(branch_tip.clone()),
686        steps,
687        &[
688            format!(
689                "git -C {} push origin {} pushes the trunk; it is a fast-forward and never a force",
690                run.target, run.trunk
691            ),
692            format!(
693                "rk worktree prune --target {} retires the seat, then its branch",
694                run.target
695            ),
696        ],
697    )?;
698    drift.map_or(
699        Ok(()),
700        |drift| Err(drift.into_error(run.trunk, &branch_tip)),
701    )
702}
703
704/// The dry run under `rebase`, which refreshes nothing and writes nothing.
705///
706/// It judges the messages the branch carries now: a rebase keeps every
707/// message, so a refusal the apply would reach is named here first.
708fn rebase_preview(args: &IntegrateArgs, out: Output, run: &LocalRun<'_>) -> Result<(), RkError> {
709    let trunk_before = rev_parse(run.seat, run.trunk)?;
710    let branch_tip = rev_parse(run.seat, &args.branch)?;
711    let commits = branch_commits(run.seat, &trunk_before, &branch_tip, &args.branch)?;
712    refuse_commit_messages(run.seat, &commits, run.scope_required)?;
713    let steps = vec![
714        "no fetch and no lock: a preview refreshes nothing".to_owned(),
715        format!(
716            "would rebase {} onto {}, or onto whatever the fetch brings",
717            args.branch,
718            integrate::short(&trunk_before)
719        ),
720        "would run the pre-merge-commit hook in the seat".to_owned(),
721        format!(
722            "would move {} to the tip of {}, carrying its {} commit{} with their own messages and writing no new commit",
723            run.trunk,
724            args.branch,
725            commits.len(),
726            if commits.len() == 1 { "" } else { "s" }
727        ),
728    ];
729    report(
730        args,
731        out,
732        run,
733        &trunk_before,
734        None,
735        steps,
736        &[format!(
737            "rk integrate {} --target {} --apply performs it",
738            args.branch, run.target
739        )],
740    )
741}
742
743/// Refuse a trunk message under `rebase`, where no commit takes one.
744///
745/// A message given here would reach nothing: every commit of the branch
746/// keeps its own, and the integration writes no commit to carry it. A
747/// silent drop would let the operator believe it landed.
748fn refuse_message_under_rebase(args: &IntegrateArgs) -> Result<(), RkError> {
749    if args.message.is_none() {
750        return Ok(());
751    }
752    Err(RkError::refusal(
753        Diagnostic::new(
754            Reason::MergeFormMismatch,
755            "-m names a trunk message, and the recorded merge form is rebase: every commit of the branch reaches the trunk with its own message, and no commit is written to carry this one",
756        )
757        .expected("no -m under git.merge_form = \"rebase\"")
758        .action(format!(
759            "rk integrate {} --apply integrates without it; git rebase -i on the branch rewords a commit",
760            args.branch
761        ))
762        .target_state("unchanged; the trunk stands where it stood"),
763    ))
764}
765
766/// One commit the rebase form publishes, with its message.
767struct BranchCommit {
768    id: String,
769    message: String,
770}
771
772/// Every commit between the trunk and the branch tip, oldest first.
773///
774/// A branch with no commit of its own has nothing to integrate, and a
775/// publication that moved nothing would still write evidence naming it.
776fn branch_commits(
777    seat: &Utf8Path,
778    trunk: &str,
779    tip: &str,
780    branch: &str,
781) -> Result<Vec<BranchCommit>, RkError> {
782    let listed = git(seat, &["rev-list", "--reverse", &format!("{trunk}..{tip}")])?;
783    if !listed.status.success() {
784        return Err(refuse(
785            Reason::StateDrift,
786            format!(
787                "the commits of {branch} could not be listed: {}",
788                last_line(&listed.stderr)
789            ),
790        ));
791    }
792    let ids: Vec<String> = String::from_utf8_lossy(&listed.stdout)
793        .lines()
794        .filter(|line| !line.is_empty())
795        .map(str::to_owned)
796        .collect();
797    if ids.is_empty() {
798        return Err(refuse(
799            Reason::StateDrift,
800            format!(
801                "{branch} carries no commit {} does not already carry, so there is nothing to integrate",
802                integrate::short(trunk)
803            ),
804        ));
805    }
806    ids.into_iter()
807        .map(|id| {
808            let shown = git(seat, &["log", "-1", "--format=%B", &id])?;
809            if !shown.status.success() {
810                return Err(refuse(
811                    Reason::StateDrift,
812                    format!(
813                        "the message of {} could not be read: {}",
814                        integrate::short(&id),
815                        last_line(&shown.stderr)
816                    ),
817                ));
818            }
819            Ok(BranchCommit {
820                message: String::from_utf8_lossy(&shown.stdout).into_owned(),
821                id,
822            })
823        })
824        .collect()
825}
826
827/// Refuse the first branch commit whose message the landed `commit-msg`
828/// stage would refuse.
829///
830/// The move that publishes these commits fires no hook, so the whole
831/// stage is applied here through the one owner the squash form uses: the
832/// scoped Conventional Commit shape, then every finding
833/// `rk message --check` reports. `at` is the seat, for the same reason as
834/// the squash form's: the ignore rules a message is judged against are
835/// the branch's.
836fn refuse_commit_messages(
837    at: &Utf8Path,
838    commits: &[BranchCommit],
839    scope_required: bool,
840) -> Result<(), RkError> {
841    for commit in commits {
842        let subject = commit.message.lines().next().unwrap_or("").trim();
843        let named = format!("commit {}", integrate::short(&commit.id));
844        if subject.is_empty() {
845            return Err(refuse(
846                Reason::Usage,
847                format!(
848                    "{named} carries no message, and every commit reaches the trunk with its own"
849                ),
850            ));
851        }
852        if let Some(reason) = misshapen_subject(subject, scope_required) {
853            return Err(refuse(Reason::Usage, format!("{named}: {reason}")));
854        }
855        let (findings, _) = crate::commands::message::judge(
856            &commit.message,
857            crate::cli::message::MessageKind::Commit,
858            at,
859            subject,
860            crate::commands::message::Judgment {
861                exempt: crate::commands::message::exempt_title(subject),
862                scope_required,
863            },
864        );
865        if findings.is_empty() {
866            continue;
867        }
868        let listed: Vec<String> = findings
869            .iter()
870            .map(|finding| format!("{}:{} {}", finding.class, finding.line, finding.detail))
871            .collect();
872        return Err(refuse(
873            Reason::Usage,
874            format!(
875                "{named} '{subject}' carries {} finding{} the landed commit-msg stage would refuse, and the trunk move fires no hook: {}",
876                findings.len(),
877                if findings.len() == 1 { "" } else { "s" },
878                listed.join("; ")
879            ),
880        ));
881    }
882    Ok(())
883}
884
885/// The squash commit, as an object nothing references yet.
886///
887/// `git commit-tree` takes the rebased branch's tree and the trunk tip as
888/// its one parent, so the object is a squash by construction and no ref
889/// moves. Publishing it is a separate compare-and-swap, which is what
890/// makes every refusal before that point leave nothing behind.
891fn build_squash(
892    run: &LocalRun<'_>,
893    branch_tip: &str,
894    parent: &str,
895    message: &str,
896) -> Result<String, RkError> {
897    let tree = rev_parse(run.seat, &format!("{branch_tip}^{{tree}}"))?;
898    let built = git(
899        run.seat,
900        &["commit-tree", &tree, "-p", parent, "-m", message],
901    )?;
902    if !built.status.success() {
903        return Err(refuse(
904            Reason::Internal,
905            format!(
906                "the squash commit could not be built: {}",
907                last_line(&built.stderr)
908            ),
909        ));
910    }
911    Ok(String::from_utf8_lossy(&built.stdout).trim().to_owned())
912}
913
914/// Bring the local trunk level with its remote, where a remote answers.
915///
916/// Only a divergence refuses. A trunk behind its remote fast-forwards,
917/// and a trunk ahead of it is the ordinary state under local
918/// integration: integrations accumulate and the operator pushes when
919/// they decide to.
920fn refresh_trunk(run: &LocalRun<'_>, steps: &mut Vec<String>) -> Result<(), RkError> {
921    // An absent origin and an origin that will not answer are different
922    // facts. A project with no remote integrates against its local trunk
923    // alone; a project whose remote exists and cannot be reached may have
924    // a newer or divergent trunk behind that failure, so proceeding from
925    // stale local state could publish an integration nobody can push.
926    let named = git(run.seat, &["remote", "get-url", "origin"])?;
927    if !named.status.success() {
928        steps.push("no origin remote; the local trunk stands alone".to_owned());
929        return Ok(());
930    }
931    let fetched = git(run.seat, &["fetch", "--quiet", "origin"])?;
932    if !fetched.status.success() {
933        return Err(refuse(
934            Reason::ForgeTemporary,
935            format!(
936                "origin is configured and did not answer, so the trunk could not be refreshed: {}",
937                last_line(&fetched.stderr)
938            ),
939        ));
940    }
941    steps.push("fetched origin".to_owned());
942    let Some(remote) = rev_parse(run.seat, &format!("refs/remotes/origin/{}", run.trunk)).ok()
943    else {
944        steps.push(format!(
945            "origin carries no {} yet; the local trunk stands alone",
946            run.trunk
947        ));
948        return Ok(());
949    };
950    let local = rev_parse(run.seat, run.trunk)?;
951    let state = integrate::trunk_state(
952        local == remote,
953        is_ancestor(run.seat, &local, &remote),
954        is_ancestor(run.seat, &remote, &local),
955    );
956    if let Some(reason) = integrate::refuse_trunk_state(state) {
957        return Err(refuse(Reason::RemoteConflict, reason));
958    }
959    match state {
960        integrate::TrunkState::Behind => {
961            fast_forward_trunk(run, &remote, &local)?;
962            steps.push(format!(
963                "fast-forwarded {} to origin/{}",
964                run.trunk, run.trunk
965            ));
966        }
967        integrate::TrunkState::Ahead => {
968            steps.push(format!(
969                "{} carries integrations nobody pushed yet",
970                run.trunk
971            ));
972        }
973        integrate::TrunkState::Level | integrate::TrunkState::Diverged => {}
974    }
975    Ok(())
976}
977
978/// Move the trunk ref forward to its remote tip, through the seat that
979/// holds it where one does, so no working tree is left behind its own HEAD.
980///
981/// This runs before the gate, and nothing is integrated yet, so a refresh
982/// that completed and then could not be confirmed, or was raced, refuses
983/// the integration. Its diagnostic describes the completed refresh: the
984/// trunk moved to its remote tip, and no integration was published.
985fn fast_forward_trunk(run: &LocalRun<'_>, to: &str, from: &str) -> Result<(), RkError> {
986    let PostPublication::Unsettled(unsettled) = trunk_move(run, to, from, "fast-forward")? else {
987        return Ok(());
988    };
989    Err(unsettled.into_refresh_error(run.trunk, from, to))
990}
991
992/// Publish the integrated commit: the squash commit, or the branch tip
993/// under `rebase`.
994///
995/// `Some` is a publication the trunk's read-back did not confirm as the
996/// planned move; the caller reports the publication and then fails with
997/// [`Unsettled::into_error`].
998fn publish(run: &LocalRun<'_>, commit: &str, expected: &str) -> Result<Option<Unsettled>, RkError> {
999    Ok(match trunk_move(run, commit, expected, "integration")? {
1000        PostPublication::Confirmed => None,
1001        PostPublication::Unsettled(unsettled) => Some(unsettled),
1002    })
1003}
1004
1005/// What a trunk move came to once it was made.
1006///
1007/// Every refusal of a move is an `Err` of [`trunk_move`] and happens before
1008/// anything is written. Once the held trunk's fast-forward succeeded, the
1009/// trunk is published, and what follows is this type and never an error:
1010/// [`confirm_move`] returns it and cannot fail, so no read-back problem can
1011/// travel the refusal path and claim the trunk stands where it stood.
1012#[derive(Debug, Clone, PartialEq, Eq)]
1013enum PostPublication {
1014    /// The move was the planned one: a compare-and-swap of an unheld
1015    /// trunk, or a held fast-forward whose start and end were confirmed.
1016    Confirmed,
1017    /// The trunk moved, and the read-back did not confirm the plan.
1018    Unsettled(Unsettled),
1019}
1020
1021/// A completed move of the held trunk that is not confirmed as planned.
1022#[derive(Debug, Clone, PartialEq, Eq)]
1023enum Unsettled {
1024    /// A confirmation source shows the move started elsewhere: a writer
1025    /// outside rk moved the trunk during the publication.
1026    Raced(Drift),
1027    /// No source confirms where the move started, for the reason given.
1028    Unconfirmed {
1029        /// The commit the observation found before the gate.
1030        expected: String,
1031        /// Why no source confirmed the move.
1032        reason: String,
1033    },
1034}
1035
1036impl Unsettled {
1037    /// The report line naming the uncertainty beside the publication.
1038    fn step(&self, trunk: &str) -> String {
1039        match self {
1040            Self::Raced(drift) => drift.step(trunk),
1041            Self::Unconfirmed { expected, reason } => format!(
1042                "{trunk}'s move from the observed {} is not confirmed: {reason}",
1043                integrate::short(expected)
1044            ),
1045        }
1046    }
1047
1048    /// The diagnostic of a publication that is not confirmed as planned:
1049    /// the trunk is published, nothing is rolled back, and the operator
1050    /// reads what moved it.
1051    fn into_error(self, trunk: &str, published: &str) -> RkError {
1052        match self {
1053            Self::Raced(drift) => drift.into_error(trunk, published),
1054            Self::Unconfirmed { expected, reason } => {
1055                unconfirmed_error(trunk, &expected, published, &reason)
1056            }
1057        }
1058    }
1059
1060    /// The diagnostic of a pre-gate refresh that completed and is not
1061    /// confirmed as planned: the trunk moved to its remote tip, and no
1062    /// integration was published, so the integration refuses.
1063    fn into_refresh_error(self, trunk: &str, from: &str, to: &str) -> RkError {
1064        let message = match &self {
1065            Self::Raced(drift) => format!(
1066                "{trunk} was fast-forwarded to its remote tip {}, and its last move went from {} to {} where this run observed {}: a writer outside rk moved it at the same time, so no integration was published",
1067                integrate::short(to),
1068                integrate::short(&drift.found_old),
1069                integrate::short(&drift.found_new),
1070                integrate::short(from)
1071            ),
1072            Self::Unconfirmed { reason, .. } => format!(
1073                "{trunk} was fast-forwarded to its remote tip {}, but rk could not confirm that the move started at the observed {}: {reason}; no integration was published",
1074                integrate::short(to),
1075                integrate::short(from)
1076            ),
1077        };
1078        RkError::refusal(
1079            Diagnostic::new(Reason::StateDrift, message)
1080                .action(format!(
1081                    "read git reflog {trunk} and git log {}..{}, then run the integration again",
1082                    integrate::short(from),
1083                    integrate::short(to)
1084                ))
1085                .target_state(format!(
1086                    "{trunk} was refreshed to its remote tip {}, with no rollback; no integration was published",
1087                    integrate::short(to)
1088                )),
1089        )
1090    }
1091}
1092
1093/// The diagnostic of a publication no source confirmed.
1094fn unconfirmed_error(trunk: &str, expected: &str, published: &str, reason: &str) -> RkError {
1095    let expected = integrate::short(expected);
1096    let published = integrate::short(published);
1097    RkError::check_failed(
1098        Diagnostic::new(
1099            Reason::StateDrift,
1100            format!(
1101                "{trunk} now stands at the published {published}, but rk could not confirm that the move started at the observed {expected}: {reason}"
1102            ),
1103        )
1104        .expected(format!("a confirmed move of {trunk} from {expected} to {published}"))
1105        .action(format!(
1106            "read git reflog {trunk} and git log {expected}..{published}, and decide whether anything else moved {trunk}; rk moves nothing back"
1107        ))
1108        .target_state(format!(
1109            "{trunk} is published at {published}, with no rollback and no reset; the staged evidence names {published} and the trunk reaches it"
1110        )),
1111    )
1112}
1113
1114/// A held trunk's move, read back, that did not start at the observed tip.
1115#[derive(Debug, Clone, PartialEq, Eq)]
1116struct Drift {
1117    /// The commit the observation found before the gate.
1118    expected: String,
1119    /// The commit the move started at.
1120    found_old: String,
1121    /// The commit the move ended at.
1122    found_new: String,
1123}
1124
1125impl Drift {
1126    /// The report line naming the drift beside the publication.
1127    fn step(&self, trunk: &str) -> String {
1128        format!(
1129            "{trunk}'s last move went from {} to {}, where this run observed {}",
1130            integrate::short(&self.found_old),
1131            integrate::short(&self.found_new),
1132            integrate::short(&self.expected)
1133        )
1134    }
1135
1136    /// The diagnostic of a publication a writer outside rk raced: the
1137    /// trunk is published, nothing is rolled back, and the operator reads
1138    /// the commits that writer added.
1139    fn into_error(self, trunk: &str, published: &str) -> RkError {
1140        RkError::check_failed(
1141            Diagnostic::new(
1142                Reason::StateDrift,
1143                format!(
1144                    "{trunk} now stands at the published {}, and its last move went from {} to {}, not from the observed {}: a writer outside rk moved it during the publication",
1145                    integrate::short(published),
1146                    integrate::short(&self.found_old),
1147                    integrate::short(&self.found_new),
1148                    integrate::short(&self.expected)
1149                ),
1150            )
1151            .expected(format!(
1152                "a move of {trunk} from the observed {} to the published {}",
1153                integrate::short(&self.expected),
1154                integrate::short(published)
1155            ))
1156            .action(format!(
1157                "read the commits between the observed and the found starting commit, git log {}..{}, and decide whether they belong on {trunk}; rk moves nothing back",
1158                integrate::short(&self.expected),
1159                integrate::short(&self.found_old)
1160            ))
1161            .target_state(format!(
1162                "{trunk} is published at {}, with no rollback and no reset; the staged evidence names {} and the trunk reaches it",
1163                integrate::short(published),
1164                integrate::short(published)
1165            )),
1166        )
1167    }
1168}
1169
1170/// One trunk move from `expected` to `to`.
1171///
1172/// The worktrees and the trunk are read again immediately before the
1173/// move: a trunk that moved since the observation refuses with the
1174/// `moved` refusal, and a trunk that became checked out, or stopped being
1175/// checked out, since then refuses too, because the form of the move
1176/// depends on who holds it. Nothing was written in either case.
1177///
1178/// Where no worktree holds the trunk, the ref moves by `git update-ref`
1179/// carrying `expected` as its old value, a compare-and-swap. Where a
1180/// worktree holds it, Git offers no such swap that also moves the
1181/// worktree, so the move is that worktree's own fast-forward merge, which
1182/// keeps its index and working tree with HEAD. A writer outside rk can
1183/// still move the trunk between the re-observation and the merge. A merge
1184/// that refuses writes nothing and is an `Err`. A merge that succeeds has
1185/// published, and [`confirm_move`] then reads where the move started.
1186fn trunk_move(
1187    run: &LocalRun<'_>,
1188    to: &str,
1189    expected: &str,
1190    what: &str,
1191) -> Result<PostPublication, RkError> {
1192    let observed = run
1193        .seats
1194        .iter()
1195        .find(|seat| seat.branch.as_deref() == Some(run.trunk))
1196        .map(|seat| seat.path.clone());
1197    let live_seats = seats(run.target)?;
1198    let holder = live_seats
1199        .iter()
1200        .find(|seat| seat.branch.as_deref() == Some(run.trunk));
1201    if let Some(changed) = holder_change(
1202        run.trunk,
1203        observed.as_deref(),
1204        holder.map(|seat| seat.path.as_path()),
1205        what,
1206    ) {
1207        return Err(refuse(Reason::StateDrift, changed));
1208    }
1209    let reference = format!("refs/heads/{}", run.trunk);
1210    let live = rev_parse(run.seat, &reference)?;
1211    if live != expected {
1212        return Err(moved(run.trunk, expected, &live));
1213    }
1214    let Some(holder) = holder else {
1215        let swapped = git(run.seat, &["update-ref", &reference, to, expected])?;
1216        if !swapped.status.success() {
1217            let now =
1218                rev_parse(run.seat, &reference).unwrap_or_else(|_| "an unreadable tip".to_owned());
1219            return Err(moved(run.trunk, expected, &now));
1220        }
1221        return Ok(PostPublication::Confirmed);
1222    };
1223    if is_dirty(&holder.path)? {
1224        return Err(refuse(
1225            Reason::StateDrift,
1226            format!(
1227                "{} has the trunk checked out and carries uncommitted changes, so the {what} would leave it behind its own HEAD",
1228                holder.path
1229            ),
1230        ));
1231    }
1232    // The reflog is written whatever the clone says, and the merge reports
1233    // its own move in English with full object names, so the move can be
1234    // read back from either.
1235    let merged = git_in_c_locale(
1236        &holder.path,
1237        &[
1238            "-c",
1239            "core.logAllRefUpdates=always",
1240            "-c",
1241            "core.abbrev=no",
1242            "merge",
1243            "--ff-only",
1244            to,
1245        ],
1246    )?;
1247    if !merged.status.success() {
1248        return Err(refuse(
1249            Reason::StateDrift,
1250            format!(
1251                "the {what} is not a fast-forward of {}, so nothing was published: {}",
1252                holder.path,
1253                last_line(&merged.stderr)
1254            ),
1255        ));
1256    }
1257    let report = String::from_utf8_lossy(&merged.stdout).into_owned();
1258    Ok(confirm_move(run, &reference, expected, to, &report))
1259}
1260
1261/// Where the held trunk's completed fast-forward started and ended, read
1262/// back, and what that makes of it. It cannot fail: every problem is an
1263/// unconfirmed publication.
1264///
1265/// The sources, in order: the files backend's raw reflog entry, which
1266/// records the transition as written; else the newest two entries of
1267/// `git reflog show`, where two exist; and the merge's own `Updating
1268/// <old>..<new>` line, with full object names. A reflog source and the
1269/// merge's line that disagree confirm nothing. Only exact full-name
1270/// equality confirms: the start equals the observed tip and the end the
1271/// published object. A source that shows another start, with the planned
1272/// end, is the race; anything else is unconfirmed.
1273fn confirm_move(
1274    run: &LocalRun<'_>,
1275    reference: &str,
1276    expected: &str,
1277    to: &str,
1278    merge_report: &str,
1279) -> PostPublication {
1280    let reflog = reflog_transition(run, reference);
1281    let reported = parse_updating(merge_report, expected.len());
1282    judge_move(expected, to, reflog, reported)
1283}
1284
1285/// The judgment over the two read-backs; see [`confirm_move`].
1286fn judge_move(
1287    expected: &str,
1288    to: &str,
1289    reflog: Result<(String, String), String>,
1290    reported: Result<(String, String), String>,
1291) -> PostPublication {
1292    let unconfirmed = |reason: String| {
1293        PostPublication::Unsettled(Unsettled::Unconfirmed {
1294            expected: expected.to_owned(),
1295            reason,
1296        })
1297    };
1298    let transition = match (reflog, reported) {
1299        (Ok(logged), Ok(said)) if logged != said => {
1300            return unconfirmed(format!(
1301                "the reflog shows {}..{} and the fast-forward reported {}..{}",
1302                integrate::short(&logged.0),
1303                integrate::short(&logged.1),
1304                integrate::short(&said.0),
1305                integrate::short(&said.1)
1306            ));
1307        }
1308        (Ok(logged), _) => logged,
1309        (Err(_), Ok(said)) => said,
1310        (Err(logged), Err(said)) => {
1311            return unconfirmed(format!("{logged}, and {said}"));
1312        }
1313    };
1314    let (old, new) = transition;
1315    if new != to {
1316        return unconfirmed(format!(
1317            "the move read back ends at {}, not at the published {}",
1318            integrate::short(&new),
1319            integrate::short(to)
1320        ));
1321    }
1322    if old == expected {
1323        return PostPublication::Confirmed;
1324    }
1325    PostPublication::Unsettled(Unsettled::Raced(Drift {
1326        expected: expected.to_owned(),
1327        found_old: old,
1328        found_new: new,
1329    }))
1330}
1331
1332/// Whether `name` is a full object name of `len` hexadecimal characters.
1333fn full_name(name: &str, len: usize) -> bool {
1334    name.len() == len && name.bytes().all(|byte| byte.is_ascii_hexdigit())
1335}
1336
1337/// The old and new value of the trunk's newest reflog entry, or why they
1338/// cannot be read.
1339///
1340/// The files backend keeps the raw transition in the ref's log, read as
1341/// written. A backend with no such file answers through the reflog
1342/// command, whose second entry carries the value the newest one started
1343/// from; with one entry, as after an expiry, it answers nothing.
1344fn reflog_transition(run: &LocalRun<'_>, reference: &str) -> Result<(String, String), String> {
1345    let path = run.git_dir.join("logs").join(reference);
1346    match std::fs::read_to_string(path.as_std_path()) {
1347        Ok(text) => {
1348            let line = text.lines().last().unwrap_or_default();
1349            let mut fields = line.split_whitespace();
1350            match (fields.next(), fields.next()) {
1351                (Some(old), Some(new))
1352                    if full_name(old, new.len()) && full_name(new, old.len()) =>
1353                {
1354                    Ok((old.to_owned(), new.to_owned()))
1355                }
1356                _ => Err(format!("the reflog file {path} holds no readable entry")),
1357            }
1358        }
1359        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
1360            let listed = git(
1361                run.seat,
1362                &["reflog", "show", "--format=%H", "-n", "2", reference],
1363            )
1364            .map_err(|error| format!("git reflog did not run: {error}"))?;
1365            if !listed.status.success() {
1366                return Err(format!(
1367                    "git reflog show {reference} failed: {}",
1368                    last_line(&listed.stderr)
1369                ));
1370            }
1371            let text = String::from_utf8_lossy(&listed.stdout).into_owned();
1372            let mut lines = text.lines();
1373            match (lines.next(), lines.next()) {
1374                (Some(new), Some(old))
1375                    if full_name(new, old.len()) && full_name(old, new.len()) =>
1376                {
1377                    Ok((old.to_owned(), new.to_owned()))
1378                }
1379                _ => Err(format!(
1380                    "the reflog of {reference} holds fewer than two readable entries"
1381                )),
1382            }
1383        }
1384        Err(error) => Err(format!("the reflog file {path} could not be read: {error}")),
1385    }
1386}
1387
1388/// The `<old>` and `<new>` of the fast-forward's own `Updating
1389/// <old>..<new>` line, each a full object name of `len` characters, or why
1390/// the report confirms nothing: no such line, more than one, a malformed
1391/// one, or an abbreviated name.
1392fn parse_updating(report: &str, len: usize) -> Result<(String, String), String> {
1393    let lines: Vec<&str> = report
1394        .lines()
1395        .filter_map(|line| line.strip_prefix("Updating "))
1396        .collect();
1397    let [line] = lines.as_slice() else {
1398        return Err(if lines.is_empty() {
1399            "the fast-forward reported no Updating line".to_owned()
1400        } else {
1401            "the fast-forward reported more than one Updating line".to_owned()
1402        });
1403    };
1404    let Some((old, new)) = line.trim().split_once("..") else {
1405        return Err(format!(
1406            "the fast-forward's Updating line is malformed: {line}"
1407        ));
1408    };
1409    if !full_name(old, len) || !full_name(new, len) {
1410        return Err(format!(
1411            "the fast-forward's Updating line names no full object names: {line}"
1412        ));
1413    }
1414    Ok((old.to_owned(), new.to_owned()))
1415}
1416
1417/// Why the trunk's holder differs from the one observed, or `None`.
1418fn holder_change(
1419    trunk: &str,
1420    observed: Option<&Utf8Path>,
1421    live: Option<&Utf8Path>,
1422    what: &str,
1423) -> Option<String> {
1424    match (observed, live) {
1425        (None, None) => None,
1426        (Some(before), Some(now)) if before == now => None,
1427        (None, Some(now)) => Some(format!(
1428            "{trunk} was checked out in {now} after this run observed it, so the {what} would leave that worktree behind its own HEAD; nothing was published"
1429        )),
1430        (Some(before), None) => Some(format!(
1431            "{trunk} stopped being checked out in {before} after this run observed it, so the {what} no longer has the worktree it was planned for; nothing was published"
1432        )),
1433        (Some(before), Some(now)) => Some(format!(
1434            "{trunk} moved from being checked out in {before} to {now} after this run observed it; nothing was published"
1435        )),
1436    }
1437}
1438
1439/// The refusal for a trunk that moved between the observation and the write.
1440///
1441/// This one refusal comes after the evidence was staged, so it says what
1442/// is actually on disk rather than repeating the general claim: the trunk
1443/// stands where it stood, and the staged entry names a commit the trunk
1444/// does not reach, which both prune verbs ignore.
1445fn moved(trunk: &str, expected: &str, now: &str) -> RkError {
1446    RkError::refusal(
1447        Diagnostic::new(
1448            Reason::StateDrift,
1449            integrate::refuse_moved_trunk(expected, now).unwrap_or_else(|| {
1450                format!(
1451                    "{trunk} could not be moved and stands at {}",
1452                    integrate::short(now)
1453                )
1454            }),
1455        )
1456        .target_state(format!(
1457            "{trunk} stands where it stood; the staged evidence names a commit it does not reach, which every prune ignores"
1458        )),
1459    )
1460}
1461
1462/// Warn where the message states release intent and the squash changes no
1463/// file the crate ships, under a record whose release bot is release-plz.
1464///
1465/// release-plz attributes a commit to a package only where the commit
1466/// changes a file `cargo package --list` prints, so such a commit reaches
1467/// neither the changelog nor a release. The checks run cheapest first, so a
1468/// message stating no intent or a target another driver releases spawns no
1469/// cargo. Anything that cannot answer leaves the integration silent: a
1470/// warning built on an unproved listing teaches the operator to ignore it.
1471/// The listing runs `--locked --offline`, so it writes nothing into the
1472/// tree the gate judges.
1473///
1474/// SATISFIES git:a-local-integration-warns-of-an-uncounted-release
1475fn warn_if_uncounted(
1476    out: Output,
1477    run: &LocalRun<'_>,
1478    message: &str,
1479    range: &[&str],
1480    previewed: bool,
1481) {
1482    let Some(intent) = integrate::release_intent(message) else {
1483        return;
1484    };
1485    if !rust_automatic(run.target) {
1486        return;
1487    }
1488    let mut diff = vec!["diff", "--name-only", "--no-renames", "-z"];
1489    diff.extend_from_slice(range);
1490    let Ok(changed) = git(run.seat, &diff) else {
1491        return;
1492    };
1493    if !changed.status.success() {
1494        return;
1495    }
1496    let changed = String::from_utf8_lossy(&changed.stdout).into_owned();
1497    let changed: Vec<&str> = changed
1498        .split('\0')
1499        .filter(|path| !path.is_empty())
1500        .collect();
1501    let root_manifest = run.seat.as_std_path().join("Cargo.toml");
1502    let probe = crate::cargo_package::probe(&root_manifest, &["--locked", "--offline"], |args| {
1503        cargo_in(run.seat, args)
1504    });
1505    let Ok(crate::cargo_package::Probe::Listed(listing)) = probe else {
1506        return;
1507    };
1508    if !listing.touched_by(changed.iter().copied()) {
1509        out.warn(integrate::uncounted_release(intent, previewed));
1510    }
1511}
1512
1513/// Whether the target's record releases a rust crate automatically, which
1514/// is when the uncounted-release warning asks cargo for a listing.
1515fn rust_automatic(target: &Utf8Path) -> bool {
1516    crate::landing::manifest::load(target)
1517        .ok()
1518        .flatten()
1519        .is_some_and(|record| {
1520            let release = &record.profile.release;
1521            release.mode == crate::profile::ReleaseMode::Automatic
1522                && release.driver.as_deref() == Some("rust")
1523        })
1524}
1525
1526/// One cargo call in the seat, for the listing the warning reads.
1527fn cargo_in(seat: &Utf8Path, args: &[&str]) -> Result<crate::cargo_package::Answer, ()> {
1528    let mut command = std::process::Command::new("cargo");
1529    for var in GIT_HOOK_VARS {
1530        command.env_remove(var);
1531    }
1532    command
1533        .current_dir(seat.as_std_path())
1534        .args(args)
1535        .stdin(std::process::Stdio::null())
1536        .output()
1537        .map(|output| crate::cargo_package::Answer {
1538            success: output.status.success(),
1539            stdout: output.stdout,
1540            stderr: output.stderr,
1541        })
1542        .map_err(|_| ())
1543}
1544
1545/// The hook event the gate asks git to run: the checks a project runs
1546/// before work merges into its trunk.
1547const GATE_HOOK: &str = "pre-merge-commit";
1548
1549/// The line git prints when the repository installs no hook for the
1550/// event. git prints it untranslated, so it reads the same in every
1551/// locale.
1552const NO_HOOK: &str = "cannot find a hook named pre-merge-commit";
1553
1554/// What the gate saw: the hook's output, or a hook that left the seat
1555/// changed.
1556enum Gate {
1557    /// The hook ran and the seat stands as the gate staged it.
1558    Ran(std::process::Output),
1559    /// The hook committed on the detached `HEAD` or changed the index, so
1560    /// the staged change is no longer the squash it judged. It carries
1561    /// what changed and the hook's output.
1562    ChangedTheSeat(SeatChange, std::process::Output),
1563}
1564
1565/// Run the pre-integrate gate: the repository's `pre-merge-commit` hook,
1566/// through git, on the squash staged in the seat.
1567///
1568/// The seat's `HEAD` points at the trunk commit while the index and the
1569/// files stay at the branch tip, so the staged change is exactly what the
1570/// integration writes onto the trunk, and the project's hook manager
1571/// selects its files from that change natively. rk names no hook runner:
1572/// git runs whatever hook the project installed, and a clone with none
1573/// fails with git's own error.
1574fn gate(
1575    seat: &Utf8Path,
1576    branch: &str,
1577    trunk_commit: &str,
1578    branch_tip: &str,
1579) -> Result<Gate, RkError> {
1580    let tree = rev_parse(seat, &format!("{branch_tip}^{{tree}}"))?;
1581    let pointed = git(
1582        seat,
1583        &[
1584            "update-ref",
1585            "--no-deref",
1586            "-m",
1587            "rk integrate: stage the squash for the pre-merge-commit hook",
1588            "HEAD",
1589            trunk_commit,
1590        ],
1591    )?;
1592    if !pointed.status.success() {
1593        return Err(refuse(
1594            Reason::StateDrift,
1595            format!(
1596                "the seat's HEAD in {seat} could not point at the trunk commit {}: {}",
1597                integrate::short(trunk_commit),
1598                last_line(&pointed.stderr)
1599            ),
1600        ));
1601    }
1602    let restore = SeatHead {
1603        seat,
1604        branch,
1605        armed: true,
1606    };
1607    let mut command = std::process::Command::new(crate::probes::git_bin());
1608    for var in GIT_HOOK_VARS {
1609        command.env_remove(var);
1610    }
1611    let ran = command
1612        .arg("-C")
1613        .arg(seat.as_std_path())
1614        .args(["hook", "run", GATE_HOOK])
1615        .stdin(std::process::Stdio::null())
1616        .output()
1617        .map_err(|source| {
1618            RkError::subprocess(
1619                Diagnostic::new(
1620                    Reason::SubprocessSpawn,
1621                    format!("git did not run in {seat}: {source}"),
1622                )
1623                .target_state("unchanged; the trunk stands where it stood"),
1624            )
1625        })?;
1626    // An inspection that fails is an error, not a change: the `?` drops
1627    // the armed guard, which points `HEAD` back at the branch.
1628    if let Some(change) = seat_change(seat, trunk_commit, &tree)? {
1629        restore.leave();
1630        return Ok(Gate::ChangedTheSeat(change, ran));
1631    }
1632    restore.restore()?;
1633    Ok(Gate::Ran(ran))
1634}
1635
1636/// How a hook left the seat changed.
1637enum SeatChange {
1638    /// `HEAD` moved off the trunk commit to this commit: the hook
1639    /// committed.
1640    Committed(String),
1641    /// `HEAD` still names the trunk commit, and the index no longer holds
1642    /// the branch tip's tree: the hook staged a change.
1643    Staged,
1644}
1645
1646/// How the hook left the seat changed, or `None` where `HEAD` still names
1647/// the trunk commit and the index still writes the branch tip's tree. A
1648/// git call that fails is an error, so it never reads as a change.
1649fn seat_change(
1650    seat: &Utf8Path,
1651    trunk_commit: &str,
1652    tree: &str,
1653) -> Result<Option<SeatChange>, RkError> {
1654    let inspect = |args: &[&str], what: &str| -> Result<String, RkError> {
1655        let answer = git(seat, args)?;
1656        if !answer.status.success() {
1657            return Err(refuse(
1658                Reason::StateDrift,
1659                format!(
1660                    "{what} in {seat} after the pre-merge-commit hook could not be read: {}",
1661                    last_line(&answer.stderr)
1662                ),
1663            ));
1664        }
1665        Ok(String::from_utf8_lossy(&answer.stdout).trim().to_owned())
1666    };
1667    let head = inspect(&["rev-parse", "--verify", "--quiet", "HEAD"], "HEAD")?;
1668    if head != trunk_commit {
1669        return Ok(Some(SeatChange::Committed(head)));
1670    }
1671    let written = inspect(&["write-tree"], "the index")?;
1672    Ok((written != tree).then_some(SeatChange::Staged))
1673}
1674
1675/// The seat's `HEAD`, pointed at the trunk for the gate, with the branch
1676/// it goes back to. Dropped while armed, it restores `HEAD` on any early
1677/// exit; [`SeatHead::restore`] does it on the ordinary path and reports a
1678/// failure, and [`SeatHead::leave`] keeps the seat as the hook left it.
1679struct SeatHead<'a> {
1680    seat: &'a Utf8Path,
1681    branch: &'a str,
1682    armed: bool,
1683}
1684
1685impl SeatHead<'_> {
1686    /// The symbolic ref that points `HEAD` back at the branch.
1687    fn point_back(&self) -> Result<std::process::Output, RkError> {
1688        git(
1689            self.seat,
1690            &[
1691                "symbolic-ref",
1692                "HEAD",
1693                &format!("refs/heads/{}", self.branch),
1694            ],
1695        )
1696    }
1697
1698    /// Point `HEAD` back at the branch, and refuse where git does not.
1699    fn restore(mut self) -> Result<(), RkError> {
1700        self.armed = false;
1701        let answer = self.point_back()?;
1702        if answer.status.success() {
1703            return Ok(());
1704        }
1705        Err(refuse(
1706            Reason::StateDrift,
1707            format!(
1708                "the seat {} stays detached at the trunk commit, because HEAD did not point back at {}: {}; run git -C {} symbolic-ref HEAD refs/heads/{}",
1709                self.seat,
1710                self.branch,
1711                last_line(&answer.stderr),
1712                self.seat,
1713                self.branch
1714            ),
1715        ))
1716    }
1717
1718    /// Keep the seat as the hook left it, for the operator to read.
1719    fn leave(mut self) {
1720        self.armed = false;
1721    }
1722}
1723
1724impl Drop for SeatHead<'_> {
1725    fn drop(&mut self) {
1726        if self.armed {
1727            let _ = self.point_back();
1728        }
1729    }
1730}
1731
1732/// Judge what the gate answered: `Ok` where the hook passed, and the
1733/// refusal that names what stopped it otherwise.
1734fn judge_gate(out: Output, run: &LocalRun<'_>, branch: &str, gate: Gate) -> Result<(), RkError> {
1735    let ran = match gate {
1736        Gate::Ran(ran) => ran,
1737        Gate::ChangedTheSeat(change, ran) => {
1738            out.child_passthrough(crate::events::ChildStream::Stderr, &ran.stderr);
1739            out.child_passthrough(crate::events::ChildStream::Stdout, &ran.stdout);
1740            let seat = run.seat;
1741            let repair = format!("git -C {seat} symbolic-ref HEAD refs/heads/{branch}");
1742            let (what, action) = match change {
1743                SeatChange::Committed(head) => (
1744                    format!(
1745                        "the hook committed, so HEAD moved from the trunk commit to {}",
1746                        integrate::short(&head)
1747                    ),
1748                    format!(
1749                        "read what the hook left in {seat}; keep the hook's commit if you want it with git -C {seat} branch <name> HEAD, because the next step leaves it on no ref; then run {repair} and integrate again"
1750                    ),
1751                ),
1752                SeatChange::Staged => (
1753                    "the hook staged a change, so the index no longer holds the branch tip's tree"
1754                        .to_owned(),
1755                    format!(
1756                        "read what the hook staged in {seat}, then run {repair}, restore the index with git -C {seat} reset -q, and integrate again"
1757                    ),
1758                ),
1759            };
1760            return Err(RkError::refusal(
1761                Diagnostic::new(
1762                    Reason::StateDrift,
1763                    format!(
1764                        "the hook changed the seat {seat}: {what}; nothing reached {}",
1765                        run.trunk
1766                    ),
1767                )
1768                .expected("a pre-merge-commit hook that judges the staged squash and changes nothing")
1769                .action(action)
1770                .target_state(
1771                    "unchanged; the trunk stands where it stood, and the seat stays as the hook left it",
1772                ),
1773            ));
1774        }
1775    };
1776    if ran.status.success() {
1777        return Ok(());
1778    }
1779    out.child_passthrough(crate::events::ChildStream::Stderr, &ran.stderr);
1780    out.child_passthrough(crate::events::ChildStream::Stdout, &ran.stdout);
1781    if String::from_utf8_lossy(&ran.stderr).contains(NO_HOOK) {
1782        return Err(RkError::subprocess(
1783            Diagnostic::new(
1784                Reason::SubprocessSpawn,
1785                format!(
1786                    "the repository of {} installs no pre-merge-commit hook, so the gate has nothing to run",
1787                    run.seat
1788                ),
1789            )
1790            .expected("a pre-merge-commit hook installed in this clone, the gate that the project's hook manager runs")
1791            .action("install the hook with the project's hook manager, for example prek install --hook-type pre-merge-commit, then integrate again")
1792            .target_state("unchanged; the trunk stands where it stood"),
1793        ));
1794    }
1795    Err(refuse(
1796        Reason::StateDrift,
1797        format!(
1798            "the pre-merge-commit hook failed in {}, so nothing reached {}",
1799            run.seat, run.trunk
1800        ),
1801    ))
1802}
1803
1804/// The refusal for a seat that a gate left detached at the trunk: a run
1805/// that a signal killed while the hook ran, or a hook that changed the
1806/// seat. `None` where no such seat holds this branch's work.
1807fn left_detached(
1808    seats: &[crate::worktree::Worktree],
1809    branch: &str,
1810    target: &Utf8Path,
1811    trunk: &str,
1812) -> Option<RkError> {
1813    let trunk_commit = rev_parse(target, trunk).ok()?;
1814    let tree = rev_parse(target, &format!("refs/heads/{branch}^{{tree}}")).ok()?;
1815    let seat = seats.iter().find(|seat| {
1816        !seat.bare
1817            && seat.branch.is_none()
1818            && seat.head == trunk_commit
1819            && git(&seat.path, &["write-tree"])
1820                .ok()
1821                .filter(|answer| answer.status.success())
1822                .is_some_and(|answer| String::from_utf8_lossy(&answer.stdout).trim() == tree)
1823    })?;
1824    Some(RkError::refusal(
1825        Diagnostic::new(
1826            Reason::StateDrift,
1827            format!(
1828                "{} is detached at the trunk commit with {branch}'s tree staged, as an interrupted gate leaves it",
1829                seat.path
1830            ),
1831        )
1832        .expected(format!("{branch} checked out in its seat"))
1833        .action(format!(
1834            "git -C {} symbolic-ref HEAD refs/heads/{branch} puts the seat back on the branch; then integrate again",
1835            seat.path
1836        ))
1837        .target_state("unchanged; the trunk stands where it stood"),
1838    ))
1839}
1840
1841/// Emit one report.
1842fn report(
1843    args: &IntegrateArgs,
1844    out: Output,
1845    run: &LocalRun<'_>,
1846    trunk_before: &str,
1847    trunk_commit: Option<String>,
1848    steps: Vec<String>,
1849    next: &[String],
1850) -> Result<(), RkError> {
1851    for step in &steps {
1852        out.result_line(step);
1853    }
1854    out.emit(&Report {
1855        schema: "rk.integrate/1",
1856        mode: if args.apply { "apply" } else { "preview" },
1857        target: run.target.to_string(),
1858        integration: Integration::Local.as_str(),
1859        authority_source: run.authority_source,
1860        merge_form: run.merge_form.as_str(),
1861        branch: args.branch.clone(),
1862        trunk: run.trunk.to_owned(),
1863        seat: run.seat.to_string(),
1864        trunk_before: trunk_before.to_owned(),
1865        trunk_commit,
1866        steps,
1867        next: next.to_vec(),
1868    })?;
1869    out.next(next);
1870    Ok(())
1871}
1872
1873/// The shape a trunk commit message states, named once.
1874const SHAPE: &str = "a scoped Conventional Commit: <type>(<scope>): <description>";
1875
1876/// The shape a trunk commit message states where the record names no
1877/// release, and a scope is preferred rather than required.
1878const SHAPE_SCOPE_PREFERRED: &str =
1879    "a Conventional Commit: <type>(<scope>): <description>, or <type>: <description>";
1880
1881/// The Conventional Commit types the branch grammar admits, which is the
1882/// same set the landed `rk-branch-name` hook tests.
1883const TYPES: [&str; 11] = [
1884    "build", "chore", "ci", "docs", "feat", "fix", "perf", "refactor", "revert", "style", "test",
1885];
1886
1887/// Refuse a trunk commit message the landed guards would refuse.
1888///
1889/// `at` is the seat, never the trunk checkout: whether a path is ignored
1890/// is answered by the ignore rules standing where the implementation was
1891/// written, and a branch that adds one is exactly the case the landed
1892/// `commit-msg` stage would have judged there.
1893///
1894/// `git commit-tree` fires no hook, so the whole `commit-msg` stage is
1895/// applied here instead, and it is applied through the one owner rather
1896/// than a second, weaker copy: the Conventional Commit shape the
1897/// `conventional-pre-commit` hook holds, and then every finding
1898/// `rk message --check` reports — agent attribution, a reference to a
1899/// path the target ignores, and a scope outside the title check's shape.
1900/// A message that reaches the trunk here reaches a permanent history and
1901/// a forge-facing changelog, so the two paths judge one set.
1902///
1903/// # Errors
1904///
1905/// Returns [`RkError::Refusal`] naming what a landed guard would have
1906/// refused, with the target untouched.
1907fn refuse_message(target: &Utf8Path, text: &str, scope_required: bool) -> Result<(), RkError> {
1908    let subject = text.lines().next().unwrap_or("").trim();
1909    if subject.is_empty() {
1910        return Err(refuse(
1911            Reason::Usage,
1912            "a local integration writes the trunk's commit message, so --message is required",
1913        ));
1914    }
1915    if let Some(reason) = misshapen_subject(subject, scope_required) {
1916        return Err(refuse(Reason::Usage, reason));
1917    }
1918    let (findings, _) = crate::commands::message::judge(
1919        text,
1920        crate::cli::message::MessageKind::Commit,
1921        target,
1922        subject,
1923        crate::commands::message::Judgment {
1924            exempt: crate::commands::message::exempt_title(subject),
1925            scope_required,
1926        },
1927    );
1928    if findings.is_empty() {
1929        return Ok(());
1930    }
1931    let named: Vec<String> = findings
1932        .iter()
1933        .map(|finding| format!("{}:{} {}", finding.class, finding.line, finding.detail))
1934        .collect();
1935    Err(refuse(
1936        Reason::Usage,
1937        format!(
1938            "the trunk message carries {} finding{} the landed commit-msg stage would refuse, and git commit-tree fires no hook: {}",
1939            findings.len(),
1940            if findings.len() == 1 { "" } else { "s" },
1941            named.join("; ")
1942        ),
1943    ))
1944}
1945
1946/// Why a subject is not the Conventional Commit the record asks for, or
1947/// `None`: a scoped one wherever `scope_required`, and one whose scope may
1948/// be absent where the record names no release.
1949#[must_use]
1950fn misshapen_subject(subject: &str, scope_required: bool) -> Option<String> {
1951    let shape = if scope_required {
1952        SHAPE
1953    } else {
1954        SHAPE_SCOPE_PREFERRED
1955    };
1956    let Some((head, description)) = subject.split_once(": ") else {
1957        return Some(format!("'{subject}' is not {shape}"));
1958    };
1959    if description.trim().is_empty() {
1960        return Some(format!(
1961            "'{subject}' is not {shape}: it states no description"
1962        ));
1963    }
1964    // A breaking `!` sits after the scope, so it comes off the head
1965    // before the scope is read out of it.
1966    let head = head.strip_suffix('!').unwrap_or(head);
1967    let (kind, scope) = match head.split_once('(') {
1968        None if scope_required => {
1969            return Some(format!("'{subject}' is not {shape}: it names no scope"));
1970        }
1971        None => (head, None),
1972        Some((kind, scope)) => {
1973            let Some(scope) = scope.strip_suffix(')') else {
1974                return Some(format!("'{subject}' is not {shape}: its scope is unclosed"));
1975            };
1976            (kind, Some(scope))
1977        }
1978    };
1979    if !TYPES.contains(&kind) {
1980        return Some(format!(
1981            "'{kind}' is not a Conventional Commit type; the types are: {}",
1982            TYPES.join(", ")
1983        ));
1984    }
1985    if let Some(scope) = scope
1986        && !crate::projection::scope_is_shaped(scope)
1987    {
1988        return Some(format!(
1989            "the scope '{scope}' is outside {}: lowercase letters, digits, and _ . / -",
1990            crate::projection::SCOPE_SHAPE
1991        ));
1992    }
1993    None
1994}
1995
1996/// Every worktree this clone registers.
1997fn seats(target: &Utf8Path) -> Result<Vec<crate::worktree::Worktree>, RkError> {
1998    let listed = git(target, &["worktree", "list", "--porcelain", "-z"])?;
1999    if !listed.status.success() {
2000        return Err(RkError::missing(
2001            Diagnostic::new(
2002                Reason::TargetNotFound,
2003                format!("target {target} is not a git repository"),
2004            )
2005            .expected("a repository whose worktrees git can list"),
2006        ));
2007    }
2008    crate::worktree::parse_worktrees(&listed.stdout)
2009        .map_err(|detail| refuse(Reason::PrerequisiteUnmet, detail))
2010}
2011
2012/// The worktree seating one branch.
2013fn seat_for(
2014    seats: &[crate::worktree::Worktree],
2015    branch: &str,
2016    target: &Utf8Path,
2017) -> Result<Utf8PathBuf, RkError> {
2018    seats
2019        .iter()
2020        .find(|seat| seat.branch.as_deref() == Some(branch))
2021        .map(|seat| seat.path.clone())
2022        .ok_or_else(|| {
2023            refuse(
2024                Reason::StateDrift,
2025                format!(
2026                    "no worktree of {target} has {branch} checked out; rk worktree add {branch} --apply seats it"
2027                ),
2028            )
2029        })
2030}
2031
2032/// Whether a working tree carries uncommitted changes, untracked included.
2033fn is_dirty(seat: &Utf8Path) -> Result<bool, RkError> {
2034    let status = git(seat, &["status", "--porcelain"])?;
2035    Ok(!status.stdout.is_empty())
2036}
2037
2038/// One revision's full object name.
2039fn rev_parse(seat: &Utf8Path, revision: &str) -> Result<String, RkError> {
2040    let answer = git(seat, &["rev-parse", "--verify", "--quiet", revision])?;
2041    if !answer.status.success() {
2042        return Err(refuse(
2043            Reason::StateDrift,
2044            format!("{revision} does not resolve in {seat}"),
2045        ));
2046    }
2047    Ok(String::from_utf8_lossy(&answer.stdout).trim().to_owned())
2048}
2049
2050/// Whether `ancestor` is reachable from `descendant`.
2051fn is_ancestor(seat: &Utf8Path, ancestor: &str, descendant: &str) -> bool {
2052    git(seat, &["merge-base", "--is-ancestor", ancestor, descendant])
2053        .is_ok_and(|answer| answer.status.success())
2054}
2055
2056/// The clone's common git directory, which every linked seat shares.
2057fn common_git_dir(target: &Utf8Path) -> Result<Utf8PathBuf, RkError> {
2058    let answer = git(
2059        target,
2060        &["rev-parse", "--path-format=absolute", "--git-common-dir"],
2061    )?;
2062    if !answer.status.success() {
2063        return Err(RkError::missing(
2064            Diagnostic::new(
2065                Reason::TargetNotFound,
2066                format!("target {target} is not a git repository"),
2067            )
2068            .expected("a repository whose common git directory git can name"),
2069        ));
2070    }
2071    let path = String::from_utf8_lossy(&answer.stdout).trim().to_owned();
2072    Utf8PathBuf::from_path_buf(std::path::PathBuf::from(path)).map_err(|path| {
2073        refuse(
2074            Reason::PrerequisiteUnmet,
2075            format!("the common git directory {} is not UTF-8", path.display()),
2076        )
2077    })
2078}
2079
2080/// Read the ledger, or an empty one where none exists.
2081fn read_ledger(path: &Utf8Path) -> Result<Ledger, RkError> {
2082    match std::fs::read_to_string(path) {
2083        Ok(text) => {
2084            Ledger::parse(&text).map_err(|detail| refuse(Reason::UnsupportedSchema, detail))
2085        }
2086        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Ledger::default()),
2087        Err(error) => Err(RkError::Io(error)),
2088    }
2089}
2090
2091/// Write the ledger, atomically.
2092fn write_ledger(path: &Utf8Path, ledger: &Ledger) -> Result<(), RkError> {
2093    let text = ledger
2094        .render()
2095        .map_err(|detail| refuse(Reason::Internal, detail))?;
2096    if let Some(parent) = path.parent() {
2097        std::fs::create_dir_all(parent)?;
2098    }
2099    crate::atomic::write(path.as_std_path(), text.as_bytes())?;
2100    Ok(())
2101}
2102
2103/// One refusal that states the target was left alone.
2104fn refuse(reason: Reason, message: impl Into<String>) -> RkError {
2105    RkError::refusal(
2106        Diagnostic::new(reason, message).target_state("unchanged; the trunk stands where it stood"),
2107    )
2108}
2109
2110/// Run one git command against a directory under the C locale, so its
2111/// human report reads in English; a spawn failure refuses.
2112fn git_in_c_locale(at: &Utf8Path, args: &[&str]) -> Result<std::process::Output, RkError> {
2113    let mut command = std::process::Command::new(crate::probes::git_bin());
2114    for var in GIT_HOOK_VARS {
2115        command.env_remove(var);
2116    }
2117    command
2118        .env("LC_ALL", "C")
2119        .arg("-C")
2120        .arg(at.as_std_path())
2121        .args(args)
2122        .output()
2123        .map_err(|source| {
2124            RkError::subprocess(
2125                Diagnostic::new(
2126                    Reason::SubprocessSpawn,
2127                    format!("git did not run in {at}: {source}"),
2128                )
2129                .target_state("unchanged"),
2130            )
2131        })
2132}
2133
2134/// Run one git command against a directory; a spawn failure refuses.
2135fn git(at: &Utf8Path, args: &[&str]) -> Result<std::process::Output, RkError> {
2136    let mut command = std::process::Command::new(crate::probes::git_bin());
2137    for var in GIT_HOOK_VARS {
2138        command.env_remove(var);
2139    }
2140    command
2141        .arg("-C")
2142        .arg(at.as_std_path())
2143        .args(args)
2144        .output()
2145        .map_err(|source| {
2146            RkError::subprocess(
2147                Diagnostic::new(
2148                    Reason::SubprocessSpawn,
2149                    format!("git did not run in {at}: {source}"),
2150                )
2151                .target_state("unchanged"),
2152            )
2153        })
2154}
2155
2156#[cfg(test)]
2157mod tests {
2158    use camino::Utf8Path;
2159
2160    use super::{
2161        BranchCommit, misshapen_subject, refuse_commit_messages, refuse_message, request_commands,
2162    };
2163    use crate::landing::MergeForm;
2164
2165    /// SATISFIES git:the-merge-form-is-a-landing-parameter
2166    #[test]
2167    fn merge_form_rebase_asks_gitlab_for_no_squash() {
2168        let gitlab = "git@gitlab.com:acme/widget.git";
2169        let squash = request_commands(gitlab, "master", "feat/x", MergeForm::Squash, true);
2170        assert_eq!(
2171            squash[0],
2172            "glab mr create --source-branch feat/x --target-branch master --squash-before-merge"
2173        );
2174        assert!(squash[1].contains("the title is the trunk's commit message"));
2175        let rebase = request_commands(gitlab, "master", "feat/x", MergeForm::Rebase, true);
2176        assert_eq!(
2177            rebase[0],
2178            "glab mr create --source-branch feat/x --target-branch master"
2179        );
2180        assert!(
2181            !rebase.iter().any(|line| line.contains("squash")),
2182            "{rebase:?}"
2183        );
2184        assert!(
2185            rebase[1].contains("every commit of the branch reaches the trunk with its own message"),
2186            "{rebase:?}"
2187        );
2188        assert!(!rebase[1].contains("title"), "{rebase:?}");
2189    }
2190
2191    #[test]
2192    fn merge_form_keeps_the_github_request_command() {
2193        let github = "git@github.com:acme/widget.git";
2194        for form in [MergeForm::Squash, MergeForm::Rebase] {
2195            assert_eq!(
2196                request_commands(github, "master", "feat/x", form, true)[0],
2197                "gh pr create --base master --head feat/x"
2198            );
2199        }
2200    }
2201
2202    #[test]
2203    fn a_trunk_subject_is_held_to_the_landed_convention() {
2204        assert_eq!(
2205            misshapen_subject("feat(integrate): land the verb", true),
2206            None
2207        );
2208        assert_eq!(misshapen_subject("feat(a/b)!: break it", true), None);
2209        assert!(
2210            misshapen_subject("land the verb", true)
2211                .expect("an unscoped subject refuses")
2212                .contains("Conventional Commit")
2213        );
2214        assert!(
2215            misshapen_subject("feat: land the verb", true)
2216                .expect("a missing scope refuses")
2217                .contains("names no scope")
2218        );
2219        assert!(
2220            misshapen_subject("feat(integrate):   ", true)
2221                .expect("an empty description refuses")
2222                .contains("no description")
2223        );
2224        assert!(
2225            misshapen_subject("wat(integrate): land it", true)
2226                .expect("an unknown type refuses")
2227                .contains("not a Conventional Commit type")
2228        );
2229        assert!(
2230            misshapen_subject("feat(Integrate): land it", true)
2231                .expect("a misshapen scope refuses")
2232                .contains("outside")
2233        );
2234    }
2235
2236    /// The whole landed commit-msg stage runs here, not the subject
2237    /// alone: `git commit-tree` fires no hook, so a body the landed
2238    /// guard refuses must refuse here or it reaches a permanent history.
2239    #[test]
2240    fn a_trunk_body_is_judged_by_the_one_message_owner() {
2241        let dir = tempfile::tempdir().expect("a scratch dir exists");
2242        let target = Utf8Path::from_path(dir.path()).expect("utf-8");
2243        refuse_message(
2244            target,
2245            "feat(integrate): land the verb\n\nThe context.\n",
2246            true,
2247        )
2248        .expect("a clean message passes");
2249        let error = refuse_message(
2250            target,
2251            "feat(integrate): land the verb\n\nCo-Authored-By: Claude <noreply@anthropic.com>\n",
2252            true,
2253        )
2254        .expect_err("agent attribution refuses")
2255        .to_string();
2256        assert!(error.contains("attribution"), "{error}");
2257        assert!(error.contains("commit-tree fires no hook"), "{error}");
2258        let error = refuse_message(
2259            target,
2260            "feat(integrate): land the verb\n\nSee .draft/plan.md for the rest.\n",
2261            true,
2262        )
2263        .expect_err("an internal path refuses")
2264        .to_string();
2265        assert!(error.contains("internal-path"), "{error}");
2266        let error = refuse_message(target, "", true)
2267            .expect_err("an empty message refuses")
2268            .to_string();
2269        assert!(error.contains("--message is required"), "{error}");
2270    }
2271
2272    /// Under `rebase` every commit of the branch becomes a trunk commit,
2273    /// so each message takes the whole landed commit-msg judgment and the
2274    /// refusal names the commit that failed it.
2275    #[test]
2276    fn rebase_integrate_judges_every_commit_message() {
2277        let dir = tempfile::tempdir().expect("a scratch dir exists");
2278        let target = Utf8Path::from_path(dir.path()).expect("utf-8");
2279        let commit = |id: &str, message: &str| BranchCommit {
2280            id: id.to_owned(),
2281            message: message.to_owned(),
2282        };
2283        refuse_commit_messages(
2284            target,
2285            &[
2286                commit("1111111aaaa", "feat(greeting): add it\n"),
2287                commit("2222222bbbb", "fix(greeting): mend it\n\nThe context.\n"),
2288            ],
2289            true,
2290        )
2291        .expect("clean messages pass");
2292        let error = refuse_commit_messages(
2293            target,
2294            &[
2295                commit("1111111aaaa", "feat(greeting): add it\n"),
2296                commit(
2297                    "2222222bbbb",
2298                    "fix(greeting): mend it\n\nCo-Authored-By: Claude <noreply@anthropic.com>\n",
2299                ),
2300            ],
2301            true,
2302        )
2303        .expect_err("agent attribution refuses")
2304        .to_string();
2305        assert!(error.contains("commit 2222222"), "{error}");
2306        assert!(error.contains("attribution"), "{error}");
2307        let error = refuse_commit_messages(target, &[commit("3333333cccc", "mend it\n")], true)
2308            .expect_err("an unscoped subject refuses")
2309            .to_string();
2310        assert!(error.contains("commit 3333333"), "{error}");
2311        assert!(error.contains("Conventional Commit"), "{error}");
2312        let error = refuse_commit_messages(target, &[commit("4444444dddd", "\n")], true)
2313            .expect_err("an empty message refuses")
2314            .to_string();
2315        assert!(error.contains("carries no message"), "{error}");
2316    }
2317
2318    /// Where the record names no release, a scope is preferred and not
2319    /// required: a header with none passes, while every other part of the
2320    /// shape, the type and a present scope's shape included, still holds.
2321    ///
2322    /// SATISFIES project-profile:a-release-less-landing-carries-no-release-text
2323    #[test]
2324    fn workflow_only_a_trunk_subject_may_name_no_scope() {
2325        assert_eq!(misshapen_subject("fix: drop the stale path", false), None);
2326        assert_eq!(misshapen_subject("feat!: break it", false), None);
2327        assert_eq!(misshapen_subject("feat(a/b): add it", false), None);
2328        assert!(
2329            misshapen_subject("fix: drop the stale path", true)
2330                .expect("a release requires the scope")
2331                .contains("names no scope")
2332        );
2333        assert!(
2334            misshapen_subject("wat: drop it", false)
2335                .expect("an unknown type refuses")
2336                .contains("not a Conventional Commit type")
2337        );
2338        assert!(
2339            misshapen_subject("drop the stale path", false)
2340                .expect("a subject with no type refuses")
2341                .contains("<type>: <description>")
2342        );
2343        assert!(
2344            misshapen_subject("fix(Bad): mend it", false)
2345                .expect("a misshapen scope refuses")
2346                .contains("outside")
2347        );
2348        let dir = tempfile::tempdir().expect("a scratch dir exists");
2349        let target = Utf8Path::from_path(dir.path()).expect("utf-8");
2350        refuse_message(target, "fix: drop the stale path\n", false)
2351            .expect("a release-less trunk message names no scope");
2352        refuse_commit_messages(
2353            target,
2354            &[BranchCommit {
2355                id: "5555555eeee".to_owned(),
2356                message: "fix: drop the stale path\n".to_owned(),
2357            }],
2358            false,
2359        )
2360        .expect("a release-less branch commit names no scope");
2361    }
2362
2363    /// Under `release.mode = "none"` the forge request guidance asks for a
2364    /// Conventional Commit whose scope is preferred, never a scoped one, in
2365    /// either merge form.
2366    ///
2367    /// SATISFIES project-profile:a-release-less-landing-carries-no-release-text
2368    #[test]
2369    fn workflow_only_request_guidance_prefers_the_scope() {
2370        for remote in [
2371            "git@gitlab.com:acme/widget.git",
2372            "git@github.com:acme/widget.git",
2373        ] {
2374            for form in [MergeForm::Squash, MergeForm::Rebase] {
2375                let lines = request_commands(remote, "master", "feat/x", form, false);
2376                assert!(!lines[1].contains("scoped"), "{lines:?}");
2377                assert!(
2378                    lines[1].contains("scope is preferred and not required"),
2379                    "{lines:?}"
2380                );
2381                let releasing = request_commands(remote, "master", "feat/x", form, true);
2382                assert!(
2383                    releasing[1].contains("scoped Conventional Commit"),
2384                    "{releasing:?}"
2385                );
2386                assert_eq!(lines[0], releasing[0], "the command itself does not change");
2387            }
2388        }
2389    }
2390
2391    /// The publication a writer outside rk raced reads as a publication:
2392    /// a check failure with the reason `state-drift`, naming the published
2393    /// object, the observed tip, and the move the reflog shows, telling the
2394    /// operator what to read, and never claiming the trunk stands where it
2395    /// stood.
2396    ///
2397    /// SATISFIES git:a-local-integration-is-a-transaction
2398    #[test]
2399    fn integrate_reports_a_raced_publication_as_published() {
2400        let drift = super::Drift {
2401            expected: "a".repeat(40),
2402            found_old: "b".repeat(40),
2403            found_new: "c".repeat(40),
2404        };
2405        assert!(drift.step("master").contains("bbbbbbb to ccccccc"));
2406        let error = drift.into_error("master", &"c".repeat(40));
2407        assert_eq!(error.exit_code(), 1);
2408        let diagnostic = error.diagnostic();
2409        assert_eq!(diagnostic.reason, crate::diagnostic::Reason::StateDrift);
2410        for named in [
2411            "published ccccccc",
2412            "bbbbbbb",
2413            "observed aaaaaaa",
2414            "outside rk",
2415        ] {
2416            assert!(
2417                diagnostic.message.contains(named),
2418                "{named}: {}",
2419                diagnostic.message
2420            );
2421        }
2422        assert!(
2423            !diagnostic.message.contains("nothing"),
2424            "{}",
2425            diagnostic.message
2426        );
2427        let state = diagnostic.target_state.unwrap_or_default();
2428        assert!(state.contains("published at ccccccc"), "{state}");
2429        assert!(state.contains("no rollback"), "{state}");
2430        assert!(!state.contains("where it stood"), "{state}");
2431        let action = diagnostic.action.unwrap_or_default();
2432        assert!(action.contains("git log aaaaaaa..bbbbbbb"), "{action}");
2433    }
2434
2435    /// The holder observed before the gate must be the holder at the
2436    /// publication: a trunk checked out since, or no longer, refuses.
2437    ///
2438    /// SATISFIES git:a-local-integration-is-a-transaction
2439    #[test]
2440    fn integrate_refuses_a_changed_trunk_holder() {
2441        let main = Utf8Path::new("/repo");
2442        let other = Utf8Path::new("/repo@trunk");
2443        assert_eq!(
2444            super::holder_change("master", None, None, "integration"),
2445            None
2446        );
2447        assert_eq!(
2448            super::holder_change("master", Some(main), Some(main), "integration"),
2449            None
2450        );
2451        for (observed, live) in [
2452            (None, Some(other)),
2453            (Some(main), None),
2454            (Some(main), Some(other)),
2455        ] {
2456            let reason = super::holder_change("master", observed, live, "integration")
2457                .expect("a changed holder refuses");
2458            assert!(reason.contains("checked out"), "{reason}");
2459            assert!(reason.contains("nothing was published"), "{reason}");
2460        }
2461    }
2462
2463    /// A publication no source confirmed reads as a publication: a check
2464    /// failure with the reason `state-drift`, naming the published object
2465    /// and the observed tip, telling the operator what to read, and never
2466    /// claiming the trunk stands where it stood. The pre-gate refresh of a
2467    /// held trunk, completed and unconfirmed or raced, says the trunk was
2468    /// refreshed and that no integration was published.
2469    ///
2470    /// SATISFIES git:a-local-integration-is-a-transaction
2471    #[test]
2472    fn integrate_reports_an_unconfirmed_move_as_published() {
2473        let expected = "a".repeat(40);
2474        let published = "c".repeat(40);
2475        let unsettled = super::Unsettled::Unconfirmed {
2476            expected: expected.clone(),
2477            reason: "the reflog holds one entry".to_owned(),
2478        };
2479        assert!(unsettled.step("master").contains("is not confirmed"));
2480        let error = unsettled.clone().into_error("master", &published);
2481        assert_eq!(error.exit_code(), 1);
2482        let diagnostic = error.diagnostic();
2483        assert_eq!(diagnostic.reason, crate::diagnostic::Reason::StateDrift);
2484        assert_eq!(
2485            diagnostic.message,
2486            "master now stands at the published ccccccc, but rk could not confirm that the move started at the observed aaaaaaa: the reflog holds one entry"
2487        );
2488        assert_eq!(
2489            diagnostic.expected.as_deref(),
2490            Some("a confirmed move of master from aaaaaaa to ccccccc")
2491        );
2492        assert_eq!(
2493            diagnostic.action.as_deref(),
2494            Some(
2495                "read git reflog master and git log aaaaaaa..ccccccc, and decide whether anything else moved master; rk moves nothing back"
2496            )
2497        );
2498        assert_eq!(
2499            diagnostic.target_state.as_deref(),
2500            Some(
2501                "master is published at ccccccc, with no rollback and no reset; the staged evidence names ccccccc and the trunk reaches it"
2502            )
2503        );
2504
2505        let raced = super::Unsettled::Raced(super::Drift {
2506            expected: expected.clone(),
2507            found_old: "b".repeat(40),
2508            found_new: published.clone(),
2509        });
2510        for refresh in [unsettled, raced] {
2511            let diagnostic = refresh
2512                .into_refresh_error("master", &expected, &published)
2513                .diagnostic();
2514            assert!(
2515                diagnostic
2516                    .message
2517                    .contains("was fast-forwarded to its remote tip ccccccc")
2518            );
2519            assert!(diagnostic.message.contains("no integration was published"));
2520            let state = diagnostic.target_state.unwrap_or_default();
2521            assert!(
2522                state.contains("refreshed to its remote tip ccccccc"),
2523                "{state}"
2524            );
2525            for unchanged in ["unchanged", "where it stood", "now stands at the published"] {
2526                assert!(!diagnostic.message.contains(unchanged), "{unchanged}");
2527                assert!(!state.contains(unchanged), "{unchanged}");
2528            }
2529        }
2530    }
2531
2532    /// The fast-forward's own report confirms only through one well-formed
2533    /// `Updating <old>..<new>` line of full object names.
2534    ///
2535    /// SATISFIES git:a-local-integration-is-a-transaction
2536    #[test]
2537    fn integrate_parses_only_a_full_updating_line() {
2538        let old = "a".repeat(40);
2539        let new = "b".repeat(40);
2540        assert_eq!(
2541            super::parse_updating(&format!("Updating {old}..{new}\nFast-forward\n"), 40),
2542            Ok((old.clone(), new.clone()))
2543        );
2544        for report in [
2545            "Fast-forward\n".to_owned(),
2546            format!("Updating {}..{}\n", &old[..7], &new[..7]),
2547            format!("Updating {old}..{}\n", &new[..12]),
2548            format!("Updating {old} {new}\n"),
2549            format!("Updating {old}..{new}\nUpdating {new}..{old}\n"),
2550            format!("Updating {}..{new}\n", "g".repeat(40)),
2551            format!("Updating {old}..{new}\n").replace("Updating", "Mise à jour"),
2552        ] {
2553            assert!(super::parse_updating(&report, 40).is_err(), "{report}");
2554        }
2555    }
2556
2557    /// The read-backs confirm only an exact full-name match; a start
2558    /// elsewhere is the race; an end elsewhere, two sources that disagree,
2559    /// and no source at all are unconfirmed.
2560    ///
2561    /// SATISFIES git:a-local-integration-is-a-transaction
2562    #[test]
2563    fn integrate_judges_the_read_backs_of_a_held_move() {
2564        use super::{PostPublication, Unsettled, judge_move};
2565        let expected = "a".repeat(40);
2566        let other = "b".repeat(40);
2567        let to = "c".repeat(40);
2568        let pair = |old: &str, new: &str| Ok((old.to_owned(), new.to_owned()));
2569        let none = || Err::<(String, String), String>("unavailable".to_owned());
2570        assert_eq!(
2571            judge_move(&expected, &to, pair(&expected, &to), none()),
2572            PostPublication::Confirmed
2573        );
2574        assert_eq!(
2575            judge_move(&expected, &to, none(), pair(&expected, &to)),
2576            PostPublication::Confirmed
2577        );
2578        assert_eq!(
2579            judge_move(&expected, &to, pair(&expected, &to), pair(&expected, &to)),
2580            PostPublication::Confirmed
2581        );
2582        assert!(matches!(
2583            judge_move(&expected, &to, pair(&other, &to), none()),
2584            PostPublication::Unsettled(Unsettled::Raced(_))
2585        ));
2586        for judged in [
2587            judge_move(&expected, &to, pair(&expected, &to), pair(&other, &to)),
2588            judge_move(&expected, &to, none(), pair(&expected, &other)),
2589            judge_move(&expected, &to, none(), none()),
2590        ] {
2591            assert!(
2592                matches!(
2593                    judged,
2594                    PostPublication::Unsettled(Unsettled::Unconfirmed { .. })
2595                ),
2596                "{judged:?}"
2597            );
2598        }
2599    }
2600}