heddle-cli 0.10.4

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
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
// SPDX-License-Identifier: Apache-2.0
//! CLI verification adapter: Machine-Contract catalog injection, RecoveryAdvice,
//! and thin wrappers around the single core proof owner.
//!
//! **Do not construct Repository Verification Health/State here.** Proof
//! construction lives in `heddle_core::status` / `heddle_core::verify`. This
//! module injects command-catalog coverage, builds refusal advice, and
//! formats setup guidance for text/render paths.

use std::{collections::BTreeSet, path::Path, sync::OnceLock};

// Re-exported for unit tests in operator/thread_shaping modules.
#[cfg(test)]
pub(crate) use heddle_core::VerificationCheck;
use heddle_core::status::next_action::{
    canonical_git_import_ref_command, canonical_git_repair_ref_preview_command,
    heddle_action as core_heddle_action, import_guidance_includes_active_branch,
    remote_tracking_next_action_for, remote_tracking_status,
};
pub(crate) use heddle_core::{
    ActionTemplate, MachineContractCoverage, MachineContractInput, PlainGitVerifyProbe,
    RepositoryVerificationCheck, RepositoryVerificationHealth, RepositoryVerificationState,
    repository_setup_guidance, verify::serialize_empty_action_as_null,
};
use objects::{object::ThreadName, worktree::WorktreeStatus};
use refs::Head;
use repo::{
    CommitGraphIndex, GitOverlayBranchTip, GitRemoteTrackingStatus, OperationKind, OperationScope,
    Repository,
};

use super::{
    advice::RecoveryAdvice,
    command_catalog::{
        ActionFields, build_command_catalog, heddle_action, recommended_action_template,
    },
    schemas::opaque_schema_verbs,
};

pub(crate) type PlainGitVerificationProbe = PlainGitVerifyProbe;

pub(crate) fn primary_recovery_command(health: &RepositoryVerificationHealth) -> Option<&str> {
    health.recovery_commands.first().map(String::as_str)
}

pub(crate) fn override_trust_recommended_action(
    trust: &mut RepositoryVerificationState,
    action: impl Into<String>,
) {
    let action = action.into();
    let action_fields = ActionFields::from_action(&action);
    trust.recommended_action_template = action_fields.template.clone();
    trust.recommended_action = action.clone();
    if let Some(check) = trust
        .checks
        .iter_mut()
        .find(|check| check.name == "Workflow")
    {
        check.recommended_action_template = action_fields.template;
        check.recommended_action = Some(action);
    }
}
pub(crate) fn trust_visible_worktree_status(
    repo: &Repository,
    trust: &RepositoryVerificationState,
) -> anyhow::Result<Option<WorktreeStatus>> {
    if matches!(
        trust.status.as_str(),
        "needs_import" | "needs_reconcile" | "git_branch_advanced"
    ) {
        return Ok(Some(
            repo.git_overlay_worktree_status()?.unwrap_or_default(),
        ));
    }
    Ok(None)
}

fn machine_contract_is_clean(coverage: &MachineContractCoverage) -> bool {
    coverage.verified_scope_json_commands_without_schema == 0
        && coverage.verified_scope_mutating_commands_without_schema == 0
        && coverage.verified_scope_json_commands_with_accepted_opaque_schema == 0
        && coverage.verified_scope_mutating_commands_with_accepted_opaque_schema == 0
        && coverage.unaccepted_opaque_schema_verbs_total == 0
}

pub(crate) fn machine_contract_status(coverage: &MachineContractCoverage) -> &'static str {
    if !machine_contract_is_clean(coverage) {
        return "schema_gaps";
    } else if coverage.undocumented_schema_verbs_total > 0 {
        return "available_with_doc_gaps";
    }
    "available"
}

/// CLI adapter: injects command-catalog Machine-Contract Proof into core's
/// single Repository Verification State owner.
pub(crate) fn build_repository_verification_state(
    repo: &Repository,
) -> RepositoryVerificationState {
    match heddle_core::verify::build_repository_verification_state_with_machine_contract(
        repo,
        &MachineContractInput::from_coverage(machine_contract_coverage()),
    ) {
        Ok(state) => state,
        Err(error) => degraded_repository_verification_state(repo, error.to_string()),
    }
}

/// Sub-phase timings for [`build_repository_verification_state_profiled`], in
/// milliseconds. Used by `adopt`'s `HEDDLE_PROFILE=1` instrumentation.
#[derive(Debug, Default, Clone, Copy)]
pub(crate) struct VerificationProfile {
    pub worktree_status_ms: u128,
    pub health_ms: u128,
    pub from_health_ms: u128,
}

/// Profiled adapter around the core verification owner. Classification matches
/// [`build_repository_verification_state`]; only wall-clock phase splits differ.
pub(crate) fn build_repository_verification_state_profiled(
    repo: &Repository,
) -> (RepositoryVerificationState, VerificationProfile) {
    let total_start = std::time::Instant::now();
    let worktree_status_start = std::time::Instant::now();
    let worktree_status = worktree_status_for_verification(repo);
    let worktree_status_ms = worktree_status_start.elapsed().as_millis();

    let health_start = std::time::Instant::now();
    let health = heddle_core::status::build_repository_verification_health_with_worktree_status(
        repo,
        &worktree_status,
    );
    let health_ms = health_start.elapsed().as_millis();

    let from_health_start = std::time::Instant::now();
    let state = heddle_core::verify::build_repository_verification_state_with_worktree_status_and_machine_contract(
        repo,
        health,
        &worktree_status,
        &MachineContractInput::from_coverage(machine_contract_coverage()),
    );
    let from_health_ms = from_health_start.elapsed().as_millis();
    let _ = total_start;

    (
        state,
        VerificationProfile {
            worktree_status_ms,
            health_ms,
            from_health_ms,
        },
    )
}

/// Core-owned verification state with a reused worktree-status `Result`.
pub(crate) fn build_repository_verification_state_with_worktree_status(
    repo: &Repository,
    worktree_status: &repo::Result<Option<WorktreeStatus>>,
) -> RepositoryVerificationState {
    let health = heddle_core::status::build_repository_verification_health_with_worktree_status(
        repo,
        worktree_status,
    );
    heddle_core::verify::build_repository_verification_state_with_worktree_status_and_machine_contract(
        repo,
        health,
        worktree_status,
        &MachineContractInput::from_coverage(machine_contract_coverage()),
    )
}

/// Core-owned health proof (CLI may inspect recovery commands for doctor text).
pub(crate) fn build_verification_health(repo: &Repository) -> RepositoryVerificationHealth {
    let worktree_status = worktree_status_for_verification(repo);
    heddle_core::status::build_repository_verification_health_with_worktree_status(
        repo,
        &worktree_status,
    )
}

/// Health proof reusing a caller's worktree-status `Result`.
///
/// Kept as the catalog-injection-free health adapter for hot paths that already
/// hold a worktree status `Result` (mirrors the state-with-worktree adapter).
#[allow(dead_code)]
pub(crate) fn build_verification_health_with_worktree_status(
    repo: &Repository,
    worktree_status: &repo::Result<Option<WorktreeStatus>>,
) -> RepositoryVerificationHealth {
    heddle_core::status::build_repository_verification_health_with_worktree_status(
        repo,
        worktree_status,
    )
}

fn worktree_status_for_verification(repo: &Repository) -> repo::Result<Option<WorktreeStatus>> {
    if repo.capability() == repo::RepositoryCapability::GitOverlay {
        repo.git_overlay_worktree_status()
    } else {
        let Some(state) = repo.current_state()? else {
            return Ok(Some(WorktreeStatus::default()));
        };
        let tree = repo.require_tree(&state.tree)?;
        repo.compare_worktree_cached(&tree).map(Some)
    }
}

fn degraded_repository_verification_state(
    repo: &Repository,
    summary: String,
) -> RepositoryVerificationState {
    let coverage = machine_contract_coverage();
    RepositoryVerificationState {
        verified: false,
        status: "degraded".to_string(),
        repository_mode: repo.capability_label().to_string(),
        heddle_initialized: true,
        git_branch: repo.git_overlay_current_branch().ok().flatten(),
        heddle_thread: repo.current_lane().ok().flatten(),
        worktree_dirty: false,
        worktree_state: "not_checked".to_string(),
        import_state: "not_checked".to_string(),
        mapping_state: "not_checked".to_string(),
        remote_drift: "not_checked".to_string(),
        active_operation: None,
        default_remote: None,
        clone_verification: "not_checked".to_string(),
        machine_contract: machine_contract_status(&coverage).to_string(),
        machine_contract_coverage: coverage,
        workflow_status: "not_checked".to_string(),
        workflow_summary: "workflow readiness is checked after repository verification is restored"
            .to_string(),
        summary,
        recommended_action: "heddle doctor".to_string(),
        recommended_action_template: action_template("heddle doctor"),
        recovery_commands: vec!["heddle doctor".to_string()],
        recovery_action_templates: action_templates(&["heddle doctor".to_string()]),
        checks: Vec::new(),
    }
}
/// Sub-phase timings for [`build_repository_verification_state_profiled`], in
/// milliseconds. Used by `adopt`'s `HEDDLE_PROFILE=1` instrumentation to attribute
/// Sub-phase timings for [`build_repository_verification_state_profiled`], in
/// milliseconds. Used by `adopt`'s `HEDDLE_PROFILE=1` instrumentation to attribute
/// the post-import verification cost across its three phases.
/// [`build_repository_verification_state`] that additionally reports per-phase
/// timings. Classification is identical; the only difference is the elapsed
/// [`build_repository_verification_state`] that additionally reports per-phase
/// timings. Classification is identical; the only difference is the elapsed
/// clocks around each phase.
/// Verification-state build that reuses an already-computed git-overlay worktree
/// status instead of re-walking + re-SHA-1ing every tracked file. Used by the
/// Verification-state build that reuses an already-computed git-overlay worktree
/// status instead of re-walking + re-SHA-1ing every tracked file. Used by the
/// `checkpoint` hot path, where the same status would otherwise be recomputed
/// Verification-state build that reuses an already-computed git-overlay worktree
/// status instead of re-walking + re-SHA-1ing every tracked file. Used by the
/// `checkpoint` hot path, where the same status would otherwise be recomputed
/// across the preflight, the verification preflight, and the output build. The
/// Verification-state build that reuses an already-computed git-overlay worktree
/// status instead of re-walking + re-SHA-1ing every tracked file. Used by the
/// `checkpoint` hot path, where the same status would otherwise be recomputed
/// across the preflight, the verification preflight, and the output build. The
/// classification is byte-identical to [`build_repository_verification_state`]
/// Verification-state build that reuses an already-computed git-overlay worktree
/// status instead of re-walking + re-SHA-1ing every tracked file. Used by the
/// `checkpoint` hot path, where the same status would otherwise be recomputed
/// across the preflight, the verification preflight, and the output build. The
/// classification is byte-identical to [`build_repository_verification_state`]
/// because it threads the exact `Result` from `git_overlay_worktree_status()`.
pub(crate) fn unimported_git_history_advice(
    repo: &Repository,
    action: &str,
) -> anyhow::Result<Option<RecoveryAdvice>> {
    if repo.capability() != repo::RepositoryCapability::GitOverlay {
        return Ok(None);
    }

    let Some(hint) = repo.git_import_guidance()? else {
        return Ok(None);
    };
    if !import_guidance_includes_active_branch(&hint) {
        return Ok(None);
    }
    let missing = hint.missing_branches;
    let primary_command = hint.recommended_command;
    let branch_summary = crate::cli::render::preview_list(&missing, missing.len());
    Ok(Some(RecoveryAdvice::safety_refusal(
        "git_history_needs_import",
        format!("Refusing to {action}: Git history has not been imported into Heddle"),
        format!("Run `{primary_command}` before retrying `heddle {action}`."),
        format!("Git branch(es) waiting for Heddle import: {branch_summary}"),
        format!(
            "{action} would write new Heddle state before Heddle has adopted the existing Git history"
        ),
        "Git refs, Heddle refs, and worktree files were left unchanged",
        primary_command.clone(),
        vec![primary_command],
    )))
}
pub(crate) fn raw_git_operation_mutation_advice(
    repo: &Repository,
    action: &str,
) -> anyhow::Result<Option<RecoveryAdvice>> {
    let Some(operation) = repo.operation_status()? else {
        return Ok(None);
    };
    if !matches!(operation.scope, OperationScope::Git) {
        return Ok(None);
    }
    let primary_command = "heddle verify".to_string();
    let hint = raw_git_operation_recovery_hint(&operation.kind, &primary_command, action);
    Ok(Some(RecoveryAdvice::safety_refusal(
        "raw_git_operation_in_progress",
        format!(
            "Refusing to {action}: an externally-started Git {} is in progress",
            operation.kind
        ),
        hint,
        format!(
            "Git {} is {}; Heddle cannot safely turn sequencer state into a saved change inside the no-git runtime",
            operation.kind, operation.state
        ),
        format!(
            "{action} would capture worktree/index contents while Git still has unresolved sequencer metadata"
        ),
        "Git refs, Git sequencer files, Heddle refs, and worktree files were left unchanged",
        primary_command.clone(),
        vec![primary_command],
    )))
}
fn raw_git_operation_recovery_hint(
    kind: &OperationKind,
    primary_command: &str,
    action: &str,
) -> String {
    format!(
        "Inspect with `{primary_command}`. Heddle did not start this raw Git {kind}, so finish or abort it with the Git-compatible tool that started it, then run `heddle verify` for the exact adoption command before retrying `heddle {action}`."
    )
}
pub(crate) fn verification_blocking_mutation_advice(
    repo: &Repository,
    action: &str,
) -> anyhow::Result<Option<RecoveryAdvice>> {
    verification_blocking_mutation_advice_with_trust(
        repo,
        action,
        build_repository_verification_state(repo),
    )
}
fn verification_blocking_mutation_advice_with_trust(
    repo: &Repository,
    action: &str,
    trust: RepositoryVerificationState,
) -> anyhow::Result<Option<RecoveryAdvice>> {
    if trust.status != "needs_reconcile" {
        return Ok(None);
    }
    if uncheckpointed_heddle_state_is_ahead_of_git(repo)? {
        return Ok(None);
    }
    Ok(Some(repository_verification_blocked_advice(
        "repository_verification_blocked",
        format!(
            "Refusing to {action}: repository verification is blocked ({})",
            trust.status
        ),
        format!("retrying `heddle {action}`"),
        &trust,
        format!(
            "repository verification status is {}: {}",
            trust.status, trust.summary
        ),
        format!("{action} would write new Heddle or Git state while Git and Heddle disagree"),
        "Git refs, Heddle refs, Git checkpoint metadata, and worktree files were left unchanged",
        None,
    )))
}
fn uncheckpointed_heddle_state_is_ahead_of_git(repo: &Repository) -> anyhow::Result<bool> {
    let Some(tip) = current_branch_tip(repo)? else {
        return Ok(false);
    };
    let Some(mapped) = tip.mapped_state else {
        return Ok(false);
    };
    let Some(current) = repo.current_state()? else {
        return Ok(false);
    };
    if mapped == current.state_id {
        return Ok(false);
    }
    if mapped_change_relation(repo, &mapped, &current.state_id) != "git_behind_heddle" {
        return Ok(false);
    }
    Ok(repo
        .latest_git_checkpoint_for_state(&current.state_id)?
        .is_none())
}

fn current_branch_tip(repo: &Repository) -> anyhow::Result<Option<GitOverlayBranchTip>> {
    let Some(branch) = repo.git_overlay_current_branch()? else {
        return Ok(None);
    };
    repo.git_overlay_branch_tip(&branch).map_err(Into::into)
}

fn mapped_change_relation(
    repo: &Repository,
    git_mapped: &objects::object::StateId,
    heddle_current: &objects::object::StateId,
) -> &'static str {
    let mut graph = CommitGraphIndex::new(repo);
    let git_is_ancestor = graph
        .is_ancestor(git_mapped, heddle_current)
        .unwrap_or(false);
    let heddle_is_ancestor = graph
        .is_ancestor(heddle_current, git_mapped)
        .unwrap_or(false);
    match (git_is_ancestor, heddle_is_ancestor) {
        (true, false) => "git_behind_heddle",
        (false, true) => "git_ahead_of_heddle",
        (true, true) => "same",
        (false, false) => "diverged",
    }
}
#[derive(Debug, Clone, Copy)]
pub(crate) struct GitOverlayMutationPreflight {
    pub check_detached_head: bool,
    pub check_unimported_git_history: bool,
    pub check_raw_git_operation: bool,
    pub check_verification: bool,
}
impl GitOverlayMutationPreflight {
    pub(crate) fn capture_like() -> Self {
        Self {
            check_detached_head: false,
            check_unimported_git_history: true,
            check_raw_git_operation: true,
            check_verification: true,
        }
    }

    pub(crate) fn checkpoint_like() -> Self {
        Self {
            check_detached_head: true,
            check_unimported_git_history: true,
            check_raw_git_operation: true,
            check_verification: true,
        }
    }
}
pub(crate) fn plain_git_mutation_preflight_advice(
    start: &std::path::Path,
    action: &str,
) -> anyhow::Result<Option<RecoveryAdvice>> {
    Ok(build_plain_git_verification_probe(start)?
        .map(|probe| plain_git_mutation_advice(&probe, action)))
}
pub(crate) fn plain_git_setup_advice(
    probe: &PlainGitVerificationProbe,
    command: &str,
    requested_target: Option<&str>,
) -> RecoveryAdvice {
    let primary = if probe.trust.recommended_action.is_empty() {
        "heddle init".to_string()
    } else {
        probe.trust.recommended_action.clone()
    };
    let mut recovery_commands = probe.trust.recovery_commands.clone();
    if recovery_commands.is_empty() {
        recovery_commands.push(primary.clone());
    }
    let retry = requested_target
        .map(|target| format!("heddle {command} {target}"))
        .unwrap_or_else(|| format!("heddle {command}"));
    let mut advice = RecoveryAdvice::safety_refusal(
        "plain_git_needs_init",
        "Heddle is not initialized for this Git repo",
        format!("Run `{primary}` to create the Heddle sidecar, then retry `{retry}`."),
        format!(
            "plain Git repository at '{}' has no .heddle metadata",
            probe.root.display()
        ),
        format!(
            "`heddle {command}` needs Heddle history before it can inspect Heddle states without guessing"
        ),
        "observe-only command; Heddle metadata, Git refs, index, and worktree files were left unchanged",
        primary,
        recovery_commands,
    );
    advice.extra_json_fields.insert(
        "repository_capability".to_string(),
        serde_json::Value::String("plain-git".to_string()),
    );
    advice.extra_json_fields.insert(
        "storage_model".to_string(),
        serde_json::Value::String("git".to_string()),
    );
    advice.extra_json_fields.insert(
        "requested_command".to_string(),
        serde_json::Value::String(command.to_string()),
    );
    if let Some(target) = requested_target {
        advice.extra_json_fields.insert(
            "requested_target".to_string(),
            serde_json::Value::String(target.to_string()),
        );
    }
    if let Ok(verification) = serde_json::to_value(&probe.trust) {
        advice
            .extra_json_fields
            .insert("verification".to_string(), verification);
    }
    advice
}
pub(crate) fn git_overlay_mutation_preflight_advice(
    repo: &Repository,
    action: &str,
    preflight: GitOverlayMutationPreflight,
) -> anyhow::Result<Option<RecoveryAdvice>> {
    git_overlay_mutation_preflight_advice_inner(repo, action, preflight, None)
}
/// `checkpoint` hot-path variant of [`git_overlay_mutation_preflight_advice`]
/// that reuses an already-computed git-overlay worktree status for the
/// `check_verification` branch instead of re-walking the worktree. All other
/// branches and the resulting advice are identical.
pub(crate) fn git_overlay_mutation_preflight_advice_with_worktree_status(
    repo: &Repository,
    action: &str,
    preflight: GitOverlayMutationPreflight,
    worktree_status: &repo::Result<Option<WorktreeStatus>>,
) -> anyhow::Result<Option<RecoveryAdvice>> {
    git_overlay_mutation_preflight_advice_inner(repo, action, preflight, Some(worktree_status))
}
fn git_overlay_mutation_preflight_advice_inner(
    repo: &Repository,
    action: &str,
    preflight: GitOverlayMutationPreflight,
    worktree_status: Option<&repo::Result<Option<WorktreeStatus>>>,
) -> anyhow::Result<Option<RecoveryAdvice>> {
    if repo.capability() != repo::RepositoryCapability::GitOverlay {
        return Ok(None);
    }
    if preflight.check_detached_head && repo.git_overlay_head_is_detached()? {
        return Ok(Some(detached_git_head_mutation_advice(repo, action)));
    }
    if preflight.check_unimported_git_history
        && let Some(advice) = unimported_git_history_advice(repo, action)?
    {
        return Ok(Some(advice));
    }
    if preflight.check_raw_git_operation
        && let Some(advice) = raw_git_operation_mutation_advice(repo, action)?
    {
        return Ok(Some(advice));
    }
    if preflight.check_verification {
        let advice = match worktree_status {
            Some(status) => verification_blocking_mutation_advice_with_trust(
                repo,
                action,
                build_repository_verification_state_with_worktree_status(repo, status),
            )?,
            None => verification_blocking_mutation_advice(repo, action)?,
        };
        if let Some(advice) = advice {
            return Ok(Some(advice));
        }
    }
    Ok(None)
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn repository_verification_blocked_advice(
    kind: &'static str,
    error: impl Into<String>,
    retry_context: impl Into<String>,
    trust: &RepositoryVerificationState,
    unsafe_condition: impl Into<String>,
    would_change: impl Into<String>,
    preserved: impl Into<String>,
    primary_override: Option<String>,
) -> RecoveryAdvice {
    let primary_command =
        primary_override.unwrap_or_else(|| repository_verification_primary_command(trust));
    let recovery_commands = repository_verification_recovery_commands(trust, &primary_command);
    RecoveryAdvice::safety_refusal(
        kind,
        error,
        format!("Run `{}` before {}.", primary_command, retry_context.into()),
        unsafe_condition,
        would_change,
        preserved,
        primary_command,
        recovery_commands,
    )
}
pub(crate) fn repository_verification_primary_command(
    trust: &RepositoryVerificationState,
) -> String {
    if trust.recommended_action.trim().is_empty() {
        "heddle verify".to_string()
    } else {
        trust.recommended_action.clone()
    }
}
pub(crate) fn repository_verification_blockers(trust: &RepositoryVerificationState) -> Vec<String> {
    trust
        .checks
        .iter()
        .filter(|check| !check.clean)
        .map(|check| format!("{}: {}", check.name, check.summary))
        .collect()
}
pub(crate) fn repository_verification_recovery_commands(
    trust: &RepositoryVerificationState,
    primary_command: &str,
) -> Vec<String> {
    if primary_command != trust.recommended_action && !trust.recommended_action.trim().is_empty() {
        vec![primary_command.to_string(), "heddle verify".to_string()]
    } else if trust.recovery_commands.is_empty() {
        vec![primary_command.to_string()]
    } else {
        trust.recovery_commands.clone()
    }
}
pub(crate) fn plain_git_mutation_advice(
    probe: &PlainGitVerificationProbe,
    action: &str,
) -> RecoveryAdvice {
    let primary_command = if probe.trust.recommended_action.trim().is_empty() {
        "heddle init".to_string()
    } else {
        probe.trust.recommended_action.clone()
    };
    let recovery_commands = if probe.trust.recovery_commands.is_empty() {
        vec![primary_command.clone()]
    } else {
        probe.trust.recovery_commands.clone()
    };
    let dirty_detail = if probe.changes.is_clean() {
        "Git worktree is clean".to_string()
    } else {
        let mut paths = Vec::new();
        paths.extend(
            probe
                .changes
                .modified
                .iter()
                .map(|path| path.display().to_string()),
        );
        paths.extend(
            probe
                .changes
                .added
                .iter()
                .map(|path| path.display().to_string()),
        );
        paths.extend(
            probe
                .changes
                .deleted
                .iter()
                .map(|path| path.display().to_string()),
        );
        format!(
            "Git worktree has {} dirty path(s): {}",
            paths.len(),
            crate::cli::render::preview_list(&paths, paths.len())
        )
    };
    RecoveryAdvice::safety_refusal(
        "git_repo_needs_init",
        format!("Refusing to {action}: Heddle is not initialized for this Git repository"),
        format!("Run `{primary_command}` before retrying `heddle {action}`."),
        format!(
            "plain Git repository at {} has no .heddle metadata; {}",
            probe.root.display(),
            dirty_detail
        ),
        format!("{action} needs Heddle metadata before it can safely write Heddle state"),
        "Git refs, Heddle metadata, and worktree files were left unchanged",
        primary_command,
        recovery_commands,
    )
}
pub(crate) fn detached_git_head_mutation_advice(repo: &Repository, action: &str) -> RecoveryAdvice {
    let primary_command = detached_head_primary_recovery(repo);
    let needs_selection = primary_command == "heddle thread list";
    let hint = if needs_selection {
        format!(
            "Inspect managed threads with `{primary_command}`, then attach this checkout with `heddle thread switch <thread>` before retrying `heddle {action}`. Heddle could not safely infer which thread owns the detached commit."
        )
    } else {
        format!("Run `{primary_command}` before retrying `heddle {action}`.")
    };
    let recovery_commands = if needs_selection {
        vec![
            primary_command.clone(),
            "heddle thread switch <thread>".to_string(),
        ]
    } else {
        vec![primary_command.clone()]
    };
    RecoveryAdvice::safety_refusal(
        "git_head_detached",
        format!("Refusing to {action}: Git HEAD is detached"),
        hint,
        "Git HEAD points directly to a commit instead of an attached branch",
        format!(
            "{action} would need to write a Git checkpoint through a branch and could reattach or advance the wrong ref"
        ),
        "Git refs, Heddle refs, Git checkpoints, and worktree files were left unchanged",
        primary_command,
        recovery_commands,
    )
}
fn detached_head_primary_recovery(repo: &Repository) -> String {
    match repo.refs().read_head() {
        Ok(Head::Attached { thread })
            if !thread.trim().is_empty()
                && repo.refs().get_thread(&thread).ok().flatten().is_some() =>
        {
            // `switch` takes the thread as a positional; a leading-dash id needs
            // the `--` separator so clap binds it as a value, not a flag.
            // (heddle#464 close-the-class.)
            return if thread.starts_with('-') {
                heddle_action(["thread", "switch", "--", thread.as_str()])
            } else {
                heddle_action(["thread", "switch", thread.as_str()])
            };
        }
        _ => {}
    }
    if let Ok(Some(detached_commit)) = repo.git_overlay_detached_head_commit()
        && let Ok(branch_tips) = repo.git_overlay_branch_tips()
        && let Some(tip) = branch_tips
            .iter()
            .filter(|tip| tip.history_imported)
            .find(|tip| {
                tip.git_commit == detached_commit
                    && repo
                        .refs()
                        .get_thread(&ThreadName::new(&tip.branch))
                        .ok()
                        .flatten()
                        .is_some()
            })
    {
        return heddle_action(["thread", "switch", tip.branch.as_str()]);
    }
    "heddle thread list".to_string()
}
pub(crate) fn build_plain_git_verification_probe(
    start: &Path,
) -> anyhow::Result<Option<PlainGitVerificationProbe>> {
    Ok(
        heddle_core::verify::build_plain_git_verification_probe_with_machine_contract(
            start,
            &MachineContractInput::from_coverage(machine_contract_coverage()),
        )?,
    )
}
pub(crate) fn action_template(action: &str) -> Option<ActionTemplate> {
    recommended_action_template(action)
}
pub(crate) fn action_templates(commands: &[String]) -> Vec<ActionTemplate> {
    commands
        .iter()
        .filter_map(|command| action_template(command))
        .collect()
}
pub(crate) fn machine_contract_coverage() -> MachineContractCoverage {
    static COVERAGE: OnceLock<MachineContractCoverage> = OnceLock::new();
    COVERAGE
        .get_or_init(build_machine_contract_coverage)
        .clone()
}

fn build_machine_contract_coverage() -> MachineContractCoverage {
    const EXAMPLE_LIMIT: usize = 8;
    let catalog = build_command_catalog();
    let commands = catalog.commands;
    let mut json_commands_total: usize = 0;
    let mut json_commands_with_schema: usize = 0;
    let mut json_commands_with_accepted_opaque_schema: usize = 0;
    let mut verified_scope_json_commands_total: usize = 0;
    let mut verified_scope_json_commands_with_schema: usize = 0;
    let mut verified_scope_json_commands_with_accepted_opaque_schema: usize = 0;
    let mut catalog_mutating_commands_total: usize = 0;
    let mut mutating_commands_total: usize = 0;
    let mut mutating_commands_with_schema: usize = 0;
    let mut mutating_commands_with_accepted_opaque_schema: usize = 0;
    let mut verified_scope_mutating_commands_total: usize = 0;
    let mut verified_scope_mutating_commands_with_schema: usize = 0;
    let mut verified_scope_mutating_commands_with_accepted_opaque_schema: usize = 0;
    let mut schema_verbs = BTreeSet::new();
    let mut documented_schema_verbs = BTreeSet::new();
    let opaque_schema_verb_set: BTreeSet<&str> = opaque_schema_verbs().iter().copied().collect();
    let mut supports_op_id_total: usize = 0;
    let mut jsonl_commands_total: usize = 0;
    let mut missing_schema_examples = Vec::new();
    let mut missing_mutating_schema_examples = Vec::new();
    let mut verified_scope_missing_schema_examples = Vec::new();
    let mut verified_scope_accepted_opaque_schema_examples = Vec::new();
    let mut advanced_scope_accepted_opaque_schema_examples = Vec::new();
    let mut accepted_opaque_schema_examples = Vec::new();

    for command in &commands {
        let is_verified_scope = machine_contract_verified_scope(command);
        let has_concrete_schema = command
            .schema_verbs
            .iter()
            .any(|verb| !opaque_schema_verb_set.contains(verb.as_str()));
        let has_accepted_opaque_schema = command
            .schema_verbs
            .iter()
            .any(|verb| opaque_schema_verb_set.contains(verb.as_str()));
        if command.mutates {
            catalog_mutating_commands_total += 1;
        }
        if command.supports_json {
            json_commands_total += 1;
            if has_concrete_schema {
                json_commands_with_schema += 1;
            } else if has_accepted_opaque_schema {
                json_commands_with_accepted_opaque_schema += 1;
                if accepted_opaque_schema_examples.len() < EXAMPLE_LIMIT {
                    accepted_opaque_schema_examples.push(command.display.clone());
                }
                if !is_verified_scope
                    && advanced_scope_accepted_opaque_schema_examples.len() < EXAMPLE_LIMIT
                {
                    advanced_scope_accepted_opaque_schema_examples.push(command.display.clone());
                }
            } else if missing_schema_examples.len() < EXAMPLE_LIMIT {
                missing_schema_examples.push(command.display.clone());
            }
            if is_verified_scope {
                verified_scope_json_commands_total += 1;
                if has_concrete_schema {
                    verified_scope_json_commands_with_schema += 1;
                } else if has_accepted_opaque_schema {
                    verified_scope_json_commands_with_accepted_opaque_schema += 1;
                    if verified_scope_accepted_opaque_schema_examples.len() < EXAMPLE_LIMIT {
                        verified_scope_accepted_opaque_schema_examples
                            .push(command.display.clone());
                    }
                } else if verified_scope_missing_schema_examples.len() < EXAMPLE_LIMIT {
                    verified_scope_missing_schema_examples.push(command.display.clone());
                }
            }
        }
        if command.mutates && command.supports_json {
            mutating_commands_total += 1;
            if has_concrete_schema {
                mutating_commands_with_schema += 1;
            } else if has_accepted_opaque_schema {
                mutating_commands_with_accepted_opaque_schema += 1;
            } else if missing_mutating_schema_examples.len() < EXAMPLE_LIMIT {
                missing_mutating_schema_examples.push(command.display.clone());
            }
            if is_verified_scope {
                verified_scope_mutating_commands_total += 1;
                if has_concrete_schema {
                    verified_scope_mutating_commands_with_schema += 1;
                } else if has_accepted_opaque_schema {
                    verified_scope_mutating_commands_with_accepted_opaque_schema += 1;
                }
            }
        }
        if command.supports_op_id {
            supports_op_id_total += 1;
        }
        if command.json_kind == "jsonl" || command.json_kind == "json_or_jsonl" {
            jsonl_commands_total += 1;
        }
        schema_verbs.extend(command.schema_verbs.iter().map(String::as_str));
        documented_schema_verbs.extend(command.documented_schema_verbs.iter().map(String::as_str));
    }
    schema_verbs.insert("error");
    documented_schema_verbs.insert("error");

    let json_commands_without_schema = json_commands_total
        .saturating_sub(json_commands_with_schema)
        .saturating_sub(json_commands_with_accepted_opaque_schema);
    let mutating_commands_without_schema = mutating_commands_total
        .saturating_sub(mutating_commands_with_schema)
        .saturating_sub(mutating_commands_with_accepted_opaque_schema);
    let verified_scope_json_commands_without_schema = verified_scope_json_commands_total
        .saturating_sub(verified_scope_json_commands_with_schema)
        .saturating_sub(verified_scope_json_commands_with_accepted_opaque_schema);
    let verified_scope_mutating_commands_without_schema = verified_scope_mutating_commands_total
        .saturating_sub(verified_scope_mutating_commands_with_schema)
        .saturating_sub(verified_scope_mutating_commands_with_accepted_opaque_schema);
    let advanced_scope_json_commands_total =
        json_commands_total.saturating_sub(verified_scope_json_commands_total);
    let advanced_scope_json_commands_with_accepted_opaque_schema =
        json_commands_with_accepted_opaque_schema
            .saturating_sub(verified_scope_json_commands_with_accepted_opaque_schema);
    let advanced_scope_mutating_commands_total =
        mutating_commands_total.saturating_sub(verified_scope_mutating_commands_total);
    let advanced_scope_mutating_commands_with_accepted_opaque_schema =
        mutating_commands_with_accepted_opaque_schema
            .saturating_sub(verified_scope_mutating_commands_with_accepted_opaque_schema);
    let undocumented_schema_examples: Vec<String> = schema_verbs
        .difference(&documented_schema_verbs)
        .take(EXAMPLE_LIMIT)
        .map(|verb| (*verb).to_string())
        .collect();
    let accepted_opaque_schema_verbs: BTreeSet<&str> = schema_verbs
        .intersection(&opaque_schema_verb_set)
        .copied()
        .collect();
    let schema_verbs_total = schema_verbs.len();
    let documented_schema_verbs_total = documented_schema_verbs.len();
    let undocumented_schema_verbs_total = schema_verbs.difference(&documented_schema_verbs).count();
    let opaque_schema_verbs_total = accepted_opaque_schema_verbs.len();
    let accepted_opaque_schema_verbs_total = accepted_opaque_schema_verbs.len();
    let unaccepted_opaque_schema_verbs_total = 0;
    let unaccepted_opaque_schema_examples = Vec::new();
    let status = if verified_scope_json_commands_without_schema == 0
        && verified_scope_mutating_commands_without_schema == 0
        && verified_scope_json_commands_with_accepted_opaque_schema == 0
        && verified_scope_mutating_commands_with_accepted_opaque_schema == 0
        && undocumented_schema_verbs_total == 0
    {
        "available".to_string()
    } else if verified_scope_json_commands_without_schema == 0
        && verified_scope_mutating_commands_without_schema == 0
        && undocumented_schema_verbs_total == 0
        && unaccepted_opaque_schema_verbs_total == 0
    {
        "available_with_opaque_schemas".to_string()
    } else if verified_scope_json_commands_without_schema == 0
        && verified_scope_mutating_commands_without_schema == 0
        && unaccepted_opaque_schema_verbs_total == 0
    {
        "available_with_doc_gaps".to_string()
    } else {
        "available_with_schema_gaps".to_string()
    };
    let summary = if status == "available" {
        if accepted_opaque_schema_verbs_total == 0 {
            format!(
                "{} command(s), {} JSON command(s), verified everyday/agent machine surface has concrete schemas",
                commands.len(),
                json_commands_total
            )
        } else {
            format!(
                "{} command(s), {} JSON command(s), {} mutating command(s), {} mutating JSON command(s); verified everyday/agent machine surface has {} concrete schema-backed JSON command(s); advanced/internal/admin surfaces carry {} accepted opaque schema(s) outside clean verification",
                commands.len(),
                json_commands_total,
                catalog_mutating_commands_total,
                mutating_commands_total,
                verified_scope_json_commands_with_schema,
                accepted_opaque_schema_verbs_total
            )
        }
    } else if status == "available_with_opaque_schemas" {
        format!(
            "{} command(s), {} JSON command(s), verified everyday/agent machine surface has {} concrete schema-backed and {} accepted opaque schema-backed command(s)",
            commands.len(),
            json_commands_total,
            verified_scope_json_commands_with_schema,
            verified_scope_json_commands_with_accepted_opaque_schema
        )
    } else if status == "available_with_doc_gaps" {
        format!(
            "{} command(s), {} JSON command(s), {} concrete schema-backed and {} accepted opaque; {} runtime schema verb(s) need documented samples",
            commands.len(),
            json_commands_total,
            json_commands_with_schema,
            json_commands_with_accepted_opaque_schema,
            undocumented_schema_verbs_total
        )
    } else {
        format!(
            "{} command(s), {} JSON command(s), {} concrete schema-backed, {} accepted opaque, {} missing schemas ({} mutating)",
            commands.len(),
            json_commands_total,
            json_commands_with_schema,
            json_commands_with_accepted_opaque_schema,
            json_commands_without_schema,
            mutating_commands_without_schema
        )
    };

    MachineContractCoverage {
        status,
        verified_scope: "everyday_and_agent".to_string(),
        advanced_scope: "advanced_internal_admin".to_string(),
        summary,
        catalog_commands_total: commands.len(),
        catalog_mutating_commands_total,
        json_commands_total,
        json_mutating_commands_total: mutating_commands_total,
        json_commands_with_schema,
        json_commands_with_accepted_opaque_schema,
        json_commands_without_schema,
        verified_scope_json_commands_total,
        verified_scope_json_commands_with_schema,
        verified_scope_json_commands_with_accepted_opaque_schema,
        verified_scope_json_commands_without_schema,
        advanced_scope_json_commands_total,
        advanced_scope_json_commands_with_accepted_opaque_schema,
        mutating_commands_total,
        mutating_commands_with_schema,
        mutating_commands_with_accepted_opaque_schema,
        mutating_commands_without_schema,
        verified_scope_mutating_commands_total,
        verified_scope_mutating_commands_with_schema,
        verified_scope_mutating_commands_with_accepted_opaque_schema,
        verified_scope_mutating_commands_without_schema,
        advanced_scope_mutating_commands_total,
        advanced_scope_mutating_commands_with_accepted_opaque_schema,
        schema_verbs_total,
        documented_schema_verbs_total,
        undocumented_schema_verbs_total,
        opaque_schema_verbs_total,
        accepted_opaque_schema_verbs_total,
        unaccepted_opaque_schema_verbs_total,
        supports_op_id_total,
        jsonl_commands_total,
        missing_schema_examples,
        missing_mutating_schema_examples,
        verified_scope_missing_schema_examples,
        verified_scope_accepted_opaque_schema_examples,
        advanced_scope_accepted_opaque_schema_examples,
        accepted_opaque_schema_examples,
        unaccepted_opaque_schema_examples,
        undocumented_schema_examples,
    }
}
fn machine_contract_verified_scope(command: &super::command_catalog::CommandCatalogEntry) -> bool {
    command.help_visibility == "everyday"
        || matches!(
            command.path.first().map(String::as_str),
            Some("agent" | "schemas")
        )
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct RemoteDriftDecision {
    pub status: &'static str,
    pub verified_as_clean: bool,
    pub primary_action: Option<String>,
    pub recovery_commands: Vec<String>,
    pub requires_clean_worktree: bool,
}
pub(crate) fn remote_drift_decision(
    repo: &Repository,
    remote: &GitRemoteTrackingStatus,
) -> RemoteDriftDecision {
    let status = remote_tracking_status(remote);
    match status {
        "clean" => RemoteDriftDecision {
            status,
            verified_as_clean: true,
            primary_action: None,
            recovery_commands: Vec::new(),
            requires_clean_worktree: false,
        },
        "remote_untracked" => RemoteDriftDecision {
            status,
            verified_as_clean: true,
            primary_action: remote_tracking_next_action_for(remote, repo.source_authority()),
            recovery_commands: Vec::new(),
            requires_clean_worktree: false,
        },
        "remote_ahead" => RemoteDriftDecision {
            status,
            verified_as_clean: true,
            primary_action: remote_tracking_next_action_for(remote, repo.source_authority()),
            recovery_commands: Vec::new(),
            requires_clean_worktree: false,
        },
        "remote_contains_undone_checkpoint" => RemoteDriftDecision {
            status,
            verified_as_clean: false,
            primary_action: remote_tracking_next_action_for(remote, repo.source_authority()),
            recovery_commands: vec![
                remote_tracking_next_action_for(remote, repo.source_authority())
                    .expect("undone checkpoint has a source recovery action"),
                core_heddle_action(["undo", "--redo"]),
            ],
            requires_clean_worktree: true,
        },
        "remote_behind" => RemoteDriftDecision {
            status,
            verified_as_clean: false,
            primary_action: remote_tracking_next_action_for(remote, repo.source_authority()),
            recovery_commands: remote_tracking_next_action_for(remote, repo.source_authority())
                .into_iter()
                .collect(),
            requires_clean_worktree: true,
        },
        "remote_diverged" => {
            let upstream = remote.upstream.trim();
            if upstream.is_empty() {
                return RemoteDriftDecision {
                    status,
                    verified_as_clean: false,
                    primary_action: Some("heddle remote list".to_string()),
                    recovery_commands: vec![
                        "heddle remote list".to_string(),
                        "heddle pull <remote> --thread <thread>".to_string(),
                    ],
                    requires_clean_worktree: false,
                };
            }
            let import = canonical_git_import_ref_command(upstream);
            let reconcile = canonical_git_repair_ref_preview_command(None, upstream);
            let imported = upstream_thread_matches_current_git_tip(repo, upstream);
            RemoteDriftDecision {
                status,
                verified_as_clean: false,
                primary_action: Some(if imported {
                    reconcile.clone()
                } else {
                    import.clone()
                }),
                recovery_commands: if imported {
                    vec![reconcile]
                } else {
                    vec![import, reconcile]
                },
                requires_clean_worktree: false,
            }
        }
        _ => RemoteDriftDecision {
            status,
            verified_as_clean: false,
            primary_action: Some("heddle verify".to_string()),
            recovery_commands: vec!["heddle verify".to_string()],
            requires_clean_worktree: false,
        },
    }
}
fn upstream_thread_matches_current_git_tip(repo: &Repository, upstream: &str) -> bool {
    let Some(thread_tip) = repo
        .refs()
        .get_thread(&ThreadName::new(upstream))
        .ok()
        .flatten()
    else {
        return false;
    };
    repo.git_overlay_mapped_state_for_branch(upstream)
        .or(Ok(None))
        .and_then(|mapped| {
            if mapped.is_some() {
                Ok(mapped)
            } else {
                repo.git_overlay_mapped_state_for_remote_tracking_ref(upstream)
            }
        })
        .ok()
        .flatten()
        .is_some_and(|mapped_tip| mapped_tip == thread_tip)
}
pub(crate) fn remote_drift_primary_action(repo: &Repository) -> Option<String> {
    repo.git_remote_tracking_status()
        .ok()
        .flatten()
        .and_then(|remote| remote_drift_decision(repo, &remote).primary_action)
}
pub(crate) fn remote_tracking_with_verification_action(
    mut remote: GitRemoteTrackingStatus,
    trust: &RepositoryVerificationState,
) -> GitRemoteTrackingStatus {
    let remote_status = remote_tracking_status(&remote);
    if trust.status == remote_status && !trust.recommended_action.trim().is_empty() {
        remote.next_action = trust.recommended_action.clone();
    }
    remote
}

#[cfg(test)]
mod tests;