trusty-code 0.8.1

Per-project Claude-Code-compatible MPM orchestration harness (bin: tcode) — an original coding harness, tracked under epic #2052.
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
//! tcode — entry point for the trusty-code CLI.
//!
//! Why: provides the `tcode` binary that operators, agents, and TUI frontends
//! use to interact with the per-project MPM orchestration harness. As of
//! #2060 (M1 cut-line "replay via thin CLI"), `run-task`, `session list`/
//! `status`, `attach`, `cancel`, and `transcript` are all thin JSON-RPC
//! clients over a `tcode serve --stdio` child this binary spawns itself
//! (`trusty_code::cli_client` + `crate::cli`) — no orchestration logic lives
//! in the CLI. The ORIGINAL in-process `run-task` execution (epic #1039 /
//! #1034, calling `trusty_code::run_task::execute_run_task` directly) is
//! kept available behind `--legacy-in-process` (see [`Command::RunTask`]'s
//! docs for why it was kept rather than deleted) — `trusty_code::run_task`'s
//! own extensive offline test suite (`run_task::tests`) exercises that
//! library function directly and is unaffected by this CLI-layer change.
//! That legacy path's own wrapper lives in `crate::cli::legacy_run_task`
//! (#4434), alongside every other subcommand handler — this file holds no
//! subcommand body except `run_serve`.
//!
//! What: thin clap CLI. `serve` (#2053) delegates to
//! `trusty_code::serve::run_stdio` or `trusty_code::serve::uds::run_daemon`
//! (the persistent socket daemon, the only one since #6637).
//! `run-workflow` remains a stub. `workstream` (`ws` alias, #3296, DOC-48
//! §5.4) is the same thin-client shape over `workstream.*` — see
//! [`WorkstreamCommand`] and `crate::cli::workstream`. `tui` (#4424, DOC-50
//! §4.1/AC-2.4) is the odd one out: instead of spawning its own ephemeral
//! `--stdio` child, it attaches to an ALREADY-RUNNING `tcode serve` daemon
//! over its socket and hands `trusty_code::tui_client::CodeEngine` to
//! `trusty_code_tui::run::run` — see `crate::cli::tui`.
//!
//! Test: `cargo run -p trusty-code -- --version` must exit 0 and print the
//! crate version. The thin-client subcommands are covered end-to-end by
//! `tests/cli_e2e.rs` (spawns the real binary); the legacy in-process path
//! remains covered by `trusty_code::run_task::tests`.

// docs.rs builds a release's documentation once, from the uploaded tarball,
// so a broken intra-doc link is baked into that version forever and only a new
// release can correct it. Deny keeps this crate at zero rather than letting the
// ratchet in `scripts/check_rustdoc_links.sh` absorb a new one.
#![deny(rustdoc::broken_intra_doc_links)]

use std::path::{Path, PathBuf};
use std::process;

use anyhow::Result;
use clap::{Parser, Subcommand};

use trusty_code::run_task::ExitCode;

mod cli;

// #8031: clap-surface tests live in a sibling `_tests.rs`, per the crate's
// `protocol_tests.rs`/`executor_tests.rs` convention.
#[cfg(test)]
#[path = "main_tests.rs"]
mod tests;

/// tcode — per-project Claude-Code-compatible MPM orchestration harness.
#[derive(Parser)]
#[command(
    name = "tcode",
    // Not clap's bare `version` (which prints the semver alone): a semver
    // cannot identify WHICH build produced a run's artifacts (#2823), so
    // `--version` carries the git SHA + commit date too.
    version = trusty_code::build_info::LONG_VERSION,
    about = "Per-project Claude-Code-compatible MPM orchestration harness",
    long_about = None,
)]
struct Cli {
    #[command(subcommand)]
    command: Command,
}

/// Top-level subcommands for `tcode`.
///
/// Why: defines the stable CLI surface for all Phase 0+ callers. Stubs are
/// replaced by real implementations as each phase of #587/#1039 lands.
/// What: clap enum; each variant maps to one subcommand.
/// Test: `tcode --help` lists all variants; functional commands exit 0.
#[derive(Subcommand)]
enum Command {
    /// Start the per-project orchestration server.
    ///
    /// Accepts JSON-RPC 2.0 task requests from CLI clients, TUI frontends,
    /// and MCP callers. One instance per project. With no transport flag it
    /// is the persistent daemon on its owner-only Unix socket; `--stdio`
    /// serves one client over stdin/stdout instead.
    Serve {
        // #6999: same stale `.claude/`-only wording as `run-task` carried.
        /// Path to the project root. Its configuration is read from
        /// `.trusty-code/`, falling back to `.claude/` then `.open-mpm/`; none
        /// of the three has to exist.
        ///
        /// OPTIONAL: omit it to serve PROJECTLESS — a first-class state for
        /// chat/planning before a project is chosen, and the state the shell's
        /// entry screen renders. A projectless daemon indexes nothing, has no
        /// diff target, and scopes no memory palace; agents resolve from the
        /// user-level `~/.claude/agents`. The path must be an existing
        /// directory when given; it need NOT be a git repo (a plain directory
        /// binds and indexes just like a repo, minus git affordances).
        #[arg(long, short, value_name = "PATH")]
        project: Option<PathBuf>,

        /// Serve JSON-RPC 2.0 over stdio (NDJSON on stdin/stdout), matching
        /// the trusty-memory/trusty-search MCP stdio convention.
        #[arg(long)]
        stdio: bool,

        // #6637: the HTTP transport is gone. Both flags still parse, hidden,
        // so a script passing them gets an error naming the socket rather
        // than clap's bare "unexpected argument" (supervisor ruling Q4).
        #[arg(long, hide = true)]
        http: bool,

        #[arg(long, hide = true, value_name = "PORT")]
        port: Option<u16>,

        /// Bind this project's own socket instead of the shared one (#4600).
        ///
        /// The path is derived from `--project` (a sibling of the shared
        /// socket, keyed by the project root), so a second project can run a
        /// daemon while another project's daemon holds the shared socket.
        /// `tcode tui` passes this itself; there is no path to supply.
        #[arg(long, conflicts_with = "stdio")]
        project_socket: bool,
    },

    /// Launch the interactive TUI REPL, starting a `tcode serve` daemon if
    /// one isn't already running (#4424; auto-spawn #4512).
    ///
    /// The daemon answers on its Unix socket under the trusty-code data
    /// directory — one derived path, nothing to discover and no address to
    /// name (#6637). When nothing answers there, a daemon is STARTED
    /// automatically (#4512, reversing DOC-50 §4.1's deferral) and LEFT
    /// RUNNING when the REPL exits, since the daemon owns PM lifecycle and
    /// agent dispatch and this TUI is only one of its attached clients. A
    /// daemon bound to a DIFFERENT project than this TUI's is refused rather
    /// than attached to, because every session would otherwise run against
    /// the wrong repository. Since #8205 that project defaults to the
    /// repository enclosing the current directory. See `crate::cli::tui` for
    /// the wiring and `crate::cli::daemon_autospawn` for the policy.
    Tui {
        /// Path to the project root the REPL's session binds to.
        ///
        /// OPTIONAL: omit it and the session homes on the git repository
        /// enclosing the current directory (#8205); with no enclosing
        /// repository the session is projectless, since an implicit bind
        /// indexes what it binds and a plain directory never asked for
        /// that. Naming a path here binds it whether or not it is a
        /// repository. Pass `--projectless` for an unbound session. Must
        /// name an existing directory when given.
        #[arg(long, short, value_name = "PATH")]
        project: Option<PathBuf>,

        /// Run with NO project bound, ignoring the current directory (#8205).
        ///
        /// A projectless session is a first-class state — the same one
        /// `serve` without `--project` and `session.create` without a
        /// `project` support — but it is no longer the default: its file
        /// tools are rooted in a throwaway scratch directory and nothing it
        /// writes is indexed or kept. Ask for it when you want a
        /// chat/planning session that touches no repository.
        #[arg(long, conflicts_with = "project")]
        projectless: bool,

        /// Run the DELEGATING PM instead of the solo agent (#8184).
        ///
        /// An interactive session runs one agent that reads, edits and runs
        /// commands itself; the stock `pm` card asks before `bash`,
        /// `write_file`, `write_files` and `edit` (#3422), and reads are
        /// unprompted. This flag restores the pre-#8184 shape: the
        /// top-level agent gets `delegate_to_agent` and hands implementation
        /// work to a sub-agent instead of doing it. Sent as
        /// `session.create`'s `delegate` param.
        #[arg(long)]
        delegate: bool,
    },

    /// Create (or target) a session, run a task through it via the daemon's
    /// `task.run`, stream live events to the terminal as they arrive, and
    /// exit once the run reaches a terminal state (#2060, the M1 cut-line
    /// "replay via thin CLI" verb).
    ///
    /// This is a THIN CLIENT by default: it spawns an ephemeral
    /// `tcode serve --stdio` child (`crate::cli::run_task`) and drives it
    /// entirely over JSON-RPC — no agent-loop logic runs in this process.
    /// `--legacy-in-process` restores the pre-#2060 behaviour (this binary
    /// runs the PM->engineer `AgentLoop` directly, printing a diff/
    /// transcript/usage report at the end — see `crate::cli::legacy_run_task`)
    /// — kept available rather than deleted since it is still exercised by
    /// `trusty_code::run_task::tests` and some callers may depend on its
    /// diff-report output, which the daemon-driven path does not (yet)
    /// compute.
    RunTask {
        // #6999: the pre-#5426 wording named `.claude/` as the only layout.
        /// Agent name as declared in `.trusty-code/agents/<name>.md` (e.g.
        /// `pm`), falling back to `.claude/agents/` then `.open-mpm/agents/`.
        agent: String,

        /// Free-form task description passed to the agent's system prompt.
        task: String,

        // #6999: a `.trusty-code`-only project runs; `.claude/` is a fallback.
        /// Path to the project root. Its configuration is read from
        /// `.trusty-code/`, falling back to `.claude/` then `.open-mpm/`; none
        /// of the three has to exist. Defaults to the current working
        /// directory.
        #[arg(long, short, value_name = "PATH", default_value = ".")]
        project: PathBuf,

        /// Emit a machine-readable JSON report on stdout instead of human text.
        #[arg(long)]
        json: bool,

        /// Override the python-engineer's model for this run only (#1035).
        /// Falls back to the `TCODE_ENGINEER_MODEL` env var, then the agent
        /// config's own model.
        #[arg(long, value_name = "SLUG")]
        engineer_model: Option<String>,

        /// Override the TOP-LEVEL agent's own model for this run only
        /// (#8030) — the half `--engineer-model` never covered. Falls back to
        /// `TCODE_PM_MODEL`, then the agent's front-matter `model:`, then the
        /// built-in default. Accepts the short `opus`/`sonnet`/`haiku`
        /// aliases. Applies to both execution paths.
        #[arg(long, value_name = "SLUG")]
        pm_model: Option<String>,

        /// Override the top-level loop's turn cap for this run only (#8128).
        /// Falls back to `TCODE_MAX_TURNS`, then the loop's built-in 8. Raise
        /// it for a multi-step delivery task. Applies to both execution
        /// paths. Must be at least 1.
        #[arg(long, value_name = "N", value_parser = clap::value_parser!(u32).range(1..))]
        max_turns: Option<u32>,

        /// Use the ORIGINAL in-process execution path instead of the #2060
        /// thin JSON-RPC client. See this variant's docs for why it is kept.
        #[arg(long)]
        legacy_in_process: bool,

        /// Per-call `HarnessMode` override (#2059, vision spec §5.9):
        /// `daily-driver` or `parity`. Passed as `task.run`'s `mode` param
        /// (thin-client path only — ignored under `--legacy-in-process`,
        /// which has no mode concept). `TRUSTY_CODE_MODE` still overrides
        /// this per the resolution precedence in `crate::mode`'s docs.
        #[arg(long, value_name = "MODE")]
        mode: Option<String>,

        /// Override the run's wall-clock deadline, in seconds (#2207).
        /// Applies to BOTH the PM's own loop and the delegated engineer's
        /// loop, in either execution path (`--legacy-in-process` or the
        /// default thin-client/daemon path). Falls back to the
        /// `TCODE_RUN_DEADLINE_SECONDS` env var, then a generous 1800s (30
        /// minute) default — see `crate::provider::resolve_deadline_secs`'s
        /// docs for the full precedence. Use a large value (e.g. 7200-10800)
        /// for multi-hour tasks.
        #[arg(long, value_name = "SECONDS")]
        timeout_seconds: Option<u64>,

        /// What a headless `--legacy-in-process` run does with an agent's
        /// `ask` permission rule (#7948): `default` refuses it, `allow-asks`
        /// permits it. Falls back to `TCODE_PERMISSION_MODE`, then `default`.
        /// A `deny` rule is refused regardless.
        #[arg(long, value_name = "MODE")]
        permission_mode: Option<String>,

        /// Run AGENT alone (#8031): `delegate_to_agent` is not registered, so
        /// AGENT cannot hand the task to `python-engineer`; instead AGENT gets
        /// its own tcode tools (`read_file`, `write_file`, `edit`, `bash`, …),
        /// exactly the set and permission gating a delegated run of AGENT
        /// would get. Applies to both execution paths — the default
        /// thin-client path sends it as `task.run`'s `no_delegate` param, and
        /// `--legacy-in-process` passes it as `RunTaskParams.no_delegate`.
        ///
        /// With the default AGENT (`pm`) the stock card ASKS before `bash`,
        /// `write_file`, `write_files` and `edit` (#3422, #8184), so a run
        /// with no interactive client to answer refuses those calls. Set
        /// `TCODE_PERMISSION_MODE=allow-asks` in the daemon's environment —
        /// or, on `--legacy-in-process`, `--permission-mode allow-asks` — to
        /// permit them. A `deny` rule is refused regardless.
        #[arg(long)]
        no_delegate: bool,
    },

    /// Execute a named MPM workflow end-to-end.
    ///
    /// Loads the workflow definition from `.claude/workflows/<name>.toml` and
    /// runs it through the PM main-loop.
    RunWorkflow {
        /// Workflow name (matches the filename without extension).
        name: String,

        /// Path to the project root.
        #[arg(long, short, value_name = "PATH", default_value = ".")]
        project: PathBuf,
    },

    /// Inspect and manage daemon-owned sessions (#2060).
    Session {
        #[command(subcommand)]
        action: SessionCommand,
    },

    /// Attach to a live session and stream its events to the terminal until
    /// it reaches a terminal state or you press Ctrl-C (#2060).
    ///
    /// Dials the running daemon for `--project` on its Unix socket, starting
    /// one if none answers (#10169).
    Attach {
        /// The session id to attach to.
        session_id: String,

        /// Path to the project root the daemon should be rooted at.
        #[arg(long, short, value_name = "PATH", default_value = ".")]
        project: PathBuf,
    },

    /// Send a cancellation signal to a session (#2060).
    Cancel {
        /// The session id to cancel.
        session_id: String,

        /// Path to the project root the daemon should be rooted at.
        #[arg(long, short, value_name = "PATH", default_value = ".")]
        project: PathBuf,
    },

    /// Print a session's stored transcript (turns, tool calls, usage, cost)
    /// via `session.get_transcript` (#2058, #2060).
    Transcript {
        /// The session id to inspect.
        session_id: String,

        /// Path to the project root the daemon should be rooted at.
        #[arg(long, short, value_name = "PATH", default_value = ".")]
        project: PathBuf,

        /// Emit the raw JSON result instead of a human-readable rendering.
        #[arg(long)]
        json: bool,
    },

    /// Manage inference provider configuration (API keys) — the universal
    /// `config keys set/list/test/unset` surface shared by every trusty-*
    /// binary (epic #2400 Wave 1, #2405).
    Config(trusty_common::inference::config::ConfigCommand),

    /// Inspect and migrate trusty-code's own configuration layout (#5426).
    ///
    /// Trusty Code reads `<project>/.trusty-code/` first and falls back to
    /// `.claude/` then `.open-mpm/`; it WRITES only beneath `.trusty-code/`.
    /// Private mutable state (transcripts, logs, telemetry) lives in
    /// `~/.trusty-code/` at mode 0700.
    Paths {
        #[command(subcommand)]
        action: PathsCommand,
    },

    /// Manage workstreams — durable named groupings of sessions bound to the
    /// daemon's project (#3296, DOC-48 §5.4). `tcode ws` is a short alias
    /// for this whole family (DOC-48 AC-5.3).
    #[command(alias = "ws")]
    Workstream {
        #[command(subcommand)]
        action: WorkstreamCommand,
    },

    /// Judge a retained L1-L3 bake-off evidence bundle against the milestone
    /// exit gate (#5441).
    ///
    /// Entirely offline: it reads the bundle a frozen candidate's real
    /// bake-off already produced and never runs a model, a daemon, or the
    /// runner. Exits 0 when the milestone may close on this evidence, 1 when
    /// the gate refuses, and 2 when it could not reach a verdict at all.
    /// Bundle layout and a worked invocation:
    /// `docs/reference/bakeoff-exit-gate.md`.
    BakeoffGate {
        /// Root of the candidate bundle — the directory holding `L1/`, `L2/`,
        /// `L3/` and an optional `dispositions.json`.
        #[arg(long, value_name = "PATH")]
        bundle: PathBuf,

        /// Root of the previous accepted milestone's bundle. Without it the
        /// preflight still runs, but no regression comparison is performed.
        #[arg(long, value_name = "PATH")]
        baseline: Option<PathBuf>,

        /// The frozen candidate's git commit. Every level must report it.
        #[arg(long, value_name = "SHA")]
        expect_commit: Option<String>,

        /// SHA-256 of the binary built from that commit.
        #[arg(long, value_name = "HEX")]
        expect_binary_sha256: Option<String>,

        /// The bake-off runner revision the invocation was defined against.
        #[arg(long, value_name = "REV")]
        expect_runner_revision: Option<String>,

        /// Percentage a cost/token/turn/duration metric may move before it
        /// needs a documented disposition.
        #[arg(long, value_name = "PCT", default_value_t = trusty_code::bakeoff::compare::DEFAULT_TOLERANCE_PCT)]
        tolerance_pct: f64,

        /// Emit the verdict as one JSON document instead of a human summary.
        #[arg(long)]
        json: bool,
    },
}

/// `tcode paths <action>` subcommands (#5426).
///
/// Both variants carry their own `--project` (defaulting to `.`), matching the
/// per-leaf convention every other subcommand family here uses.
#[derive(Subcommand)]
enum PathsCommand {
    /// Report which configuration root wins for each entry, plus the write
    /// root and the private state directory's permissions.
    Show {
        /// Path to the project root.
        #[arg(long, short, value_name = "PATH", default_value = ".")]
        project: PathBuf,

        /// Emit the report as JSON instead of a human-readable table.
        #[arg(long)]
        json: bool,
    },

    /// Import `.claude/agents`, `.claude/skills`, and `.claude/settings.json`
    /// into `.trusty-code/`, never overwriting an existing file.
    ///
    /// Exits 1 if any entry was refused — a symlink escape, an executable, a
    /// secret-bearing `settings.json`, or a target that already exists (#6999).
    /// `--dry-run` reports the same code the real run would.
    Import {
        /// Path to the project root.
        #[arg(long, short, value_name = "PATH", default_value = ".")]
        project: PathBuf,

        /// Print the plan and exit without writing anything.
        #[arg(long)]
        dry_run: bool,
    },
}

/// `tcode workstream <action>` / `tcode ws <action>` subcommands (#3296,
/// DOC-48 §5.4).
///
/// Every variant carries its own `--project` (defaulting to `.`), matching
/// [`SessionCommand`]/[`Command::Attach`]/[`Command::Cancel`]/
/// [`Command::Transcript`]'s existing per-leaf convention rather than
/// hoisting it onto the parent [`Command::Workstream`] variant (clap
/// subcommand args aren't inherited from an enclosing variant without a
/// shared flattened struct, which would be a bigger change than this
/// ticket's scope).
#[derive(Subcommand)]
enum WorkstreamCommand {
    /// List workstreams in the daemon's project (tm-ls-style table; DOC-48
    /// AC-5.1).
    List {
        /// Include closed workstreams (default: false, DOC-48 §4.4).
        #[arg(long)]
        include_closed: bool,

        /// Path to the project root the daemon should be rooted at.
        #[arg(long, short, value_name = "PATH", default_value = ".")]
        project: PathBuf,
    },

    /// Show one workstream's full record as JSON.
    Get {
        /// The workstream id — a FULL UUID only (prefix-matching is a
        /// documented future nicety; see `crate::cli::workstream`'s module
        /// docs for why it isn't implemented client-side today).
        id: String,

        #[arg(long, short, value_name = "PATH", default_value = ".")]
        project: PathBuf,
    },

    /// Create a new workstream.
    Create {
        /// Human-readable name (defaults to empty/untitled if omitted).
        #[arg(long)]
        name: Option<String>,

        #[arg(long, short, value_name = "PATH", default_value = ".")]
        project: PathBuf,
    },

    /// Activate a workstream, making it the daemon's one active workstream
    /// (DOC-48 §6.1, AC-5.2).
    Activate {
        /// The workstream id to activate (full UUID only).
        id: String,

        /// Force-switch even if a DIFFERENT workstream is currently active
        /// (deactivates the prior one; DOC-48 §6.1). Without this flag,
        /// activating while another workstream is active fails with a clear
        /// message naming the active workstream.
        #[arg(long)]
        force: bool,

        #[arg(long, short, value_name = "PATH", default_value = ".")]
        project: PathBuf,
    },

    /// Deactivate the currently active workstream, if any (no-op otherwise).
    Deactivate {
        #[arg(long, short, value_name = "PATH", default_value = ".")]
        project: PathBuf,
    },

    /// Irreversibly close a workstream (DOC-48 §4.4).
    Close {
        /// The workstream id to close (full UUID only).
        id: String,

        #[arg(long, short, value_name = "PATH", default_value = ".")]
        project: PathBuf,
    },
}

/// `tcode session <action>` subcommands (#2060).
#[derive(Subcommand)]
enum SessionCommand {
    /// List every session the daemon currently knows about.
    List {
        /// Path to the project root the daemon should be rooted at.
        #[arg(long, short, value_name = "PATH", default_value = ".")]
        project: PathBuf,
    },
    /// Show one session's current status.
    Status {
        /// The session id to look up.
        session_id: String,

        /// Path to the project root the daemon should be rooted at.
        #[arg(long, short, value_name = "PATH", default_value = ".")]
        project: PathBuf,
    },
}

#[tokio::main]
async fn main() -> Result<()> {
    let cli = Cli::parse();

    // Initialise tracing to stderr (never stdout — stdout is the API transport,
    // and `--json` mode requires stdout to carry only the JSON report).
    //
    // #6537: `tcode serve` additionally gets a durable file log
    // (`logging::file_log_dir`) — it is the one long-running mode that
    // accumulates enough log volume to be worth draining, and the one this
    // process spawns `log_drain::spawn` from (`serve::build_router`). The
    // guard must outlive `main`: dropping it early silently discards
    // buffered log records.
    let _log_guard = if matches!(cli.command, Command::Serve { .. }) {
        trusty_code::logging::init_tracing_with_file_log()
    } else {
        trusty_code::logging::init_tracing();
        None
    };

    match cli.command {
        Command::Serve {
            project,
            stdio,
            http,
            port,
            project_socket,
        } => run_serve(project, stdio, http, port, project_socket).await,

        // #4424: the launch point for the TUI REPL — reuses `run_thin_client`
        // so a daemon-resolution failure prints `tcode tui: <actionable
        // message>` and exits nonzero, exactly like every other subcommand's
        // failure.
        // #4512: that failure is now rare — a missing daemon is started, not
        // reported.
        // #8184: `--delegate` is the ONE opt-in back to the delegating PM.
        Command::Tui {
            project,
            projectless,
            delegate,
        } => run_thin_client(cli::tui::run(project, projectless, delegate), "tui").await,

        Command::RunTask {
            agent,
            task,
            project,
            json,
            engineer_model,
            legacy_in_process,
            mode,
            timeout_seconds,
            permission_mode,
            no_delegate,
            // #8030/#8128: both reach either execution path below.
            pm_model,
            max_turns,
        } => {
            if legacy_in_process {
                // #4434: the in-process path (and the agent-name validation
                // and LLM-client construction only it needs) lives in
                // `cli::legacy_run_task` — `main.rs` had reached 498 of the
                // 500-SLOC cap and is now clap definitions plus dispatch.
                cli::legacy_run_task::run(
                    &agent,
                    &task,
                    &project,
                    json,
                    engineer_model,
                    timeout_seconds,
                    permission_mode,
                    // #8031: single-agent run — no `delegate_to_agent`.
                    no_delegate,
                    pm_model,
                    max_turns,
                )
                .await
            } else {
                let project = canonicalize_project_or_exit(&project, "run-task");
                match cli::run_task::run(
                    &project,
                    &agent,
                    &task,
                    json,
                    engineer_model,
                    mode,
                    timeout_seconds,
                    // #8031: single-agent run — no `delegate_to_agent`.
                    no_delegate,
                    pm_model,
                    max_turns,
                )
                .await
                {
                    Ok(code) => process::exit(code),
                    Err(e) => {
                        eprintln!("tcode run-task: {e:#}");
                        process::exit(ExitCode::RunFailure.code());
                    }
                }
            }
        }

        Command::RunWorkflow { name, project } => {
            eprintln!(
                "tcode run-workflow: not yet implemented (#587 Phase 5+) [name={name}, project={}]",
                project.display()
            );
            process::exit(1);
        }

        Command::Session { action } => match action {
            SessionCommand::List { project } => {
                let project = canonicalize_project_or_exit(&project, "session list");
                run_thin_client(cli::session::list(&project), "session list").await
            }
            SessionCommand::Status {
                session_id,
                project,
            } => {
                let project = canonicalize_project_or_exit(&project, "session status");
                run_thin_client(
                    cli::session::status(&project, &session_id),
                    "session status",
                )
                .await
            }
        },

        Command::Attach {
            session_id,
            project,
        } => {
            let project = canonicalize_project_or_exit(&project, "attach");
            run_thin_client(cli::attach::run(&project, &session_id), "attach").await
        }

        Command::Cancel {
            session_id,
            project,
        } => {
            let project = canonicalize_project_or_exit(&project, "cancel");
            run_thin_client(cli::cancel::run(&project, &session_id), "cancel").await
        }

        Command::Transcript {
            session_id,
            project,
            json,
        } => {
            let project = canonicalize_project_or_exit(&project, "transcript");
            run_thin_client(
                cli::transcript::run(&project, &session_id, json),
                "transcript",
            )
            .await
        }

        Command::Config(cmd) => cmd.run().await,

        // #5426: offline and daemon-free — it reads the project tree and, for
        // `import`, writes only beneath `<project>/.trusty-code/`.
        Command::Paths { action } => match action {
            PathsCommand::Show { project, json } => cli::paths::show(&project, json),
            // #6999: a refused entry must reach the caller as an exit code, not
            // only as a line of plan output.
            PathsCommand::Import { project, dry_run } => {
                match cli::paths::import(&project, dry_run) {
                    Ok(code) => process::exit(code),
                    Err(e) => {
                        eprintln!("tcode paths import: {e:#}");
                        process::exit(ExitCode::RunFailure.code());
                    }
                }
            }
        },

        Command::Workstream { action } => match action {
            WorkstreamCommand::List {
                include_closed,
                project,
            } => {
                let project = canonicalize_project_or_exit(&project, "workstream list");
                run_thin_client(
                    cli::workstream::list(&project, include_closed),
                    "workstream list",
                )
                .await
            }
            WorkstreamCommand::Get { id, project } => {
                let project = canonicalize_project_or_exit(&project, "workstream get");
                run_thin_client(cli::workstream::get(&project, &id), "workstream get").await
            }
            WorkstreamCommand::Create { name, project } => {
                let project = canonicalize_project_or_exit(&project, "workstream create");
                run_thin_client(cli::workstream::create(&project, name), "workstream create").await
            }
            WorkstreamCommand::Activate { id, force, project } => {
                let project = canonicalize_project_or_exit(&project, "workstream activate");
                run_thin_client(
                    cli::workstream::activate(&project, &id, force),
                    "workstream activate",
                )
                .await
            }
            WorkstreamCommand::Deactivate { project } => {
                let project = canonicalize_project_or_exit(&project, "workstream deactivate");
                run_thin_client(
                    cli::workstream::deactivate(&project),
                    "workstream deactivate",
                )
                .await
            }
            WorkstreamCommand::Close { id, project } => {
                let project = canonicalize_project_or_exit(&project, "workstream close");
                run_thin_client(cli::workstream::close(&project, &id), "workstream close").await
            }
        },

        // #5441: the only subcommand that neither starts nor calls a daemon —
        // it judges evidence a frozen candidate's bake-off already retained.
        Command::BakeoffGate {
            bundle,
            baseline,
            expect_commit,
            expect_binary_sha256,
            expect_runner_revision,
            tolerance_pct,
            json,
        } => {
            let pins = trusty_code::bakeoff::Pins::new(
                expect_commit,
                expect_binary_sha256,
                expect_runner_revision,
            );
            process::exit(cli::bakeoff::run(
                &bundle,
                baseline.as_deref(),
                pins,
                tolerance_pct,
                json,
            ));
        }
    }
}

/// Canonicalize `project`, printing a `tcode <cmd>:`-prefixed error and
/// exiting with [`ExitCode::ConfigError`] on failure.
///
/// Why: every thin-client subcommand needs the SAME "must be a real,
/// existing directory" validation `run-task`'s legacy path already applies
/// — centralised so each one-line match arm above doesn't repeat it.
/// What: `Path::canonicalize`, exiting on `Err` rather than returning one
/// (matching this binary's existing `process::exit`-on-config-error style).
fn canonicalize_project_or_exit(project: &Path, cmd: &str) -> PathBuf {
    project.canonicalize().unwrap_or_else(|e| {
        eprintln!(
            "tcode {cmd}: invalid --project path '{}': {e}",
            project.display()
        );
        process::exit(ExitCode::ConfigError.code());
    })
}

/// Run a thin-client subcommand's future, printing a `tcode <cmd>:`-prefixed
/// error and exiting nonzero on failure; exits 0 on success.
///
/// Why: every non-`run-task` thin-client subcommand (`session list`/
/// `status`, `attach`, `cancel`, `transcript`) shares the exact same
/// "await, print error verbatim (`RpcClientError`'s `Display` already
/// includes the daemon's JSON-RPC error message/code where applicable),
/// exit nonzero" shape — centralised here instead of repeated per arm.
/// What: `ExitCode::RunFailure`'s numeric value on error (mirrors
/// `run-task`'s exit-code contract); exits 0 (falls through, returning
/// `Ok(())`) on success.
async fn run_thin_client(
    fut: impl std::future::Future<Output = Result<()>>,
    cmd: &str,
) -> Result<()> {
    if let Err(e) = fut.await {
        eprintln!("tcode {cmd}: {e:#}");
        process::exit(ExitCode::RunFailure.code());
    }
    Ok(())
}

/// Execute `tcode serve`: the persistent socket daemon, or `--stdio`.
///
/// Why: keeps `main`'s match arm a one-liner, matching the shape of the
/// `cli::*` subcommand wrappers. The binary layer owns only the CLI-shaped
/// concern (which transport was requested); `trusty_code::serve` owns router
/// assembly and both transport loops.
/// What: `--http`/`--port` are refused first with [`http_removed_message`]
/// and exit code 2 (#6637), before the project is resolved or anything binds.
/// `--stdio` delegates to `trusty_code::serve::run_stdio`; otherwise
/// `serve::uds::run_daemon`, or `serve::uds::run_project_daemon` under
/// `--project-socket` (#4600). Both run until shutdown (SIGTERM/SIGINT, or
/// stdin EOF for `--stdio`), logging to stderr only, and a fatal error exits 1.
/// `project` is optional: `None` serves PROJECTLESS. It is resolved into a
/// typed `ProjectBinding` HERE, at the boundary, so an unusable `--project`
/// (missing, or not a directory) fails fast with an actionable message rather
/// than surfacing later as a confusing per-task error.
/// Test: `tests/daemon_no_tcp_6637.rs` (every command line, the real binary);
/// `trusty_code::serve::tests` and `serve::uds::uds_tests` cover what this
/// delegates to.
async fn run_serve(
    project: Option<PathBuf>,
    stdio: bool,
    http: bool,
    port: Option<u16>,
    project_socket: bool,
) -> Result<()> {
    // #6637: a hard error, never a silent no-op (supervisor ruling Q4).
    if http || port.is_some() {
        eprintln!(
            "{}",
            http_removed_message(project.as_deref(), project_socket)
        );
        process::exit(2);
    }
    let binding = match trusty_code::binding::ProjectBinding::resolve(project) {
        Ok(b) => b,
        Err(e) => {
            eprintln!("tcode serve: {e}");
            eprintln!(
                "hint: pass an existing directory to --project, or omit --project \
                 entirely to serve projectless (chat/planning; no index, no diff)."
            );
            process::exit(1);
        }
    };
    if stdio {
        if let Err(e) = trusty_code::serve::run_stdio(binding).await {
            eprintln!("tcode serve --stdio: fatal error: {e:#}");
            process::exit(1);
        }
        return Ok(());
    }

    let served = if project_socket {
        trusty_code::serve::uds::run_project_daemon(binding).await
    } else {
        trusty_code::serve::uds::run_daemon(binding).await
    };
    if let Err(e) = served {
        eprintln!("tcode serve: fatal error: {e:#}");
        process::exit(1);
    }
    Ok(())
}

/// The error `tcode serve --http` / `--port` prints (#6637).
///
/// Why: the flags selected a loopback TCP listener that no longer exists. A
/// caller still passing them needs to learn where the daemon answers now, so
/// the message names the socket path this invocation would have bound.
/// What: resolves the shared socket path (or, under `--project-socket`, the
/// project's own sibling of it); a path that cannot be resolved is described
/// instead of failing a second time.
/// Test: `tests/daemon_no_tcp_6637.rs::serve_http_and_port_exit_non_zero_naming_the_socket`.
fn http_removed_message(project: Option<&Path>, project_socket: bool) -> String {
    let socket = match trusty_code::serve::uds::socket_path() {
        Ok(shared) if project_socket => {
            let root = project.and_then(|p| p.canonicalize().ok());
            trusty_code::serve::uds::project_socket_path(&shared, root.as_deref())
                .display()
                .to_string()
        }
        Ok(shared) => shared.display().to_string(),
        Err(e) => format!("<the trusty-code data directory>/trusty-code.sock ({e:#})"),
    };
    format!(
        "tcode serve: --http and --port were removed (#6637). The daemon serves only its \
         owner-only Unix socket, at {socket}. Run `tcode serve` with no transport flag; \
         clients (`tcode tui`, trusty-code-gui) dial the socket themselves."
    )
}