heddle-cli 0.3.1

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
// SPDX-License-Identifier: Apache-2.0
//! Heddle: An AI-native version control system.

use std::{any::Any, time::Instant};

use anyhow::Result;
use clap::{Arg, ArgAction, CommandFactory, Parser, error::ErrorKind};
#[cfg(feature = "semantic")]
use cli::cli::commands::cmd_semantic;
#[cfg(feature = "git-overlay")]
use cli::cli::{
    BridgeCommands,
    commands::{cmd_bridge_git, cmd_git_overlay_guide},
};
use cli::{
    cli::{
        ActorCommands, AgentCommands, Cli, CloneArgs, CollapseArgs, Commands, ContextCommands,
        DaemonCommands, DiagnoseArgs, DiffArgs, ExpandArgs, IntegrationCommands, LogArgs,
        MergeArgs, ResolveArgs, RetroArgs, RevertArgs, RunArgs, SessionCommands, SessionEndArgs,
        SessionListArgs, SessionSegmentArgs, SessionShowArgs, SessionStartArgs, UndoArgs,
        cli_args::{LandArgs, SyncArgs},
        commands::{
            LogCommandOptions, RetroCommandOptions, SnapshotAgentOverrides, build_command_catalog,
            cmd_abort, cmd_actor_done, cmd_actor_explain, cmd_actor_list, cmd_actor_show,
            cmd_actor_spawn, cmd_adopt, cmd_agent, cmd_capture_split, cmd_checkpoint,
            cmd_cherry_pick, cmd_clean, cmd_clone, cmd_collapse, cmd_commit_compat, cmd_complete,
            cmd_context_audit, cmd_context_check, cmd_context_edit, cmd_context_get,
            cmd_context_history, cmd_context_list, cmd_context_rm, cmd_context_set,
            cmd_context_suggest, cmd_context_supersede, cmd_continue, cmd_daemon_serve,
            cmd_daemon_status, cmd_daemon_stop, cmd_diagnose, cmd_diff, cmd_discuss,
            cmd_doctor_docs, cmd_doctor_schemas, cmd_expand, cmd_fetch, cmd_fsck, cmd_hook,
            cmd_init, cmd_integration, cmd_land, cmd_log, cmd_maintenance, cmd_merge, cmd_oplog,
            cmd_pull, cmd_push, cmd_query, cmd_ready, cmd_rebase, cmd_redo, cmd_remote,
            cmd_resolve, cmd_retro, cmd_revert, cmd_review, cmd_run, cmd_schemas, cmd_session_end,
            cmd_session_list, cmd_session_segment, cmd_session_show, cmd_session_start, cmd_shell,
            cmd_show, cmd_snapshot, cmd_start, cmd_stash, cmd_status, cmd_switch_compat,
            cmd_sync_smart, cmd_thread, cmd_timeline, cmd_transaction, cmd_try, cmd_undo,
            cmd_verify, cmd_watch, command_runtime_contract_for_command, print_error_with_hint,
            print_parse_error_json_envelope,
        },
        render::write_json_stdout,
    },
    config::UserConfig,
    exit::HeddleExitCode,
    logging::{LoggingConfig, init_logging},
    operation_id::{resolve_operation_id, run_local_idempotency_if_requested},
    perf::{ProfileField, emit_profile, profile_enabled},
};
use tracing::debug;

// `current_thread` flavor avoids spinning up a CPU-count-sized worker
// pool on every CLI invocation. The foreground `heddle` binary is a
// one-shot command — `heddle status`, `heddle capture`, etc. don't
// fan out across cores. Daemon variants (`heddle daemon serve`,
// `heddle agent serve`) override this with their own runtime setup
// when they need real concurrency. Saves ~10-30ms of startup that the
// multi-thread flavor pays for thread-pool creation + teardown.
fn main() -> Result<()> {
    install_broken_pipe_panic_hook();
    let runtime = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()?;
    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        runtime.block_on(async_main())
    }));
    match result {
        Ok(Ok(())) => Ok(()),
        Ok(Err(error)) if is_broken_pipe_error(&error) => Ok(()),
        Ok(Err(error)) => Err(error),
        Err(payload) if is_broken_pipe_panic(payload.as_ref()) => Ok(()),
        Err(payload) => std::panic::resume_unwind(payload),
    }
}

async fn async_main() -> Result<()> {
    // Install the ring crypto provider as the rustls default. Without this,
    // any rustls TLS handshake (gRPC, GitHub REST, `bridge git import
    // https://…`) panics in 0.23.x. We pin ring instead of aws-lc-rs to
    // keep the 80s aws-lc-sys C build out of release builds. Measured
    // ~0ms on macOS — defensive ordering rather than a perf hot spot.
    let _ = rustls::crypto::ring::default_provider().install_default();

    // Register lazy-clone hydrator factories with the `repo` crate's
    // global registry. This must happen before any `Repository::open`
    // call so that opening a lazy-cloned repo can reconstruct + install
    // the on-read blob hydrator transparently. Without these
    // registrations, the second-and-subsequent CLI invocation against a
    // `--lazy` clone would see `MissingObject` on every blob read.
    cli::cli::commands::register_git_overlay_factory();
    #[cfg(feature = "client")]
    heddle_client::grpc_hosted::register_hosted_factory();

    // Pick the WeftExtensions implementation at startup. OSS builds
    // get NoopWeftExtensions (returns friendly errors for `auth`,
    // `support`, `presence` commands). client builds get the
    // EnabledWeftExtensions adapter that delegates to the existing
    // in-cli command impls; Step 5 of the OSS extraction plan moves
    // those impls into a separate closed crate.
    #[cfg(feature = "client")]
    let hosted: Box<dyn weft_client_shim::WeftExtensions> =
        Box::new(cli::extensions::EnabledWeftExtensions);
    // OSS builds dispatch no hosted commands (those `Commands` variants
    // are gated behind `client`), so the trait object is unused
    // and we drop the binding entirely. Keeping the shim trait + Noop
    // visible for downstream consumers and post-split closed builds.

    let total_start = Instant::now();
    let profile = profile_enabled();
    // Intercept the bare-help shapes BEFORE clap parses, so we
    // serve the curated everyday list instead of clap's auto-help.
    // Catches `heddle`, `heddle --help`, `heddle -h`, `heddle help`,
    // AND the case where only global flags were passed (e.g.
    // `heddle --output text`). Without the global-flags branch, clap
    // emits its 60+ verb wall-of-text on missing subcommand — which is
    // exactly the noisy first impression the curated printer is meant
    // to replace.
    {
        let raw: Vec<String> = std::env::args().skip(1).collect();
        let bare = raw.is_empty()
            || raw == ["--help"]
            || raw == ["-h"]
            || raw == ["help"]
            || is_global_flags_only(&raw);
        if bare {
            let command_start = Instant::now();
            if raw_wants_json(&raw) {
                write_json_stdout(&build_command_catalog())?;
            } else {
                cli::cli::help::print_help(&Cli::command(), &[])?;
            }
            if profile {
                emit_profile(
                    "help",
                    &[
                        ProfileField::duration("command_body_ms", command_start.elapsed()),
                        ProfileField::duration("total_ms", total_start.elapsed()),
                    ],
                );
            }
            return Ok(());
        }
        if let Some(result) = cli::cli::help::print_direct_help_for_raw(&Cli::command(), &raw) {
            result?;
            if profile {
                emit_profile(
                    "help",
                    &[ProfileField::duration("total_ms", total_start.elapsed())],
                );
            }
            return Ok(());
        }
        // `heddle help <topic>` — let clap handle when the user passes
        // the verb explicitly (it dispatches to Commands::Help). A two-
        // arg form `heddle help <topic>` also goes through clap.
    }
    let raw_argv: Vec<String> = std::env::args().collect();
    let parse_argv = rewrite_phase_2_alias_argv(&raw_argv).unwrap_or(raw_argv);
    let cli = match Cli::try_parse_from(parse_argv) {
        Ok(cli) => cli,
        Err(err) => {
            let raw: Vec<String> = std::env::args().skip(1).collect();
            if raw_wants_json(&raw)
                && !matches!(
                    err.kind(),
                    ErrorKind::DisplayHelp | ErrorKind::DisplayVersion
                )
            {
                print_parse_error_json_envelope(&err);
                std::process::exit(HeddleExitCode::from_clap(&err).into());
            }
            err.print()?;
            std::process::exit(HeddleExitCode::from_clap(&err).into());
        }
    };
    // `heddle capture --help-agent`: clap has now parsed the entire command
    // line — every global spelling it accepts (`-C <path>`, `--output <fmt>`,
    // clustered `-vC <path>`, attached forms, any position) was handled by
    // clap, not a hand-rolled token scan. Inspect the parsed result and render
    // the reveal help before running capture. This is help, not diagnostics,
    // so it exits before config/logging init.
    if let Commands::Capture(args) = &cli.command
        && args.help_agent
    {
        cli::cli::help::print_capture_agent_help(&Cli::command())?;
        if profile {
            emit_profile(
                "help",
                &[ProfileField::duration("total_ms", total_start.elapsed())],
            );
        }
        return Ok(());
    }
    // Resolve color decision once, before any rendering site fires.
    // The helpers in `cli::style` consult a process-wide OnceLock —
    // doing this inside each render path would re-query the env on
    // every line and fight the brand goal of restraint.
    cli::cli::style::init_from_cli(&cli);
    let command_contract = command_runtime_contract_for_command(&cli.command);
    let command_name = command_contract.display.clone();
    let command_supports_op_id = command_contract.supports_op_id;
    let config_start = Instant::now();
    // Route early UserConfig load failures through the same typed
    // envelope as command-body errors. Without this, a legacy
    // `output.format = "auto"` in the global user config (or via
    // `HEDDLE_CONFIG`) exits with a raw TOML parse error and bypasses
    // the `Next:` / JSON-envelope contract #271 promised — `?` here
    // would propagate to `main` and print via anyhow's Debug impl.
    let user_config = match UserConfig::load_default() {
        Ok(config) => config,
        // Hidden harness relay hooks must reach harness init so that a bad
        // user config is reported as a warning and the hook can continue.
        // Normal foreground commands keep the strict typed error path.
        Err(_) if is_harness_relay_invocation(&cli.command) => UserConfig::default(),
        Err(err) => {
            let code = HeddleExitCode::from_error(&err);
            print_error_with_hint(&cli, &err);
            std::process::exit(code.into());
        }
    };
    let config_load_ms = config_start.elapsed().as_millis();
    let logging_start = Instant::now();
    // Foreground CLI commands default to WARN-level logs so the human-facing
    // surface stays quiet. Long-running daemons keep the historical INFO
    // default since their stderr is the operator's audit log.
    let base_logging = LoggingConfig::from_user_and_env(Some(&user_config));
    let logging = if is_daemon_invocation(&cli.command) {
        base_logging.with_verbosity(cli.verbose.max(1), cli.quiet)
    } else {
        base_logging.with_verbosity(cli.verbose, cli.quiet)
    };
    let telemetry = init_logging(logging);
    let logging_init_ms = logging_start.elapsed().as_millis();

    debug!(
        command = command_name.as_str(),
        config_load_ms,
        logging_init_ms,
        startup_ms = total_start.elapsed().as_millis(),
        "CLI startup complete"
    );

    // Unsupported-output gates exit through `from_error` so the process
    // exit code and the envelope's `exit_code` field agree: DataErr (65),
    // because `--output json[-compact]` here is well-formed syntax the
    // command semantically rejects — not a malformed invocation (Usage 64).
    // Agents treat 64 as "fix your argv" and retry-with-mutation; 65 tells
    // them to fall back to a supported output mode (HeddleCo/heddle#648).
    if explicit_json_requested(&cli) && !command_contract.supports_json {
        telemetry.shutdown();
        let err = anyhow::anyhow!(cli::cli::commands::RecoveryAdvice::json_unsupported(
            &command_name
        ));
        let code = HeddleExitCode::from_error(&err);
        print_error_with_hint(&cli, &err);
        std::process::exit(code.into());
    }
    if cli::cli::output_is_compact(&cli) && !command_contract.supports_json_compact {
        telemetry.shutdown();
        let err = anyhow::anyhow!(
            cli::cli::commands::RecoveryAdvice::json_compact_unsupported(&command_name)
        );
        let code = HeddleExitCode::from_error(&err);
        print_error_with_hint(&cli, &err);
        std::process::exit(code.into());
    }

    match run_local_idempotency_if_requested(&cli, &command_name, command_supports_op_id) {
        Ok(true) => {
            telemetry.shutdown();
            return Ok(());
        }
        Ok(false) => {}
        Err(err) => {
            telemetry.shutdown();
            let code = HeddleExitCode::from_error(&err);
            print_error_with_hint(&cli, &err);
            std::process::exit(code.into());
        }
    }

    if command_supports_op_id {
        resolve_operation_id(&cli)?;
    }

    let command_start = Instant::now();
    let result = match &cli.command {
        Commands::Init(args) => cmd_init(&cli, args.clone()),

        Commands::Adopt(args) => cmd_adopt(&cli, args.clone()),

        Commands::Help { topics } => {
            // Curated help printer. No op-id (read-only), no
            // structured output unless explicitly asked to print the
            // command catalog.
            if explicit_json_requested(&cli) {
                write_json_stdout(&build_command_catalog())
            } else {
                cli::cli::help::print_help(&Cli::command(), topics).map_err(Into::into)
            }
        }

        Commands::Status {
            short,
            watch,
            watch_iterations,
            watch_interval_ms,
        } => cmd_status(&cli, *short, *watch, *watch_iterations, *watch_interval_ms).await,

        Commands::Watch(args) => cmd_watch(&cli, args.clone()).await,

        Commands::Verify => cmd_verify(&cli, cli.verbose > 0),

        Commands::Doctor(args) => match &args.command {
            None => cmd_diagnose(
                &cli,
                DiagnoseArgs {
                    profile: args.profile,
                },
            ),
            Some(cli::cli::DoctorCommands::Docs(docs_args)) => {
                cmd_doctor_docs(&cli, docs_args.clone())
            }
            Some(cli::cli::DoctorCommands::Schemas(schema_args)) => {
                cmd_doctor_schemas(&cli, schema_args.clone())
            }
        },

        Commands::Schemas { verb } => cmd_schemas(&cli, verb),

        #[cfg(feature = "git-overlay")]
        Commands::GitOverlay => cmd_git_overlay_guide(&cli),

        Commands::Start(args) => cmd_start(&cli, args.clone()),

        Commands::Run(RunArgs { thread, command }) => {
            cmd_run(&cli, thread.clone(), command.clone())
        }

        Commands::Try(args) => cmd_try(&cli, args.clone()),

        Commands::Sync(SyncArgs { thread }) => {
            // Codex's enhanced sync (rebase-aware fast-forward path);
            // main wired `cmd_sync` here pre-rebase. The smart variant
            // is a strict superset, so we use it on the merged
            // branch.
            cmd_sync_smart(
                &cli,
                SyncArgs {
                    thread: thread.clone(),
                },
            )
            .await
        }

        Commands::Continue => cmd_continue(&cli).await,

        Commands::Abort => cmd_abort(&cli),

        Commands::Land(LandArgs {
            thread,
            message,
            no_squash,
            push,
            no_push,
            remote,
        }) => {
            cmd_land(
                &cli,
                LandArgs {
                    thread: thread.clone(),
                    message: message.clone(),
                    no_squash: *no_squash,
                    push: *push,
                    no_push: *no_push,
                    remote: remote.clone(),
                },
            )
            .await
        }

        Commands::Ready(args) => cmd_ready(&cli, args.clone()).await,

        Commands::Capture(args) => {
            if args.split {
                cmd_capture_split(
                    &cli,
                    args.into.clone().unwrap_or_default(),
                    args.paths.clone(),
                    args.intent.clone(),
                )
            } else {
                cmd_snapshot(
                    &cli,
                    args.intent.clone(),
                    args.confidence,
                    args.force,
                    SnapshotAgentOverrides {
                        provider: args.agent_provider.clone(),
                        model: args.agent_model.clone(),
                        session: args.agent_session.clone(),
                        segment: args.agent_segment.clone(),
                        policy: args.policy.clone(),
                        no_policy: args.no_policy,
                        no_agent: args.no_agent,
                    },
                )
                .await
            }
        }

        Commands::Commit(args) => cmd_commit_compat(&cli, args.clone()).await,

        Commands::Log(LogArgs {
            state,
            limit,
            all,
            graph,
            oneline,
            reflog,
            timeline,
            thread,
            agent,
            paths,
            since,
        }) => {
            cmd_log(
                &cli,
                LogCommandOptions {
                    state: state.clone(),
                    limit: *limit,
                    all: *all,
                    graph: *graph,
                    oneline: *oneline,
                    reflog: *reflog,
                    timeline: *timeline,
                    thread: thread.clone(),
                    agent: agent.clone(),
                    paths: paths.clone(),
                    since: since.clone(),
                },
            )
            .await
        }

        Commands::Show { state } => cmd_show(&cli, state.clone()),

        Commands::Timeline(args) => cmd_timeline(&cli, args.clone()),

        Commands::Retro(RetroArgs {
            since,
            include_merges,
            include_undos,
            full,
        }) => {
            cmd_retro(
                &cli,
                RetroCommandOptions {
                    since: since.clone(),
                    include_merges: *include_merges,
                    include_undos: *include_undos,
                    verbose: *full,
                },
            )
            .await
        }

        Commands::Clean { force, dry_run } => cmd_clean(&cli, *force, *dry_run),

        Commands::Diff(DiffArgs {
            from,
            to,
            semantic,
            stat,
            name_only,
            unified,
            context,
            patch,
        }) => cmd_diff(
            &cli,
            from.clone(),
            to.clone(),
            *semantic,
            *stat,
            *name_only,
            *unified,
            *context,
            *patch,
        ),

        Commands::Switch(args) => cmd_switch_compat(&cli, args.clone()).await,

        Commands::Revert(RevertArgs {
            state,
            message,
            no_commit,
        }) => cmd_revert(&cli, state.clone(), message.clone(), *no_commit),

        Commands::Undo(UndoArgs {
            steps,
            list,
            depth,
            preview,
            redo,
            allow_redact_undo,
        }) => {
            if *redo {
                cmd_redo(&cli, *steps, *preview)
            } else {
                cmd_undo(&cli, *steps, *list, *depth, *preview, *allow_redact_undo)
            }
        }

        Commands::Fetch { remote, all } => cmd_fetch(&cli, remote.clone(), *all).await,

        Commands::Fsck {
            full,
            thorough,
            repair,
            bridge,
        } => cmd_fsck(&cli, *full, *thorough, *repair, *bridge),

        Commands::Oplog { command } => cmd_oplog(&cli, command.clone()),

        Commands::Collapse(CollapseArgs {
            states,
            into,
            confidence,
        }) => cmd_collapse(&cli, states.clone(), into.clone(), *confidence),

        Commands::Expand(ExpandArgs { reference }) => cmd_expand(&cli, reference.clone()),

        Commands::Thread { command } => cmd_thread(&cli, command.clone()).await,

        Commands::Shell { command } => cmd_shell(&cli, command.clone()),

        Commands::Complete { subject } => cmd_complete(&cli, *subject),

        Commands::Merge(MergeArgs {
            thread,
            message,
            no_commit,
            preview,
            with_diff,
            no_semantic,
            git_commit,
        }) => cmd_merge(
            &cli,
            thread.clone(),
            message.clone(),
            *no_commit,
            *preview,
            *with_diff,
            *no_semantic,
            *git_commit,
        ),

        Commands::Resolve(ResolveArgs {
            path,
            all,
            list,
            ours,
            theirs,
            force,
            abort,
        }) => cmd_resolve(
            &cli,
            path.clone(),
            *all,
            *list,
            *ours,
            *theirs,
            *force,
            *abort,
        ),

        Commands::Push(args) => {
            cmd_push(
                &cli,
                args.remote.clone(),
                args.thread_name(),
                args.state.clone(),
                args.force,
                args.all_threads,
                args.mirror.clone(),
            )
            .await
        }

        Commands::Pull(args) => {
            cmd_pull(
                &cli,
                args.remote_op.remote.clone(),
                args.remote_op.thread.clone(),
                args.local_thread.clone(),
                args.lazy,
            )
            .await
        }

        Commands::Remote { command } => cmd_remote(&cli, command.clone()),

        #[cfg(feature = "client")]
        Commands::Auth { command } => {
            let cmd = command.clone();
            hosted.auth(&cli, &cmd).await
        }

        Commands::Context { command } => match command {
            ContextCommands::Set(args) => {
                cmd_context_set(
                    &cli,
                    args.target.path.clone(),
                    args.target.state.clone(),
                    args.scope.clone(),
                    args.kind.clone(),
                    args.tag.clone(),
                    args.message.clone(),
                    args.file.clone(),
                )
                .await
            }
            ContextCommands::Get(args) => {
                cmd_context_get(
                    &cli,
                    args.target.path.clone(),
                    args.target.state.clone(),
                    args.scope.clone(),
                    args.tag.clone(),
                    args.r#ref.clone(),
                )
                .await
            }
            ContextCommands::List(args) => {
                cmd_context_list(
                    &cli,
                    args.prefix.clone(),
                    args.tag.clone(),
                    args.r#ref.clone(),
                    args.include_superseded,
                )
                .await
            }
            ContextCommands::History(args) => {
                cmd_context_history(&cli, args.annotation_id.clone(), args.r#ref.clone()).await
            }
            ContextCommands::Edit(args) => {
                cmd_context_edit(
                    &cli,
                    args.annotation_id.clone(),
                    args.kind.clone(),
                    args.tag.clone(),
                    args.message.clone(),
                    args.file.clone(),
                )
                .await
            }
            ContextCommands::Supersede(args) => {
                cmd_context_supersede(
                    &cli,
                    args.annotation_id.clone(),
                    args.target.path.clone(),
                    args.target.state.clone(),
                    args.scope.clone(),
                    args.kind.clone(),
                    args.tag.clone(),
                    args.message.clone(),
                    args.file.clone(),
                )
                .await
            }
            ContextCommands::Rm(args) => {
                cmd_context_rm(
                    &cli,
                    args.target.path.clone(),
                    args.target.state.clone(),
                    args.scope.clone(),
                    args.all,
                )
                .await
            }
            ContextCommands::Check(args) => {
                cmd_context_check(
                    &cli,
                    args.path.clone(),
                    args.state.clone(),
                    args.tag.clone(),
                    args.r#ref.clone(),
                )
                .await
            }
            ContextCommands::Suggest(args) => {
                cmd_context_suggest(&cli, args.r#ref.clone(), args.limit).await
            }
            ContextCommands::Audit(args) => cmd_context_audit(&cli, args.r#ref.clone()).await,
        },

        Commands::Integration { command } => cmd_integration(&cli, command.clone()),

        Commands::Stash { command } => cmd_stash(&cli, command.clone()),

        #[cfg(feature = "client")]
        Commands::Support { command } => {
            let cmd = command.clone();
            hosted.support(&cli, &cmd).await
        }

        #[cfg(feature = "git-overlay")]
        Commands::Bridge { command } => match command {
            BridgeCommands::Git { command } => cmd_bridge_git(&cli, command.clone()),
        },

        #[cfg(feature = "semantic")]
        Commands::Semantic { command } => cmd_semantic(&cli, command.clone()),

        Commands::Daemon { command } => match command {
            DaemonCommands::Serve => cmd_daemon_serve(&cli),
            DaemonCommands::Status => cmd_daemon_status(&cli),
            DaemonCommands::Stop => cmd_daemon_stop(&cli),
        },

        Commands::Agent { command } => cmd_agent(&cli, command).await,

        Commands::Discuss { command } => cmd_discuss(&cli, command).await,

        Commands::Query(args) => cmd_query(&cli, args).await,

        Commands::Checkpoint(args) => cmd_checkpoint(&cli, args).await,

        Commands::Transaction { command } => cmd_transaction(&cli, command).await,

        Commands::Review { command } => cmd_review(&cli, command).await,

        Commands::Redact { command } => cli::cli::commands::cmd_redact(&cli, command.clone()),

        Commands::Visibility { command } => {
            cli::cli::commands::cmd_visibility(&cli, command.clone())
        }

        Commands::Maintenance { command } => cmd_maintenance(&cli, command.clone()),

        Commands::CherryPick {
            commit,
            message,
            no_commit,
            force,
        } => cmd_cherry_pick(&cli, commit.clone(), message.clone(), *no_commit, *force),

        Commands::Clone(CloneArgs {
            remote,
            local,
            thread,
            depth,
            lazy,
            filter,
        }) => {
            cmd_clone(
                &cli,
                remote.clone(),
                local.clone(),
                thread.clone(),
                *depth,
                *lazy,
                filter.clone(),
            )
            .await
        }

        Commands::Rebase {
            thread,
            abort,
            cont,
            force,
        } => cmd_rebase(&cli, thread.as_deref(), *abort, *cont, *force),

        Commands::Hook { command } => cmd_hook(&cli, command.clone()),

        Commands::Actor { command } => match command {
            ActorCommands::Spawn(args) => {
                cmd_actor_spawn(
                    &cli,
                    args.thread.clone(),
                    args.no_thread,
                    args.provider.clone(),
                    args.model.clone(),
                )
                .await
            }
            ActorCommands::List(args) => cmd_actor_list(&cli, args.active).await,
            ActorCommands::Show(args) => cmd_actor_show(&cli, args.session.clone()).await,
            ActorCommands::Explain(args) => cmd_actor_explain(&cli, args.session.clone()).await,
            ActorCommands::Done(args) => cmd_actor_done(&cli, args.session.clone()).await,
        },

        // cmd_agent is the unified dispatcher: daemon variants
        // (Serve/Status/Stop) plus the reservation API (Reserve/
        // Heartbeat/Capture/Ready/Release/List).
        Commands::Session { command } => match command {
            SessionCommands::Start(SessionStartArgs {
                provider,
                model,
                policy,
            }) => cmd_session_start(&cli, provider.clone(), model.clone(), policy.clone()).await,
            SessionCommands::Segment(SessionSegmentArgs {
                provider,
                model,
                policy,
            }) => cmd_session_segment(&cli, provider.clone(), model.clone(), policy.clone()).await,
            SessionCommands::End(SessionEndArgs { session_id }) => {
                cmd_session_end(&cli, session_id.clone()).await
            }
            SessionCommands::Show(SessionShowArgs { session_id }) => {
                cmd_session_show(&cli, session_id.clone()).await
            }
            SessionCommands::List(SessionListArgs { active }) => {
                cmd_session_list(&cli, *active).await
            }
        },

        #[cfg(feature = "client")]
        Commands::Presence { command } => match command {
            cli::cli::PresenceCommands::Publish {
                session,
                interval_secs,
            } => {
                hosted
                    .presence_publish(&cli, session.clone(), *interval_secs)
                    .await
            }
        },
    };

    debug!(
        command = command_name.as_str(),
        config_load_ms,
        logging_init_ms,
        command_body_ms = command_start.elapsed().as_millis(),
        total_ms = total_start.elapsed().as_millis(),
        "CLI command complete"
    );

    if profile {
        emit_profile(
            &command_name,
            &[
                ProfileField::millis("config_load_ms", config_load_ms),
                ProfileField::millis("logging_init_ms", logging_init_ms),
                ProfileField::duration("command_body_ms", command_start.elapsed()),
                ProfileField::duration("total_ms", total_start.elapsed()),
            ],
        );
    }

    telemetry.shutdown();
    match result {
        Ok(()) => Ok(()),
        Err(err) if is_broken_pipe_error(&err) => Ok(()),
        Err(err) => {
            let code = HeddleExitCode::from_error(&err);
            print_error_with_hint(&cli, &err);
            std::process::exit(code.into());
        }
    }
}

fn is_harness_relay_invocation(command: &Commands) -> bool {
    matches!(
        command,
        Commands::Integration {
            command: IntegrationCommands::Relay(_),
        }
    )
}

fn rewrite_phase_2_alias_argv(argv: &[String]) -> Option<Vec<String>> {
    let root = first_command_index(argv)?;
    match argv[root].as_str() {
        "blame" => {
            let mut rewritten = Vec::with_capacity(argv.len() + 1);
            rewritten.extend_from_slice(&argv[..root]);
            rewritten.push("query".to_string());
            rewritten.push("--attribution".to_string());
            rewritten.extend_from_slice(&argv[root + 1..]);
            Some(rewritten)
        }
        "purge" => {
            let mut rewritten = Vec::with_capacity(argv.len() + 1);
            rewritten.extend_from_slice(&argv[..root]);
            rewritten.push("redact".to_string());
            rewritten.push("purge".to_string());
            rewritten.extend_from_slice(&argv[root + 1..]);
            Some(rewritten)
        }
        _ => None,
    }
}

fn first_command_index(argv: &[String]) -> Option<usize> {
    let mut index = 1;
    while index < argv.len() {
        let arg = argv[index].as_str();
        match arg {
            "--" => return None,
            "--output" | "--repo" | "-C" | "--op-id" => index += 2,
            "--no-color" | "--verbose" | "--quiet" | "-v" | "-q" => index += 1,
            _ if arg.starts_with("--output=")
                || arg.starts_with("--repo=")
                || arg.starts_with("--op-id=")
                || (arg.starts_with("-C") && arg.len() > 2)
                || short_verbose_quiet_cluster(arg) =>
            {
                index += 1;
            }
            _ => return Some(index),
        }
    }
    None
}

fn short_verbose_quiet_cluster(arg: &str) -> bool {
    arg.len() > 2
        && arg.starts_with('-')
        && !arg.starts_with("--")
        && arg[1..].chars().all(|ch| matches!(ch, 'v' | 'q'))
}

/// True when the raw argv (after the program name) contains only global
/// flags and their values — i.e. the user typed `heddle --output text` or
/// `heddle --no-color -v` with no subcommand verb. We want to show the
/// curated everyday-verb help in that case, not clap's wall-of-subcommands
/// error.
///
/// The global flag set comes from clap metadata so this pre-parse fast path
/// tracks the real CLI contract, including hidden globals and aliases.
fn is_global_flags_only(raw: &[String]) -> bool {
    if raw.is_empty() {
        return false; // caller already handles the truly-empty case
    }

    let command = Cli::command();
    raw_global_flags(&command, raw).is_some()
}

fn raw_wants_json(raw: &[String]) -> bool {
    let command = Cli::command();
    let mut wants_json = false;
    let mut index = 0;

    while index < raw.len() {
        let Some((arg, value, consumed)) = raw_global_flag_at(&command, raw, index) else {
            index += 1;
            continue;
        };
        if arg.get_id().as_str() == "output" && value.is_some_and(|value| value == "json") {
            wants_json = true;
        }
        index += consumed;
    }

    wants_json
}

fn raw_global_flags<'a>(
    command: &'a clap::Command,
    raw: &'a [String],
) -> Option<Vec<(&'a Arg, Option<&'a str>)>> {
    let mut flags = Vec::new();
    let mut index = 0;
    while index < raw.len() {
        let (arg, value, consumed) = raw_global_flag_at(command, raw, index)?;
        flags.push((arg, value));
        index += consumed;
    }
    Some(flags)
}

fn raw_global_flag_at<'a>(
    command: &'a clap::Command,
    raw: &'a [String],
    index: usize,
) -> Option<(&'a Arg, Option<&'a str>, usize)> {
    let token = raw.get(index)?.as_str();
    if let Some(long) = token.strip_prefix("--") {
        let (long, inline_value) = long.split_once('=').unwrap_or((long, ""));
        let inline_value = token.contains('=').then_some(inline_value);
        let arg = global_arg_by_long(command, long)?;
        if global_arg_takes_value(arg) {
            if let Some(value) = inline_value {
                return Some((arg, Some(value), 1));
            }
            let value = raw.get(index + 1)?.as_str();
            if value.starts_with('-') {
                return None;
            }
            return Some((arg, Some(value), 2));
        }
        return inline_value.is_none().then_some((arg, None, 1));
    }

    let short_flags = token.strip_prefix('-')?;
    if short_flags.is_empty() {
        return None;
    }

    let chars: Vec<(usize, char)> = short_flags.char_indices().collect();
    let mut offset = 0;
    while offset < chars.len() {
        let (byte_index, short) = chars[offset];
        let arg = global_arg_by_short(command, short)?;
        if global_arg_takes_value(arg) {
            let value_start = byte_index + short.len_utf8();
            if value_start < short_flags.len() {
                return Some((arg, Some(&short_flags[value_start..]), 1));
            }
            let value = raw.get(index + 1)?.as_str();
            if value.starts_with('-') {
                return None;
            }
            return Some((arg, Some(value), 2));
        }
        offset += 1;
    }

    let first_short = chars.first().map(|(_, short)| *short)?;
    Some((global_arg_by_short(command, first_short)?, None, 1))
}

fn global_arg_by_long<'a>(command: &'a clap::Command, long: &str) -> Option<&'a Arg> {
    command
        .get_arguments()
        .filter(|arg| arg.is_global_set())
        .find(|arg| {
            arg.get_long() == Some(long)
                || arg
                    .get_all_aliases()
                    .unwrap_or_default()
                    .into_iter()
                    .any(|alias| alias == long)
                || arg
                    .get_visible_aliases()
                    .unwrap_or_default()
                    .into_iter()
                    .any(|alias| alias == long)
        })
}

fn global_arg_by_short(command: &clap::Command, short: char) -> Option<&Arg> {
    command
        .get_arguments()
        .filter(|arg| arg.is_global_set())
        .find(|arg| {
            arg.get_short() == Some(short)
                || arg
                    .get_all_short_aliases()
                    .unwrap_or_default()
                    .into_iter()
                    .any(|alias| alias == short)
                || arg
                    .get_visible_short_aliases()
                    .unwrap_or_default()
                    .into_iter()
                    .any(|alias| alias == short)
        })
}

fn global_arg_takes_value(arg: &Arg) -> bool {
    matches!(arg.get_action(), ArgAction::Set | ArgAction::Append)
}

fn explicit_json_requested(cli: &Cli) -> bool {
    matches!(
        cli.output,
        Some(cli::cli::OutputMode::Json | cli::cli::OutputMode::JsonCompact)
    )
}

fn is_broken_pipe_error(error: &anyhow::Error) -> bool {
    error
        .downcast_ref::<std::io::Error>()
        .is_some_and(|io| io.kind() == std::io::ErrorKind::BrokenPipe)
        || error.to_string().contains("Broken pipe")
}

fn is_broken_pipe_panic(payload: &(dyn Any + Send)) -> bool {
    payload
        .downcast_ref::<String>()
        .is_some_and(|message| message.contains("Broken pipe"))
        || payload
            .downcast_ref::<&'static str>()
            .is_some_and(|message| message.contains("Broken pipe"))
}

fn install_broken_pipe_panic_hook() {
    let previous = std::panic::take_hook();
    std::panic::set_hook(Box::new(move |info| {
        if is_broken_pipe_panic(info.payload()) {
            return;
        }
        previous(info);
    }));
}

/// True for long-running daemon entry points whose stderr is the operator's
/// audit log. These keep an INFO-level default; everything else defaults to
/// WARN so a human running `heddle status` doesn't see internal tracing.
fn is_daemon_invocation(command: &Commands) -> bool {
    matches!(
        command,
        Commands::Daemon {
            command: DaemonCommands::Serve
        } | Commands::Agent {
            command: AgentCommands::Serve(_)
        }
    )
}

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

    fn args(raw: &[&str]) -> Vec<String> {
        raw.iter().map(|arg| (*arg).to_string()).collect()
    }

    #[test]
    fn global_flags_only_accepts_text_output_globals() {
        assert!(is_global_flags_only(&args(&["--output", "text"])));
        assert!(is_global_flags_only(&args(&["--output=text"])));
        assert!(is_global_flags_only(&args(&["--no-color", "-v"])));
        assert!(is_global_flags_only(&args(&["-C", "."])));
        assert!(is_global_flags_only(&args(&["-C."])));
        assert!(is_global_flags_only(&args(&["-vvv"])));
        assert!(is_global_flags_only(&args(&["-qv"])));
    }

    #[test]
    fn global_flags_only_accepts_json_globals() {
        assert!(is_global_flags_only(&args(&["--output", "json"])));
        assert!(is_global_flags_only(&args(&["--output=json"])));
    }

    #[test]
    fn global_flags_only_rejects_commands_unknowns_and_dangling_values() {
        assert!(!is_global_flags_only(&args(&[])));
        assert!(!is_global_flags_only(&args(&["status"])));
        assert!(!is_global_flags_only(&args(&["--not-a-global"])));
        assert!(!is_global_flags_only(&args(&["--output"])));
        assert!(!is_global_flags_only(&args(&["--output", "--no-color"])));
        assert!(!is_global_flags_only(&args(&["--repo"])));
        assert!(!is_global_flags_only(&args(&["-C"])));
    }

    #[test]
    fn raw_wants_json_uses_clap_global_metadata() {
        assert!(raw_wants_json(&args(&["--output", "json"])));
        assert!(raw_wants_json(&args(&["--output=json"])));
        assert!(!raw_wants_json(&args(&["--output", "text"])));
        assert!(!raw_wants_json(&args(&["--output=text"])));
        assert!(!raw_wants_json(&args(&["--output", "--no-color"])));
    }
}