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
//! In-project spawn path: shared base clone + per-session worktrees (#1706, #1803, #2032).
//!
//! Why: operators who run `tm` from inside a git repository should get a managed
//! session against a git-worktree slice of that repo rather than a full clone.
//! This module implements the "in-project" path: (a) a durable PROTECTED base
//! clone under `~/trusty-mpm-projects/<owner>/<repo>/` that is always on the
//! default branch and owned by the daemon, and (b) a per-session git worktree
//! at `<base>/.worktrees/<worktree_name>` branched off that clone so each
//! session works in isolation. Since #2032 `worktree_name` is the SEMANTIC
//! tmux session name (e.g. `tm-trusty-tools-01`), not the raw session UUID —
//! resolving that name requires the async `SessionManager`, which this module
//! deliberately does not depend on, so worktree CREATION is split from
//! DETECTION (see [`try_inproject_spawn`] vs [`create_session_worktree`]).
//! Existing UUID-named worktrees are left as-is; only NEW sessions get the
//! semantic name.
//! What: [`repos_root`] resolves the configurable root; [`base_clone_path`]
//! computes the per-project clone directory; [`ensure_base_clone`] clones if
//! absent; [`try_inproject_spawn`] is the main entry point called from the
//! lifecycle layer — it detects the GitHub identity and ensures the base
//! clone, returning `(base_path, owner, repo)`; [`create_session_worktree`]
//! adds a per-session worktree at `<base>/.worktrees/<worktree_name>` given a
//! CALLER-RESOLVED name; [`worktree_name_collides`] lets the caller steer name
//! resolution away from an existing worktree dir/branch;
//! [`ensure_worktrees_gitignored`] keeps the worktree directory out of
//! `git status`; [`get_origin_url`] reads the remote.origin.url from a git
//! directory.
//! Test: `try_inproject_spawn_returns_none_for_non_git_path` unit test covers the
//! non-git early exit; integration coverage via `tests/local_spawn.rs`.
use ;
use ;
/// Environment variable that overrides the managed repos root.
///
/// Why: operators need an escape hatch (tests, non-standard layouts) that wins
/// over config without touching the config file.
/// What: `"TRUSTY_MPM_REPOS_ROOT"`.
/// Test: indirectly by integration tests that set this env var.
pub const REPOS_ROOT_ENV: &str = "TRUSTY_MPM_REPOS_ROOT";
/// Default repos root directory name under `$HOME`.
///
/// Why: mirrors the canonical trusty-mpm-projects directory that `workspace_root()`
/// also resolves to, so both the guided-default path and `tm launch` converge on
/// the same base clone location (#1803).
/// What: `"trusty-mpm-projects"`.
/// Test: `repos_root_default_ends_with_canonical_segment`.
pub const DEFAULT_REPOS_DIR: &str = "trusty-mpm-projects";
/// Resolve the absolute root for base clones, with an optional direct override.
///
/// Why: tests that control the repos root must not mutate process-wide env vars
/// (which races other threads). Exposing the override as a parameter lets callers
/// supply the value directly without `set_var` / `remove_var`.
/// What: `env_override` wins over the `TRUSTY_MPM_REPOS_ROOT` env var, which
/// wins over `workspace_root()`. Falls back to `/tmp/trusty-mpm-projects` only
/// when the home directory is unresolvable AND nothing absolute was supplied.
/// Test: `repos_root_default_ends_with_canonical_segment`; `base_clone_path_respects_repos_root_override` (integration).
/// Resolve the absolute root for base clones.
///
/// Why: the base-clone path needs ONE answer for "where do managed base clones
/// live?", with precedence TRUSTY_MPM_REPOS_ROOT env > TRUSTY_MPM_WORKSPACE_ROOT
/// env > config template > built-in `~/trusty-mpm-projects` (#1803).
/// What: delegates to [`repos_root_from`] with no in-process override, reading
/// `TRUSTY_MPM_REPOS_ROOT` from the environment as usual.
/// Falls back to `/tmp/trusty-mpm-projects` only when the home directory is
/// unresolvable AND nothing absolute was supplied.
/// Test: `repos_root_default_ends_with_canonical_segment`.
/// Expand a leading `~` in a path string to `home`.
///
/// Why: env values are often home-relative; normalizing them once here keeps
/// caller code free of `~` handling.
/// What: replaces a leading `~/` or bare `~` with `home`; other paths pass through.
/// Test: covered indirectly by `repos_root` env-override tests.
/// Compute the base clone path for a GitHub `owner/repo`.
///
/// Why: the base clone directory must be stable and deterministic so multiple
/// sessions against the same repo all share one protected clone.
/// What: returns `<repos_root>/<owner>/<repo>`.
/// Test: `base_clone_path_resolves_to_canonical_root` (unit); wiring via integration tests.
/// Filename-suffix stem used when migrating a pre-#1803 old-layout dir aside.
///
/// Why: naming the backup suffix once keeps [`migrate_old_layout_aside`] and any
/// operator-facing docs/tests in agreement, and makes the moved directory
/// self-describing (`<repo>.old-layout-backup-<unix_ts>`).
/// What: `".old-layout-backup-"` — the timestamp is appended by the migrator.
/// Test: `ensure_base_clone_migrates_old_layout_dir_aside` asserts a sibling
/// directory whose name contains this stem is created.
pub const OLD_LAYOUT_BACKUP_SUFFIX: &str = ".old-layout-backup-";
/// Detect and migrate a pre-#1803 OLD-LAYOUT base directory out of the way (#1805).
///
/// Why: before #1803 the managed base directory `<repos_root>/<owner>/<repo>/` was
/// a plain container of per-session UUID full-clone subdirectories with NO
/// top-level `.git`. The new shared-base design wants to `git clone` INTO that same
/// path, but git refuses to clone into a non-empty directory — so the clone failed
/// and the daemon silently fell back to the legacy full-clone-per-session behaviour,
/// meaning migrated repos never got the `.worktrees/` layout. Moving the stale dir
/// aside (rather than erroring) upholds the project's "operator does nothing"
/// north-star: the fresh clone proceeds automatically and the old data is preserved
/// under a clearly-named backup the operator can inspect or delete at leisure.
/// What: acts ONLY when `base_path` exists, is a directory, is non-empty, and has
/// NO top-level `.git` (the precise old-layout signature). In that case it renames
/// `base_path` to a sibling `<repo><OLD_LAYOUT_BACKUP_SUFFIX><unix_nanos>` and
/// returns `Ok(Some(backup))`. Empty dirs, already-`.git` dirs, and absent paths
/// are left untouched (`Ok(None)`) — git clone handles an empty/absent dir fine and
/// the caller handles the `.git` case before ever calling this. Loudly `warn!`s so
/// the migration is never silent.
/// Test: `ensure_base_clone_migrates_old_layout_dir_aside`,
/// `migrate_old_layout_aside_ignores_empty_and_git_dirs`.
/// Ensure a base clone exists at `base_path`, cloning from `origin_url` if not.
///
/// Why: the first session against a repo triggers a one-time clone; subsequent
/// sessions reuse the same base directory and only add worktrees.
/// What: if `base_path/.git` exists, calls `ensure_worktrees_gitignored` and
/// returns `Ok(())` (idempotent). Otherwise it first migrates any pre-#1803
/// old-layout dir aside via [`migrate_old_layout_aside`] (#1805 — so a non-empty,
/// non-git directory no longer makes the clone fail and silently fall back to the
/// legacy full-clone-per-session path), then runs
/// `git clone --no-local <origin_url> <base_path>` and calls
/// `ensure_worktrees_gitignored`. A clone failure returns `Err` with the
/// command's stderr.
/// Test: idempotent path covered by unit tests; migration path by
/// `ensure_base_clone_migrates_old_layout_dir_aside`; clone path by integration tests.
/// Compute the per-session worktree directory for `worktree_name` under `base_path`.
///
/// Why: both [`create_session_worktree`] and the caller-side collision check
/// ([`worktree_name_collides`], used by the in-project spawn routing layer to
/// steer `SessionManager::resolve_session_name` away from a name whose
/// worktree already exists on disk, #2032) must agree on exactly where a
/// worktree for a given name would live.
/// What: `<base_path>/.worktrees/<worktree_name>` (dot-prefixed so
/// `ensure_worktrees_gitignored` hides it from `git status`).
/// Test: `session_worktree_path_uses_dot_prefix`.
/// Compute the per-session branch name for `worktree_name`.
///
/// Why: re-exported here (rather than defined here) so existing callers in
/// this module keep the short `worktree_branch_for(...)` spelling. The single
/// source of truth lives in [`crate::core::worktree_naming`] — an
/// unconditionally-compiled module — specifically so
/// `session_manager::decommission` (which is NOT gated behind the `daemon`
/// feature) can depend on the SAME convention without pulling in this
/// feature-gated `daemon` module (#2032; see that module's doc for why the
/// dependency direction matters).
/// What: `format!("session/{worktree_name}")`.
/// Test: `crate::core::worktree_naming::tests::worktree_branch_for_adds_session_prefix`.
pub use crateworktree_branch_for;
/// Check whether a worktree directory or branch already exists for `worktree_name`.
///
/// Why (#2032): `tmux_name` collisions were already guarded by
/// `SessionManager::resolve_session_name`'s live-tmux-session check, but that
/// check knows nothing about git worktrees or branches — a DIFFERENT
/// collision surface. Without this, two names could theoretically differ in
/// tmux-liveness (one dead, one live) yet share the same worktree directory
/// once #2032 makes the worktree leaf equal to the tmux name, silently
/// clobbering (or failing to clobber, but confusingly erroring on) a stale
/// worktree left behind by a hand-deleted-but-not-decommissioned session.
/// This predicate is threaded into `resolve_session_name` as its
/// `extra_collision` callback so a colliding candidate is retried with the
/// next free serial BEFORE `create_session_worktree` ever runs, rather than
/// discovered as a raw `git worktree add`/`git branch` failure.
/// What: `true` if `<base_path>/.worktrees/<worktree_name>` exists on disk OR
/// `refs/heads/session/<worktree_name>` already exists in `base_path`'s repo.
/// Test: `worktree_name_collides_detects_existing_dir_and_branch`.
/// Create a per-session git worktree branched off the base clone.
///
/// Why: each managed session must work in an isolated branch; git worktrees
/// achieve this without duplicating the object store of the base clone. Since
/// #2032 the caller supplies the ALREADY-RESOLVED semantic tmux name (e.g.
/// `tm-trusty-tools-01`) rather than the raw session UUID, so the worktree
/// directory and branch are human-readable and match the tmux session the
/// operator actually sees in `tm session ls`.
///
/// NOTE for #2033 (trusty-search index-id derivation): the worktree LEAF NAME
/// computed here (`worktree_name`) is significant beyond this function — the
/// trusty-search index id for a managed session is derived from the worktree
/// path, so #2033 must read the ACTUAL path this function returns (or the
/// record's `workspace_path`, which `spawn_managed_inproject` sets to this
/// same path) rather than re-deriving a path from the session id.
/// What: runs `git -C <base_path> worktree add -b session/<worktree_name>
/// <base_path>/.worktrees/<worktree_name>`. Returns the worktree path on
/// success. Fails loudly (rather than silently clobbering) if the target
/// worktree directory already exists — callers are expected to have already
/// steered `SessionManager::resolve_session_name` away from a colliding name
/// via [`worktree_name_collides`], so hitting this guard indicates a TOCTOU
/// race or a caller that skipped the collision check.
/// Test: covered by integration tests against a real temp repo;
/// `create_session_worktree_rejects_existing_worktree_dir`.
/// Best-effort-idempotent: add `.worktrees/` to the base clone's `.git/info/exclude`.
///
/// Why: per-session worktrees live at `<base>/.worktrees/<session-id>/`; without
/// a gitignore entry `git status` inside the base clone reports the `.worktrees/`
/// directory as untracked, polluting the output for every harness that runs there.
/// Adding to `.git/info/exclude` (not `.gitignore`) keeps the entry local to the
/// clone and does not affect any committed `.gitignore`.
/// What: creates `<base>/.git/info/` if absent, then reads the current exclude
/// file and appends `.worktrees/` only when the entry is absent. The read-then-
/// append window means concurrent callers racing at first launch may each observe
/// an absent entry and both append — resulting in a duplicate line. Git tolerates
/// duplicate patterns (same set is matched), so this is safe; single-caller
/// invocations are strictly idempotent. Returns `Ok(())` on success or when the
/// entry already exists; propagates I/O errors.
/// Test: `ensure_worktrees_gitignored_idempotent`.
/// Read the `remote.origin.url` from a git repository at `path`.
///
/// Why: the in-project spawn path needs the remote URL to determine the
/// `owner/repo` identity and locate the matching base clone.
/// What: runs `git -C <path> config --get remote.origin.url` and returns the
/// trimmed stdout on success, or `None` if git fails or there is no remote origin.
/// Test: `get_origin_url_returns_none_for_non_git` (unit).
/// Main entry point for the in-project spawn path's DETECTION phase (#1706, #2032).
///
/// Why: the lifecycle layer needs a single call that encapsulates in-project
/// detection: is the given path inside a git repo with a GitHub remote? If so,
/// ensure the base clone exists. Since #2032 this function STOPS SHORT of
/// creating the per-session worktree: the worktree directory/branch must be
/// named after the semantic tmux name (resolved via
/// `SessionManager::resolve_session_name`), which requires the session
/// manager's async store/tmux state that this synchronous, decoupled module
/// deliberately has no access to. The caller
/// (`daemon::managed_routes::lifecycle::spawn_managed_routed`) resolves the
/// name and calls [`create_session_worktree`] itself.
/// What: (1) checks that `path` is an existing directory with a `.git` entry;
/// (2) reads the `remote.origin.url` — returns `Ok(None)` if absent;
/// (3) parses the URL via `trusty_common::github_path::parse_github_path` —
/// returns `Ok(None)` if unparseable; (4) calls [`ensure_base_clone`];
/// (5) returns `Ok(Some((base_clone_path, owner, repo)))` — NOT a worktree
/// path (that was the pre-#2032 contract). Step 4 errors propagate as `Err`.
/// Test: `try_inproject_spawn_returns_none_for_non_git_path` (unit).