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
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
//! 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, keeping "no remote" and "git failed" apart so a failure cannot
//! be mistaken for an absent remote (#4734). The sibling [`untracked_sync`]
//! module (#2196) syncs an
//! allowlist of untracked/secret files (e.g. `.env*`) from the operator's
//! live checkout into a freshly-created session worktree; it is called from
//! `lifecycle::reserve_inproject_worktree`, not from this module directly,
//! since only that call site holds both the live-checkout source path and
//! the resolved worktree destination.
//! 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 ;
// #7166 review follow-up: split out to keep this file under the 500-SLOC cap.
// #9091: the base clone and its account seam, split out for the 500-SLOC cap.
pub use ensure_base_clone;
// #7166 owner ruling ("do B"): per-account gh config dir bootstrap, used by
// `account_clone` — a sibling module (not nested under it) so both this file
// and `account_clone` can reach it via `super`/direct path without an extra
// re-export hop.
// #8914: the `--account` session gate builds and checks the same dir.
pub use ensure_account_config_dir;
/// Resolve (building if necessary) the per-account `gh` config directory for
/// `login`, for callers outside this module that need to persist it (#7166
/// review follow-up CRITICAL).
///
/// Why: [`ensure_base_clone`] only builds this directory on a genuine first
/// clone — an already-`.git`-containing `base_path` returns early without
/// ever calling [`account_clone::account_clone_env`]/the bootstrap. The CLI
/// (`bin/tm/commands/run_target.rs`'s `run_managed`, `main.rs`'s `Register`
/// handler) needs the SAME directory on every `--account` invocation,
/// including a reused-checkout run, so it can persist
/// `Project.github.config_dir` and keep every LATER session spawn (fetches,
/// pushes, `gh` calls) on the discriminating `GH_CONFIG_DIR` path instead of
/// the demoted `gh auth token -u` fallback.
/// What: delegates to
/// [`account_config_dir::ensure_account_config_dir_default`] — idempotent:
/// builds once from the operator's own logged-in `hosts.yml`, reused
/// untouched on every later call.
/// Test: covered indirectly via `account_config_dir::tests`, which exercise
/// the bootstrap this thin wrapper delegates to; this function adds no logic
/// of its own to test hermetically.
/// 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.
///
/// #4270 carves a whole class out of that automatic rename: a directory holding
/// git or trusty-mpm state. A project directory with `.base` or `.worktrees`
/// matches the old-layout signature exactly (non-empty, no top-level `.git`)
/// but is nothing like it — those hold real repositories and checked-out
/// worktrees, and renaming the parent orphans every one of them at once,
/// possibly while a session is live. That is the #3605 failure mode with a
/// bigger blast radius, so this returns `Err` there instead. The `.git`
/// early-return below does not make `.git` redundant in that check:
/// `Path::exists` answers `false` for an entry it lacks permission to stat, so
/// an EACCES blip on `.git` would otherwise fall through to the rename.
/// What: acts ONLY when `base_path` exists, is a directory, is non-empty, has
/// NO top-level `.git` (the precise old-layout signature), and holds none of the
/// protected entries [`crate::core::harness_root::protected_state_in`] names. 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`,
/// `migrate_old_layout_aside_refuses_a_dir_holding_a_dot_base_store`,
/// `migrate_old_layout_aside_refuses_a_dir_holding_live_worktrees`.
/// 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-dirname>/<worktree_name>`, where the base name
/// is the configured one (#5204) and defaults to `.worktrees` — dot-prefixed so
/// `ensure_worktrees_gitignored` hides it from `git status`.
/// Test: `session_worktree_path_uses_dot_prefix`,
/// `worktree_path_for_honours_configured_base`.
/// 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, refusing when the disk is too full.
///
/// Why (#7497): this is the name every tm-owned provisioning path calls, so the
/// `disk.max_usage_pct` gate belongs on it rather than beside it — a creation
/// path that forgets to check is then a call to a differently-spelled function,
/// not an omission. The ungated mechanics stay reachable as
/// [`create_session_worktree_unchecked`], which is what a test fixture building
/// a worktree to exercise something else calls.
/// What: measures the mount the worktree would land on and delegates to
/// [`create_session_worktree_measured`].
/// Test: `create_session_worktree_measures_a_real_mount` in
/// `tests/worktree_disk_usage_gate.rs` — the live half; the decision itself is
/// pinned through [`create_session_worktree_measured`].
/// [`create_session_worktree`] with the measurement source named explicitly.
///
/// Why (#7603): the gate's target path is built HERE, from `base_path` and
/// `worktree_name`, so a caller that wants to pin the measurement cannot take it
/// itself — it has to hand down a [`DiskGate`] and let this function apply it.
/// That is what keeps the tm-bin provisioning tests off the developer's real
/// volume and real `~/.trusty-tools/trusty-mpm/config.yaml`.
/// What: resolves the measurement through `gate` and delegates to
/// [`create_session_worktree_measured`] — same threshold, same decision, only
/// the measurement's source differs.
/// Test: `provision_for_launch_explicit_request_creates_worktree`,
/// `a_pinned_over_threshold_gate_refuses_a_launch_worktree`.
///
/// [`DiskGate`]: crate::core::disk_usage_guard::DiskGate
/// [`create_session_worktree_gated`], recorded in the worktree ledger (#8994).
///
/// Why: every tm provisioning route must enter the tree it creates into
/// `~/.trusty-mpm/worktrees.jsonl`, and a ledger it cannot write must refuse
/// the creation instead of producing an unrecorded tree. One helper serves the
/// daemon and the CLI so the two routes record identically.
/// What: [`crate::core::worktree_ledger::record::create_recorded`] around
/// [`create_session_worktree_gated`], with the session branch and `origin`.
/// Test: `reserve_inproject_worktree_refuses_when_the_ledger_cannot_record`,
/// `reserve_inproject_worktree_records_the_created_tree`,
/// `a_launch_worktree_is_refused_when_the_ledger_cannot_record`.
/// The daemon's [`create_session_worktree`], recorded in the operator's ledger
/// (#8994).
///
/// What: [`create_session_worktree_recorded`] with the real disk measurement,
/// the `$HOME` ledger and [`crate::core::worktree_ledger::Origin::TmDaemon`];
/// no resolvable home is a refusal.
/// Test: `reserve_inproject_worktree_refuses_when_the_ledger_cannot_record`.
/// [`create_session_worktree`] against an ALREADY-TAKEN measurement.
///
/// Why: the seam the end-to-end tests pin a synthetic percentage through, so
/// the gate's behaviour at, over and below the threshold — and on an
/// unmeasurable mount — is asserted deterministically rather than depending on
/// how full the runner's volume happens to be (#7497 review).
/// What: applies [`crate::core::disk_usage_guard::check_measured`] — fail-closed
/// on `None` per ADR-0037 — and creates nothing when it refuses.
/// Test: `create_session_worktree_refuses_a_pinned_over_threshold_measurement`,
/// `create_session_worktree_refuses_an_unmeasurable_mount`,
/// `create_session_worktree_creates_on_a_pinned_under_threshold_measurement`.
/// Create a per-session git worktree branched off the base clone, with NO disk
/// gate.
///
/// 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> <start-point>`, where `<start-point>`
/// is `origin/<default-branch>` freshly fetched by
/// [`super::inproject_start_point::resolve`] (#4957 — omitting it inherits the
/// base checkout's local `HEAD`, which starts every session as stale as the
/// operator's last `git pull`). A fetch that fails degrades to the last-known
/// remote-tracking ref (or `HEAD`) and is `warn!`-logged, never silent.
/// 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.
/// `owner_session_id` (#3649, Option B): the managed session this worktree is
/// being created FOR — written into the ownership sentinel (as a JSON
/// payload, replacing the pre-#3649 zero-byte convention) so the orphan-GC
/// sweep and the `decommission` owner gate can later resolve who is entitled
/// to reclaim this worktree.
/// Test: covered by integration tests against a real temp repo;
/// `create_session_worktree_rejects_existing_worktree_dir`,
/// `create_session_worktree_writes_owner_sentinel` (#3649),
/// `session_worktree_branches_from_fetched_origin_not_stale_local_main` (#4957).
/// Give a freshly-created session worktree a working `git pull` from the
/// default branch, WITHOUT making `git push` target that branch (#2189).
///
/// Why: [`create_session_worktree`] leaves the new `session/<name>` branch
/// with no upstream at all, so a bare `git pull` inside the worktree fails
/// with "There is no tracking information for the current branch." Setting
/// the upstream to `origin/<default>` fixes `pull`/`fetch`-with-merge, but
/// naively doing so ALSO makes a bare `git push` try to push the session
/// branch's commits onto the shared default branch — which is exactly what a
/// per-session isolated branch must never do. Scoping `push.default =
/// current` to this one worktree (via `extensions.worktreeConfig` +
/// `--worktree` config) keeps push targeting `origin/session/<name>` while
/// pull still tracks the default branch.
///
/// ORDERING IS A SAFETY PROPERTY (#2867). `branch.<session>.merge =
/// refs/heads/<default>` is a FOREIGN upstream: the session worktree does not
/// own the default branch. It is only safe while `push.default = current` is
/// actually in effect for this worktree — that is the single knob keeping a
/// bare `git push` off the default branch. The push pin is therefore
/// established and READ BACK FIRST, and the foreign upstream is written only
/// once the pin is confirmed. When the pin cannot be confirmed (an old git
/// without `extensions.worktreeConfig`, a read-only base config, a sandbox
/// blocking the config write) the worktree is left with NO upstream at all:
/// `git pull` then needs a one-off `git pull origin <default>`, which is a far
/// cheaper failure than an armed worktree whose bare push lands on a branch it
/// does not own — the exact shape that clobbered PR #2863's reviewed lineage.
///
/// What: (1) runs `git -C <base_path> config extensions.worktreeConfig true`
/// to enable per-worktree config on the shared base repo (idempotent — safe to
/// set on every call); (2) runs `git -C <worktree_path> config --worktree
/// push.default current` so `git push` always targets the current (session)
/// branch; (3) reads the EFFECTIVE `push.default` back from the worktree and
/// aborts without setting any upstream unless it resolves to `current`; (4)
/// resolves the default branch via
/// [`super::inproject_hygiene::get_default_branch`], falling back to `"main"`
/// when it cannot be determined, and runs `git -C <worktree_path> branch
/// --set-upstream-to=origin/<default>` so `git pull` works. Every step is
/// best-effort: a failure is logged via `warn!` and does NOT fail worktree
/// creation — the worktree itself was already created successfully by the time
/// this runs, and an operator can always set tracking manually as a fallback.
/// Test: `create_session_worktree_sets_pull_upstream_and_worktree_scoped_push`
/// and `push_pin_detection_matches_effective_config` (real temp git repos with
/// a bare `origin` remote).
/// Does the effective `push.default` say a bare `git push` targets the current
/// branch?
///
/// Note the deliberately narrow claim: this reports on `push.default` only. It
/// is NOT a proof that no push can leave the current branch. A configured
/// `remote.<name>.push` refspec bypasses `push.default` entirely, and the gate
/// is equally satisfied by a GLOBAL `push.default = current` that trusty-mpm
/// does not own and the user may change later, re-arming an upstream already
/// written under it. The `pre-push` guard (`crate::core::push_guard`) is the
/// backstop for both; this check only decides whether writing a foreign
/// upstream is defensible in the first place.
///
/// Why: this is the precondition for [`configure_session_branch_tracking`] to
/// be allowed to write a FOREIGN upstream (#2867). Checking the exit status of
/// the `git config --worktree push.default current` write is not enough — it
/// answers "did the write succeed", not "what will `git push` actually do".
/// What: reads the EFFECTIVE `push.default` with `git config --get`, which
/// resolves the whole config stack (system → global → local → `config.worktree`)
/// exactly as `git push` will, and reports whether it is `current`. Any failure
/// to read (git missing, not a repo, key unset) is reported as NOT pinned —
/// the fail-safe direction.
/// Test: `push_pin_detection_matches_effective_config`.
/// Keep the base clone's `.worktrees/` out of `git status` AND out of reach of
/// `git clean -ffd`.
///
/// Why: re-exported here (rather than defined here) so this module's existing
/// callers keep the short spelling, exactly like [`worktree_branch_for`] above.
/// The single source of truth moved to [`crate::core::worktree_naming`] in
/// #4270 because `provisioner::workspace` — which is NOT gated behind the
/// `daemon` feature — now produces the identical topology and needs the same
/// entry. See that module for the `git clean` evidence.
/// What: appends `.worktrees/` to `<base>/.git/info/exclude`, idempotently.
/// Test: `ensure_worktrees_gitignored_idempotent`,
/// `worktrees_exclude_entry_protects_against_double_force_clean`.
pub use crateensure_worktrees_gitignored;
/// Confirm git reads the repository rooted at `path`, when one is rooted there.
///
/// Why: `git config --get` answers from whatever repository DISCOVERY finds,
/// and discovery walks straight past a `.git` it cannot read — which hides two
/// faults the exit code cannot express (#4734). A `.git` directory at mode 000
/// with no repo above it exits **1 with empty stderr**, identical to "no origin
/// remote"; the same `.git` nested inside another repo exits **0 with the
/// PARENT repo's origin**, which would have the daemon provision a managed
/// clone of the wrong repository. Neither shows up in the exit code or in
/// stderr, so the exit-code split alone cannot catch them and no amount of
/// stderr matching would either.
/// What: `path/.git` existing means a repository is rooted at `path`, so git's
/// own `rev-parse --show-toplevel` must name `path` back. A failure to answer,
/// or an answer naming a different directory, is `Err`. When `path/.git` does
/// NOT exist the check is skipped, which keeps the two legitimate cases
/// working: `path` is not in a repo at all (the caller's read exits 1, a true
/// `Ok(None)`), or `path` is a subdirectory of a repo, where discovering the
/// enclosing repo is exactly what callers want. `--show-toplevel` rather than
/// the git dir because a linked worktree's git dir lives under the main
/// checkout while its toplevel is the worktree itself — and tm creates linked
/// worktrees, so that case is load-bearing.
/// Test: `get_origin_url_errors_when_the_git_dir_is_unreadable`,
/// `get_origin_url_errors_when_discovery_escapes_to_a_parent_repo`,
/// `get_origin_url_reads_a_linked_worktree`.
/// 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. Before #4734 this
/// returned a bare `Option`, so "this repo has no `origin` remote" and "git
/// could not answer at all" were the same value, and every caller read it as
/// the former — `tm launch` and the guided default told the operator a repo
/// they could not read had no remote, or was not a GitHub project, and sent
/// them to `tm connect` for a checkout that is fine.
/// What: guards with [`ensure_repo_rooted_at`], then runs
/// `git -C <path> config --get remote.origin.url` and keeps apart the outcomes
/// git distinguishes by exit code. Exit 0 yields `Ok(Some(url))`, or `Ok(None)`
/// when the configured value is empty. Exit 1 is git-config's "the key is not
/// set" answer, so it yields `Ok(None)` — both a plain non-git directory and a
/// repo with no `origin` land there, which is why this split changes no
/// existing caller's behaviour on a healthy machine (a multi-valued `origin`,
/// the one working setup that could have regressed into `Err`, exits 0).
/// Anything else — a spawn failure, or a fatal exit such as 128 for an
/// unreadable `.git/config`, a dangling gitdir pointer, or a `safe.directory`
/// ownership refusal — is `Err`, for the caller to fail closed on.
/// Test: `get_origin_url_returns_none_for_non_git`,
/// `get_origin_url_returns_none_for_repo_without_origin`,
/// `get_origin_url_handles_a_multi_valued_origin`,
/// `get_origin_url_reads_a_linked_worktree`,
/// `get_origin_url_errors_when_git_config_is_unreadable`,
/// `get_origin_url_errors_when_the_git_dir_is_unreadable`,
/// `get_origin_url_errors_when_discovery_escapes_to_a_parent_repo` (unit);
/// `try_inproject_spawn_errors_when_git_cannot_read_the_remote`
/// (`tests/inproject_git_failure.rs`).
/// 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, and `Err`
/// when git could not answer at all (#4734: this step used to collapse those
/// two into `Ok(None)`, so the caller went on to report a repo git could not
/// read as one with no GitHub remote);
/// (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),
/// `try_inproject_spawn_errors_when_git_cannot_read_the_remote`
/// (`tests/inproject_git_failure.rs`).