Skip to main content

verbs/
workflow.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Ready / land workflow domain: pure preflight, policy, and step accounting.
3//!
4//! Owns decision logic shared by `heddle ready`, `heddle land`, and `heddle sync`:
5//! - verification fail-closed preflight for readiness
6//! - land push option planning
7//! - auto-land confidence / verification policy blockers
8//! - non-staleness / heavy-impact classification
9//! - land performed / skipped step accounting
10//! - integrated-land next-action selection
11//! - ready classification and report next-action filtering
12//!
13//! Network, mutation, capture, and render remain CLI-owned.
14
15use std::path::{Path, PathBuf};
16
17use objects::object::StateId;
18use oplog::OpRecord;
19use repo::{GitImportGuidance, GitRemoteTrackingStatus, RepositoryOperationStatus, shell_quote};
20
21use crate::{
22    RepositoryVerificationState, ThreadPreviewReport,
23    status::next_action::{NextActionInput, effective_next_action, non_empty_action},
24};
25
26/// Minimum agent confidence allowed for automatic land without re-capture.
27pub const AUTO_LAND_CONFIDENCE_THRESHOLD: f32 = 0.75;
28
29/// Recovery breadcrumb when auto-land policy blocks on confidence / tests.
30pub const AUTO_LAND_CONFIDENCE_RECOVERY_ACTION: &str =
31    "heddle capture -m \"...\" --confidence <confidence>";
32
33// ---------------------------------------------------------------------------
34// Ready verification preflight
35// ---------------------------------------------------------------------------
36
37/// Statuses that must fail closed before readiness / land preflight can run.
38pub fn ready_verification_preflight_blocks(trust: &RepositoryVerificationState) -> bool {
39    ready_verification_status_blocks(trust.status.as_str())
40}
41
42/// Pure status-string check used by [`ready_verification_preflight_blocks`].
43pub fn ready_verification_status_blocks(status: &str) -> bool {
44    matches!(
45        status,
46        "needs_init" | "needs_import" | "needs_reconcile" | "git_branch_advanced"
47    )
48}
49
50// ---------------------------------------------------------------------------
51// Ready classification
52// ---------------------------------------------------------------------------
53
54/// Whether a thread preview has an integration target configured.
55pub fn has_integration_target(merge_relation: &str) -> bool {
56    merge_relation != "no_target"
57}
58
59/// Conflict-free and policy-clear: safe to mark ready / land.
60pub fn is_integration_clear(conflict_count: usize, blockers: &[String]) -> bool {
61    conflict_count == 0 && blockers.is_empty()
62}
63
64/// Inputs for classifying a ready-command outcome without performing I/O.
65#[derive(Debug, Clone, Copy)]
66pub struct ReadyDecisionInput<'a> {
67    pub merge_relation: &'a str,
68    pub captured: bool,
69    /// Whether the thread is already in [`repo::ThreadState::Ready`].
70    pub thread_already_ready: bool,
71    pub conflict_count: usize,
72    pub blockers: &'a [String],
73}
74
75/// Pure classification of readiness after preview / policy blockers are known.
76#[derive(Debug, Clone, Copy, PartialEq, Eq)]
77pub struct ReadyDecision {
78    pub has_integration_target: bool,
79    /// Thread was already ready and no capture ran this invocation.
80    pub already_ready: bool,
81    /// Clean thread with no integration target configured.
82    pub ready_without_target: bool,
83    /// Conflict-free and no blockers (would mark Ready when a target exists).
84    pub integration_clear: bool,
85    /// Operator envelope should report `completed` (ready or no-target clean).
86    pub operator_completed: bool,
87}
88
89/// Classify ready outcome from preview facts (no I/O).
90pub fn classify_ready_decision(input: ReadyDecisionInput<'_>) -> ReadyDecision {
91    let has_target = has_integration_target(input.merge_relation);
92    let clear = is_integration_clear(input.conflict_count, input.blockers);
93    let already_ready = has_target && !input.captured && input.thread_already_ready && clear;
94    let ready_without_target = !has_target && clear;
95    ReadyDecision {
96        has_integration_target: has_target,
97        already_ready,
98        ready_without_target,
99        integration_clear: clear,
100        // Matches CLI: completed when no target is configured, or when the
101        // thread is (or would be) Ready after this invocation.
102        operator_completed: !has_target || clear,
103    }
104}
105
106/// Drop self-merge / land recommendations when the thread has no target.
107pub fn ready_report_recommended_action(
108    merge_relation: &str,
109    recommended_action: &str,
110) -> Option<String> {
111    if merge_relation == "no_target" {
112        return None;
113    }
114    non_empty_action(Some(recommended_action)).map(str::to_string)
115}
116
117/// Ready-scoped next-action selection (operation → thread fallback → publish).
118pub fn ready_scoped_next_action(
119    operation: Option<&RepositoryOperationStatus>,
120    remote_tracking: Option<&GitRemoteTrackingStatus>,
121    import_hint: Option<&GitImportGuidance>,
122    thread_action: Option<&str>,
123) -> String {
124    effective_next_action(
125        NextActionInput::default(operation, remote_tracking, import_hint, thread_action).ready(),
126    )
127}
128
129/// Whether land should squash the thread into one Git commit on write-through.
130pub fn should_squash_land(no_squash: bool, config_squash: bool) -> bool {
131    !no_squash && config_squash
132}
133
134// ---------------------------------------------------------------------------
135// Auto-land policy
136// ---------------------------------------------------------------------------
137
138/// Facts needed for auto-land policy without opening the object store.
139#[derive(Debug, Clone, Copy)]
140pub struct AutoLandPolicyInput {
141    pub agent_authored: bool,
142    pub confidence: Option<f32>,
143    pub tests_passed: Option<bool>,
144}
145
146/// Policy blockers that prevent automatic land (confidence / verification).
147pub fn auto_land_policy_blockers(input: AutoLandPolicyInput) -> Vec<String> {
148    let mut blockers = Vec::new();
149    if input.agent_authored
150        && let Some(confidence) = input.confidence
151        && confidence < AUTO_LAND_CONFIDENCE_THRESHOLD
152    {
153        blockers.push(format!(
154            "confidence {:.2} is below the auto-land threshold of {AUTO_LAND_CONFIDENCE_THRESHOLD:.2}",
155            confidence
156        ));
157    }
158    if matches!(input.tests_passed, Some(false)) {
159        blockers.push("verification summary reports failing tests".to_string());
160    }
161    blockers
162}
163
164/// Combine preview blockers with auto-land policy, honoring manual resolution.
165pub fn integration_blockers(
166    manual_resolution_current: bool,
167    preview_blockers: &[String],
168    policy: AutoLandPolicyInput,
169) -> Vec<String> {
170    let mut blockers = if manual_resolution_current {
171        Vec::new()
172    } else {
173        non_staleness_blockers(preview_blockers)
174    };
175    blockers.extend(auto_land_policy_blockers(policy));
176    blockers
177}
178
179/// Recovery breadcrumb for confidence / verification policy blockers.
180pub fn integration_blocker_recommended_action(
181    blockers: &[String],
182    scope_to_checkout: Option<&Path>,
183) -> Option<String> {
184    blockers
185        .iter()
186        .any(|blocker| {
187            blocker.starts_with("confidence ")
188                || blocker == "verification summary reports failing tests"
189        })
190        .then(|| auto_land_confidence_recovery_action(scope_to_checkout))
191}
192
193/// Scope the confidence recovery capture to the thread's checkout when needed.
194pub fn auto_land_confidence_recovery_action(scope_to_checkout: Option<&Path>) -> String {
195    match scope_to_checkout {
196        Some(path) => format!(
197            "heddle --repo {} {}",
198            shell_quote(&path.display().to_string()),
199            AUTO_LAND_CONFIDENCE_RECOVERY_ACTION
200                .strip_prefix("heddle ")
201                .expect("recovery action is a heddle command"),
202        ),
203        None => AUTO_LAND_CONFIDENCE_RECOVERY_ACTION.to_string(),
204    }
205}
206
207/// Returns the thread checkout when it is a real, distinct path from the
208/// current checkout (so recovery breadcrumbs must re-scope via `--repo`).
209pub fn recovery_scope_checkout(execution_path: &Path, current_checkout: &Path) -> Option<PathBuf> {
210    if execution_path.as_os_str().is_empty() {
211        return None;
212    }
213    let canonical = |path: &Path| path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
214    (canonical(execution_path) != canonical(current_checkout)).then(|| execution_path.to_path_buf())
215}
216
217// ---------------------------------------------------------------------------
218// Blocker classification / land preview surface
219// ---------------------------------------------------------------------------
220
221/// Heavy-impact lines are advisories for land, not hard blockers for sync.
222pub fn is_heavy_impact_advisory(blocker: &str) -> bool {
223    blocker.to_lowercase().contains("heavy-impact change")
224}
225
226/// Drop staleness and heavy-impact advisories from a blocker list.
227pub fn non_staleness_blockers(blockers: &[String]) -> Vec<String> {
228    blockers
229        .iter()
230        .filter(|blocker| {
231            !blocker.contains(" is stale against ") && !is_heavy_impact_advisory(blocker)
232        })
233        .cloned()
234        .collect()
235}
236
237/// Expand preview conflicts into land blockers, then sort/dedup.
238pub fn land_blockers_for_preview(
239    preview: &ThreadPreviewReport,
240    blockers: &[String],
241) -> Vec<String> {
242    let mut out = blockers.to_vec();
243    if preview.conflict_count > 0 {
244        out.push(format!(
245            "{} path conflict(s) need manual resolution",
246            preview.conflict_count
247        ));
248        out.extend(
249            preview
250                .conflicts
251                .iter()
252                .map(|path| format!("conflict: {path}")),
253        );
254    }
255    out.sort();
256    out.dedup();
257    out
258}
259
260/// Heavy-impact advisories for land (warnings, not hard blockers).
261pub fn land_warnings_for_preview(preview: &ThreadPreviewReport) -> Vec<String> {
262    let mut warnings = preview
263        .blockers
264        .iter()
265        .filter(|blocker| is_heavy_impact_advisory(blocker))
266        .cloned()
267        .collect::<Vec<_>>();
268    if warnings.is_empty() && !preview.heavy_impact_paths.is_empty() {
269        warnings.push(format!(
270            "Heavy-impact change: {} — review broader impact before merging",
271            preview.heavy_impact_paths.join(", ")
272        ));
273    }
274    warnings.sort();
275    warnings.dedup();
276    warnings
277}
278
279// ---------------------------------------------------------------------------
280// Land step accounting + post-integrate next action
281// ---------------------------------------------------------------------------
282
283/// Whether a land/preview blocker is the heavy-impact manual-review advisory.
284pub fn is_manual_review_blocker(blocker: &str) -> bool {
285    blocker.starts_with("Heavy-impact change:")
286}
287
288/// Human text for a land performed/skipped step token.
289pub fn land_text_step(step: &str) -> String {
290    match step {
291        "capture" => "saved".to_string(),
292        "sync" => "refreshed".to_string(),
293        "merge" => "merged".to_string(),
294        "checkpoint" => "committed".to_string(),
295        "capture(no changes)" => "no unsaved changes".to_string(),
296        "sync(current)" => "already refreshed".to_string(),
297        "merge(blocked)" => "merge blocked".to_string(),
298        "merge(already_integrated)" => "already landed".to_string(),
299        "checkpoint(not needed)" => "no Git commit needed".to_string(),
300        "checkpoint(not reached)" => "Git commit skipped because merge did not run".to_string(),
301        other => other.to_string(),
302    }
303}
304
305/// Scope a `heddle …` recommended action to an explicit `--repo` path.
306pub fn scope_action_to_repo(action: &str, repo_path: &str) -> String {
307    let Some(rest) = action.strip_prefix("heddle ") else {
308        return action.to_string();
309    };
310    if rest.starts_with("--repo ") || rest.starts_with("-R ") {
311        return action.to_string();
312    }
313    format!(
314        "heddle --repo {} {rest}",
315        quote_recommended_action_arg(repo_path)
316    )
317}
318
319/// Quote a recommended-action path/arg when it is not shell-safe bare.
320pub fn quote_recommended_action_arg(value: &str) -> String {
321    if !value.is_empty()
322        && value
323            .bytes()
324            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'/' | b'.' | b'_' | b'-' | b'+'))
325    {
326        value.to_string()
327    } else {
328        format!("\"{}\"", value.replace('\\', "\\\\").replace('"', "\\\""))
329    }
330}
331
332/// Ready summary labels from preview merge relation strings.
333pub fn ready_merge_type_label(result: &str) -> String {
334    match result {
335        "fast_forward" => "fast-forward".to_string(),
336        "already_integrated" => "already integrated".to_string(),
337        "no_target" => "none configured".to_string(),
338        other => other.replace('_', " "),
339    }
340}
341
342/// Ready status line for operator text (`clean` vs thread health).
343pub fn ready_status_summary(
344    merge_relation: &str,
345    blockers_empty: bool,
346    thread_health: &str,
347) -> String {
348    if merge_relation == "no_target" && blockers_empty {
349        "clean".to_string()
350    } else {
351        thread_health.replace('_', " ")
352    }
353}
354
355/// Integration column for ready summary.
356pub fn ready_integration_summary(merge_relation: &str) -> String {
357    match merge_relation {
358        "no_target" => "n/a (no integration target configured)".to_string(),
359        "not_checked" => "not checked (readiness checks did not run)".to_string(),
360        "blocked" => "not checked (repository verification is blocked)".to_string(),
361        _ => "configured".to_string(),
362    }
363}
364
365/// Freshness column for ready summary.
366pub fn ready_freshness_summary(merge_relation: &str, freshness: &str) -> String {
367    match merge_relation {
368        "no_target" => "n/a (no integration target configured)".to_string(),
369        "not_checked" => "not checked (readiness checks did not run)".to_string(),
370        "blocked" => "not checked (repository verification is blocked)".to_string(),
371        _ => freshness.replace('_', " "),
372    }
373}
374
375/// Merge-type column for ready summary.
376pub fn ready_merge_type_summary(merge_relation: &str) -> String {
377    match merge_relation {
378        "no_target" => "n/a (no integration target configured)".to_string(),
379        "not_checked" => "not checked (readiness checks did not run)".to_string(),
380        "blocked" => "not checked (repository verification is blocked)".to_string(),
381        other => ready_merge_type_label(other),
382    }
383}
384
385/// Steps that actually ran during land.
386pub fn land_performed_steps(
387    captured: bool,
388    synced: bool,
389    integrated: bool,
390    checkpointed: bool,
391) -> Vec<String> {
392    [
393        (captured, "capture"),
394        (synced, "sync"),
395        (integrated, "merge"),
396        (checkpointed, "checkpoint"),
397    ]
398    .into_iter()
399    .filter(|&(done, _step)| done)
400    .map(|(_done, step)| step.to_string())
401    .collect()
402}
403
404/// Steps skipped (with reason tokens) during land.
405pub fn land_skipped_steps(
406    captured: bool,
407    synced: bool,
408    integrated: bool,
409    checkpointed: bool,
410) -> Vec<String> {
411    [
412        (!captured, "capture(no changes)"),
413        (!synced, "sync(current)"),
414        (!integrated, "merge(blocked)"),
415        (!checkpointed && integrated, "checkpoint(not needed)"),
416        (!checkpointed && !integrated, "checkpoint(not reached)"),
417    ]
418    .into_iter()
419    .filter(|&(skipped, _step)| skipped)
420    .map(|(_skipped, step)| step.to_string())
421    .collect()
422}
423
424/// Next action after a successful sync (already current or refreshed).
425///
426/// Sync is its own job — refresh this thread onto its target — not land.
427/// Operation / remote / import still win. There is no `land --thread`
428/// fallback: a completed sync does not prescribe landing.
429pub fn sync_completed_next_action(
430    operation: Option<&RepositoryOperationStatus>,
431    remote_tracking: Option<&GitRemoteTrackingStatus>,
432    import_hint: Option<&GitImportGuidance>,
433) -> Option<String> {
434    non_empty_action(Some(&effective_next_action(NextActionInput::default(
435        operation,
436        remote_tracking,
437        import_hint,
438        None,
439    ))))
440    .map(str::to_string)
441}
442
443/// Whether sync has nothing left to refresh.
444///
445/// The no-op is freshness-current **or** the synthesized default
446/// checkout (a HEAD-attached ref with no ThreadManager record, often
447/// named `main`). A persisted managed thread with `target_thread: None`
448/// (created from detached HEAD) is **not** a no-op — it must reach
449/// `refresh_thread` and surface `missing_target_thread`.
450pub fn sync_is_already_current(freshness_is_current: bool, is_synthesized_checkout: bool) -> bool {
451    freshness_is_current || is_synthesized_checkout
452}
453
454/// Next action after a successful local land (push if trust says so, else cleanup).
455pub fn integrated_land_next_action(
456    integrated: bool,
457    trust_recommended_action: &str,
458) -> Option<String> {
459    if !integrated {
460        return None;
461    }
462    if trust_recommended_action == "heddle push" {
463        Some(trust_recommended_action.to_string())
464    } else {
465        Some("heddle thread cleanup --merged --dry-run".to_string())
466    }
467}
468
469/// Checkpoint / squash message for land write-through.
470///
471/// Precedence: explicit non-empty message → land subject when preferred →
472/// current intent → task → `Land <thread_id>`.
473pub fn land_checkpoint_message(
474    explicit: Option<&str>,
475    prefer_land_subject: bool,
476    thread_id: &str,
477    intent: Option<&str>,
478    task: Option<&str>,
479) -> String {
480    if let Some(message) = explicit.filter(|message| !message.trim().is_empty()) {
481        return message.to_string();
482    }
483    if prefer_land_subject {
484        return format!("Land {thread_id}");
485    }
486    if let Some(intent) = intent.filter(|intent| !intent.trim().is_empty()) {
487        return intent.to_string();
488    }
489    if let Some(task) = task.filter(|task| !task.trim().is_empty()) {
490        return task.to_string();
491    }
492    format!("Land {thread_id}")
493}
494
495/// Whether a change id matches a short or full display form from operator text.
496pub fn state_id_matches_display(short: &str, full: &str, display: &str) -> bool {
497    short == display || full == display
498}
499
500/// Whether an oplog record advances HEAD/thread to a land merge target.
501pub fn op_targets_merge_state(op: &OpRecord, merge_state: &str) -> bool {
502    match op {
503        OpRecord::Snapshot { new_state, .. } => {
504            state_id_matches_display(&new_state.short(), &new_state.to_string_full(), merge_state)
505        }
506        OpRecord::Checkpoint { state, .. } => {
507            state_id_matches_display(&state.short(), &state.to_string_full(), merge_state)
508        }
509        OpRecord::Goto { target, .. } => {
510            state_id_matches_display(&target.short(), &target.to_string_full(), merge_state)
511        }
512        OpRecord::FastForward { post_target_id, .. } => state_id_matches_display(
513            &post_target_id.short(),
514            &post_target_id.to_string_full(),
515            merge_state,
516        ),
517        // Enumerated explicitly (no wildcard) so a new state-advancing variant
518        // must be considered here (heddle#354 r9).
519        OpRecord::ThreadCreate { .. }
520        | OpRecord::ThreadDelete { .. }
521        | OpRecord::ThreadUpdate { .. }
522        | OpRecord::Fork { .. }
523        | OpRecord::Collapse { .. }
524        | OpRecord::MarkerCreate { .. }
525        | OpRecord::MarkerDelete { .. }
526        | OpRecord::TransactionAbort { .. }
527        | OpRecord::EphemeralThreadCollapse { .. }
528        | OpRecord::ConflictResolved { .. }
529        | OpRecord::TransactionCommit { .. }
530        | OpRecord::Redact { .. }
531        | OpRecord::Purge { .. }
532        | OpRecord::GitCheckpoint { .. }
533        | OpRecord::RemoteThreadUpdate { .. }
534        | OpRecord::RemoteThreadDelete { .. }
535        | OpRecord::UndoRecoveryUpdate { .. }
536        | OpRecord::StateVisibilitySet { .. }
537        | OpRecord::StateVisibilityPromote { .. }
538        | OpRecord::HeadUpdate { .. } => false,
539    }
540}
541
542/// Convenience: match a [`StateId`] against operator display text.
543pub fn state_id_matches_op_display(id: &StateId, display: &str) -> bool {
544    state_id_matches_display(&id.short(), &id.to_string_full(), display)
545}
546
547#[cfg(test)]
548mod tests {
549    use repo::{OperationKind, OperationScope};
550
551    use super::*;
552    use crate::status::next_action as core_next_action;
553
554    fn bare_trust(status: &str) -> RepositoryVerificationState {
555        RepositoryVerificationState {
556            verified: false,
557            status: status.to_string(),
558            repository_mode: "native".to_string(),
559            heddle_initialized: true,
560            git_branch: None,
561            heddle_thread: None,
562            worktree_dirty: false,
563            worktree_state: "clean".to_string(),
564            import_state: "ok".to_string(),
565            mapping_state: "ok".to_string(),
566            remote_drift: "none".to_string(),
567            active_operation: None,
568            default_remote: None,
569            clone_verification: "not_applicable".to_string(),
570            machine_contract: "not_checked".to_string(),
571            machine_contract_coverage: crate::MachineContractCoverage::not_checked(),
572            workflow_status: "idle".to_string(),
573            workflow_summary: String::new(),
574            summary: status.to_string(),
575            recommended_action: "heddle verify".to_string(),
576            recommended_action_template: None,
577            recovery_commands: Vec::new(),
578            recovery_action_templates: Vec::new(),
579            checks: Vec::new(),
580        }
581    }
582
583    fn preview(merge_relation: &str) -> ThreadPreviewReport {
584        ThreadPreviewReport {
585            thread: "feature".to_string(),
586            thread_mode: "solid".to_string(),
587            thread_state: "ready".to_string(),
588            freshness: "current".to_string(),
589            task: None,
590            changed_paths: Vec::new(),
591            changed_path_count: 0,
592            impact_categories: Vec::new(),
593            heavy_impact_paths: Vec::new(),
594            merge_relation: merge_relation.to_string(),
595            conflicts: Vec::new(),
596            conflict_count: 0,
597            blockers: Vec::new(),
598            recommended_action: "heddle land --thread feature".to_string(),
599            recommended_action_template: None,
600            thread_health: "ready".to_string(),
601        }
602    }
603
604    #[test]
605    fn ready_preflight_blocks_setup_and_mapping_statuses() {
606        for status in [
607            "needs_init",
608            "needs_import",
609            "needs_reconcile",
610            "git_branch_advanced",
611        ] {
612            assert!(
613                ready_verification_preflight_blocks(&bare_trust(status)),
614                "{status} should block ready preflight"
615            );
616        }
617        assert!(!ready_verification_preflight_blocks(&bare_trust("clean")));
618        assert!(!ready_verification_preflight_blocks(&bare_trust(
619            "dirty_worktree"
620        )));
621    }
622
623    #[test]
624    fn ready_decision_classifies_already_ready_and_no_target() {
625        let clear = classify_ready_decision(ReadyDecisionInput {
626            merge_relation: "fast_forward",
627            captured: false,
628            thread_already_ready: true,
629            conflict_count: 0,
630            blockers: &[],
631        });
632        assert!(clear.already_ready);
633        assert!(clear.integration_clear);
634        assert!(clear.operator_completed);
635
636        let no_target = classify_ready_decision(ReadyDecisionInput {
637            merge_relation: "no_target",
638            captured: false,
639            thread_already_ready: false,
640            conflict_count: 0,
641            blockers: &[],
642        });
643        assert!(no_target.ready_without_target);
644        assert!(!no_target.has_integration_target);
645        assert!(no_target.operator_completed);
646
647        let blocked = classify_ready_decision(ReadyDecisionInput {
648            merge_relation: "conflicted",
649            captured: false,
650            thread_already_ready: false,
651            conflict_count: 1,
652            blockers: &["conflict".to_string()],
653        });
654        assert!(!blocked.integration_clear);
655        assert!(!blocked.operator_completed);
656    }
657
658    #[test]
659    fn ready_suppresses_action_without_target() {
660        assert_eq!(
661            ready_report_recommended_action("no_target", "heddle land --thread main"),
662            None
663        );
664        assert_eq!(
665            ready_report_recommended_action("fast_forward", "heddle land --thread feature"),
666            Some("heddle land --thread feature".to_string())
667        );
668    }
669
670    #[test]
671    fn ready_scoped_next_action_matches_core_matrix() {
672        let operation = RepositoryOperationStatus {
673            scope: OperationScope::Heddle,
674            kind: OperationKind::Merge,
675            in_progress: true,
676            state: "in_progress".to_string(),
677            message: "merge in progress".to_string(),
678            next_action: "heddle continue".to_string(),
679        };
680        let remote_ahead = GitRemoteTrackingStatus {
681            branch: "feature".to_string(),
682            upstream: "origin/feature".to_string(),
683            ahead: 1,
684            behind: 0,
685            local_oid: Some("local".to_string()),
686            upstream_oid: Some("upstream".to_string()),
687            upstream_is_undone_checkpoint: false,
688            message: String::new(),
689            next_action: String::new(),
690        };
691        let fallback = Some("heddle land --thread feature");
692        let scoped = ready_scoped_next_action(Some(&operation), None, None, fallback);
693        let core = core_next_action::effective_next_action(
694            core_next_action::NextActionInput::default(Some(&operation), None, None, fallback)
695                .ready(),
696        );
697        assert_eq!(scoped, core);
698        assert_eq!(scoped, "heddle continue");
699
700        let publish = ready_scoped_next_action(None, Some(&remote_ahead), None, None);
701        assert_eq!(
702            publish,
703            core_next_action::effective_next_action(
704                core_next_action::NextActionInput::default(None, Some(&remote_ahead), None, None,)
705                    .ready(),
706            )
707        );
708    }
709
710    #[test]
711    fn auto_land_policy_blocks_low_confidence_and_failing_tests() {
712        let blockers = auto_land_policy_blockers(AutoLandPolicyInput {
713            agent_authored: true,
714            confidence: Some(0.40),
715            tests_passed: Some(false),
716        });
717        assert_eq!(
718            blockers,
719            vec![
720                "confidence 0.40 is below the auto-land threshold of 0.75".to_string(),
721                "verification summary reports failing tests".to_string(),
722            ]
723        );
724        assert!(
725            auto_land_policy_blockers(AutoLandPolicyInput {
726                agent_authored: false,
727                confidence: Some(0.10),
728                tests_passed: Some(true),
729            })
730            .is_empty()
731        );
732    }
733
734    #[test]
735    fn confidence_blocker_recovery_scopes_to_thread_checkout() {
736        let blockers = vec!["confidence 0.40 is below the auto-land threshold of 0.75".to_string()];
737        let action = integration_blocker_recommended_action(
738            &blockers,
739            Some(Path::new("/work/threads/agent-thread")),
740        )
741        .expect("confidence blocker must yield recovery");
742        assert_eq!(
743            action,
744            "heddle --repo /work/threads/agent-thread capture -m \"...\" --confidence <confidence>"
745        );
746
747        let unscoped =
748            integration_blocker_recommended_action(&blockers, None).expect("unscoped recovery");
749        assert_eq!(unscoped, AUTO_LAND_CONFIDENCE_RECOVERY_ACTION);
750
751        assert!(
752            integration_blocker_recommended_action(
753                &["3 path conflict(s) need manual resolution".to_string()],
754                None
755            )
756            .is_none()
757        );
758    }
759
760    #[test]
761    fn non_staleness_drops_stale_and_heavy_impact() {
762        let blockers = vec![
763            "Thread 'agent-thread' is stale against 'main'".to_string(),
764            "Heavy-impact change: crates/wire/src/lib.rs — review broader impact before merging"
765                .to_string(),
766            "confidence 0.40 is below the auto-land threshold of 0.75".to_string(),
767        ];
768        assert_eq!(
769            non_staleness_blockers(&blockers),
770            vec!["confidence 0.40 is below the auto-land threshold of 0.75".to_string()]
771        );
772    }
773
774    #[test]
775    fn land_warnings_surface_heavy_impact_review() {
776        let mut report = preview("would_merge");
777        report.heavy_impact_paths = vec!["crates/wire/src/lib.rs".to_string()];
778        report.blockers = vec![
779            "Heavy-impact change: crates/wire/src/lib.rs — review broader impact before merging"
780                .to_string(),
781        ];
782        assert_eq!(
783            land_warnings_for_preview(&report),
784            vec![
785                "Heavy-impact change: crates/wire/src/lib.rs — review broader impact before merging"
786                    .to_string()
787            ]
788        );
789    }
790
791    #[test]
792    fn land_step_accounting_and_next_action() {
793        assert_eq!(
794            land_performed_steps(true, false, true, true),
795            vec!["capture", "merge", "checkpoint"]
796        );
797        assert!(land_skipped_steps(true, true, true, true).is_empty());
798        assert_eq!(
799            integrated_land_next_action(true, "heddle push"),
800            Some("heddle push".to_string())
801        );
802        assert_eq!(
803            integrated_land_next_action(true, "heddle push"),
804            Some("heddle push".to_string())
805        );
806        assert_eq!(integrated_land_next_action(false, "heddle push"), None);
807    }
808
809    #[test]
810    fn sync_completed_next_action_is_not_land_thread() {
811        assert_eq!(sync_completed_next_action(None, None, None), None);
812
813        let operation = RepositoryOperationStatus {
814            scope: OperationScope::Heddle,
815            kind: OperationKind::Merge,
816            in_progress: true,
817            state: "in_progress".to_string(),
818            message: "merge in progress".to_string(),
819            next_action: "heddle continue".to_string(),
820        };
821        assert_eq!(
822            sync_completed_next_action(Some(&operation), None, None),
823            Some("heddle continue".to_string())
824        );
825
826        assert!(sync_is_already_current(true, false));
827        assert!(sync_is_already_current(false, true));
828        assert!(!sync_is_already_current(false, false));
829    }
830
831    #[test]
832    fn recovery_scope_checkout_distinguishes_isolated_from_in_thread() {
833        assert_eq!(
834            recovery_scope_checkout(
835                Path::new("/work/threads/agent-thread"),
836                Path::new("/work/parent"),
837            ),
838            Some(PathBuf::from("/work/threads/agent-thread")),
839        );
840        assert_eq!(
841            recovery_scope_checkout(
842                Path::new("/work/threads/agent-thread"),
843                Path::new("/work/threads/agent-thread"),
844            ),
845            None,
846        );
847        assert_eq!(
848            recovery_scope_checkout(Path::new(""), Path::new("/work/parent")),
849            None,
850        );
851    }
852
853    #[test]
854    fn should_squash_respects_no_squash_and_config() {
855        assert!(should_squash_land(false, true));
856        assert!(!should_squash_land(true, true));
857        assert!(!should_squash_land(false, false));
858    }
859
860    #[test]
861    fn land_checkpoint_message_precedence() {
862        assert_eq!(
863            land_checkpoint_message(Some("explicit"), false, "t", Some("intent"), Some("task")),
864            "explicit"
865        );
866        assert_eq!(
867            land_checkpoint_message(Some("  "), true, "t", Some("intent"), None),
868            "Land t"
869        );
870        assert_eq!(
871            land_checkpoint_message(None, false, "t", Some("intent"), Some("task")),
872            "intent"
873        );
874        assert_eq!(
875            land_checkpoint_message(None, false, "t", None, Some("task")),
876            "task"
877        );
878        assert_eq!(
879            land_checkpoint_message(None, false, "t", None, None),
880            "Land t"
881        );
882    }
883
884    #[test]
885    fn state_id_matches_short_or_full() {
886        assert!(state_id_matches_display("abc", "abcdef", "abc"));
887        assert!(state_id_matches_display("abc", "abcdef", "abcdef"));
888        assert!(!state_id_matches_display("abc", "abcdef", "zzz"));
889    }
890
891    #[test]
892    fn land_text_scope_and_manual_review() {
893        assert_eq!(land_text_step("capture"), "saved");
894        assert_eq!(land_text_step("merge(blocked)"), "merge blocked");
895        assert_eq!(
896            land_text_step("merge(already_integrated)"),
897            "already landed"
898        );
899        assert_eq!(
900            land_text_step("checkpoint(not reached)"),
901            "Git commit skipped because merge did not run"
902        );
903        assert!(is_manual_review_blocker("Heavy-impact change: Cargo.lock"));
904        assert!(!is_manual_review_blocker("stale"));
905        assert_eq!(
906            scope_action_to_repo("heddle land main", "/tmp/repo"),
907            "heddle --repo /tmp/repo land main"
908        );
909        assert_eq!(ready_merge_type_label("fast_forward"), "fast-forward");
910        assert_eq!(
911            ready_merge_type_label("already_integrated"),
912            "already integrated"
913        );
914        assert_eq!(ready_merge_type_label("no_target"), "none configured");
915    }
916}