heddle-cli 0.7.0

An AI-native version control system
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
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
// SPDX-License-Identifier: Apache-2.0
//! Git adapter command implementations.

use std::{collections::BTreeMap, fs, path::Path, time::Instant};

use anyhow::{Context, Result, anyhow};
use objects::{
    object::{Agent, Blob, ChangeId, ContentHash, Principal, ThreadName, Tree, TreeEntry},
    store::ObjectStore,
    worktree::{WorktreeIgnoreMatcher, build_worktree_ignore},
};
use oplog::{OpBatch, OpLogBackend, OpRecord};
use repo::{Repository, RepositoryCapability};
use serde::Serialize;
use sley::{
    BString as GitBString, GitObjectType, Index, IndexEntry, IndexStage, ObjectId,
    Repository as SleyRepository, ShortStatusOptions, ShortStatusRow, StatusUntrackedMode,
    StreamControl,
};

use super::{
    action_line::print_next,
    advice::RecoveryAdvice,
    checkpoint::{
        create_git_checkpoint_from_index_snapshot_with_worktree_status,
        create_git_checkpoint_with_worktree_status,
    },
    command_catalog::{ActionFields, ActionTemplate},
    git_overlay_health::RepositoryVerificationState,
    git_overlay_txn,
    next_action::{NextActionValidationContext, write_full_command_json},
    snapshot::{
        SnapshotAgentOverrides, create_snapshot, create_snapshot_from_tree,
        create_snapshot_profiled_with_worktree_status, is_placeholder_principal,
        placeholder_principal_warning,
        preflight_large_capture_for_git_adapter_commit_with_worktree_status, resolve_principal,
    },
    thread_cmd::cmd_thread,
};
use crate::{
    cli::{
        Cli, CommitArgs, SwitchArgs, ThreadCommands, should_output_json, style,
        worktree_status_options,
    },
    config::UserConfig,
    perf::{ProfileField, emit_profile, profile_enabled},
};

const GIT_MODE_FILE: u32 = 0o100644;
const GIT_MODE_FILE_EXECUTABLE: u32 = 0o100755;
const GIT_MODE_SYMLINK: u32 = 0o120000;
const GIT_MODE_COMMIT: u32 = 0o160000;
const GIT_MODE_DIR: u32 = 0o040000;

#[derive(Serialize)]
struct GitAdapterCommitOutput {
    output_kind: &'static str,
    status: &'static str,
    action: &'static str,
    change_id: String,
    git_commit: Option<String>,
    git_previous_commit: Option<String>,
    summary: String,
    confidence: Option<f32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    git_index: Option<GitIndexPlan>,
    #[serde(skip_serializing_if = "Option::is_none")]
    included_pending_capture: Option<String>,
    principal: CommitPrincipalOutput,
    agent: Option<CommitAgentOutput>,
    #[serde(skip)]
    placeholder_principal_warning: Option<String>,
    next_action: Option<String>,
    next_action_template: Option<ActionTemplate>,
    recommended_action: Option<String>,
    recommended_action_template: Option<ActionTemplate>,
    #[serde(rename = "verification")]
    trust: RepositoryVerificationState,
}

#[derive(Serialize)]
struct CommitPrincipalOutput {
    name: String,
    email: String,
}

#[derive(Serialize)]
struct CommitAgentOutput {
    provider: String,
    model: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    session_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    segment_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    policy_id: Option<String>,
}

impl From<Principal> for CommitPrincipalOutput {
    fn from(principal: Principal) -> Self {
        Self {
            name: principal.name,
            email: principal.email,
        }
    }
}

impl From<Agent> for CommitAgentOutput {
    fn from(agent: Agent) -> Self {
        Self {
            provider: agent.provider,
            model: agent.model,
            session_id: agent.session_id,
            segment_id: agent.segment_id,
            policy_id: agent.policy_id,
        }
    }
}

pub async fn cmd_commit_git_adapter(cli: &Cli, args: CommitArgs) -> Result<()> {
    let message = require_commit_message(args.message.clone())?;
    let cwd;
    let start = if let Some(path) = cli.repo.as_ref() {
        path
    } else {
        cwd = std::env::current_dir()?;
        &cwd
    };
    git_overlay_txn::preflight_plain_git_mutation(start, "commit")?;

    let repo = Repository::open(start)?;
    // Compute the git-overlay worktree status ONCE up front. The commit mutation
    // preflight here is PRE-mutation and shared by every commit path; the clean
    // fast-path below reuses the same status for its verification preflight and
    // for the checkpoint it triggers, all of which observe the same pre-mutation
    // git state (no Git ref moves until `create_git_checkpoint`). This is the
    // exact `Result` from a full worktree walk that re-reads + SHA-1s every
    // tracked file — before this, the clean fast-path paid that walk 3× before
    // the ref ever moved.
    let preflight_worktree_status_start = Instant::now();
    let git_overlay_facts = git_overlay_txn::gather_mutation_facts(&repo);
    let preflight_worktree_status_ms = preflight_worktree_status_start.elapsed().as_millis();
    git_overlay_txn::preflight_commit(&repo, &git_overlay_facts)?;
    let user_config = UserConfig::load_default().unwrap_or_default();
    let placeholder_principal_warning =
        placeholder_principal_first_commit_warning(&repo, &user_config)?;
    // Heddle-side clean-check: walks the worktree against the current Heddle tree
    // (load index + read + SHA-1 every tracked file + save index). This is a
    // SEPARATE walk from the git-overlay `worktree_status` above (different
    // representation/semantics), so it cannot be threaded from it. It is only
    // needed to distinguish "nothing to commit" / index-only-intent from a real
    // change; the dirty path discards the result. Profiled below so the cost is
    // attributed. Cutting it (cheap is-dirty probe for the dirty path) is a
    // noted L-effort follow-up.
    let mut clean_check_status_ms = 0u128;
    if let Some(state) = repo.current_state()? {
        let tree = repo.require_tree(&state.tree)?;
        let clean_check_start = Instant::now();
        let status = repo.compare_worktree_cached_with_options(
            &tree,
            &worktree_status_options(Some(repo.config())),
        )?;
        clean_check_status_ms = clean_check_start.elapsed().as_millis();
        // A clean worktree (matches Heddle's current tree) can still
        // hide real index-only intent on a Git-overlay checkout — e.g.
        // `git rm --cached path` stages a deletion without touching
        // the file on disk. Treating that as "nothing to commit" would
        // silently drop the staged removal, so fall through to the
        // Git-overlay staged-index path below when one exists.
        let has_staged_index_intent = !args.all
            && repo.capability() == RepositoryCapability::GitOverlay
            && !git_index_intent_for_repo(&repo)?.staged_paths.is_empty();
        if status.is_clean() && !has_staged_index_intent {
            // Reuse the pre-mutation git-overlay worktree status computed at the
            // top: no Git ref has moved on this fast-path, so the verification
            // state is byte-identical to a fresh walk here.
            let trust = git_overlay_txn::preflight_verify_with_worktree_status(
                &repo,
                git_overlay_facts.worktree_status(),
            );
            // `--no-all` forces an index-only commit and must never auto-commit
            // the captured worktree state. On this fast-path the worktree is
            // clean and the index has no staged intent, so an index-only commit
            // has nothing to commit — surface that instead of silently
            // checkpointing the pending capture into Git.
            if args.no_all {
                return Err(anyhow!(nothing_to_commit_advice()));
            }
            if trust.status == "needs_checkpoint" {
                git_overlay_txn::preflight_git_checkpoint_identity(
                    &repo,
                    &user_config,
                    "commit",
                    "heddle commit -m \"...\"",
                )?;
                let git_previous_commit = git_head_oid(repo.root());
                // Thread the same pre-mutation status into the checkpoint so it
                // does not re-run its own pre-mutation worktree walk. The
                // checkpoint then advances the Git ref, so the post-checkpoint
                // `build_repository_verification_state` below stays a FRESH walk.
                let record = create_git_checkpoint_with_worktree_status(
                    &repo,
                    Some(message.as_str()),
                    worktree_status_options(Some(repo.config())),
                    git_overlay_facts.worktree_status(),
                )?;
                let trust = git_overlay_txn::post_verify_commit(&repo);
                let output = GitAdapterCommitOutput {
                    output_kind: "commit",
                    status: "committed",
                    action: "commit",
                    change_id: state.change_id.short(),
                    git_commit: Some(record.git_commit),
                    git_previous_commit,
                    summary: record.summary,
                    confidence: state.confidence,
                    git_index: None,
                    included_pending_capture: Some(state.change_id.short()),
                    principal: state.attribution.principal.into(),
                    agent: state.attribution.agent.map(CommitAgentOutput::from),
                    placeholder_principal_warning: placeholder_principal_warning.clone(),
                    next_action: commit_next_action(&trust),
                    next_action_template: None,
                    recommended_action: None,
                    recommended_action_template: None,
                    trust,
                };
                let output = with_commit_action_metadata(output);
                render_git_adapter_commit(
                    &output,
                    should_output_json(cli, Some(repo.config())),
                    repo.capability(),
                )?;
                return Ok(());
            }
            if !trust.verified {
                return Err(anyhow!(git_overlay_txn::commit_blocked_by_trust_advice(
                    &trust
                )));
            }
            return Err(anyhow!(nothing_to_commit_advice()));
        }
    }
    if repo.capability() != RepositoryCapability::GitOverlay {
        let snapshot = create_snapshot(
            &repo,
            &user_config,
            Some(message.clone()),
            args.confidence,
            SnapshotAgentOverrides {
                provider: None,
                model: None,
                session: None,
                segment: None,
                policy: None,
                no_policy: false,
                no_agent: false,
            },
        )?;
        let captured_state = repo
            .current_state()?
            .ok_or_else(|| anyhow!("capture succeeded but no current state was recorded"))?;
        let trust = git_overlay_txn::post_verify_commit(&repo);
        let output = GitAdapterCommitOutput {
            output_kind: "commit",
            status: "committed",
            action: "commit",
            change_id: snapshot.change_id,
            git_commit: None,
            git_previous_commit: None,
            summary: snapshot.message,
            confidence: captured_state.confidence,
            git_index: None,
            included_pending_capture: None,
            principal: captured_state.attribution.principal.into(),
            agent: captured_state
                .attribution
                .agent
                .map(CommitAgentOutput::from),
            placeholder_principal_warning: placeholder_principal_warning.clone(),
            next_action: commit_next_action(&trust),
            next_action_template: None,
            recommended_action: None,
            recommended_action_template: None,
            trust,
        };
        let output = with_commit_action_metadata(output);

        render_git_adapter_commit(
            &output,
            should_output_json(cli, Some(repo.config())),
            repo.capability(),
        )?;
        return Ok(());
    }

    let index_intent = git_index_intent_for_repo(&repo)?;
    if args.no_all && !args.all && index_intent.staged_paths.is_empty() {
        // `--no-all` is index-only. With no staged paths the index is identical
        // to HEAD (empty index, or index == HEAD), so there is nothing genuinely
        // staged. Surface the standard nothing-to-commit outcome BEFORE the
        // commit preflights: identity config and ref-update availability are
        // irrelevant for a commit that was never going to write anything, so an
        // unconfigured identity or blocked ref update must not mask the
        // nothing-to-commit result.
        return Err(anyhow!(nothing_to_commit_advice()));
    }

    git_overlay_txn::preflight_git_checkpoint_identity(
        &repo,
        &user_config,
        "commit",
        "heddle commit -m \"...\"",
    )?;
    git_overlay_txn::preflight_commit_checkpoint_ref_update(&repo, &git_overlay_facts)?;
    let git_previous_commit = git_head_oid(repo.root());
    let pending_capture = pending_capture_before_commit(&repo)?;
    if !args.all && (args.no_all || !index_intent.staged_paths.is_empty()) {
        // The `--no-all` + empty-index case short-circuited above, so reaching
        // here always has staged paths present (either via `--no-all` with real
        // staged changes, or the non-`--no-all` disjunct that requires them).
        commit_staged_index(
            cli,
            &repo,
            &user_config,
            StagedIndexCommit {
                message: &message,
                confidence: args.confidence,
                intent: index_intent,
                pending_capture,
                git_overlay_facts: &git_overlay_facts,
            },
        )?;
        return Ok(());
    }
    let git_index = GitIndexPlan::from_intent(&index_intent, args.all);

    // Reuse the pre-mutation git-overlay worktree status computed at the top of
    // this command (`worktree_status`) for the dirty-commit path's three
    // PRE-mutation consumers: the large-capture safety preflight, the capture
    // mutation preflight inside the snapshot, and the checkpoint's two
    // preflights. None of these moves a Git ref, so they all observe the same
    // pre-mutation git state and reuse is byte-identical to a fresh walk. Before
    // this, the dirty path re-walked the worktree (re-reading + SHA-1ing every
    // tracked file) four-plus times here — the large-capture preflight, the
    // snapshot preflight, and both checkpoint preflights each ran their own
    // walk. The post-checkpoint verification (`build_repository_verification_state`
    // below) is left FRESH: the checkpoint advances the Git ref, which flips the
    // git-overlay health classification.
    let large_capture_start = Instant::now();
    preflight_large_capture_for_git_adapter_commit_with_worktree_status(
        args.force,
        git_overlay_facts.worktree_status(),
    )?;
    let large_capture_preflight_ms = large_capture_start.elapsed().as_millis();
    let snapshot_start = Instant::now();
    let (snapshot, _snapshot_profile) = create_snapshot_profiled_with_worktree_status(
        &repo,
        &user_config,
        Some(message.clone()),
        args.confidence,
        SnapshotAgentOverrides {
            provider: None,
            model: None,
            session: None,
            segment: None,
            policy: None,
            no_policy: false,
            no_agent: false,
        },
        git_overlay_facts.worktree_status(),
    )?;
    let snapshot_ms = snapshot_start.elapsed().as_millis();
    let captured_state = repo
        .current_state()?
        .ok_or_else(|| anyhow!("capture succeeded but no current state was recorded"))?;
    let snapshot_batch = find_recent_snapshot_batch(&repo, &captured_state.change_id)?;
    let checkpoint_start = Instant::now();
    let record = create_git_checkpoint_with_worktree_status(
        &repo,
        Some(message.as_str()),
        worktree_status_options(Some(repo.config())),
        git_overlay_facts.worktree_status(),
    )
    .map_err(|err| {
        anyhow!(git_overlay_txn::commit_checkpoint_failed_advice(
            &snapshot.change_id,
            Some(message.as_str()),
            &err,
            false,
        ))
    })?;
    let checkpoint_ms = checkpoint_start.elapsed().as_millis();
    let checkpoint_batch = find_recent_git_checkpoint_batch(&repo, &record.git_commit)?;
    repo.oplog()
        .coalesce_batches(snapshot_batch.id, checkpoint_batch.id)
        .context(
            "commit completed but failed to record capture and Git checkpoint as one undo batch",
        )?;

    let verify_start = Instant::now();
    let trust = git_overlay_txn::post_verify_commit(&repo);
    let verify_ms = verify_start.elapsed().as_millis();
    if profile_enabled() {
        emit_profile(
            "commit phases",
            &[
                ProfileField::millis("preflight_worktree_status_ms", preflight_worktree_status_ms),
                ProfileField::millis("clean_check_status_ms", clean_check_status_ms),
                ProfileField::millis("large_capture_preflight_ms", large_capture_preflight_ms),
                ProfileField::millis("snapshot_ms", snapshot_ms),
                ProfileField::millis("checkpoint_ms", checkpoint_ms),
                ProfileField::millis("verify_ms", verify_ms),
            ],
        );
    }
    let output = GitAdapterCommitOutput {
        output_kind: "commit",
        status: "committed",
        action: "commit",
        change_id: snapshot.change_id,
        git_commit: Some(record.git_commit),
        git_previous_commit,
        summary: record.summary,
        confidence: captured_state.confidence,
        git_index: Some(git_index),
        included_pending_capture: pending_capture.map(|state| state.short()),
        principal: captured_state.attribution.principal.into(),
        agent: captured_state
            .attribution
            .agent
            .map(CommitAgentOutput::from),
        placeholder_principal_warning: placeholder_principal_warning.clone(),
        next_action: commit_next_action(&trust),
        next_action_template: None,
        recommended_action: None,
        recommended_action_template: None,
        trust,
    };
    let output = with_commit_action_metadata(output);

    render_git_adapter_commit(
        &output,
        should_output_json(cli, Some(repo.config())),
        repo.capability(),
    )?;

    Ok(())
}

struct StagedIndexCommit<'a> {
    message: &'a str,
    confidence: Option<f32>,
    intent: GitIndexIntent,
    pending_capture: Option<ChangeId>,
    git_overlay_facts: &'a git_overlay_txn::GitOverlayMutationFacts,
}

fn commit_staged_index(
    cli: &Cli,
    repo: &Repository,
    user_config: &UserConfig,
    staged: StagedIndexCommit<'_>,
) -> Result<()> {
    let StagedIndexCommit {
        message,
        confidence,
        intent,
        pending_capture,
        git_overlay_facts,
    } = staged;
    let index_tree = git_index_tree(repo)?;
    let snapshot = create_snapshot_from_tree(
        repo,
        user_config,
        index_tree,
        Some(message.to_string()),
        confidence,
        SnapshotAgentOverrides {
            provider: None,
            model: None,
            session: None,
            segment: None,
            policy: None,
            no_policy: false,
            no_agent: false,
        },
    )?;
    let captured_state = repo
        .current_state()?
        .ok_or_else(|| anyhow!("capture succeeded but no current state was recorded"))?;
    let snapshot_batch = find_recent_snapshot_batch(repo, &captured_state.change_id)?;
    let git_previous_commit = git_head_oid(repo.root());
    let record = create_git_checkpoint_from_index_snapshot_with_worktree_status(
        repo,
        Some(message),
        worktree_status_options(Some(repo.config())),
        git_overlay_facts.worktree_status(),
    )
    .map_err(|err| {
        anyhow!(git_overlay_txn::commit_checkpoint_failed_advice(
            &snapshot.change_id,
            Some(message),
            &err,
            true,
        ))
    })?;
    let checkpoint_batch = find_recent_git_checkpoint_batch(repo, &record.git_commit)?;
    repo.oplog()
        .coalesce_batches(snapshot_batch.id, checkpoint_batch.id)
        .context(
            "commit completed but failed to record capture and Git checkpoint as one undo batch",
        )?;

    let trust = git_overlay_txn::post_verify_commit(repo);
    let output = GitAdapterCommitOutput {
        output_kind: "commit",
        status: "committed",
        action: "commit",
        change_id: snapshot.change_id,
        git_commit: Some(record.git_commit),
        git_previous_commit,
        summary: staged_commit_summary(&record.summary, &intent),
        confidence: captured_state.confidence,
        git_index: Some(GitIndexPlan::index_only(&intent)),
        included_pending_capture: pending_capture.map(|state| state.short()),
        principal: captured_state.attribution.principal.into(),
        agent: captured_state
            .attribution
            .agent
            .map(CommitAgentOutput::from),
        placeholder_principal_warning: placeholder_principal_first_commit_warning(
            repo,
            user_config,
        )?,
        next_action: commit_next_action(&trust),
        next_action_template: None,
        recommended_action: None,
        recommended_action_template: None,
        trust,
    };
    let output = with_commit_action_metadata(output);
    render_git_adapter_commit(
        &output,
        should_output_json(cli, Some(repo.config())),
        repo.capability(),
    )?;
    Ok(())
}

fn staged_commit_summary(summary: &str, intent: &GitIndexIntent) -> String {
    if intent.extra_paths.is_empty() {
        return summary.to_string();
    }
    format!(
        "{summary} (committed {} staged path(s); left {} unstaged/untracked path(s) in the worktree)",
        intent.staged_paths.len(),
        intent.extra_paths.len()
    )
}

fn require_commit_message(message: Option<String>) -> Result<String> {
    match message {
        Some(message) if !message.trim().is_empty() => Ok(message),
        _ => Err(anyhow!(missing_commit_message_advice())),
    }
}

fn missing_commit_message_advice() -> RecoveryAdvice {
    RecoveryAdvice::safety_refusal(
        "missing_commit_message",
        "refusing to commit without a message",
        "Provide a short message with `heddle commit -m \"...\"`.",
        "no commit message was supplied with -m/--message/--intent",
        "committing without a message would create a weak provenance record",
        "repository state, refs, metadata, Git checkpoints, and worktree files were left unchanged",
        "heddle commit -m \"...\"",
        vec!["heddle commit -m \"...\"".to_string()],
    )
}

#[derive(Default)]
pub(crate) struct GitIndexIntent {
    pub(crate) staged_paths: Vec<String>,
    pub(crate) extra_paths: Vec<String>,
}

#[derive(Clone, Debug, Serialize)]
pub(crate) struct GitIndexPlan {
    pub(crate) commit_mode: &'static str,
    pub(crate) has_staged_changes: bool,
    pub(crate) staged_paths: Vec<String>,
    pub(crate) unstaged_paths: Vec<String>,
    pub(crate) untracked_paths: Vec<String>,
    pub(crate) will_commit: Vec<String>,
    pub(crate) preserved_after_commit: Vec<String>,
}

impl GitIndexPlan {
    pub(crate) fn from_intent(intent: &GitIndexIntent, include_all: bool) -> Self {
        let (unstaged_paths, untracked_paths) = split_extra_paths(&intent.extra_paths);
        let has_staged_changes = !intent.staged_paths.is_empty();
        let mut will_commit = Vec::new();
        if has_staged_changes {
            will_commit.extend(intent.staged_paths.iter().cloned());
        }
        if include_all || !has_staged_changes {
            will_commit.extend(unstaged_paths.iter().cloned());
            will_commit.extend(untracked_paths.iter().cloned());
        }
        let commit_mode = if has_staged_changes && include_all {
            "worktree_all_explicit"
        } else if has_staged_changes {
            "staged_index"
        } else if will_commit.is_empty() {
            "none"
        } else {
            "worktree_all"
        };
        let preserved_after_commit = if has_staged_changes && !include_all {
            intent.extra_paths.clone()
        } else {
            Vec::new()
        };
        Self {
            commit_mode,
            has_staged_changes,
            staged_paths: intent.staged_paths.clone(),
            unstaged_paths,
            untracked_paths,
            will_commit,
            preserved_after_commit,
        }
    }

    /// Plan for an index-only commit: checkpoint exactly the staged index (which
    /// may be empty, as on the `--no-all` path) and preserve every unstaged or
    /// untracked worktree path. Never sweeps the worktree.
    pub(crate) fn index_only(intent: &GitIndexIntent) -> Self {
        let (unstaged_paths, untracked_paths) = split_extra_paths(&intent.extra_paths);
        Self {
            commit_mode: "staged_index",
            has_staged_changes: !intent.staged_paths.is_empty(),
            staged_paths: intent.staged_paths.clone(),
            unstaged_paths,
            untracked_paths,
            will_commit: intent.staged_paths.clone(),
            preserved_after_commit: intent.extra_paths.clone(),
        }
    }
}

/// True when `root` is itself the top of a Git worktree, not merely
/// nested inside one. A Heddle thread checkout now lives under the parent
/// repo's `.heddle/threads/` (heddle#572); it's a *native* isolated
/// checkout that shares the parent's object store but is NOT a Git
/// worktree of its own. Bare git discovery walks up the directory tree,
/// so from inside such a checkout it would find the PARENT repo's `.git`
/// and read its index/HEAD as though they belonged to the checkout.
/// Requiring the discovered worktree to equal `root` keeps git-index
/// inspection scoped to genuine git-overlay roots — and matches the
/// pre-#572 behaviour where a sibling checkout had no git above it at all.
fn git_worktree_rooted_at(root: &Path) -> bool {
    match SleyRepository::discover(root) {
        Ok(git) => git_worktree_matches_root(&git, root),
        Err(_) => false,
    }
}

fn git_worktree_matches_root(git: &SleyRepository, root: &Path) -> bool {
    git.workdir()
        .is_some_and(|workdir| paths_equal(&workdir, root))
}

fn paths_equal(left: &Path, right: &Path) -> bool {
    let left = left.canonicalize();
    let right = right.canonicalize();
    match (left, right) {
        (Ok(left), Ok(right)) => left == right,
        _ => false,
    }
}

pub(crate) fn git_index_plan_for_root(root: &Path) -> Result<Option<GitIndexPlan>> {
    if !git_worktree_rooted_at(root) {
        return Ok(None);
    }
    Ok(Some(GitIndexPlan::from_intent(
        &git_index_intent_for_root(root)?,
        false,
    )))
}

fn split_extra_paths(extra_paths: &[String]) -> (Vec<String>, Vec<String>) {
    let mut unstaged_paths = Vec::new();
    let mut untracked_paths = Vec::new();
    for path in extra_paths {
        if let Some(path) = path.strip_prefix("unstaged: ") {
            unstaged_paths.push(path.to_string());
        } else if let Some(path) = path.strip_prefix("untracked: ") {
            untracked_paths.push(path.to_string());
        }
    }
    (unstaged_paths, untracked_paths)
}

fn empty_git_index() -> Index {
    Index {
        version: 2,
        entries: Vec::new(),
        extensions: Vec::new(),
        checksum: None,
    }
}

fn index_or_empty(git: &SleyRepository) -> Result<Index> {
    Ok(git.open_index()?.unwrap_or_else(empty_git_index))
}

fn git_index_intent(repo: &Repository, git: &SleyRepository) -> Result<GitIndexIntent> {
    let ignore_patterns = repo.ignore_patterns()?;
    git_index_intent_for_root_with_ignore_and_repo(repo.root(), &ignore_patterns, git)
}

fn git_index_intent_for_repo(repo: &Repository) -> Result<GitIndexIntent> {
    let git = repo
        .git_overlay_sley_repository()?
        .ok_or_else(|| anyhow!("failed to inspect Git index before commit"))?;
    git_index_intent(repo, &git)
}

pub(crate) fn git_index_intent_for_root(root: &Path) -> Result<GitIndexIntent> {
    let ignore_patterns = git_ignore_patterns_for_root(root)?;
    git_index_intent_for_root_with_ignore(root, &ignore_patterns)
}

fn git_index_intent_for_root_with_ignore(
    root: &Path,
    ignore_patterns: &[String],
) -> Result<GitIndexIntent> {
    let git =
        SleyRepository::discover(root).context("failed to inspect Git index before commit")?;
    git_index_intent_for_root_with_ignore_and_repo(root, ignore_patterns, &git)
}

fn git_index_intent_for_root_with_ignore_and_repo(
    root: &Path,
    ignore_patterns: &[String],
    git: &SleyRepository,
) -> Result<GitIndexIntent> {
    let ignore_matcher = build_worktree_ignore(ignore_patterns);
    let mut intent = GitIndexIntent::default();
    git.stream_short_status_with_options(
        ShortStatusOptions {
            untracked_mode: StatusUntrackedMode::All,
            ..ShortStatusOptions::default()
        },
        |entry| {
            append_status_row_to_index_intent(&mut intent, &ignore_matcher, entry);
            Ok(StreamControl::Continue)
        },
    )
    .with_context(|| {
        format!(
            "failed to inspect Git status before commit at {}",
            root.display()
        )
    })?;

    Ok(intent)
}

fn append_status_row_to_index_intent(
    intent: &mut GitIndexIntent,
    ignore_matcher: &WorktreeIgnoreMatcher,
    entry: ShortStatusRow<'_>,
) {
    let path = String::from_utf8_lossy(entry.path).into_owned();
    if path.is_empty() {
        return;
    }
    if entry.index == b'?' && entry.worktree == b'?' {
        if !ignore_matcher.is_ignored(Path::new(&path)) {
            intent.extra_paths.push(format!("untracked: {path}"));
        }
        return;
    }
    if entry.index != b' ' && entry.index != b'!' {
        intent.staged_paths.push(path.clone());
    }
    if entry.worktree != b' '
        && entry.worktree != b'!'
        && !status_row_is_gitlink_worktree_only(entry)
    {
        intent.extra_paths.push(format!("unstaged: {path}"));
    }
}

fn status_row_is_gitlink_worktree_only(entry: ShortStatusRow<'_>) -> bool {
    entry.index == b' '
        && (entry.index_mode == Some(GIT_MODE_COMMIT)
            || entry.head_mode == Some(GIT_MODE_COMMIT)
            || entry.worktree_mode == Some(GIT_MODE_COMMIT))
}

fn git_ignore_patterns_for_root(root: &Path) -> Result<Vec<String>> {
    let git = SleyRepository::discover(root)
        .context("failed to inspect Git ignore files before commit")?;
    let mut patterns = Vec::new();
    append_ignore_file_patterns(&mut patterns, &root.join(".gitignore"))?;
    append_ignore_file_patterns(&mut patterns, &git.git_dir().join("info").join("exclude"))?;
    Ok(patterns)
}

fn append_ignore_file_patterns(patterns: &mut Vec<String>, path: &Path) -> Result<()> {
    if !path.exists() {
        return Ok(());
    }
    let contents = fs::read_to_string(path)
        .with_context(|| format!("failed to read ignore file {}", path.display()))?;
    for line in contents.lines() {
        let trimmed = line.trim();
        if trimmed.is_empty() || trimmed.starts_with('#') {
            continue;
        }
        if !patterns.iter().any(|pattern| pattern == trimmed) {
            patterns.push(trimmed.to_string());
        }
    }
    Ok(())
}

fn git_index_tree(repo: &Repository) -> Result<Tree> {
    let git = repo
        .git_overlay_sley_repository()?
        .ok_or_else(|| anyhow!("failed to inspect Git index before commit"))?;
    let index = index_or_empty(&git).context("failed to inspect Git index before commit")?;
    let mut builder = IndexTreeBuilder::default();

    for entry in index.entries {
        let path = git_path_from_bstring(&entry.path);
        if entry.stage() != IndexStage::Normal {
            return Err(anyhow!(unmerged_git_index_advice(&path)));
        }
        let node = index_entry_node(repo, &git, &path, &entry)?;
        builder.insert(&path, node)?;
    }

    builder.into_tree(repo)
}

#[derive(Default)]
struct IndexTreeBuilder {
    entries: BTreeMap<String, IndexTreeNode>,
}

enum IndexTreeNode {
    Blob(TreeEntry),
    Tree(IndexTreeBuilder),
}

impl IndexTreeBuilder {
    fn insert(&mut self, path: &str, node: IndexTreeNode) -> Result<()> {
        let mut parts = path.split('/').filter(|part| !part.is_empty());
        let first = parts
            .next()
            .ok_or_else(|| anyhow!("Git index contained an empty path"))?
            .to_string();
        let rest = parts.collect::<Vec<_>>();
        if rest.is_empty() {
            if self.entries.contains_key(&first) {
                return Err(anyhow!("Git index contains duplicate path '{path}'"));
            }
            self.entries.insert(first, node);
            return Ok(());
        }

        let child = self
            .entries
            .entry(first.clone())
            .or_insert_with(|| IndexTreeNode::Tree(IndexTreeBuilder::default()));
        let IndexTreeNode::Tree(builder) = child else {
            return Err(anyhow!(
                "Git index contains both file and directory entries at '{first}'"
            ));
        };
        builder.insert(&rest.join("/"), node)
    }

    fn into_tree(self, repo: &Repository) -> Result<Tree> {
        let mut entries = Vec::new();
        for (name, node) in self.entries {
            match node {
                IndexTreeNode::Blob(mut entry) => {
                    entry.set_name(name)?;
                    entries.push(entry);
                }
                IndexTreeNode::Tree(builder) => {
                    let tree = builder.into_tree(repo)?;
                    let hash = repo.store().put_tree(&tree)?;
                    entries.push(TreeEntry::directory(name, hash)?);
                }
            }
        }
        Ok(Tree::from_entries(entries))
    }
}

fn index_entry_node(
    repo: &Repository,
    git: &SleyRepository,
    path: &str,
    entry: &IndexEntry,
) -> Result<IndexTreeNode> {
    let tree_entry = match entry.mode {
        mode if mode == GIT_MODE_FILE || mode == GIT_MODE_FILE_EXECUTABLE => {
            let hash = import_index_blob(repo, git, entry.oid, path)?;
            TreeEntry::file(
                leaf_name(path),
                hash,
                entry.mode == GIT_MODE_FILE_EXECUTABLE,
            )?
        }
        mode if mode == GIT_MODE_SYMLINK => {
            let hash = import_index_blob(repo, git, entry.oid, path)?;
            TreeEntry::symlink(leaf_name(path), hash)?
        }
        mode if mode == GIT_MODE_COMMIT => TreeEntry::gitlink(leaf_name(path), entry.oid)?,
        mode if mode == GIT_MODE_DIR => {
            return Err(anyhow!(sparse_git_index_advice(path)));
        }
        _ => {
            return Err(anyhow!(
                "Git index path '{path}' has unsupported mode {:o}",
                entry.mode
            ));
        }
    };
    Ok(IndexTreeNode::Blob(tree_entry))
}

fn import_index_blob(
    repo: &Repository,
    git: &SleyRepository,
    oid: ObjectId,
    path: &str,
) -> Result<ContentHash> {
    let object = git
        .read_object(&oid)
        .with_context(|| format!("failed to read staged Git blob for '{path}'"))?;
    if object.object_type != GitObjectType::Blob {
        return Err(anyhow!(
            "Git index path '{path}' points at {}, not a blob",
            object.object_type.as_str()
        ));
    }
    let blob = Blob::new(object.body.clone());
    Ok(repo.store().put_blob(&blob)?)
}

fn leaf_name(path: &str) -> String {
    path.rsplit('/').next().unwrap_or(path).to_string()
}

fn unmerged_git_index_advice(path: &str) -> RecoveryAdvice {
    RecoveryAdvice::safety_refusal(
        "git_index_unmerged",
        format!("Git index has unresolved conflict stages at {path}"),
        "Resolve the Git index conflict, stage the resolved files, then retry `heddle commit -m \"...\"`.",
        format!("path '{path}' has non-stage-0 entries in the Git index"),
        "committing an unresolved multi-stage index would lose conflict-side information",
        "no Heddle capture, Git checkpoint, refs, index, or worktree files were changed",
        "heddle status",
        vec!["heddle status".to_string()],
    )
}

fn sparse_git_index_advice(path: &str) -> RecoveryAdvice {
    RecoveryAdvice::safety_refusal(
        "git_index_sparse_entry",
        format!("Git index contains sparse directory entry {path}"),
        "Expand the sparse index or commit with `heddle commit --all -m \"...\"` after materializing the desired files.",
        format!("path '{path}' is a sparse directory entry"),
        "Heddle cannot yet prove the exact staged tree for sparse index directory entries",
        "no Heddle capture, Git checkpoint, refs, index, or worktree files were changed",
        "heddle status",
        vec!["heddle status".to_string()],
    )
}

fn git_path_from_bstring(path: &GitBString) -> String {
    String::from_utf8_lossy(path.as_bytes()).into_owned()
}

fn commit_next_action(trust: &RepositoryVerificationState) -> Option<String> {
    if !trust.recommended_action.trim().is_empty() {
        return Some(trust.recommended_action.clone());
    }
    if !trust.verified {
        return Some("heddle verify".to_string());
    }
    trust
        .default_remote
        .as_ref()
        .map(|_| "heddle push".to_string())
}

fn pending_capture_before_commit(repo: &Repository) -> Result<Option<ChangeId>> {
    if repo.capability() != RepositoryCapability::GitOverlay {
        return Ok(None);
    }
    let Some(current) = repo.current_state()? else {
        return Ok(None);
    };
    let Some(branch) = repo.git_overlay_current_branch()? else {
        return Ok(None);
    };
    let Some(tip) = repo.git_overlay_branch_tip(&branch)? else {
        return Ok(None);
    };
    let Some(tip) = tip.mapped_change else {
        return Ok(None);
    };
    if tip == current.change_id {
        return Ok(None);
    }
    if repo
        .latest_git_checkpoint_for_change(&current.change_id)?
        .is_some()
    {
        return Ok(None);
    }
    Ok(Some(current.change_id))
}

fn with_commit_action_metadata(mut output: GitAdapterCommitOutput) -> GitAdapterCommitOutput {
    output.recommended_action = output.next_action.clone();
    let next_action = ActionFields::from_optional_action_ref(output.next_action.as_deref());
    let recommended_action =
        ActionFields::from_optional_action_ref(output.recommended_action.as_deref());
    output.next_action_template = next_action.template;
    output.recommended_action_template = recommended_action.template;
    output
}

fn nothing_to_commit_advice() -> RecoveryAdvice {
    RecoveryAdvice::safety_refusal(
        "nothing_to_commit",
        "nothing to commit: worktree has no changes eligible for Heddle capture",
        "Inspect the worktree with `heddle status`; make changes before running `heddle commit -m \"...\"`.",
        "the worktree has no modified, deleted, or untracked paths relative to the current Heddle state",
        "commit would not capture a new Heddle state or write a meaningful Git checkpoint",
        "repository state was left unchanged",
        "heddle status",
        vec!["heddle status".to_string()],
    )
}

fn find_recent_snapshot_batch(repo: &Repository, state: &ChangeId) -> Result<OpBatch> {
    repo.oplog()
        .recent_batches_scoped(8, Some(&repo.op_scope()))?
        .into_iter()
        .find(|batch| {
            batch.entries.iter().any(|entry| {
                matches!(
                    &entry.operation,
                    OpRecord::Snapshot { new_state, .. } if new_state == state
                )
            })
        })
        .ok_or_else(|| anyhow!("capture succeeded but its oplog batch was not found"))
}

fn find_recent_git_checkpoint_batch(repo: &Repository, git_commit: &str) -> Result<OpBatch> {
    repo.oplog()
        .recent_batches_scoped(8, Some(&repo.op_scope()))?
        .into_iter()
        .find(|batch| {
            batch.entries.iter().any(|entry| {
                matches!(
                    &entry.operation,
                    OpRecord::GitCheckpoint { new_git_oid, .. } if new_git_oid == git_commit
                )
            })
        })
        .ok_or_else(|| anyhow!("Git checkpoint succeeded but its oplog batch was not found"))
}

fn git_head_oid(root: &Path) -> Option<String> {
    let git = SleyRepository::discover(root).ok()?;
    git.head().ok()?.oid.map(|id| id.to_string())
}

fn placeholder_principal_first_commit_warning(
    repo: &Repository,
    user_config: &UserConfig,
) -> Result<Option<String>> {
    if !current_state_is_bootstrap(repo)? {
        return Ok(None);
    }
    let principal = resolve_principal(repo, user_config)?;
    if is_placeholder_principal(&principal) {
        return Ok(Some(placeholder_principal_warning(&principal)));
    }
    Ok(None)
}

fn current_state_is_bootstrap(repo: &Repository) -> Result<bool> {
    let Some(state) = repo.current_state()? else {
        return Ok(true);
    };
    Ok(state
        .intent
        .as_deref()
        .is_none_or(|intent| intent.trim().is_empty()))
}

fn render_git_adapter_commit(
    output: &GitAdapterCommitOutput,
    json: bool,
    repository_capability: RepositoryCapability,
) -> Result<()> {
    if json {
        write_full_command_json(
            output,
            NextActionValidationContext::new(&["commit"], repository_capability),
        )?;
    } else {
        println!(
            "{}",
            match &output.git_commit {
                Some(git_commit) => format!(
                    "Committed {} as Git commit {}",
                    style::change_id(&output.change_id),
                    style::dim(&git_commit[..std::cmp::min(12, git_commit.len())])
                ),
                None => format!(
                    "Committed Heddle state {}",
                    style::change_id(&output.change_id)
                ),
            }
        );
        if let (Some(before), Some(after)) = (&output.git_previous_commit, &output.git_commit)
            && before != after
        {
            println!(
                "Git HEAD moved: {} -> {}",
                style::dim(&before[..std::cmp::min(12, before.len())]),
                style::dim(&after[..std::cmp::min(12, after.len())])
            );
        }
        if let Some(pending) = &output.included_pending_capture {
            println!(
                "Included prior Heddle-only save {}; this Git commit checkpoints the resulting state.",
                style::change_id(pending)
            );
        }
        println!(
            "Saved by: {}",
            style::principal(&output.principal.name, &output.principal.email)
        );
        if let Some(agent) = &output.agent {
            println!(
                "Agent: {}/{}",
                style::bold(&agent.provider),
                style::dim(&agent.model)
            );
        }
        if let Some(warning) = output.placeholder_principal_warning.as_deref() {
            eprintln!("{}", style::warn(warning));
        }
        if let Some(plan) = &output.git_index {
            println!("Commit scope: {}", commit_scope_text(plan));
            if !plan.will_commit.is_empty() {
                println!("Included: {}", plan.will_commit.join(", "));
            }
            if !plan.preserved_after_commit.is_empty() {
                println!(
                    "Left in worktree: {}",
                    plan.preserved_after_commit.join(", ")
                );
            }
        }
        if let Some(next) = &output.next_action {
            print_next(next);
        } else if output.trust.verified {
            println!("Verification: clean");
        }
    }

    Ok(())
}

fn commit_scope_text(plan: &GitIndexPlan) -> &'static str {
    match plan.commit_mode {
        "staged_index" => {
            "staged Git index only; unstaged and untracked paths stay in the worktree"
        }
        "worktree_all_explicit" => "all staged, unstaged, and untracked worktree changes (--all)",
        "worktree_all" => "all unstaged and untracked worktree changes",
        "none" => "no Git paths",
        _ => "Git worktree changes",
    }
}

pub async fn cmd_switch_git_adapter(cli: &Cli, args: SwitchArgs) -> Result<()> {
    if args.create {
        let path = args.target.replace('/', "-");
        let primary = format!("heddle start {} --path ../{}", args.target, path);
        return Err(anyhow!(RecoveryAdvice::safety_refusal(
            "git_checkout_create_branch",
            "`heddle switch -c` / `git checkout -b` are guided to Heddle's isolated thread flow",
            format!(
                "Create a Heddle thread with `{primary}` so the new work has its own checkout, provenance, and ready/land path."
            ),
            "Git-style branch creation would hide whether the user wants an in-place thread or an isolated checkout",
            "Heddle did not create a branch, move HEAD, or write the worktree",
            "repository refs, metadata, and worktree files were left unchanged",
            primary.clone(),
            vec![primary],
        )));
    }
    let repo = cli.open_repo()?;
    if refs::validate_ref_name(&args.target).is_ok()
        && repo
            .refs()
            .get_thread(&ThreadName::new(&args.target))?
            .is_some()
    {
        return cmd_thread(
            cli,
            ThreadCommands::Switch {
                name: args.target,
                print_cd_path: args.print_cd_path,
                force: args.force,
            },
        )
        .await;
    }
    if args.print_cd_path {
        return Err(anyhow!(RecoveryAdvice::safety_refusal(
            "switch_print_cd_path_requires_thread",
            "`--print-cd-path` only applies when switching to a thread",
            "Use `heddle switch --print-cd-path <thread>` for a materialized thread, or omit `--print-cd-path` when checking out a state.",
            "the target did not resolve to a Heddle thread with a checkout path",
            "checking out a state would move the worktree but could not report a thread checkout path",
            "Heddle did not move HEAD or write the worktree",
            "heddle switch <thread> --print-cd-path",
            vec![
                "heddle switch <thread> --print-cd-path".to_string(),
                "heddle switch <state>".to_string(),
            ],
        )));
    }
    super::goto::cmd_switch_state_checkout(cli, args.target, args.force)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn nothing_to_commit_advice_names_status_recovery() {
        let advice = nothing_to_commit_advice();

        assert_eq!(advice.kind, "nothing_to_commit");
        assert_eq!(advice.primary_command, "heddle status");
        assert!(advice.error.contains("nothing to commit"));
        assert!(advice.primary_hint().contains("heddle status"));
    }
}