trusty-mpm 1.8.2

trusty-mpm: unified multi-agent orchestration platform (core, daemon, CLI, TUI, Telegram)
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
//! Project-identity + branch-label segment for `tm statusline`.
//!
//! Why: split out of `mod.rs` (#2031 follow-up) once the file approached the
//! 500-SLOC production cap — this module owns everything needed to resolve
//! the `<project> ⎇ <branch>` half of the statusline: the GitHub `owner/repo`
//! label, the tmux-session-name-over-git-branch selection, and the managed-
//! session branch elision.
//! What: exposes [`project_segment`] as the single entry point; all other
//! items are private helpers plus their bounded-thread probes.
//! Test: see the `tests` module below.

/// Build the project-identity + branch-label segment from `cwd`.
///
/// Why (#1913-followup): a managed tm session runs in `.worktrees/<uuid>/`, so the
/// cwd basename is just the session UUID — useless as a project label and a
/// duplicate of the `session/<uuid>` branch. The leading field should instead be
/// the GitHub `owner/repo` slug (the codebase's canonical `source_id`), and the
/// redundant `session/<…>` branch is dropped so the operator can actually tell
/// which project and branch they are on.
/// What: derives `owner/repo` from the git remote (reusing
/// [`trusty_common::github_path::derive_github_path`] — the same parser
/// `derive_source_id_for_record` uses; handles https and scp-style remotes),
/// falling back to the cwd basename only when there is no parseable GitHub remote.
/// Appends ` ⎇ <branch>` for meaningful branches, but omits it for the auto-created
/// `session/<…>` managed-session branch and for detached `HEAD`.
/// Test: `project_segment_basename_fallback_non_git`, `git_owner_repo_reads_remote`,
/// `render_project_segment_*`, `render_statusline_minimal_input` (empty cwd → None).
pub(crate) fn project_segment(cwd: &str) -> Option<String> {
    if cwd.is_empty() {
        return None;
    }
    let branch = select_branch_label(tmux_session_name(), || git_branch(cwd));
    project_segment_with(cwd, branch.as_deref())
}

/// [`project_segment`] with the branch-position label already resolved (#4407).
///
/// Why: `project_segment` calls [`tmux_session_name`], a probe bounded at 100 ms
/// that returns `None` on timeout. `project_segment_basename_fallback_non_git`
/// used to derive its expectation by calling that probe a SECOND time and
/// requiring the two runs to agree - under machine load either could time out
/// independently, so the test failed on a tree it had just passed on (measured:
/// ok / FAILED / ok across three isolated runs). CI never saw it, because the
/// probe short-circuits on `$TMUX` and GitHub's runners do not set it. Taking
/// the label as an argument lets the test state one deterministic input instead
/// of hoping two timed probes agree.
/// What: the project-identity half only - the GitHub `owner/repo` slug from the
/// git remote, falling back to the cwd basename - composed with `branch` by
/// [`render_project_segment`].
/// Test: `project_segment_basename_fallback_non_git`.
fn project_segment_with(cwd: &str, branch: Option<&str>) -> Option<String> {
    if cwd.is_empty() {
        return None;
    }
    // Prefer the GitHub owner/repo slug from the git remote; fall back to the cwd
    // basename only when there is no parseable remote (non-GitHub / non-git dir).
    let project = git_owner_repo(cwd).unwrap_or_else(|| {
        std::path::Path::new(cwd)
            .file_name()
            .map(|n| n.to_string_lossy().to_string())
            .unwrap_or_default()
    });
    render_project_segment(project, branch)
}

/// Choose the branch-position label: prefer the tmux session name, falling
/// back to the git branch when no session name is available.
///
/// Why (#2031): a managed tm session runs in `.worktrees/<uuid>/` on a bare
/// session-UUID branch (not the elided `session/<uuid>` form the old check
/// covered), so [`git_branch`] alone leaked the UUID into the status bar. The
/// tmux session name (e.g. `tm-trusty-tools-01`) is the human-meaningful label
/// tm actually assigns to the session, so it takes priority whenever present.
/// Keeping the git-branch source lazy (`FnOnce`) means the fallback probe's
/// subprocess call is skipped entirely on the common managed-session path
/// where a tmux session name is already available.
/// What: returns `tmux_session` when `Some` and non-empty; otherwise invokes
/// `fallback` and returns its result. Pure aside from the lazy call.
/// Test: `select_branch_label_selection_contract`.
fn select_branch_label(
    tmux_session: Option<String>,
    fallback: impl FnOnce() -> Option<String>,
) -> Option<String> {
    tmux_session.filter(|s| !s.is_empty()).or_else(fallback)
}

/// Assemble the project segment string from an already-resolved label and branch.
///
/// Why: keeping the label/branch combination pure (no git I/O) makes the
/// branch-omission logic unit-testable without spawning subprocesses.
/// What: returns `None` for an empty label; otherwise `"<project> ⎇ <branch>"`
/// (single space, per the #2011 layout) for a meaningful branch, or just
/// `"<project>"` when the branch is empty, detached `HEAD`, or a managed
/// `session/<…>` branch (see [`is_managed_session_branch`]).
/// Test: `render_project_segment_omits_managed_session_branch`,
/// `render_project_segment_keeps_real_branch`, `render_project_segment_empty_label`.
fn render_project_segment(project: String, branch: Option<&str>) -> Option<String> {
    if project.is_empty() {
        return None;
    }
    Some(match branch {
        Some(b) if !b.is_empty() && b != "HEAD" && !is_managed_session_branch(b) => {
            format!("{project} \u{2387} {b}")
        }
        _ => project,
    })
}

/// Report whether `branch` is an auto-created managed tm session branch.
///
/// Why: tm provisions each managed session on a `session/<uuid>` branch; showing
/// it in the status bar just repeats the session id and crowds out the real
/// project identity, so it is elided.
/// What: matches the literal `session` branch and any `session/<…>` prefix.
/// Test: `is_managed_session_branch_matches_session_prefix`.
fn is_managed_session_branch(branch: &str) -> bool {
    branch == "session" || branch.starts_with("session/")
}

/// Run `git rev-parse --abbrev-ref HEAD` in `cwd` with a hard 100 ms wall-clock
/// timeout and return the branch name.
///
/// Why: `statusline` is on Claude Code's hot render path; a stuck credential
/// helper, network filesystem, or git hook would otherwise block every render
/// cycle. The bounded thread + `recv_timeout` pattern matches
/// [`super::compaction::compaction_segment`]. Spawns via
/// [`trusty_mpm::core::spawn_disclaim::disclaimed_output`] (issue #3580) rather than
/// a raw `Command::new("git")`: this runs on EVERY prompt render, so — of the
/// three sites #3580 fixes — it is the highest-frequency undisclaimed spawn in
/// the crate, making the signed `trusty-mpm` binary TCC's misattributed
/// "responsible process" for a git child on every single render.
/// What: spawns a detached thread that calls `git rev-parse` through
/// `disclaimed_output`, sends the result over an mpsc channel; the caller waits
/// ≤100 ms, returns `None` on timeout. `disclaimed_output` mirrors
/// `Command::new(program).args(args).output()` exactly (same captured
/// stdout/stderr, same success/failure semantics) — on macOS it just spawns via
/// `posix_spawnp` with the TCC disclaim attribute set instead of `std`'s
/// internal spawn path; on non-macOS (no TCC) it IS `Command::output()`.
/// Test: `render_statusline_full_payload` (in `mod.rs`) exercises the detected
/// branch path; covered here via [`select_branch_label`]'s fallback tests.
fn git_branch(cwd: &str) -> Option<String> {
    use std::sync::mpsc;
    use std::time::Duration;

    let cwd = cwd.to_string();
    let (tx, rx) = mpsc::channel::<Option<String>>();
    std::thread::spawn(move || {
        let result = (|| -> Option<String> {
            let args = [
                "-C".to_string(),
                cwd.clone(),
                "rev-parse".to_string(),
                "--abbrev-ref".to_string(),
                "HEAD".to_string(),
            ];
            let out = trusty_mpm::core::spawn_disclaim::disclaimed_output("git", &args).ok()?;
            if !out.status.success() {
                return None;
            }
            let branch = String::from_utf8_lossy(&out.stdout).trim().to_string();
            if branch.is_empty() {
                None
            } else {
                Some(branch)
            }
        })();
        let _ = tx.send(result);
    });
    rx.recv_timeout(Duration::from_millis(100)).ok().flatten()
}

/// Run `tmux display-message -p '#S'` with a hard 100 ms wall-clock timeout to
/// resolve the current tmux session's name.
///
/// Why (#2031): managed tm sessions run in `.worktrees/<uuid>/` and Claude Code
/// inherits the tmux session's `$TMUX` env var from the shell that launched it;
/// probing the CURRENT session (no `-t` target) recovers tm's actual
/// human-meaningful session label (e.g. `tm-trusty-tools-01`) without any extra
/// plumbing. The bounded-thread pattern matches [`git_branch`].
/// What: returns `None` immediately when `$TMUX` is unset (not inside tmux);
/// otherwise spawns a detached thread that runs `tmux display-message -p '#S'`
/// (via `core::tmux::display_message_argv`/`run_tmux_argv_with_bin` — #2414;
/// the resolve-then-spawn work happens INSIDE the bounded thread, so a slow
/// binary resolution still cannot push this probe past its 100 ms budget —
/// the caller's `recv_timeout` bounds it regardless), trims the output, and
/// returns `None` on missing binary, non-zero exit, empty output, or a stall
/// past 100 ms.
/// Test: environment-dependent (requires a live tmux session), so covered
/// indirectly via the pure [`select_branch_label`] selection tests and
/// `project_segment_basename_fallback_non_git`, which asserts against this
/// probe's own live result rather than assuming an environment.
///
/// `pub(crate)` since #5539: the `tm ls` picker's bulk glob delete needs the
/// SAME "what is my own tmux session called" answer to exclude the caller's
/// session from a pattern. Promoted rather than copied — a second probe with
/// its own timeout and its own `$TMUX` handling is exactly the drift the
/// common-entry-point rule exists to prevent.
pub(crate) fn tmux_session_name() -> Option<String> {
    use std::sync::mpsc;
    use std::time::Duration;

    std::env::var_os("TMUX")?;

    let (tx, rx) = mpsc::channel::<Option<String>>();
    std::thread::spawn(move || {
        let result = (|| -> Option<String> {
            // #2414: resolved binary + shared spawn primitive, matching
            // every other tmux call site in the crate.
            let tmux_bin = trusty_mpm::core::tmux::resolve_tmux_binary_or_bare();
            let argv = trusty_mpm::core::tmux::display_message_argv(None, "#S");
            let out = trusty_mpm::core::tmux::run_tmux_argv_with_bin(&tmux_bin, &argv).ok()?;
            if !out.status.success() {
                return None;
            }
            let name = String::from_utf8_lossy(&out.stdout).trim().to_string();
            if name.is_empty() { None } else { Some(name) }
        })();
        let _ = tx.send(result);
    });
    rx.recv_timeout(Duration::from_millis(100)).ok().flatten()
}

/// Derive the GitHub `owner/repo` slug for `cwd` with a 100 ms wall-clock timeout.
///
/// Why: the leading status-bar field must identify the project, not the worktree
/// UUID; the canonical identity is the repo's `owner/repo` (the `source_id`). The
/// bounded-thread pattern (matching [`git_branch`]) keeps a stuck git config /
/// filesystem from blocking Claude Code's hot render path.
/// What: spawns a detached thread that calls the shared parser
/// [`trusty_common::github_path::derive_github_path`] (which shells to
/// `git -C <cwd> config --get remote.origin.url` — no network — and parses both
/// https and scp-style remotes), formats `owner/repo`, and sends it over an mpsc
/// channel; the caller waits ≤100 ms and returns `None` on timeout, no remote, or
/// an unparseable / non-GitHub URL.
/// Test: `git_owner_repo_reads_remote` (temp repo with a github origin);
/// `git_owner_repo_none_outside_repo` (bare temp dir → None).
fn git_owner_repo(cwd: &str) -> Option<String> {
    use std::sync::mpsc;
    use std::time::Duration;

    let cwd = cwd.to_string();
    let (tx, rx) = mpsc::channel::<Option<String>>();
    std::thread::spawn(move || {
        let result = trusty_common::github_path::derive_github_path(std::path::Path::new(&cwd))
            .map(|gh| format!("{}/{}", gh.owner, gh.repo));
        let _ = tx.send(result);
    });
    rx.recv_timeout(Duration::from_millis(100)).ok().flatten()
}

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

    /// Why: a managed tm session runs on a `session/<uuid>` branch that just
    /// repeats the session id; it must be elided while real branches stay.
    /// Test: itself.
    #[test]
    fn is_managed_session_branch_matches_session_prefix() {
        assert!(is_managed_session_branch("session/2dfb23d1-579f-4168-9d28"));
        assert!(is_managed_session_branch("session/anything"));
        assert!(is_managed_session_branch("session"));
        assert!(!is_managed_session_branch("main"));
        assert!(!is_managed_session_branch("fix/foo"));
        // Not the managed prefix (note the trailing `s`).
        assert!(!is_managed_session_branch("sessions/foo"));
    }

    /// Why: a managed session must render `owner/repo` with NO branch (and hence
    /// no duplicated UUID) even though a `session/<uuid>` branch is checked out.
    /// Test: itself.
    #[test]
    fn render_project_segment_omits_managed_session_branch() {
        let seg = render_project_segment(
            "bobmatnyc/trusty-tools".to_string(),
            Some("session/2dfb23d1-579f-4168-9d28"),
        );
        assert_eq!(seg.as_deref(), Some("bobmatnyc/trusty-tools"));
        // No branch marker and no UUID leaked in.
        let s = seg.unwrap();
        assert!(!s.contains('\u{2387}'), "managed branch must be omitted");
        assert!(!s.contains("2dfb23d1"), "session UUID must not appear");
    }

    /// Why: a normal checkout on a meaningful branch must keep `⎇ <branch>`.
    /// Test: itself.
    #[test]
    fn render_project_segment_keeps_real_branch() {
        let seg = render_project_segment("bobmatnyc/trusty-tools".to_string(), Some("main"));
        assert_eq!(seg.as_deref(), Some("bobmatnyc/trusty-tools \u{2387} main"));

        // Detached HEAD and empty branch collapse to just the label.
        assert_eq!(
            render_project_segment("owner/repo".to_string(), Some("HEAD")).as_deref(),
            Some("owner/repo")
        );
        assert_eq!(
            render_project_segment("owner/repo".to_string(), None).as_deref(),
            Some("owner/repo")
        );
    }

    /// Why: an empty label (basename resolution failed) must omit the segment
    /// entirely rather than emit a stray `⎇`.
    /// Test: itself.
    #[test]
    fn render_project_segment_empty_label() {
        assert_eq!(render_project_segment(String::new(), Some("main")), None);
    }

    /// Why (#2031): pins the full selection contract in one place — tmux wins
    /// when present and non-empty; the git-branch fallback is used only when
    /// it's absent or empty; both absent yields no branch. The tmux-present
    /// case passes a panicking fallback to prove it is never invoked.
    /// Test: itself.
    #[test]
    fn select_branch_label_selection_contract() {
        let panics = || -> Option<String> {
            panic!("fallback must not run when tmux session name is present")
        };
        assert_eq!(
            select_branch_label(Some("tm-trusty-tools-01".to_string()), panics).as_deref(),
            Some("tm-trusty-tools-01")
        );
        assert_eq!(
            select_branch_label(None, || Some("main".to_string())).as_deref(),
            Some("main")
        );
        assert_eq!(
            select_branch_label(Some(String::new()), || Some("main".to_string())).as_deref(),
            Some("main")
        );
        assert_eq!(select_branch_label(None, || None), None);
    }

    /// Why: a bare directory with no git repo must fall back to the cwd basename
    /// and never panic.
    ///
    /// #4407: this used to call [`tmux_session_name`] a second time to derive
    /// its expectation, so it required two independent 100 ms-bounded probes to
    /// agree - either could time out under load, and the test then failed on a
    /// tree it had just passed on. It now drives [`project_segment_with`] with
    /// the label stated outright, covering both arms (no label, and a live
    /// session name) deterministically. [`project_segment`]'s own choice between
    /// the two sources stays covered by `select_branch_label_selection_contract`.
    /// Test: itself.
    #[test]
    fn project_segment_basename_fallback_non_git() {
        let tmp = tempfile::TempDir::new().expect("tempdir");
        let cwd = tmp.path().to_string_lossy().to_string();
        let basename = tmp
            .path()
            .file_name()
            .map(|n| n.to_string_lossy().to_string())
            .unwrap_or_default();

        let bare = project_segment_with(&cwd, None).expect("basename segment");
        assert_eq!(bare, basename, "non-git cwd -> basename, no branch");
        assert!(
            !bare.contains('\u{2387}'),
            "no branch marker for a bare dir"
        );

        let labelled =
            project_segment_with(&cwd, Some("tm-trusty-tools-01")).expect("basename segment");
        assert_eq!(
            labelled,
            format!("{basename} \u{2387} tm-trusty-tools-01"),
            "a resolved session label -> basename + label"
        );
    }

    /// Why: the leading field must resolve to the GitHub `owner/repo` slug parsed
    /// from the git remote (both scp-style and https), matching `source_id`.
    ///
    /// #6663: [`git_owner_repo`] gives its worker thread a 100 ms
    /// `recv_timeout`, and that worker shells out to `git`. Under a loaded
    /// `--no-fail-fast` run one `git` invocation can exceed 100 ms, so a single
    /// call returned `None` and the test failed on a tree it had just passed
    /// on. The retry below waits for the condition — a resolved slug — rather
    /// than assuming one attempt fits in the budget. Each attempt re-arms the
    /// production timeout, so this loosens nothing about what is asserted: the
    /// slug must still be exactly right, and an unresolvable remote still fails
    /// at the deadline.
    /// Test: itself (temp git repo; skipped when git is unavailable on the runner).
    #[test]
    fn git_owner_repo_reads_remote() {
        let tmp = tempfile::TempDir::new().expect("tempdir");
        let dir = tmp.path();
        let git = |args: &[&str]| {
            std::process::Command::new("git")
                .arg("-C")
                .arg(dir)
                .args(args)
                .output()
                .map(|o| o.status.success())
                .unwrap_or(false)
        };
        if !git(&["init"]) {
            return; // no git on runner
        }
        assert!(git(&[
            "remote",
            "add",
            "origin",
            "git@github.com:bobmatnyc/trusty-tools.git",
        ]));
        let cwd = dir.to_string_lossy().to_string();
        // #6663: poll the condition instead of trusting one 100 ms attempt.
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
        let mut resolved = git_owner_repo(&cwd);
        while resolved.is_none() && std::time::Instant::now() < deadline {
            std::thread::sleep(std::time::Duration::from_millis(25));
            resolved = git_owner_repo(&cwd);
        }
        assert_eq!(
            resolved.as_deref(),
            Some("bobmatnyc/trusty-tools"),
            "scp-style remote → owner/repo slug"
        );
    }

    /// Why: outside any git repo `git_owner_repo` must yield `None` so callers
    /// fall back to the basename.
    /// Test: itself.
    #[test]
    fn git_owner_repo_none_outside_repo() {
        let tmp = tempfile::TempDir::new().expect("tempdir");
        let cwd = tmp.path().to_string_lossy().to_string();
        assert_eq!(git_owner_repo(&cwd), None);
    }
}