1use 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
26pub const AUTO_LAND_CONFIDENCE_THRESHOLD: f32 = 0.75;
28
29pub const AUTO_LAND_CONFIDENCE_RECOVERY_ACTION: &str =
31 "heddle capture -m \"...\" --confidence <confidence>";
32
33pub fn ready_verification_preflight_blocks(trust: &RepositoryVerificationState) -> bool {
39 ready_verification_status_blocks(trust.status.as_str())
40}
41
42pub 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
50pub fn has_integration_target(merge_relation: &str) -> bool {
56 merge_relation != "no_target"
57}
58
59pub fn is_integration_clear(conflict_count: usize, blockers: &[String]) -> bool {
61 conflict_count == 0 && blockers.is_empty()
62}
63
64#[derive(Debug, Clone, Copy)]
66pub struct ReadyDecisionInput<'a> {
67 pub merge_relation: &'a str,
68 pub captured: bool,
69 pub thread_already_ready: bool,
71 pub conflict_count: usize,
72 pub blockers: &'a [String],
73}
74
75#[derive(Debug, Clone, Copy, PartialEq, Eq)]
77pub struct ReadyDecision {
78 pub has_integration_target: bool,
79 pub already_ready: bool,
81 pub ready_without_target: bool,
83 pub integration_clear: bool,
85 pub operator_completed: bool,
87}
88
89pub 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 operator_completed: !has_target || clear,
103 }
104}
105
106pub 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
117pub 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
129pub fn should_squash_land(no_squash: bool, config_squash: bool) -> bool {
131 !no_squash && config_squash
132}
133
134#[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
146pub 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
164pub 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
179pub 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
193pub 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
207pub 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
217pub fn is_heavy_impact_advisory(blocker: &str) -> bool {
223 blocker.to_lowercase().contains("heavy-impact change")
224}
225
226pub 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
237pub 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
260pub 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
279pub fn is_manual_review_blocker(blocker: &str) -> bool {
285 blocker.starts_with("Heavy-impact change:")
286}
287
288pub 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
305pub 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
319pub 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
332pub 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
342pub 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
355pub 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
365pub 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
375pub 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
385pub 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
404pub 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
424pub 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
443pub fn sync_is_already_current(freshness_is_current: bool, is_synthesized_checkout: bool) -> bool {
451 freshness_is_current || is_synthesized_checkout
452}
453
454pub 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
469pub 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
495pub fn state_id_matches_display(short: &str, full: &str, display: &str) -> bool {
497 short == display || full == display
498}
499
500pub 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 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::EntryVisibilitySet { .. }
539 | OpRecord::HeadUpdate { .. } => false,
540 }
541}
542
543pub fn state_id_matches_op_display(id: &StateId, display: &str) -> bool {
545 state_id_matches_display(&id.short(), &id.to_string_full(), display)
546}
547
548#[cfg(test)]
549mod tests {
550 use repo::{OperationKind, OperationScope};
551
552 use super::*;
553 use crate::status::next_action as core_next_action;
554
555 fn bare_trust(status: &str) -> RepositoryVerificationState {
556 RepositoryVerificationState {
557 verified: false,
558 status: status.to_string(),
559 repository_mode: "native".to_string(),
560 heddle_initialized: true,
561 git_branch: None,
562 heddle_thread: None,
563 worktree_dirty: false,
564 worktree_state: "clean".to_string(),
565 import_state: "ok".to_string(),
566 mapping_state: "ok".to_string(),
567 remote_drift: "none".to_string(),
568 active_operation: None,
569 default_remote: None,
570 clone_verification: "not_applicable".to_string(),
571 machine_contract: "not_checked".to_string(),
572 machine_contract_coverage: crate::MachineContractCoverage::not_checked(),
573 workflow_status: "idle".to_string(),
574 workflow_summary: String::new(),
575 summary: status.to_string(),
576 recommended_action: "heddle verify".to_string(),
577 recommended_action_template: None,
578 recovery_commands: Vec::new(),
579 recovery_action_templates: Vec::new(),
580 checks: Vec::new(),
581 }
582 }
583
584 fn preview(merge_relation: &str) -> ThreadPreviewReport {
585 ThreadPreviewReport {
586 thread: "feature".to_string(),
587 thread_mode: "solid".to_string(),
588 thread_state: "ready".to_string(),
589 freshness: "current".to_string(),
590 task: None,
591 changed_paths: Vec::new(),
592 changed_path_count: 0,
593 impact_categories: Vec::new(),
594 heavy_impact_paths: Vec::new(),
595 merge_relation: merge_relation.to_string(),
596 conflicts: Vec::new(),
597 conflict_count: 0,
598 blockers: Vec::new(),
599 recommended_action: "heddle land --thread feature".to_string(),
600 recommended_action_template: None,
601 thread_health: "ready".to_string(),
602 }
603 }
604
605 #[test]
606 fn ready_preflight_blocks_setup_and_mapping_statuses() {
607 for status in [
608 "needs_init",
609 "needs_import",
610 "needs_reconcile",
611 "git_branch_advanced",
612 ] {
613 assert!(
614 ready_verification_preflight_blocks(&bare_trust(status)),
615 "{status} should block ready preflight"
616 );
617 }
618 assert!(!ready_verification_preflight_blocks(&bare_trust("clean")));
619 assert!(!ready_verification_preflight_blocks(&bare_trust(
620 "dirty_worktree"
621 )));
622 }
623
624 #[test]
625 fn ready_decision_classifies_already_ready_and_no_target() {
626 let clear = classify_ready_decision(ReadyDecisionInput {
627 merge_relation: "fast_forward",
628 captured: false,
629 thread_already_ready: true,
630 conflict_count: 0,
631 blockers: &[],
632 });
633 assert!(clear.already_ready);
634 assert!(clear.integration_clear);
635 assert!(clear.operator_completed);
636
637 let no_target = classify_ready_decision(ReadyDecisionInput {
638 merge_relation: "no_target",
639 captured: false,
640 thread_already_ready: false,
641 conflict_count: 0,
642 blockers: &[],
643 });
644 assert!(no_target.ready_without_target);
645 assert!(!no_target.has_integration_target);
646 assert!(no_target.operator_completed);
647
648 let blocked = classify_ready_decision(ReadyDecisionInput {
649 merge_relation: "conflicted",
650 captured: false,
651 thread_already_ready: false,
652 conflict_count: 1,
653 blockers: &["conflict".to_string()],
654 });
655 assert!(!blocked.integration_clear);
656 assert!(!blocked.operator_completed);
657 }
658
659 #[test]
660 fn ready_suppresses_action_without_target() {
661 assert_eq!(
662 ready_report_recommended_action("no_target", "heddle land --thread main"),
663 None
664 );
665 assert_eq!(
666 ready_report_recommended_action("fast_forward", "heddle land --thread feature"),
667 Some("heddle land --thread feature".to_string())
668 );
669 }
670
671 #[test]
672 fn ready_scoped_next_action_matches_core_matrix() {
673 let operation = RepositoryOperationStatus {
674 scope: OperationScope::Heddle,
675 kind: OperationKind::Merge,
676 in_progress: true,
677 state: "in_progress".to_string(),
678 message: "merge in progress".to_string(),
679 next_action: "heddle continue".to_string(),
680 };
681 let remote_ahead = GitRemoteTrackingStatus {
682 branch: "feature".to_string(),
683 upstream: "origin/feature".to_string(),
684 ahead: 1,
685 behind: 0,
686 local_oid: Some("local".to_string()),
687 upstream_oid: Some("upstream".to_string()),
688 upstream_is_undone_checkpoint: false,
689 message: String::new(),
690 next_action: String::new(),
691 };
692 let fallback = Some("heddle land --thread feature");
693 let scoped = ready_scoped_next_action(Some(&operation), None, None, fallback);
694 let core = core_next_action::effective_next_action(
695 core_next_action::NextActionInput::default(Some(&operation), None, None, fallback)
696 .ready(),
697 );
698 assert_eq!(scoped, core);
699 assert_eq!(scoped, "heddle continue");
700
701 let publish = ready_scoped_next_action(None, Some(&remote_ahead), None, None);
702 assert_eq!(
703 publish,
704 core_next_action::effective_next_action(
705 core_next_action::NextActionInput::default(None, Some(&remote_ahead), None, None,)
706 .ready(),
707 )
708 );
709 }
710
711 #[test]
712 fn auto_land_policy_blocks_low_confidence_and_failing_tests() {
713 let blockers = auto_land_policy_blockers(AutoLandPolicyInput {
714 agent_authored: true,
715 confidence: Some(0.40),
716 tests_passed: Some(false),
717 });
718 assert_eq!(
719 blockers,
720 vec![
721 "confidence 0.40 is below the auto-land threshold of 0.75".to_string(),
722 "verification summary reports failing tests".to_string(),
723 ]
724 );
725 assert!(
726 auto_land_policy_blockers(AutoLandPolicyInput {
727 agent_authored: false,
728 confidence: Some(0.10),
729 tests_passed: Some(true),
730 })
731 .is_empty()
732 );
733 }
734
735 #[test]
736 fn confidence_blocker_recovery_scopes_to_thread_checkout() {
737 let blockers = vec!["confidence 0.40 is below the auto-land threshold of 0.75".to_string()];
738 let action = integration_blocker_recommended_action(
739 &blockers,
740 Some(Path::new("/work/threads/agent-thread")),
741 )
742 .expect("confidence blocker must yield recovery");
743 assert_eq!(
744 action,
745 "heddle --repo /work/threads/agent-thread capture -m \"...\" --confidence <confidence>"
746 );
747
748 let unscoped =
749 integration_blocker_recommended_action(&blockers, None).expect("unscoped recovery");
750 assert_eq!(unscoped, AUTO_LAND_CONFIDENCE_RECOVERY_ACTION);
751
752 assert!(
753 integration_blocker_recommended_action(
754 &["3 path conflict(s) need manual resolution".to_string()],
755 None
756 )
757 .is_none()
758 );
759 }
760
761 #[test]
762 fn non_staleness_drops_stale_and_heavy_impact() {
763 let blockers = vec![
764 "Thread 'agent-thread' is stale against 'main'".to_string(),
765 "Heavy-impact change: crates/wire/src/lib.rs — review broader impact before merging"
766 .to_string(),
767 "confidence 0.40 is below the auto-land threshold of 0.75".to_string(),
768 ];
769 assert_eq!(
770 non_staleness_blockers(&blockers),
771 vec!["confidence 0.40 is below the auto-land threshold of 0.75".to_string()]
772 );
773 }
774
775 #[test]
776 fn land_warnings_surface_heavy_impact_review() {
777 let mut report = preview("would_merge");
778 report.heavy_impact_paths = vec!["crates/wire/src/lib.rs".to_string()];
779 report.blockers = vec![
780 "Heavy-impact change: crates/wire/src/lib.rs — review broader impact before merging"
781 .to_string(),
782 ];
783 assert_eq!(
784 land_warnings_for_preview(&report),
785 vec![
786 "Heavy-impact change: crates/wire/src/lib.rs — review broader impact before merging"
787 .to_string()
788 ]
789 );
790 }
791
792 #[test]
793 fn land_step_accounting_and_next_action() {
794 assert_eq!(
795 land_performed_steps(true, false, true, true),
796 vec!["capture", "merge", "checkpoint"]
797 );
798 assert!(land_skipped_steps(true, true, true, true).is_empty());
799 assert_eq!(
800 integrated_land_next_action(true, "heddle push"),
801 Some("heddle push".to_string())
802 );
803 assert_eq!(
804 integrated_land_next_action(true, "heddle push"),
805 Some("heddle push".to_string())
806 );
807 assert_eq!(integrated_land_next_action(false, "heddle push"), None);
808 }
809
810 #[test]
811 fn sync_completed_next_action_is_not_land_thread() {
812 assert_eq!(sync_completed_next_action(None, None, None), None);
813
814 let operation = RepositoryOperationStatus {
815 scope: OperationScope::Heddle,
816 kind: OperationKind::Merge,
817 in_progress: true,
818 state: "in_progress".to_string(),
819 message: "merge in progress".to_string(),
820 next_action: "heddle continue".to_string(),
821 };
822 assert_eq!(
823 sync_completed_next_action(Some(&operation), None, None),
824 Some("heddle continue".to_string())
825 );
826
827 assert!(sync_is_already_current(true, false));
828 assert!(sync_is_already_current(false, true));
829 assert!(!sync_is_already_current(false, false));
830 }
831
832 #[test]
833 fn recovery_scope_checkout_distinguishes_isolated_from_in_thread() {
834 assert_eq!(
835 recovery_scope_checkout(
836 Path::new("/work/threads/agent-thread"),
837 Path::new("/work/parent"),
838 ),
839 Some(PathBuf::from("/work/threads/agent-thread")),
840 );
841 assert_eq!(
842 recovery_scope_checkout(
843 Path::new("/work/threads/agent-thread"),
844 Path::new("/work/threads/agent-thread"),
845 ),
846 None,
847 );
848 assert_eq!(
849 recovery_scope_checkout(Path::new(""), Path::new("/work/parent")),
850 None,
851 );
852 }
853
854 #[test]
855 fn should_squash_respects_no_squash_and_config() {
856 assert!(should_squash_land(false, true));
857 assert!(!should_squash_land(true, true));
858 assert!(!should_squash_land(false, false));
859 }
860
861 #[test]
862 fn land_checkpoint_message_precedence() {
863 assert_eq!(
864 land_checkpoint_message(Some("explicit"), false, "t", Some("intent"), Some("task")),
865 "explicit"
866 );
867 assert_eq!(
868 land_checkpoint_message(Some(" "), true, "t", Some("intent"), None),
869 "Land t"
870 );
871 assert_eq!(
872 land_checkpoint_message(None, false, "t", Some("intent"), Some("task")),
873 "intent"
874 );
875 assert_eq!(
876 land_checkpoint_message(None, false, "t", None, Some("task")),
877 "task"
878 );
879 assert_eq!(
880 land_checkpoint_message(None, false, "t", None, None),
881 "Land t"
882 );
883 }
884
885 #[test]
886 fn state_id_matches_short_or_full() {
887 assert!(state_id_matches_display("abc", "abcdef", "abc"));
888 assert!(state_id_matches_display("abc", "abcdef", "abcdef"));
889 assert!(!state_id_matches_display("abc", "abcdef", "zzz"));
890 }
891
892 #[test]
893 fn land_text_scope_and_manual_review() {
894 assert_eq!(land_text_step("capture"), "saved");
895 assert_eq!(land_text_step("merge(blocked)"), "merge blocked");
896 assert_eq!(
897 land_text_step("merge(already_integrated)"),
898 "already landed"
899 );
900 assert_eq!(
901 land_text_step("checkpoint(not reached)"),
902 "Git commit skipped because merge did not run"
903 );
904 assert!(is_manual_review_blocker("Heavy-impact change: Cargo.lock"));
905 assert!(!is_manual_review_blocker("stale"));
906 assert_eq!(
907 scope_action_to_repo("heddle land main", "/tmp/repo"),
908 "heddle --repo /tmp/repo land main"
909 );
910 assert_eq!(ready_merge_type_label("fast_forward"), "fast-forward");
911 assert_eq!(
912 ready_merge_type_label("already_integrated"),
913 "already integrated"
914 );
915 assert_eq!(ready_merge_type_label("no_target"), "none configured");
916 }
917}