heddle-cli 0.8.0

An AI-native version control system
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
// SPDX-License-Identifier: Apache-2.0
//! Heddle-native thread shaping helpers.

use std::path::Path;

use anyhow::{Result, anyhow};
use heddle_core::{
    CaptureSplitOptions, ThreadMoveOptions, ThreadShapingError, capture_split, thread_move,
};
use objects::object::ThreadName;
use repo::{GitOverlayImportHint, GitRemoteTrackingStatus, Repository, RepositoryOperationStatus};
use serde::Serialize;

use super::{
    action_line::print_next,
    advice::RecoveryAdvice,
    git_overlay_health::{RepositoryVerificationState, build_repository_verification_state},
    merge::merge_thread_into_current,
    next_action::{NextActionValidationContext, write_command_json},
    operator_core::{OperatorAction, OperatorCommandOutput},
    operator_loop::primary_next_action,
    ready_cmd::worktree_dirty,
    snapshot::{SnapshotAgentOverrides, create_snapshot},
    thread_cmd::{
        capture_thread_update_before, current_thread_ref_state, load_thread, refresh_thread,
        refresh_thread_freshness, save_thread_update_with_oplog, thread_not_found_advice,
    },
    thread_landing::{land_command_for_thread, land_command_with_push_target},
};
use crate::{
    cli::{
        Cli, output_is_compact, render::shell_quote, should_output_json, style,
        worktree_status_options,
    },
    config::UserConfig,
};

#[derive(Debug, Serialize)]
pub struct ThreadResolveOutput {
    #[serde(flatten)]
    pub operator: OperatorCommandOutput,
    pub thread: String,
}

impl super::compact::CompactProjection for ThreadResolveOutput {
    fn compact(&self) -> super::compact::CompactOutput {
        <OperatorCommandOutput as super::compact::CompactProjection>::compact(&self.operator)
    }
}

#[derive(Debug, Serialize)]
pub struct ThreadAbsorbOutput {
    pub thread: String,
    pub into: String,
    pub preview_only: bool,
    pub conflicts: Vec<String>,
    pub merge_state: Option<String>,
    pub message: String,
}

pub fn cmd_capture_split(
    cli: &Cli,
    into: String,
    prefixes: Vec<String>,
    intent: Option<String>,
) -> Result<()> {
    let repo = cli.open_repo()?;
    let user_config = UserConfig::load_default()?;
    let output = capture_split(
        &repo,
        CaptureSplitOptions {
            into,
            prefixes,
            intent,
            worktree_status_options: worktree_status_options(Some(repo.config())),
        },
        |target_repo, snapshot_intent| {
            Ok(create_snapshot(
                target_repo,
                &user_config,
                snapshot_intent,
                None,
                SnapshotAgentOverrides {
                    provider: None,
                    model: None,
                    session: None,
                    segment: None,
                    policy: None,
                    no_policy: false,
                    no_agent: false,
                },
            )?
            .change_id)
        },
    )
    .map_err(map_thread_shaping_anyhow_error)?;
    emit(cli, &output)
}

pub fn cmd_thread_move(
    cli: &Cli,
    from: String,
    to: String,
    prefixes: Vec<String>,
    message: Option<String>,
) -> Result<()> {
    let repo = cli.open_repo()?;
    let user_config = UserConfig::load_default()?;
    let output = thread_move(
        &repo,
        ThreadMoveOptions {
            from,
            to,
            prefixes,
            message,
        },
        |target_repo, snapshot_intent| {
            Ok(create_snapshot(
                target_repo,
                &user_config,
                snapshot_intent,
                None,
                SnapshotAgentOverrides {
                    provider: None,
                    model: None,
                    session: None,
                    segment: None,
                    policy: None,
                    no_policy: false,
                    no_agent: false,
                },
            )?
            .change_id)
        },
    )
    .map_err(map_thread_shaping_anyhow_error)?;
    emit(cli, &output)
}

pub fn cmd_thread_absorb(
    cli: &Cli,
    thread: String,
    into: Option<String>,
    message: Option<String>,
    preview: bool,
) -> Result<()> {
    let repo = cli.open_repo()?;
    let child = load_thread(&repo, &thread)?;
    let parent_id = into
        .or(child.parent_thread.clone())
        .ok_or_else(|| anyhow!(RecoveryAdvice::thread_absorb_parent_required(&child.id)))?;
    let parent = load_thread(&repo, &parent_id)?;
    let parent_repo = Repository::open(&parent.execution_path)?;
    let user_config = UserConfig::load_default()?;
    let status_options = worktree_status_options(Some(parent_repo.config()));
    if worktree_dirty(&parent_repo, &status_options)? {
        create_snapshot(
            &parent_repo,
            &user_config,
            Some(format!("Prepare absorb of {}", child.id)),
            None,
            SnapshotAgentOverrides {
                provider: None,
                model: None,
                session: None,
                segment: None,
                policy: None,
                no_policy: false,
                no_agent: false,
            },
        )?;
    }
    let output = merge_thread_into_current(
        &parent_repo,
        &child.thread,
        message,
        false,
        preview,
        false,
        false,
        false,
    )?;
    emit(
        cli,
        &ThreadAbsorbOutput {
            thread: child.id,
            into: parent_id,
            preview_only: output.preview_only,
            conflicts: output.conflicts,
            merge_state: output.merge_state,
            message: output.operator.message,
        },
    )
}

pub fn cmd_thread_resolve(cli: &Cli, thread_id: String) -> Result<()> {
    let repo = cli.open_repo()?;
    let mut thread = load_thread(&repo, &thread_id)?;
    refresh_thread_freshness(&repo, &mut thread)?;
    let source_root = if thread.execution_path.as_os_str().is_empty() {
        repo.root().to_path_buf()
    } else {
        thread.execution_path.clone()
    };
    let source_repo = Repository::open(&source_root)?;
    let rebase_state_path = source_repo.heddle_dir().join("REBASE_STATE");

    if thread.freshness == repo::ThreadFreshness::Stale {
        match refresh_thread(&repo, &thread_id, cli) {
            Ok(_) => {
                let manager = super::thread_cmd::thread_manager(&repo);
                let mut refreshed_thread = manager.load(&thread_id)?.ok_or_else(|| {
                    anyhow!(thread_not_found_advice(&thread_id, "resolve thread"))
                })?;
                let before_update =
                    capture_thread_update_before(&repo, &manager, &refreshed_thread)?;
                let resolved_state = repo
                    .refs()
                    .get_thread(&ThreadName::new(&refreshed_thread.thread))?
                    .map(|id| id.short());
                let new_state = current_thread_ref_state(&repo, &refreshed_thread)?;
                refreshed_thread.integration_policy_result.status =
                    Some("manual_resolved".to_string());
                refreshed_thread.integration_policy_result.reason =
                    Some("manual integration resolution captured".to_string());
                refreshed_thread
                    .integration_policy_result
                    .manual_resolution_state = resolved_state;
                // The stale thread refreshed cleanly (no conflicts surfaced
                // for the user to resolve), so the land message must not
                // claim a manual resolution.
                refreshed_thread
                    .integration_policy_result
                    .conflicts_resolved_manually = false;
                save_thread_update_with_oplog(
                    &repo,
                    &manager,
                    &refreshed_thread,
                    before_update,
                    new_state,
                )?;
                let operator = if rebase_state_path.exists() {
                    thread_resolve_rebase_followup_operator(
                        &source_repo,
                        &rebase_state_path,
                        &thread.id,
                    )?
                } else {
                    let trust = build_repository_verification_state(&repo);
                    thread_resolve_refresh_operator(&thread.id, &trust)
                };
                return emit_thread_resolve(
                    cli,
                    &repo,
                    &ThreadResolveOutput {
                        operator,
                        thread: thread_id,
                    },
                );
            }
            Err(err) => {
                if rebase_state_path.exists() {
                    let operator = thread_resolve_rebase_followup_operator(
                        &source_repo,
                        &rebase_state_path,
                        &thread.id,
                    )?;
                    return emit_thread_resolve(
                        cli,
                        &repo,
                        &ThreadResolveOutput {
                            operator,
                            thread: thread_id,
                        },
                    );
                }
                if let Some(operator) =
                    thread_resolve_conflict_recovery_operator(&source_repo, &thread.id)?
                {
                    return emit_thread_resolve(
                        cli,
                        &repo,
                        &ThreadResolveOutput {
                            operator,
                            thread: thread_id,
                        },
                    );
                }
                return Err(err);
            }
        }
    }

    let summary = super::thread::find_thread_summary(&repo, &thread.id)?
        .ok_or_else(|| anyhow!(thread_not_found_advice(&thread.id, "resolve thread")))?;
    let mut blockers = if rebase_state_path.exists() {
        Vec::new()
    } else {
        summary.blockers.clone()
    };
    let mut warnings = Vec::new();
    if !blockers.is_empty()
        && blockers
            .iter()
            .all(|blocker| is_manual_review_blocker(blocker))
    {
        warnings = blockers.clone();
        blockers.clear();
    }
    let mut recommended_action = summary.recommended_action.clone();
    if blockers.is_empty() && rebase_state_path.exists() {
        let rebase_state = super::rebase::load_persisted_rebase_state(&rebase_state_path)?;
        let current_state = source_repo
            .current_state()?
            .ok_or_else(|| anyhow!("Thread '{}' has no current state", thread.id))?;
        if rebase_state
            .pre_conflict_head
            .is_some_and(|head| head != current_state.change_id)
        {
            recommended_action = "heddle rebase --continue".to_string();
        } else {
            blockers.push(
                "refresh has a rebase in progress; capture a manual resolution in the thread checkout, then run `heddle rebase --continue`".to_string(),
            );
        }
    }
    if blockers.is_empty()
        && !rebase_state_path.exists()
        && thread
            .integration_policy_result
            .manual_resolution_state
            .is_none()
    {
        let preview =
            merge_thread_into_current(&repo, &thread.id, None, false, true, false, false, false)?;
        if preview.conflict_count > 0 {
            blockers.push(format!(
                "Thread '{}' still has merge conflicts: {}",
                thread.id,
                preview.conflicts.join(", ")
            ));
            recommended_action = "heddle resolve --list".to_string();
        }
    }
    if blockers.is_empty() {
        let manager = super::thread_cmd::thread_manager(&repo);
        let before_update = capture_thread_update_before(&repo, &manager, &thread)?;
        let thread_state = before_update.state;
        thread.integration_policy_result.status = Some("manual_resolved".to_string());
        thread.integration_policy_result.reason =
            Some("manual integration resolution captured".to_string());
        thread.integration_policy_result.manual_resolution_state = repo
            .refs()
            .get_thread(&ThreadName::new(&thread.thread))?
            .map(|id| id.short());
        // Reached only after the conflict preview above came back clean
        // because the operator had captured a resolution in their checkout —
        // this is the genuine `heddle resolve` manual-resolution path.
        thread.integration_policy_result.conflicts_resolved_manually = true;
        save_thread_update_with_oplog(&repo, &manager, &thread, before_update, thread_state)?;
    }
    let recommended_action = if blockers.is_empty() {
        if rebase_state_path.exists() {
            recommended_action
        } else {
            land_command_for_thread(&repo, &summary.name)
        }
    } else {
        recommended_action
    };
    let operation = repo.operation_status()?;
    let remote_tracking = repo.git_remote_tracking_status()?;
    let import_hint = repo.git_overlay_import_hint()?;
    let recommended_action = thread_resolve_next_action(
        &blockers,
        operation.as_ref(),
        remote_tracking.as_ref(),
        import_hint.as_ref(),
        &recommended_action,
    );
    emit_thread_resolve(
        cli,
        &repo,
        &ThreadResolveOutput {
            operator: OperatorCommandOutput {
                status: if blockers.is_empty() {
                    "completed".to_string()
                } else {
                    "blocked".to_string()
                },
                action: OperatorAction::ThreadResolve,
                message: if blockers.is_empty() {
                    if warnings.is_empty() {
                        "Thread manual resolution recorded".to_string()
                    } else {
                        "Thread manual review recorded".to_string()
                    }
                } else {
                    "Thread requires a manual follow-up".to_string()
                },
                blockers: blockers.clone(),
                warnings,
                next_action: recommended_action.clone(),
                recommended_action,
            },
            thread: summary.name.clone(),
        },
    )
}

fn is_manual_review_blocker(blocker: &str) -> bool {
    blocker.starts_with("Heavy-impact change:")
}

fn thread_resolve_next_action(
    blockers: &[String],
    operation: Option<&RepositoryOperationStatus>,
    remote_tracking: Option<&GitRemoteTrackingStatus>,
    import_hint: Option<&GitOverlayImportHint>,
    local_action: &str,
) -> Option<String> {
    let action = if blockers.is_empty() {
        primary_next_action(operation, remote_tracking, import_hint, Some(local_action))
    } else if let Some(operation) = operation {
        operation.next_action.clone()
    } else {
        local_action.to_string()
    };
    (!action.trim().is_empty()).then_some(action)
}

fn thread_resolve_rebase_followup_operator(
    source_repo: &Repository,
    rebase_state_path: &Path,
    thread_id: &str,
) -> Result<OperatorCommandOutput> {
    let rebase_state = super::rebase::load_persisted_rebase_state(rebase_state_path)?;
    let current_state = source_repo
        .current_state()?
        .ok_or_else(|| anyhow!("Thread '{}' has no current state", thread_id))?;
    let next_action = "heddle continue".to_string();
    let mut blockers = Vec::new();
    if rebase_state
        .pre_conflict_head
        .is_none_or(|head| head == current_state.change_id)
    {
        blockers.push(
            "refresh has a rebase in progress; capture a manual resolution in the thread checkout, then run `heddle rebase --continue`".to_string(),
        );
    }

    Ok(OperatorCommandOutput {
        status: if blockers.is_empty() {
            "completed".to_string()
        } else {
            "blocked".to_string()
        },
        action: OperatorAction::ThreadResolve,
        message: if blockers.is_empty() {
            "Thread manual resolution recorded; continue the rebase".to_string()
        } else {
            "Thread still requires a manual rebase resolution".to_string()
        },
        blockers,
        warnings: Vec::new(),
        next_action: Some(next_action.clone()),
        recommended_action: Some(next_action),
    })
}

fn thread_resolve_conflict_recovery_operator(
    source_repo: &Repository,
    thread_id: &str,
) -> Result<Option<OperatorCommandOutput>> {
    if !source_repo.merge_state_manager().is_merge_in_progress() {
        return Ok(None);
    }
    let unresolved = source_repo.merge_state_manager().unresolved()?;
    let repo_arg = shell_quote(&source_repo.root().display().to_string());
    let conflict_list_command = format!("heddle --repo {repo_arg} resolve --list");
    let recommended_action = unresolved
        .first()
        .map(|path| format!("heddle --repo {repo_arg} resolve {}", shell_quote(path)))
        .unwrap_or_else(|| format!("heddle --repo {repo_arg} continue"));
    let blockers = if unresolved.is_empty() {
        Vec::new()
    } else {
        unresolved
            .iter()
            .map(|path| format!("Resolve conflict marker path: {path}"))
            .collect()
    };
    Ok(Some(OperatorCommandOutput {
        status: "blocked".to_string(),
        action: OperatorAction::ThreadResolve,
        message: format!(
            "Thread '{thread_id}' has conflict markers in its checkout; resolve them there, then continue"
        ),
        blockers,
        warnings: Vec::new(),
        next_action: Some(conflict_list_command),
        recommended_action: Some(recommended_action),
    }))
}

fn thread_resolve_refresh_operator(
    thread_id: &str,
    trust: &RepositoryVerificationState,
) -> OperatorCommandOutput {
    let land_command = land_command_with_push_target(thread_id, trust.default_remote.is_some());
    if trust.verified {
        return OperatorCommandOutput {
            status: "synced".to_string(),
            action: OperatorAction::ThreadResolve,
            message: "Thread refreshed cleanly".to_string(),
            blockers: Vec::new(),
            warnings: Vec::new(),
            next_action: Some(land_command.clone()),
            recommended_action: Some(land_command),
        };
    }

    OperatorCommandOutput::blocked_by_repository_verification(
        OperatorAction::ThreadResolve,
        format!(
            "Thread refreshed cleanly, but repository verification is blocked: {}",
            trust.summary
        ),
        trust,
    )
}

fn map_thread_shaping_anyhow_error(err: anyhow::Error) -> anyhow::Error {
    match err.downcast::<ThreadShapingError>() {
        Ok(shaping_err) => map_thread_shaping_error(shaping_err),
        Err(err) => err,
    }
}

fn map_thread_shaping_error(err: ThreadShapingError) -> anyhow::Error {
    match err {
        ThreadShapingError::NoCurrentThread => anyhow!(RecoveryAdvice::no_current_thread(
            "capture --split",
            None,
            "heddle thread switch <name>",
        )),
        ThreadShapingError::NoPathsMatched(details) => anyhow!(RecoveryAdvice::safety_refusal(
            "no_paths_matched",
            details.error,
            format!(
                "Inspect available paths with `{}`, then retry `{}` with a matching prefix.",
                details.primary_command, details.action
            ),
            details.unsafe_condition,
            details.would_change,
            "repository state was left unchanged",
            details.primary_command,
            vec![details.primary_command.to_string()],
        )),
        ThreadShapingError::ThreadNotFound { thread_id, action } => {
            anyhow!(super::thread_cmd::thread_not_found_advice(&thread_id, action))
        }
        ThreadShapingError::ImportedGitRefNotManaged { thread_id } => {
            let reconcile_preview =
                heddle_core::status::next_action::canonical_bridge_reconcile_ref_preview_command(
                    None,
                    &thread_id,
                );
            anyhow!(RecoveryAdvice::safety_refusal(
                "imported_git_ref_not_managed_thread",
                format!("'{thread_id}' is an imported Git ref, not a managed Heddle thread"),
                format!(
                    "Preview Git/Heddle reconciliation with `{reconcile_preview}`. Use managed threads for `ready` and `land`."
                ),
                format!("thread ref '{thread_id}' exists, but no managed thread metadata exists for it"),
                "ready/land require managed thread metadata and explicit integration authority; treating an imported Git ref as landable would be ambiguous",
                "thread refs, Git refs, checkout files, and thread metadata were left unchanged",
                reconcile_preview.clone(),
                vec![reconcile_preview, "heddle thread list".to_string()],
            ))
        }
    }
}

fn emit<T: Serialize>(cli: &Cli, output: &T) -> Result<()> {
    if should_output_json(cli, None) {
        println!("{}", serde_json::to_string(output)?);
    } else {
        println!("{}", serde_json::to_string_pretty(output)?);
    }
    Ok(())
}

fn emit_thread_resolve(cli: &Cli, repo: &Repository, output: &ThreadResolveOutput) -> Result<()> {
    if should_output_json(cli, None) {
        write_command_json(
            output,
            output_is_compact(cli),
            NextActionValidationContext::new(&["thread", "resolve"], repo.capability()),
        )?;
    } else {
        println!("{}", output.operator.message);
        println!("Thread: {}", style::bold(&output.thread));
        if !output.operator.blockers.is_empty() {
            println!("{}", style::warn("Blockers:"));
            for blocker in &output.operator.blockers {
                println!("  - {}", style::warn(blocker));
            }
        }
        if !output.operator.warnings.is_empty() {
            println!("{}", style::warn("Reviewed:"));
            for warning in &output.operator.warnings {
                println!("  - {}", style::warn(warning));
            }
        }
        if let Some(next) = output
            .operator
            .recommended_action
            .as_ref()
            .or(output.operator.next_action.as_ref())
        {
            print_next(next);
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cli::commands::git_overlay_health::VerificationCheck;

    fn trust_state(verified: bool) -> RepositoryVerificationState {
        let check = VerificationCheck {
            name: "Mapping".to_string(),
            status: if verified { "clean" } else { "needs_import" }.to_string(),
            clean: verified,
            summary: if verified {
                "Git/Heddle mapping is clean"
            } else {
                "active Git branch has not been imported"
            }
            .to_string(),
            recommended_action: (!verified).then(|| "heddle adopt --ref main".to_string()),
            recommended_action_template: None,
            recovery_commands: if verified {
                Vec::new()
            } else {
                vec!["heddle adopt --ref main".to_string()]
            },
            recovery_action_templates: Vec::new(),
            details: std::collections::BTreeMap::new(),
        };
        let machine_contract_coverage =
            crate::cli::commands::git_overlay_health::machine_contract_coverage();
        RepositoryVerificationState {
            verified,
            status: if verified { "clean" } else { "needs_import" }.to_string(),
            repository_mode: "git-overlay".to_string(),
            heddle_initialized: true,
            git_branch: Some("main".to_string()),
            heddle_thread: Some("main".to_string()),
            worktree_dirty: false,
            worktree_state: "clean".to_string(),
            import_state: check.status.clone(),
            mapping_state: check.status.clone(),
            remote_drift: "clean".to_string(),
            active_operation: None,
            default_remote: None,
            clone_verification: "not_applicable".to_string(),
            machine_contract: crate::cli::commands::git_overlay_health::machine_contract_status(
                &machine_contract_coverage,
            )
            .to_string(),
            machine_contract_coverage,
            summary: check.summary.clone(),
            workflow_status: "clean".to_string(),
            workflow_summary: "no workflow attention needed".to_string(),
            recommended_action: check.recommended_action.clone().unwrap_or_default(),
            recommended_action_template: check.recommended_action_template.clone(),
            recovery_commands: check.recovery_commands.clone(),
            recovery_action_templates: check.recovery_action_templates.clone(),
            checks: vec![check],
        }
    }

    #[test]
    fn thread_resolve_reports_synced_only_when_repository_verification_is_clean() {
        let clean = thread_resolve_refresh_operator("feature/clean", &trust_state(true));
        assert_eq!(clean.status, "synced");
        assert_eq!(
            clean.recommended_action.as_deref(),
            Some("heddle land --thread feature/clean --no-push")
        );

        let blocked = thread_resolve_refresh_operator("feature/blocked", &trust_state(false));
        assert_eq!(blocked.status, "blocked");
        assert!(
            blocked
                .message
                .contains("repository verification is blocked"),
            "blocked message should name verification, got: {}",
            blocked.message
        );
        assert_eq!(
            blocked.recommended_action.as_deref(),
            Some("heddle adopt --ref main")
        );
        assert!(
            blocked
                .blockers
                .iter()
                .any(|blocker| blocker.contains("active Git branch has not been imported")),
            "verification blocker should be surfaced: {:?}",
            blocked.blockers
        );
    }

    #[test]
    fn thread_resolve_blockers_keep_local_recovery_ahead_of_remote_push() {
        let blockers = vec!["Thread still has merge conflicts".to_string()];
        let remote = GitRemoteTrackingStatus {
            branch: "main".to_string(),
            upstream: "origin/main".to_string(),
            ahead: 1,
            behind: 0,
            local_oid: None,
            upstream_oid: None,
            upstream_is_undone_checkpoint: false,
            message: "branch is ahead".to_string(),
            next_action: "heddle push".to_string(),
        };

        let action = thread_resolve_next_action(
            &blockers,
            None,
            Some(&remote),
            None,
            "heddle resolve --list",
        );

        assert_eq!(action.as_deref(), Some("heddle resolve --list"));
    }

    #[test]
    fn thread_resolve_clean_state_can_surface_remote_push() {
        let remote = GitRemoteTrackingStatus {
            branch: "main".to_string(),
            upstream: "origin/main".to_string(),
            ahead: 1,
            behind: 0,
            local_oid: None,
            upstream_oid: None,
            upstream_is_undone_checkpoint: false,
            message: "branch is ahead".to_string(),
            next_action: "heddle push".to_string(),
        };

        let action =
            thread_resolve_next_action(&[], None, Some(&remote), None, "heddle land --thread x");

        assert_eq!(action.as_deref(), Some("heddle push"));
    }

    #[test]
    fn empty_path_movement_refusals_map_to_typed_advice() {
        let split = map_thread_shaping_error(ThreadShapingError::NoPathsMatched(
            heddle_core::NoPathsMatchedDetails {
                action: "capture split",
                error: "No dirty paths matched the requested split prefixes",
                unsafe_condition: "the worktree has no dirty paths under the requested prefixes",
                would_change: "capture --split would not move any work into the target thread",
                primary_command: "heddle status",
            },
        ));
        let advice = split
            .downcast_ref::<RecoveryAdvice>()
            .expect("mapped error should carry RecoveryAdvice");
        assert_eq!(advice.kind, "no_paths_matched");
        assert_eq!(advice.primary_command, "heddle status");
        assert!(
            advice
                .to_string()
                .contains("Preserved: repository state was left unchanged"),
            "display should keep the uniform advice surface: {advice}"
        );

        let move_paths = map_thread_shaping_error(ThreadShapingError::NoPathsMatched(
            heddle_core::NoPathsMatchedDetails {
                action: "thread move",
                error: "No captured paths matched the requested prefixes",
                unsafe_condition:
                    "the source thread has no captured paths under the requested prefixes",
                would_change:
                    "thread move would not move any captured files into the target thread",
                primary_command: "heddle thread show",
            },
        ));
        let advice = move_paths
            .downcast_ref::<RecoveryAdvice>()
            .expect("mapped error should carry RecoveryAdvice");
        assert_eq!(advice.kind, "no_paths_matched");
        assert_eq!(advice.primary_command, "heddle thread show");
        assert!(
            advice.primary_hint().contains("heddle thread show"),
            "hint should name the inspection command: {}",
            advice.primary_hint()
        );
    }
}