trusty-code 0.8.2

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
//! `tcode tui` — launch the interactive TUI REPL against a running
//! `tcode serve` daemon (issue #4424; DOC-50 §4.1, AC-2.4).
//!
//! Why: every DOC-50 MVP slice landed — the shared `trusty-code-tui` framework
//! (event loop, generalized `ReplApp`, widgets) and
//! `trusty_code::tui_client::CodeEngine` (the `TuiEngine` impl) — but
//! nothing ever CONSTRUCTED a `CodeEngine` outside tests, so the REPL was
//! unreachable from a user's shell. This module is that missing integration
//! point and nothing more: it owns no REPL behaviour, no rendering, and no
//! daemon logic, matching `crate::cli`'s "translate CLI args into a call,
//! decisions belong elsewhere" contract.
//! What: [`run`] resolves the project the session homes in — since #8205
//! that defaults to the repository enclosing the launch directory, see
//! [`resolve_project`] — obtains the daemon
//! socket to drive from `super::daemon_autospawn`, and hands a `CodeEngine`
//! pointed at it to `trusty_code_tui::run::run` together with the shared
//! `ReplApp` model,
//! its reducer (`trusty_code_tui::app::apply`), and its renderer
//! (`trusty_code_tui::layout::draw`).
//!
//! `tcode tui` AUTO-SPAWNS its daemon (#4512, reversing DOC-50 §4.1's
//! deferral): the daemon answers on one derived socket path under the
//! trusty-code data directory (#6637), and nothing answering there starts
//! `tcode serve` instead of exiting with an actionable message.
//!
//! **Quitting the TUI never stops the daemon** — not even one this command
//! started. The daemon owns PM lifecycle, agent dispatch, and agent
//! communication, and a TUI is one attached client among possibly several,
//! so a client exit must not end live work (owner directive, 2026-08-01).
//! There is correspondingly NO teardown step here. A daemon bound to a
//! DIFFERENT project than this TUI is never attached to, since every session
//! would otherwise run against the wrong repository; since #4600 this TUI
//! starts its own project's daemon on a per-project socket instead. See
//! `super::daemon_autospawn` for the whole policy — none of it lives here.
//!
//! Daemon resolution deliberately runs BEFORE `trusty_code_tui::run::run` enters
//! the alternate screen, so the startup spinner and any failure land on a
//! normal terminal instead of flashing behind a TUI that is about to tear
//! itself down.
//! Test: `tui_tests::*` covers the pure project-resolution helper;
//! `super::daemon_autospawn`'s tests cover every attach/spawn/binding-check
//! branch against real child processes;
//! `tests/cli_e2e.rs::{tui_subcommand_is_listed_in_help,
//! tui_auto_spawns_a_daemon_that_outlives_it,
//! tui_refuses_to_spawn_for_an_unreachable_explicit_daemon_url,
//! tui_starts_its_own_daemon_beside_another_projects}` cover the CLI surface
//! against the REAL binary. The launch path past daemon resolution needs a
//! real TTY (`trusty_code_tui::TerminalGuard::enter`), so it is verified by
//! running `tcode tui` by hand; the engine half is already covered
//! end-to-end by `tests/tui_client_engine.rs`.

use std::path::{Path, PathBuf};
use std::sync::Arc;

use anyhow::{Context, Result};
use trusty_code::tui_client::CodeEngine;
use trusty_code_tui::ReplApp;

use super::daemon_autospawn;

/// Product label for the banner identity line and the `[tcode] ` status
/// prefix `ReplApp::new` derives from it.
const PRODUCT_LABEL: &str = "tcode";

/// Launch the TUI REPL, returning once the user quits — starting a daemon
/// first if none is running, and leaving it running on the way out.
///
/// Why/What/Test: see the module docs — this function IS the module.
/// `project` is `Option` because a projectless session is a first-class
/// state (`session.create` without a `project`), not a degraded one; it is
/// forwarded to a spawned daemon so the daemon's binding matches the TUI's,
/// and checked against a pre-existing daemon's reported binding.
///
/// (#8205) `projectless` is the opt-out from the cwd homing
/// [`resolve_project`] now performs by default.
/// (#8184) `delegate` is the `--delegate` opt-in back to the PM: `false` (the
/// default) mints the SOLO session `session.create` now defaults to, where the
/// agent reads and edits files itself through the permission prompt rather
/// than handing the work to a sub-agent.
pub async fn run(project: Option<PathBuf>, projectless: bool, delegate: bool) -> Result<()> {
    let cwd = std::env::current_dir().context("resolve the current directory")?;
    let home = home_for_guard(dirs::home_dir());
    let project = resolve_project(project, projectless, &cwd, home.as_deref())?;
    // #4512: attach to a running daemon serving this project, or start one —
    // replaces #4424's "exit and tell the user to start one". Nothing is
    // torn down afterwards: the daemon outlives every client (module docs).
    // #6637: the daemon is reached on its Unix socket, not a loopback port.
    let socket = daemon_autospawn::ensure_daemon(project.as_deref()).await?;
    // #8184: the interactive default is the solo agent; `--delegate` is the
    // one surface that asks for the delegating PM instead.
    let engine = if delegate {
        CodeEngine::with_socket_delegating(socket, project)
    } else {
        CodeEngine::with_socket(socket, project)
    };
    let mut app = ReplApp::new(PRODUCT_LABEL, user_label());
    // #8164: the banner's frame title must name the BINARY's version and SHA.
    // `ReplApp::new` defaults it to `trusty-code-tui`'s own crate version, so
    // a 0.7.0 tcode advertised itself as `tcode v0.2.0`.
    app.version = trusty_code::build_info::LONG_VERSION.to_string();

    trusty_code_tui::run::run(
        Arc::new(engine),
        app,
        trusty_code_tui::app::apply,
        trusty_code_tui::layout::draw,
    )
    .await
}

/// Decide which project a `tcode tui` session binds to.
///
/// Why (#8205): omitting `--project` used to mean "projectless", so a TUI
/// launched inside a repository ran against the executor's throwaway scratch
/// root — on 2026-09-16 an agent's `list_dir(".")` answered `(empty
/// directory)` inside a repository full of files and `search_code` found no
/// index, while the footer named the repo's workstream. DOC-75's MVP is
/// "sit in a repo, launch `tcode tui`", so the launch directory is now the
/// default binding and projectlessness is something you ask for.
///
/// This homing lives HERE, at the CLI layer, and not in
/// `ProjectBinding::resolve`: a launch directory is a choice the operator
/// made by typing the command there, whereas the daemon/protocol layer is
/// still forbidden from implicitly binding a CWD it was never told about
/// (see `ProjectBinding::agents_dir`).
///
/// An IMPLICIT bind requires an enclosing git root (PM ruling, 2026-09-16).
/// A bound binding passes `task::executor`'s `should_index` and reaches
/// `run_task`'s `ensure_project_indexed_in_background` with
/// `allow_sensitive_path: true`, so homing on any directory at all would
/// make `cd ~/Downloads && tcode tui` index Downloads. DOC-75's MVP is
/// "sits in a repo", and a repository is the one thing that says "this
/// directory is a project" without the operator saying it. An EXPLICIT
/// `--project <dir>` still binds a non-repo directory — git stays a
/// nice-to-have there (owner directive, `run_task::tests` ~1996).
///
/// What, in precedence order:
/// 1. `--project <path>` wins, canonicalized here so an unusable path fails
///    with the flag's name rather than as a confusing `-32003
///    invalid_argument` from `session.create` after the TUI has started.
///    Binds whether or not the path is a repository.
/// 2. `--projectless` yields `None` — today's behaviour, opted into.
/// 3. Otherwise the session homes on `cwd`'s enclosing git toplevel
///    ([`trusty_common::find_git_root`]). That walk is the SAME one
///    trusty-search derives an index id from, so the bound root and the
///    index `search_code` queries cannot disagree. No enclosing repository
///    means no implicit bind: projectless.
/// 4. A root that CONTAINS `home` — `home` itself, or any ancestor of it —
///    is refused and stays projectless: binding one would ask trusty-search
///    to index an entire home directory or more. A root `home` contains — the
///    everyday repository under `$HOME` — is NOT refused; the test is
///    one-directional. An explicit `--project ~` still works, rule 1
///    outranks this. `home = None` disables this rule and lets the bind
///    proceed, there being nothing to compare a root against; that arm is
///    reached only when the platform reports no home path at all, never
///    when one merely fails to canonicalize ([`home_for_guard`]).
///
/// Test: `tui_tests::resolve_project_defaults_to_the_enclosing_git_repo`,
/// `tui_tests::resolve_project_without_a_repo_stays_projectless`,
/// `tui_tests::resolve_project_projectless_opts_out_of_homing`,
/// `tui_tests::resolve_project_refuses_to_home_on_the_home_directory`,
/// `tui_tests::resolve_project_refuses_a_repo_above_the_home_directory`,
/// `tui_tests::resolve_project_binds_a_repo_below_the_home_directory`,
/// `tui_tests::resolve_project_binds_when_the_platform_reports_no_home`,
/// `tui_tests::resolve_project_canonicalizes_a_real_directory`,
/// `tui_tests::resolve_project_rejects_a_missing_path`.
fn resolve_project(
    project: Option<PathBuf>,
    projectless: bool,
    cwd: &Path,
    home: Option<&Path>,
) -> Result<Option<PathBuf>> {
    if let Some(p) = project {
        return p
            .canonicalize()
            .with_context(|| format!("invalid --project path '{}'", p.display()))
            .map(Some);
    }
    if projectless {
        return Ok(None);
    }
    let cwd = cwd
        .canonicalize()
        .with_context(|| format!("resolve the launch directory '{}'", cwd.display()))?;
    // #8205: no enclosing repository, no implicit bind — see the ruling above.
    let Some(root) = trusty_common::find_git_root(&cwd) else {
        return Ok(None);
    };
    // #8205: `starts_with` is component-wise and subsumes equality, so a
    // repository that ENCLOSES the home directory (a stray `/Users/.git`) is
    // refused too — that root would index every user's files, not just one's.
    if root.parent().is_none() || home.is_some_and(|h| h.starts_with(&root)) {
        return Ok(None);
    }
    Ok(Some(root))
}

/// The home path [`resolve_project`]'s rule-4 guard compares a git root to.
///
/// Why (#8205): rule 4 is the only alarm for "never index a home directory",
/// and a `None` here skips it while the bind proceeds. Collapsing
/// "canonicalize failed" into `None` therefore disarmed the guard on exactly
/// the input it exists for, so a home that exists but does not resolve keeps
/// its raw form instead — `Path::starts_with` is component-wise and still
/// answers usefully on an uncanonicalized path.
/// What: canonicalizes when it can, keeps the raw path when it cannot, and
/// returns `None` only for a platform that reports no home path at all.
/// Test: `tui_tests::home_for_guard_keeps_an_uncanonicalizable_path`,
/// `tui_tests::resolve_project_binds_when_the_platform_reports_no_home`.
fn home_for_guard(raw: Option<PathBuf>) -> Option<PathBuf> {
    raw.map(|h| h.canonicalize().unwrap_or(h))
}

/// Name shown on the banner's `{user} · tcode` identity line — `$USER`, or a
/// generic fallback. Mirrors tagent's `repl::run` derivation so both REPLs
/// label the human the same way.
fn user_label() -> String {
    label_or_default(std::env::var("USER").ok())
}

/// The `$USER`-to-label rule, split out from [`user_label`] so it is
/// testable without mutating process-global environment state.
fn label_or_default(raw: Option<String>) -> String {
    raw.filter(|u| !u.trim().is_empty())
        .unwrap_or_else(|| "user".to_string())
}

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

    /// A temp directory that IS a git repository (a bare `.git` directory is
    /// all `find_git_root` looks for), plus a nested subdirectory.
    fn repo_with_subdir() -> (tempfile::TempDir, PathBuf, PathBuf) {
        let dir = tempfile::tempdir().expect("tempdir");
        let root = dir.path().canonicalize().expect("canonicalize");
        std::fs::create_dir(root.join(".git")).expect("create .git");
        let nested = root.join("crates").join("x");
        std::fs::create_dir_all(&nested).expect("create nested");
        (dir, root, nested)
    }

    /// #8205: launched anywhere inside a repository with no flags, the
    /// session binds that repository's TOPLEVEL — not the subdirectory the
    /// operator happened to stand in, and not the scratch root. This is the
    /// inverse of the pre-#8205 `resolve_project_none_stays_projectless`.
    #[test]
    fn resolve_project_defaults_to_the_enclosing_git_repo() {
        let (_guard, root, nested) = repo_with_subdir();
        let resolved = resolve_project(None, false, &nested, None)
            .expect("resolve")
            .expect("a repo must bind");
        assert_eq!(resolved, root);
    }

    /// Outside any repository there is no implicit bind: a bound binding is
    /// indexed with `allow_sensitive_path: true`, so homing on any directory
    /// would make `cd ~/Downloads && tcode tui` index Downloads. `--project`
    /// is how a non-repo directory becomes a project.
    #[test]
    fn resolve_project_without_a_repo_stays_projectless() {
        let dir = tempfile::tempdir().expect("tempdir");
        let cwd = dir.path().canonicalize().expect("canonicalize");
        assert!(
            resolve_project(None, false, &cwd, None)
                .expect("resolve")
                .is_none(),
            "a directory with no enclosing repository must not bind implicitly"
        );
        // …but naming it explicitly still binds it (git is a nice-to-have for
        // an explicit `--project`, never a requirement).
        assert_eq!(
            resolve_project(Some(cwd.clone()), false, &cwd, None)
                .expect("resolve")
                .expect("--project must bind a non-repo directory"),
            cwd
        );
    }

    /// The opt-out keeps the pre-#8205 behaviour — a projectless session is
    /// still first-class, it just has to be asked for.
    #[test]
    fn resolve_project_projectless_opts_out_of_homing() {
        let (_guard, _root, nested) = repo_with_subdir();
        assert!(
            resolve_project(None, true, &nested, None)
                .expect("resolve")
                .is_none()
        );
    }

    /// `$HOME` is not a project even when it IS a repository — some operators
    /// keep a dotfiles repo there, and homing on it would hand trusty-search
    /// an entire home directory to index. The home here is a real repo, so
    /// the git-root rule alone cannot account for the `None`.
    #[test]
    fn resolve_project_refuses_to_home_on_the_home_directory() {
        let (_guard, home, nested) = repo_with_subdir();
        assert!(
            resolve_project(None, false, &home, Some(&home))
                .expect("resolve")
                .is_none(),
            "$HOME must not become the default project"
        );
        assert!(
            resolve_project(None, false, &nested, Some(&home))
                .expect("resolve")
                .is_none(),
            "a subdirectory of a $HOME repo resolves to $HOME, and is refused too"
        );
    }

    /// A repository that is an ANCESTOR of `$HOME` — a stray `/Users/.git`
    /// — must be refused too. Exact-match alone would bind it and hand
    /// trusty-search every user's files on the machine.
    #[test]
    fn resolve_project_refuses_a_repo_above_the_home_directory() {
        let dir = tempfile::tempdir().expect("tempdir");
        let above = dir.path().canonicalize().expect("canonicalize");
        std::fs::create_dir(above.join(".git")).expect("create .git");
        let home = above.join("masa");
        let cwd = home.join("projects");
        std::fs::create_dir_all(&cwd).expect("create home and cwd");

        // `cwd` has no `.git` of its own, so the walk resolves to `above` —
        // which contains `$HOME`.
        assert!(
            resolve_project(None, false, &cwd, Some(&home))
                .expect("resolve")
                .is_none(),
            "a repository enclosing $HOME must not become the default project"
        );
    }

    /// The everyday launch (#8205): a repository UNDER `$HOME`, which is
    /// where nearly every project lives. Rule 4's test is one-directional —
    /// it refuses a root CONTAINING home, never a root home contains — so an
    /// over-broad `|| root.starts_with(h)` would make this projectless and
    /// reintroduce the very bug the homing exists to fix.
    #[test]
    fn resolve_project_binds_a_repo_below_the_home_directory() {
        let dir = tempfile::tempdir().expect("tempdir");
        let home = dir.path().canonicalize().expect("canonicalize");
        let repo = home.join("projects").join("trusty-tools");
        let nested = repo.join("crates").join("x");
        std::fs::create_dir_all(&nested).expect("create nested");
        std::fs::create_dir(repo.join(".git")).expect("create .git");

        assert_eq!(
            resolve_project(None, false, &nested, Some(&home))
                .expect("resolve")
                .expect("a repo under $HOME must bind"),
            repo,
            "the guard refuses a root containing $HOME, never one $HOME contains"
        );
    }

    /// #8205 fail-open regression: a home path that EXISTS but does not
    /// canonicalize used to collapse to the same `None` as "no home at all",
    /// which skips rule 4 — so a repository ENCLOSING `$HOME` bound anyway,
    /// and the only alarm for "never index a home directory" read healthy
    /// precisely when it could not resolve home. Keeping the raw path leaves
    /// the guard armed.
    #[test]
    fn home_for_guard_keeps_an_uncanonicalizable_path() {
        let dir = tempfile::tempdir().expect("tempdir");
        let above = dir.path().canonicalize().expect("canonicalize");
        std::fs::create_dir(above.join(".git")).expect("create .git");
        let cwd = above.join("masa").join("projects");
        std::fs::create_dir_all(&cwd).expect("create cwd");
        // Never created on disk, so `canonicalize` fails on it while the
        // path itself is still a perfectly usable `starts_with` operand.
        let home = above.join("masa").join("vanished");
        assert!(home.canonicalize().is_err(), "the fixture must not resolve");

        let guarded = home_for_guard(Some(home.clone()));
        assert!(
            resolve_project(None, false, &cwd, guarded.as_deref())
                .expect("resolve")
                .is_none(),
            "a repository enclosing an unresolvable $HOME must still be refused"
        );
        assert_eq!(
            guarded.as_deref(),
            Some(home.as_path()),
            "an unresolvable home keeps its raw form rather than becoming None"
        );
    }

    /// The one remaining fail-open arm, made deliberate (#8205): with NO home
    /// path at all there is nothing to compare a root against, so rule 4 is
    /// skipped and the bind proceeds. Pinned so changing that choice has to
    /// change a test that states it.
    #[test]
    fn resolve_project_binds_when_the_platform_reports_no_home() {
        let dir = tempfile::tempdir().expect("tempdir");
        let above = dir.path().canonicalize().expect("canonicalize");
        std::fs::create_dir(above.join(".git")).expect("create .git");
        let cwd = above.join("masa").join("projects");
        std::fs::create_dir_all(&cwd).expect("create cwd");

        assert_eq!(home_for_guard(None), None, "no home path stays None");
        assert_eq!(
            resolve_project(None, false, &cwd, None)
                .expect("resolve")
                .expect("with no home to compare against, the root binds"),
            above
        );
    }

    /// `--project` outranks both the homing and the opt-out, and is
    /// canonicalized to an absolute path.
    #[test]
    fn resolve_project_canonicalizes_a_real_directory() {
        let dir = tempfile::tempdir().expect("tempdir");
        let cwd = std::env::temp_dir();
        let resolved = resolve_project(Some(dir.path().to_path_buf()), true, &cwd, None)
            .expect("resolve")
            .expect("some");
        assert!(resolved.is_absolute());
        assert_eq!(resolved, dir.path().canonicalize().expect("canonicalize"));
    }

    /// A path that does not exist is rejected with a message naming the
    /// flag and the offending path.
    #[test]
    fn resolve_project_rejects_a_missing_path() {
        let missing = std::env::temp_dir().join("tcode-tui-4424-does-not-exist");
        let cwd = std::env::temp_dir();
        let err =
            resolve_project(Some(missing.clone()), false, &cwd, None).expect_err("must reject");
        let rendered = format!("{err:#}");
        assert!(rendered.contains("invalid --project path"), "{rendered}");
        assert!(
            rendered.contains(&missing.display().to_string()),
            "{rendered}"
        );
    }

    /// The banner identity label is never empty, even with `$USER` unset or
    /// blank (the banner would otherwise render a bare `· tcode`).
    #[test]
    fn label_or_default_falls_back_when_unset_or_blank() {
        assert_eq!(label_or_default(None), "user");
        assert_eq!(label_or_default(Some("   ".to_string())), "user");
        assert_eq!(label_or_default(Some("masa".to_string())), "masa");
    }
}