trusty-code 0.7.0

Per-project Claude-Code-compatible MPM orchestration harness (bin: tcode) — an original coding harness, tracked under epic #2052.
Documentation
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
//! Known-project roster discovery for the GUI's workstream-first
//! project-picker modal (issue #3365).
//!
//! Why: DOC-48 §8/DOC-39 §4.2 shift the GUI's entry concept from "new
//! session" to "new workstream" — creating a workstream now binds it to a
//! project through a MODAL, not [`super::list_dir`]'s arbitrary-directory
//! browse-and-descend picker (7a). A modal wants a short, flat, best-guess
//! candidate LIST to click through, not a filesystem tree to navigate. The
//! prior GUI slice's own module doc recorded this exact gap: "no pre-session
//! roster endpoint exists yet" — this module is that endpoint's daemon-side
//! data source. There is no existing project/config registry in this crate
//! to reuse (`crate::binding::ProjectBinding` is the daemon's OWN one-project
//! binding, not a multi-project registry), so this is a fresh, best-effort
//! filesystem scan, deliberately narrow in scope (see `MAX_ENTRIES`).
//!
//! **Update (issue #3435):** trusty-mpm's shared project registry — a real
//! cross-machine registry this crate does not own — is now the PRIMARY
//! source for the roster the GUI actually renders; this module's scan has
//! been demoted to the SECONDARY source (surfacing local-only, unregistered
//! candidates the registry doesn't know about) plus the graceful-degradation
//! fallback for when the mpm daemon is unreachable. See `super::mpm_registry`
//! for the merge step and [`ProjectCandidate::registered`]. This module's own
//! scan behavior and discovery heuristic below are otherwise unchanged.
//!
//! **Discovery heuristic.** This workspace's own convention — visible in the
//! very checkout this crate lives in — is `~/trusty-mpm-projects/<owner>/
//! <repo>` (an owner-scoped project root trusty-mpm's own tooling
//! established). When that directory exists, [`list_projects`] scans it two
//! levels deep (owner dirs, then their repo dirs) and returns every repo dir
//! that [`super::is_git_repo`] accepts — the same discriminator 7a's picker
//! already uses. When it does NOT exist (a machine without trusty-mpm's
//! project layout), this falls back to a single-level scan of the home
//! directory itself, on the theory that a developer machine without the
//! owner-scoped layout more commonly keeps repos as direct children of `~`
//! (e.g. `~/acme-api`) — still filtered to git repos only, so a home full of
//! Documents/Downloads/etc. does not flood the picker with noise.
//!
//! What: [`ProjectCandidate`] is one flat, pre-resolved row the picker can
//! render directly (no further filesystem calls needed, unlike 7a's
//! navigate-then-list flow); [`ProjectRoster`] is the whole response body.
//! [`list_projects`] is a thin `dirs::home_dir()`-resolving wrapper around
//! [`list_projects_in`], the actual (testable) scan — mirroring
//! `crate::serve::mod::build_router`/`build_router_at`'s real-vs-injectable
//! split so tests never touch the real developer home directory. Every
//! filesystem read here is best-effort: an unreadable or missing scan root
//! degrades to an empty (or partial) roster, never an error — mirroring
//! [`super::list_dir`]'s own per-entry best-effort philosophy, appropriate
//! here since this endpoint is a convenience shortlist, not the only way to
//! bind a project (an operator can still fall back to the [`super::list_dir`]
//! browse surface, which this ticket leaves untouched).
//! Test: `tests::*`.

use std::path::Path;

use serde::Serialize;

use super::is_git_repo;

/// Hard cap on the number of roster entries returned.
///
/// Why: this is a "quick pick" shortlist for a modal, not a paginated
/// browser — an unbounded scan of a large `trusty-mpm-projects` tree (or, in
/// the fallback case, a large home directory) must never turn a "small
/// roster" call into a slow, huge response. 200 comfortably covers a
/// realistic multi-owner project tree while staying obviously "small" per
/// the issue's own requirement. `pub(super)` (not private) so
/// `super::mpm_registry`'s merge step (issue #3435) truncates the
/// registry-augmented roster to the same cap rather than duplicating the
/// magic number.
/// Test: `tests::scan_is_capped_at_max_entries`.
pub(super) const MAX_ENTRIES: usize = 200;

/// One candidate project row — everything the picker needs to render and
/// bind it without a further round-trip.
///
/// Why: mirrors [`super::DirEntryInfo`] in spirit (name + path a client can
/// bind directly), but flatter — no `is_dir` (every entry here is already
/// known to be a directory) and no `is_git_repo` (every entry here is
/// already known to be a git repo — filtering, not badging, is this
/// endpoint's job). `owner` carries the `trusty-mpm-projects/<owner>/<repo>`
/// layout's owner segment when the scan found it that way, so the picker can
/// disambiguate two repos that share a name under different owners; `None`
/// on the home-directory fallback path, where there is no owner segment.
/// `registered` (issue #3435) distinguishes a project known to trusty-mpm's
/// shared project registry from one this crate found only by scanning the
/// filesystem — a plain fs scan can never set it `true` on its own, so every
/// candidate this module produces starts `false`; only
/// `super::mpm_registry::merge` (the registry-primary merge step) flips it.
/// Test: `tests::trusty_mpm_projects_layout_is_scanned_two_levels_deep`.
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
pub struct ProjectCandidate {
    /// The repo directory's own name (e.g. `trusty-tools`).
    pub name: String,
    /// Absolute path to the repo directory.
    pub path: String,
    /// The owning directory's name under `~/trusty-mpm-projects`, when the
    /// scan found this candidate that way; `None` on the home-directory
    /// fallback path.
    pub owner: Option<String>,
    /// Whether this candidate is also known to trusty-mpm's shared project
    /// registry (issue #3435). Always `false` from a bare filesystem scan —
    /// see the struct docs.
    pub registered: bool,
}

/// Which source produced a [`ProjectRoster`] (issue #3435, code-critic PR
/// #3439 review, HIGH 2).
///
/// Why: the #3363 lesson — "nothing registered" and "the registry was
/// unreachable" are different operator-facing situations and must not
/// collapse into the same-looking empty/all-unregistered roster. A bare
/// `bool` would work, but a named enum reads at the call site
/// (`source == RosterSource::FsOnly`) without a comment explaining which
/// state `true`/`false` means, and its `serde` rendering (`"registry"` /
/// `"fs_only"`) is self-describing on the wire too.
/// What: [`Self::Registry`] means the mpm daemon was reached and `entries`
/// is the registry-primary/fs-secondary merge (see `super::mpm_registry`);
/// [`Self::FsOnly`] means the registry was never reached (unreachable
/// daemon, or not yet queried) and `entries` is the bare filesystem scan,
/// every candidate `registered: false`.
/// Test: `super::mpm_registry::tests::merged_roster_with_uses_registry_when_daemon_reachable`,
/// `super::mpm_registry::tests::merged_roster_with_degrades_to_fs_only_when_daemon_unreachable`.
#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq, Default)]
#[serde(rename_all = "snake_case")]
pub enum RosterSource {
    /// The mpm registry was reached; `entries` is the registry-primary merge.
    Registry,
    /// The mpm registry was unreachable (or never queried); `entries` is the
    /// filesystem scan alone.
    #[default]
    FsOnly,
}

/// The `fs.list_projects` response body — everything the picker needs for
/// one render.
///
/// Why: a bare `Vec<ProjectCandidate>` would work equally well over the
/// wire, but wrapping it in a named struct (mirroring [`super::DirListing`])
/// leaves room to add roster-level metadata later (e.g. a `truncated: bool`
/// flag) without a breaking wire-shape change — `source` (issue #3435) is
/// exactly that: an additive field a client predating it can simply ignore.
/// Test: `tests::empty_home_returns_empty_roster`.
#[derive(Debug, Clone, Serialize, PartialEq, Eq, Default)]
pub struct ProjectRoster {
    /// Candidate projects, sorted case-insensitively by `name`, capped at
    /// [`MAX_ENTRIES`].
    pub entries: Vec<ProjectCandidate>,
    /// Which source produced `entries` (issue #3435). A bare filesystem scan
    /// (this module's own [`list_projects`]/[`list_projects_in`]) always
    /// reports [`RosterSource::FsOnly`] — only `super::mpm_registry::merge`
    /// reports [`RosterSource::Registry`], on a successful registry fetch.
    #[serde(default)]
    pub source: RosterSource,
}

/// `fs.list_projects()` — the daemon-side entry point (issue #3365).
///
/// Why: the one function `protocol::list_projects` calls; resolves the real
/// home directory so the RPC handler itself stays a one-liner.
/// What: resolves the managed workspace root through
/// [`trusty_common::workspace_layout::workspace_root`] — the SAME resolver
/// trusty-mpm uses (#5203), so an operator who retargets the root via
/// `TRUSTY_MPM_WORKSPACE_ROOT` or `workspace_root_template` gets a picker that
/// scans where the checkouts actually are. `dirs::home_dir()` unresolvable ->
/// an empty [`ProjectRoster`] (never an error — see module docs on the
/// best-effort philosophy); it is still needed for the flat fallback scan.
/// Otherwise delegates to [`list_projects_in`].
/// Test: `tests::configured_workspace_root_is_scanned_not_the_default`
/// (the #5203 regression), plus `protocol::tests::list_projects_returns_entries_array`.
pub fn list_projects() -> ProjectRoster {
    // #5203: scan the CONFIGURED workspace root, not a hardcoded literal.
    match dirs::home_dir() {
        Some(home) => list_projects_in(&home, &trusty_common::workspace_layout::workspace_root()),
        None => ProjectRoster::default(),
    }
}

/// The testable core of [`list_projects`]: scan a given `home` directory
/// rather than resolving the real one.
///
/// Why: split out so tests can point this at a tempdir instead of the
/// developer's (or CI runner's) actual home — the same seam
/// `serve::mod::build_router_at` uses for the workstream store's data dir.
/// What: if `workspace_root` is a directory, scans it two levels deep (owner
/// dirs -> their repo dirs, each filtered to [`super::is_git_repo`]) via
/// [`scan_owner_layout`]; otherwise scans `home` itself one level deep via
/// [`scan_flat_layout`]. Either way, results are sorted case-insensitively by
/// `name` and truncated to [`MAX_ENTRIES`].
///
/// #5203 split `workspace_root` out of `home` rather than deriving it here: the
/// root is configurable and may sit anywhere, so only the caller (which owns the
/// resolver) can say where it is. `home` remains a separate parameter because
/// the FLAT fallback genuinely scans the home directory, not the workspace root.
/// Test: `tests::trusty_mpm_projects_layout_is_scanned_two_levels_deep`,
/// `tests::falls_back_to_flat_home_scan_when_no_trusty_mpm_projects_dir`,
/// `tests::non_git_directories_are_excluded`,
/// `tests::scan_is_capped_at_max_entries`,
/// `tests::empty_home_returns_empty_roster`.
///
/// `pub(super)` (not private) so `super::mpm_registry`'s tests (issue #3435)
/// can build a hermetic filesystem-only `ProjectRoster` against a tempdir
/// `home`, the same seam this module's own tests already use, rather than
/// hand-rolling a second scan helper.
pub(super) fn list_projects_in(home: &Path, workspace_root: &Path) -> ProjectRoster {
    let mut entries = if workspace_root.is_dir() {
        scan_owner_layout(workspace_root)
    } else {
        scan_flat_layout(home)
    };
    entries.sort_by_key(|e| e.name.to_lowercase());
    entries.truncate(MAX_ENTRIES);
    ProjectRoster {
        entries,
        source: RosterSource::FsOnly,
    }
}

/// Scan `<home>/trusty-mpm-projects/<owner>/<repo>` two levels deep,
/// keeping only `<repo>` dirs that are git repos.
///
/// Why: this workspace's own owner-scoped layout (see module docs) —
/// factored out from [`list_projects_in`] so each layout has its own,
/// independently testable scan function.
/// What: skips unreadable roots/owner dirs (best-effort — a permission
/// refusal on one owner dir must not blank the whole roster) and dotfile
/// entries at both levels.
/// Test: `tests::trusty_mpm_projects_layout_is_scanned_two_levels_deep`,
/// `tests::unreadable_owner_dir_is_skipped_not_fatal`.
fn scan_owner_layout(mpm_root: &Path) -> Vec<ProjectCandidate> {
    let mut out = Vec::new();
    let Ok(owners) = std::fs::read_dir(mpm_root) else {
        return out;
    };
    for owner_entry in owners.flatten() {
        let owner_path = owner_entry.path();
        if !owner_path.is_dir() {
            continue;
        }
        let owner_name = owner_entry.file_name().to_string_lossy().into_owned();
        if owner_name.starts_with('.') {
            continue;
        }
        let Ok(repos) = std::fs::read_dir(&owner_path) else {
            continue;
        };
        for repo_entry in repos.flatten() {
            let repo_path = repo_entry.path();
            if !repo_path.is_dir() {
                continue;
            }
            let repo_name = repo_entry.file_name().to_string_lossy().into_owned();
            if repo_name.starts_with('.') || !is_git_repo(&repo_path) {
                continue;
            }
            out.push(ProjectCandidate {
                name: repo_name,
                path: repo_path.display().to_string(),
                owner: Some(owner_name.clone()),
                registered: false,
            });
        }
    }
    out
}

/// Scan `home` itself one level deep, keeping only entries that are git
/// repos.
///
/// Why: the fallback layout for a machine without `~/trusty-mpm-projects`
/// (see module docs) — factored out for the same reason as
/// [`scan_owner_layout`].
/// What: skips an unreadable `home` (best-effort -> empty) and dotfile
/// entries.
/// Test: `tests::falls_back_to_flat_home_scan_when_no_trusty_mpm_projects_dir`.
fn scan_flat_layout(home: &Path) -> Vec<ProjectCandidate> {
    let mut out = Vec::new();
    let Ok(read) = std::fs::read_dir(home) else {
        return out;
    };
    for entry in read.flatten() {
        let path = entry.path();
        if !path.is_dir() {
            continue;
        }
        let name = entry.file_name().to_string_lossy().into_owned();
        if name.starts_with('.') || !is_git_repo(&path) {
            continue;
        }
        out.push(ProjectCandidate {
            name,
            path: path.display().to_string(),
            owner: None,
            registered: false,
        });
    }
    out
}

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

    fn mkdir(p: &Path) {
        std::fs::create_dir_all(p).expect("mkdir");
    }

    fn mk_git_repo(p: &Path) {
        mkdir(p);
        mkdir(&p.join(".git"));
    }

    /// The owner-scoped `trusty-mpm-projects/<owner>/<repo>` layout must be
    /// scanned two levels deep, returning only git repos with their owner
    /// attached.
    #[test]
    fn trusty_mpm_projects_layout_is_scanned_two_levels_deep() {
        let home = tempfile::tempdir().expect("tempdir");
        let root = home.path().join("trusty-mpm-projects");
        mk_git_repo(&root.join("bobmatnyc").join("trusty-tools"));
        mkdir(&root.join("bobmatnyc").join("scratch")); // not a git repo
        mk_git_repo(&root.join("acme").join("widgets"));

        let roster = list_projects_in(home.path(), &home.path().join("trusty-mpm-projects"));

        assert_eq!(roster.entries.len(), 2);
        let names: Vec<&str> = roster.entries.iter().map(|e| e.name.as_str()).collect();
        assert!(names.contains(&"trusty-tools"));
        assert!(names.contains(&"widgets"));
        let tt = roster
            .entries
            .iter()
            .find(|e| e.name == "trusty-tools")
            .expect("trusty-tools entry");
        assert_eq!(tt.owner.as_deref(), Some("bobmatnyc"));
    }

    /// Without a `trusty-mpm-projects` root, the scan falls back to `home`
    /// itself, one level deep, git repos only, `owner: None`.
    #[test]
    fn falls_back_to_flat_home_scan_when_no_trusty_mpm_projects_dir() {
        let home = tempfile::tempdir().expect("tempdir");
        mk_git_repo(&home.path().join("acme-api"));
        mkdir(&home.path().join("Downloads")); // not a git repo

        let roster = list_projects_in(home.path(), &home.path().join("trusty-mpm-projects"));

        assert_eq!(roster.entries.len(), 1);
        assert_eq!(roster.entries[0].name, "acme-api");
        assert_eq!(roster.entries[0].owner, None);
    }

    /// A non-git directory, at either scan level, must never appear in the
    /// roster — this is a project shortlist, not a general directory
    /// listing (unlike `super::list_dir`, which lists everything).
    #[test]
    fn non_git_directories_are_excluded() {
        let home = tempfile::tempdir().expect("tempdir");
        let root = home.path().join("trusty-mpm-projects");
        mkdir(&root.join("bobmatnyc").join("not-a-repo"));

        let roster = list_projects_in(home.path(), &home.path().join("trusty-mpm-projects"));

        assert!(roster.entries.is_empty());
    }

    /// A missing/unreadable `trusty-mpm-projects` OWNER dir must not blank
    /// the whole roster — best-effort per-owner scanning, mirroring
    /// `list_dir`'s per-entry philosophy.
    #[test]
    fn unreadable_owner_dir_is_skipped_not_fatal() {
        let home = tempfile::tempdir().expect("tempdir");
        let root = home.path().join("trusty-mpm-projects");
        // A file named like an owner dir (not a directory) is simply
        // skipped by the `owner_path.is_dir()` guard rather than erroring.
        mkdir(&root);
        std::fs::write(root.join("not-a-dir-owner"), "x").expect("write");
        mk_git_repo(&root.join("realowner").join("repo"));

        let roster = list_projects_in(home.path(), &home.path().join("trusty-mpm-projects"));

        assert_eq!(roster.entries.len(), 1);
        assert_eq!(roster.entries[0].owner.as_deref(), Some("realowner"));
    }

    /// A home with no `trusty-mpm-projects` dir and no git repos of its own
    /// returns an empty roster, not an error.
    #[test]
    fn empty_home_returns_empty_roster() {
        let home = tempfile::tempdir().expect("tempdir");
        mkdir(&home.path().join("Documents"));

        let roster = list_projects_in(home.path(), &home.path().join("trusty-mpm-projects"));

        assert!(roster.entries.is_empty());
    }

    /// A scan producing more than [`MAX_ENTRIES`] candidates must be capped,
    /// never returned in full — this is a "quick pick" shortlist, not a
    /// paginated browser (see `MAX_ENTRIES`'s own docs).
    #[test]
    fn scan_is_capped_at_max_entries() {
        let home = tempfile::tempdir().expect("tempdir");
        let owner = home.path().join("trusty-mpm-projects").join("owner");
        for i in 0..(MAX_ENTRIES + 25) {
            mk_git_repo(&owner.join(format!("repo-{i:04}")));
        }

        let roster = list_projects_in(home.path(), &home.path().join("trusty-mpm-projects"));

        assert_eq!(roster.entries.len(), MAX_ENTRIES);
    }

    /// Results must be sorted case-insensitively by name, regardless of
    /// owner or directory read order.
    #[test]
    fn results_are_sorted_case_insensitively_by_name() {
        let home = tempfile::tempdir().expect("tempdir");
        let root = home.path().join("trusty-mpm-projects");
        mk_git_repo(&root.join("owner").join("Zebra"));
        mk_git_repo(&root.join("owner").join("apple"));
        mk_git_repo(&root.join("owner").join("Banana"));

        let roster = list_projects_in(home.path(), &home.path().join("trusty-mpm-projects"));

        let names: Vec<&str> = roster.entries.iter().map(|e| e.name.as_str()).collect();
        assert_eq!(names, vec!["apple", "Banana", "Zebra"]);
    }

    /// #5203 REGRESSION: a CONFIGURED workspace root must be the directory the
    /// picker scans — not the hardcoded `~/trusty-mpm-projects`.
    ///
    /// Why: this is the defect itself. Before the fix, [`list_projects`] built
    /// its scan root as `home.join("trusty-mpm-projects")` and never read
    /// `TRUSTY_MPM_WORKSPACE_ROOT`, so an operator who retargeted the managed
    /// root got a picker that reported every real checkout as missing. This
    /// test drives the PRODUCTION entry point (not the injectable core) so it
    /// exercises the resolver wiring, which is exactly what was absent.
    /// What: points the env var at a tempdir holding `<owner>/<repo>/.git`, then
    /// asserts `list_projects()` finds that repo AND that the path it reports is
    /// under the configured root. Against the pre-fix commit this fails at the
    /// first assertion — the roster comes back from the default root instead.
    /// Test: this test.
    #[test]
    fn configured_workspace_root_is_scanned_not_the_default() {
        let _guard = env_lock();
        let configured = tempfile::tempdir().expect("tempdir");
        mk_git_repo(&configured.path().join("acme").join("widgets"));

        // SAFETY: every env-mutating test in this module holds `env_lock()`.
        unsafe {
            std::env::set_var(
                trusty_common::workspace_layout::WORKSPACE_ROOT_ENV,
                configured.path(),
            );
        }
        let roster = list_projects();
        // SAFETY: as above.
        unsafe {
            std::env::remove_var(trusty_common::workspace_layout::WORKSPACE_ROOT_ENV);
        }

        let found = roster
            .entries
            .iter()
            .find(|e| e.name == "widgets")
            .unwrap_or_else(|| {
                panic!(
                    "the configured workspace root {} must be scanned; roster was {:?}",
                    configured.path().display(),
                    roster.entries
                )
            });
        assert_eq!(found.owner.as_deref(), Some("acme"));
        assert!(
            Path::new(&found.path).starts_with(configured.path()),
            "entry path {} must sit under the configured root {}",
            found.path,
            configured.path().display()
        );
    }

    /// #5203: with nothing configured, the default must stay
    /// `~/trusty-mpm-projects` — the fix must not move the root for the
    /// overwhelming majority of operators who configure nothing.
    ///
    /// Why: the companion to the regression above. A resolver that honoured
    /// config but changed the unconfigured default would break every existing
    /// install silently.
    /// What: with the env var cleared AND no config template supplied, the
    /// shared resolver returns `<home>/trusty-mpm-projects`. Asserts against
    /// `resolve_workspace_root(None)` rather than the zero-argument
    /// `workspace_root()`, which reads the DEVELOPER'S OWN `config.yaml` — a
    /// machine with `workspace_root_template` set would otherwise fail this
    /// test for a correct build.
    /// Test: this test.
    #[test]
    fn default_workspace_root_is_unchanged_when_nothing_is_configured() {
        let _guard = env_lock();
        // SAFETY: guarded by `env_lock()`.
        unsafe {
            std::env::remove_var(trusty_common::workspace_layout::WORKSPACE_ROOT_ENV);
        }
        let root = trusty_common::workspace_layout::resolve_workspace_root(None);
        let home = dirs::home_dir().expect("home");
        assert_eq!(root, home.join("trusty-mpm-projects"));
    }

    /// Serialise the env-mutating tests in this module.
    ///
    /// Why: `cargo test` shares one process environment across parallel test
    /// threads, so an unguarded `set_var` leaks into a sibling's assertions.
    /// What: a process-global mutex, poison-tolerant (a panicking test must not
    /// wedge every later one).
    /// Test: used by `configured_workspace_root_is_scanned_not_the_default`,
    /// `default_workspace_root_is_unchanged_when_nothing_is_configured`.
    fn env_lock() -> std::sync::MutexGuard<'static, ()> {
        static LOCK: std::sync::OnceLock<std::sync::Mutex<()>> = std::sync::OnceLock::new();
        LOCK.get_or_init(|| std::sync::Mutex::new(()))
            .lock()
            .unwrap_or_else(|e| e.into_inner())
    }
}