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
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
//! Pre-launch preparation for a Claude Code session.
//!
//! Why: every trusty-mpm session is launched as `claude` (the Claude Code CLI),
//! never `claude-mpm`. The "trusty-mpm" behaviour is supplied entirely through
//! the custom instructions Claude Code reads at startup — the deployed agents in
//! `~/.claude/agents/` and the project `CLAUDE.md`. Both the CLI (`tm session
//! start`) and the shared client (`DaemonClient::launch_session`, used by the
//! TUI's `/connect`) must perform the identical preparation; centralizing it
//! here keeps the two launch paths from drifting.
//! What: [`prepare_session`] deploys composed agents to `~/.claude/agents/` and
//! runs the instruction merge pipeline, writing/merging the project `CLAUDE.md`
//! and stashing the merged result under `<project>/.trusty-mpm/`. It returns a
//! [`PrepReport`] describing what happened so callers can report it.
//! Test: `prepare_session_writes_claude_md_and_stash` and
//! `prepare_session_is_idempotent` in this module's tests.
// #4448: the ONE wiring of the shadowing-agent quarantine, shared by
// `prepare_session_inner` and `sync_session_assets`.
// Split out of `tests.rs` to keep it under the 1500-SLOC test-file cap
// (issue #2149 roster-deploy-failure-continues coverage) — mirrors the
// `doctor_output_style.rs` / `doctor_fs_checks.rs` split pattern.
// Split out of `tests.rs` to keep it under the 1500-SLOC test-file cap
// (issue #3427 scaffolding-gitignore wiring coverage) — mirrors the
// `tests_roster.rs` split pattern above.
// Split out of `tests.rs` to keep it under the 1500-SLOC test-file cap
// (issue #2914 ephemeral-index-leak regression coverage) — mirrors the
// `tests_roster.rs` split pattern above.
// #4181 — successor to the #3926 suite: the approval is deleted, so this file
// now pins that NO name is pre-approved and that a stale one is stripped.
// Issue #4072 — concurrency coverage for the shared `~/.claude.json`
// read-modify-write cycle both trust seeders perform. Its own file because
// `settings.rs` (485/500 production SLOC) and `tests.rs` (1482/1500 test
// SLOC) are both effectively at their caps; mirrors the split pattern above.
// Issue #4448 — call-site coverage for the shadowing-agent quarantine. Its own
// file for the same reason as the split above, and because these tests exist
// specifically to fail when the MOVE-authorising call site is deleted,
// reordered, or re-aimed at the operator's own `~/.claude/agents`.
use ;
use crate;
use crate;
use crateFrameworkPaths;
use crateDeployStats;
use ;
/// Re-export of the project-tier output-style/statusLine resolution primitives
/// for reuse by `core::standalone::settings_defaults` (issue #2214).
///
/// Why: `mod settings` above is private, so a `pub(crate)` item inside it is
/// still unreachable from outside `session_launch` without a re-export at this
/// (public) module boundary. `core::standalone::settings_defaults::ensure_settings_defaults`
/// seeds `outputStyle`/`statusLine` into the tm-owned `CLAUDE_CONFIG_DIR`
/// settings.json using these exact same values, rather than duplicating the
/// default-id constant or the absolute-binary-path resolution logic.
/// What: re-exports [`settings::OUTPUT_STYLE`],
/// [`settings::resolve_statusline_command`], and
/// [`settings::is_stale_statusline_command`] (so `settings_defaults` can
/// self-heal a stale/ephemeral `statusLine` entry — #2229) under the
/// `session_launch::` path.
/// Test: covered indirectly by
/// `core::standalone::settings_defaults` tests (this is a plain re-export, no
/// logic of its own).
pub use ;
/// Re-export of the trusty-search project-index registration entry point and
/// the trusty-memory palace-slug derivation.
///
/// Why: `mod search_index` / `mod settings` above are private, so a
/// `pub(crate)` item inside either is unreachable from outside `session_launch`
/// without a re-export at this (public) module boundary — mirroring the
/// `OUTPUT_STYLE` re-export just above. // #4181: both used to feed the
/// `.mcp.json` injectors this module owned; ADR-0042 deleted those, and
/// `core::mcp_session_env` now consumes the same two values to build the
/// `TRUSTY_INDEX` / `TRUSTY_MEMORY_PALACE` variables the spawn exports.
/// What: re-exports [`search_index::register_project_index`] and
/// [`settings::resolve_palace_slug`] — plain re-exports, no logic of their own.
/// Test: `tests_search_index.rs` and `resolve_palace_slug_*` in `tests.rs`.
pub use register_project_index;
pub use resolve_palace_slug;
/// Re-export of the #1939 palace-alias healing so it can run per launch from
/// `core::managed_config::ensure_managed_config_dir_with_root`.
///
/// Why (#4181): `maybe_register_palace_alias` had exactly one call site — inside
/// `settings::inject_trusty_memory_mcp`, immediately before the write. ADR-0042
/// deletes that injector, and deleting it as written would stop the claude-mpm
/// split-brain healing with no test failing to say so. The call is rehomed onto
/// `ensure_managed_config_dir`, which every spawn, resume and in-place relaunch
/// already reaches.
/// What: re-exports [`palace_alias::maybe_register_palace_alias`] — a plain
/// re-export, no logic of its own.
/// Test: `palace_alias`'s own unit tests, plus
/// `ensure_managed_config_dir_heals_a_bare_repo_palace_alias`, which fails if
/// the rehomed call site is deleted.
pub use maybe_register_palace_alias;
/// Re-export of the resume-time worktree/upstream sync primitives (issue
/// #2647) for reuse by `daemon::managed_routes::lifecycle::resume_managed`.
///
/// Why: `mod worktree_sync` above is private; this re-export is the public
/// boundary the resume path calls through, mirroring the `settings`
/// re-export just above.
/// What: re-exports [`worktree_sync::resume_self_heal`] — the single
/// call-site entry point wrapping [`worktree_sync::sync_worktree_with_upstream`]
/// and [`worktree_sync::self_heal_claude_md`] with logging.
/// Test: covered by `worktree_sync`'s own unit tests (this is a plain
/// re-export, no logic of its own).
pub use resume_self_heal;
/// Re-export of the asset re-sync entry point (issue #2444) for the daemon's
/// `sync-assets` route and `tm doctor`/`tm sessions ls` staleness surfaces.
///
/// Why: `mod sync_assets` above is private; this is the public boundary
/// external callers go through, mirroring the `worktree_sync` re-export above.
/// What: re-exports [`sync_assets::sync_session_assets`],
/// [`sync_assets::SyncAssetsError`], and [`sync_assets::SyncAssetsReport`].
/// Test: covered by `sync_assets`'s own unit tests (this is a plain
/// re-export, no logic of its own).
pub use ;
/// Re-export of the launch-time `ws/<session-name>` workstream-label ensure
/// (issue #3726) for the daemon's `spawn_managed_*` call sites.
///
/// Why: `mod workstream_label` above is private; this is the public boundary
/// the spawn paths call through, mirroring the `sync_assets`/`worktree_sync`
/// re-exports above.
/// What: re-exports [`workstream_label::ensure_workstream_label`], its
/// [`workstream_label::LabelOutcome`] result type, and the detached
/// [`workstream_label::spawn_workstream_label_ensure`] wrapper the daemon
/// spawn paths actually call (fire-and-forget, never on the launch critical
/// path).
/// Test: covered by `workstream_label`'s own unit tests (this is a plain
/// re-export, no logic of its own).
pub use ;
/// Outcome of the pre-launch preparation for one session.
///
/// Why: callers (CLI, client) report agent-deploy counts and CLAUDE.md status
/// to the operator; bundling them avoids returning a loose tuple.
/// What: the agent [`DeployResult`], the instruction [`PipelineOutput`], and the
/// path the merged instructions were stashed to.
/// Test: asserted by `prepare_session_writes_claude_md_and_stash`.
/// A failure raised while preparing a session for launch.
///
/// Why: preparation performs agent deployment and filesystem I/O; callers need
/// a single typed error surface that names which stage failed.
/// What: variants for the agent-deploy stage and the instruction stage.
/// Test: not exercised by the happy-path tests; surfaced on invalid paths.
/// Prepare a project directory for a fresh Claude Code session launch.
///
/// Why: launching `claude` is only correct if its custom instructions are in
/// place first — the composed agents must be deployed and the project
/// `CLAUDE.md` merged. This is the "custom instructions" step that makes a plain
/// `claude` process behave as a trusty-mpm session; both the CLI and the client
/// call this before sending `claude` into the tmux pane.
/// What: deploys composed agents from the framework agent source to
/// `~/.claude/agents/`, runs [`build_instructions`] for `project_dir` (which
/// loads or creates the project `CLAUDE.md`), writes the launch prompt — the
/// exact override-resolved AND output-style-injected text produced by
/// [`build_system_prompt_for_with_style`] — to
/// `<project_dir>/.trusty-mpm/last-instructions.md` so the inspectable stash
/// matches the live launch prompt byte-for-byte (issue #1409), and returns a
/// [`PrepReport`].
///
/// ORDERING CONTRACT (#4752, owner ruling 2026-08-04): **a session that starts
/// always has its instructions on disk, matching the text it received.** A
/// session depends on its instructions, so one that cannot get them must not
/// start.
///
/// Two steps establish them, and BOTH are fatal — the same condition reaching
/// two sites, reported as [`PrepError::Instructions`], which every spawning
/// caller refuses to launch on:
/// * [`build_instructions`] composes the merged instructions; and
/// * the same resolved prompt is written to
/// `<project_dir>/.trusty-mpm/framework/INSTRUCTIONS-COMPILED.md`
/// ([`crate::core::instruction_pipeline::compiled_prompt_path`]) as this
/// function's LAST step.
///
/// There is no exception between them: nothing that can fail in between returns
/// early. The `.trusty-mpm/last-instructions.md` stash is the one write that
/// still degrades to a warning — it is an inspection copy, and letting it
/// short-circuit would have skipped the fatal write below it and started a
/// session whose instructions were never recorded, which is precisely what this
/// contract forbids.
///
/// This is the ONE preparation CONDITION that blocks a launch — one condition,
/// two sites, not two error classes. #2149's non-fatal-preparation design still
/// governs every other variant (a roster or skill deploy failure is surfaced via
/// [`PrepReport::roster_errors`] and the session still starts);
/// [`PrepError::is_fatal`] is the discriminator.
///
/// POSITION: the compiled write is deliberately LAST, so a refusal is not also a
/// half-provisioned workspace — see the inline comment at the call.
///
/// The resume path never calls this function. Both other entry points carry the
/// same fatal write: `daemon::managed_routes::lifecycle::resume_managed` (daemon
/// resume) and `instruction_pipeline::refresh_compiled_prompt` as called from
/// the bare-`tm` in-place relaunch in `tm::commands::guided_inplace`. See spec
/// §10.3.
/// Test: `prepare_session_writes_claude_md_and_stash`, `prepare_session_is_idempotent`,
/// `prepare_session_stash_reflects_override`,
/// `prepare_session_writes_the_compiled_prompt_before_returning`,
/// `prepare_session_fails_when_the_compiled_prompt_cannot_be_written`,
/// `prepare_session_refuses_when_the_instructions_cannot_be_built`.
/// Prepare a session, threading the cloned-from `repo_url` for palace pinning.
///
/// Why (issue #1605): a managed session cloned from `repo_url` lives under a
/// throwaway `<owner>/<repo>/<session-id>/` workspace whose basename is the
/// session-id, so palace derivation from that basename picks the WRONG name. The
/// provisioner knows the `repo_url` it cloned, so threading it here supplies the
/// canonical remote. Since ADR-0042 deleted the MCP injectors, what consumes it
/// is [`maybe_register_palace_alias`] — the #1939 healing that decides whether
/// the derived `owner-repo` palace should resolve to a pre-existing bare-repo
/// one. The flag-less [`prepare_session`] delegates with `None`, which falls
/// back to the workspace's own `git remote get-url origin`.
/// What: identical to [`prepare_session`] except the optional `repo_url` (from
/// `LaunchParams`/`SessionRecord`) is threaded down as the authoritative remote.
/// Real native-style detection is applied.
/// Test: `creates_alias_for_split_brain` and the sibling guards in
/// [`palace_alias`], which cover what the threaded remote decides.
/// Prepare a session whose managed id is already known (#4832).
///
/// Why: the compiled prompt is now per-SESSION
/// (`.trusty-mpm/sessions/<id>/INSTRUCTIONS-COMPILED.md`), and the two callers
/// that provision a managed session — `WorkspaceProvisioner::provision_in` and
/// the daemon's in-project `prepare_inproject_session` — hold that id before
/// they call here. Without it, preparation would write into the unmanaged
/// `local` bucket while the spawn (which does know the id) refreshed the real
/// per-session file, leaving a stale copy no writer ever updates again — the
/// exact defect shape #4832 removes.
/// What: [`prepare_session_with_repo_url`] with the managed session id threaded
/// down to [`crate::core::harness_root::session_scope`]. Callers with no
/// session identity keep using the id-less entry points, which resolve the
/// scope from `TM_MANAGED_SESSION_ID` or fall back to
/// [`crate::core::harness_root::UNMANAGED_SESSION_SCOPE`].
/// Test: `prepare_session_for_managed_writes_the_per_session_compiled_prompt`.
/// The deploy layout for a session whose harness is spawned with
/// [`SETTING_SOURCES_FLAG`](crate::core::model_inject::SETTING_SOURCES_FLAG).
///
/// Why (issue #4203): `--setting-sources project,local` makes Claude Code read
/// ONLY the project and local tiers; the `user` tier (`$HOME/.claude`) is
/// excluded deliberately (#1269). Deploying such a session's roster through
/// `FrameworkPaths::default()` therefore writes it somewhere that session will
/// never look — and nothing reports it, because the deploy genuinely succeeds
/// and the load silently finds nothing. Naming the correct layout ONCE, here,
/// is what lets every isolated caller share it instead of each re-deriving it
/// (and three of them getting it wrong independently).
/// What: `FrameworkPaths::for_managed_workspace(project_dir)` — the deploy
/// DESTINATION becomes `<project_dir>/.claude/{agents,skills}`, which the
/// `project` and `local` tiers read, while every framework SOURCE path still
/// resolves from the home-relative install root (#1931).
/// Test: `isolated_layout_deploys_into_a_tier_the_spawn_reads`,
/// `isolated_layout_keeps_framework_source_at_the_install_root`.
pub
/// Prepare a session whose harness will be spawned with
/// [`SETTING_SOURCES_FLAG`](crate::core::model_inject::SETTING_SOURCES_FLAG).
///
/// Why (issue #4203): `tm launch`, `tm connect`, and `tm meta launch` each
/// built their own `FrameworkPaths::default()` and each therefore deployed the
/// agent roster into the one tier their own spawn flag excludes — three
/// independent instances of the same defect, because each call site was free to
/// resolve the layout itself. This entry point REMOVES that degree of freedom
/// rather than checking it after the fact: an isolated caller supplies no
/// `FrameworkPaths` at all, so there is no wrong value left to pass.
/// Callers whose spawn does NOT carry the flag must keep using
/// [`prepare_session`] with their own `fw` — notably `tm session start`, which
/// spawns a bare `claude` (`commands/session/start.rs`) and so genuinely does
/// read the user tier; pointing it here would be a regression, not a fix.
/// What: resolves [`isolated_framework_paths`] for `project_dir` (the cwd the
/// harness is spawned in) and delegates to [`prepare_session_with_repo_url`],
/// which is exactly [`prepare_session`] when `repo_url` is `None`.
/// Test: `isolated_layout_deploys_into_a_tier_the_spawn_reads`;
/// `launch_paths_prepare_through_the_isolated_seam` (tm binary) binds the call
/// sites to it.
/// Defensively (re)write the `tm statusline` config for an EXISTING session
/// workspace, without re-running the full preparation pipeline.
///
/// Why (issue #1913): sessions spawned via the pre-fix in-project worktree path
/// never ran [`prepare_session_with_repo_url`] at all, so their on-disk
/// `.claude/settings.json` may be permanently missing the `statusLine` key, and
/// nothing else in the launch path ever backfills it. Re-running the FULL prep
/// pipeline (agent/skill redeploy, CLAUDE.md merge, MCP injection) on every
/// resume is riskier than necessary here — those steps are not all confirmed
/// idempotent under a resumed (not freshly-provisioned) workspace — so this
/// exposes ONLY the one step `write_status_line` itself documents as safe to
/// call unconditionally (it never clobbers a genuine user customization). The
/// resume path calls this defensively so a session stuck in the pre-#1913
/// broken state self-heals the next time it is resumed, without the broader
/// blast radius of a full re-prep. As of #1914, the same call ALSO upgrades a
/// stale bare `tm`/`trusty-mpm statusline` command (the pre-#1914 default,
/// which silently fails to render under a minimal `PATH`) to the resolved
/// absolute path — the two self-heal concerns share this one entry point
/// rather than growing a second, duplicate resume hook.
/// What: thin `pub` wrapper over `settings::write_status_line` (`pub(super)`,
/// so not directly reachable from `crate::daemon::managed_routes`). Delegates
/// verbatim — no additional logic.
/// Test: the underlying idempotency and path-resolution guarantees are covered
/// by `write_status_line_injects_when_absent` / `write_status_line_skips_when_already_set`
/// / `write_status_line_preserves_user_config` / `write_status_line_heals_stale_tm_default`
/// / `write_status_line_heals_stale_trusty_mpm_default` in this module's test
/// file; `resume_managed_backfills_missing_status_line` in
/// `tests/session_manager_mvp.rs` covers the `resume_managed` call site.
/// Prepare a session, selecting an explicit output style (HR-4).
///
/// Why: `tm launch --style <id>` lets the operator override the configured
/// active output style for a single launch; the override must reach the
/// `outputStyle` settings key (for native-capable Claude Code) and the
/// prompt-injection seam (for older builds). The flag-less [`prepare_session`]
/// delegates here with `None`.
/// What: identical to [`prepare_session`] except the active output-style id is
/// resolved via [`crate::core::output_style::resolve_active_style`] with
/// `explicit_style` taking precedence over the `[style] active` config key and
/// the professional default. An unknown id is logged and falls back to the
/// default (DOC-17) rather than failing the launch.
/// Test: `prepare_session_writes_configured_style`,
/// `prepare_session_explicit_style_overrides_config`.
/// Prepare a session with the `native_supported` output-style decision supplied
/// explicitly (no live `claude --version` probe).
///
/// Why: the stash (`last-instructions.md`) must equal the launch prompt
/// byte-for-byte, and that prompt depends on whether Claude Code supports native
/// output styles. Probing `claude --version` inside `prepare_session` couples the
/// stash invariant to the host, which broke `prepare_session_stash_reflects_override`
/// on CI (issue #1409). This seam pins the decision so tests can assert the
/// invariant deterministically under BOTH `native_supported = true` and `false`;
/// [`prepare_session_with_style`] supplies real detection in production.
/// What: identical to [`prepare_session_with_style`] except the stash is written
/// from [`build_system_prompt_for_with_style_and_native`] using the supplied flag,
/// so the stash always reflects the exact injected (or non-injected) launch prompt.
/// Test: `prepare_session_stash_reflects_override`.
/// [`prepare_session_with_style_and_native`] with the USER-GLOBAL home supplied.
///
/// Why (#5544): `prepare_session` writes two files that belong to the user, not
/// to the project — `~/.claude.json` and `~/.claude/settings.json`. A test
/// driving the real pipeline therefore reached the developer's own home, and the
/// only way to stop it was repointing the process's `$HOME` — a global write
/// every sibling test in the same binary observes for its duration, which is the
/// flake class #5544 tracks. The home cannot come off `FrameworkPaths`:
/// `for_managed_project` relocates every `.claude/` path on it onto the
/// workspace, so deriving it there sent both writes into the operator's repo.
/// Passing it is the only shape that is correct under every root AND redirectable.
/// What: identical to [`prepare_session_with_style_and_native`], which is this
/// function with `dirs::home_dir()`. An absent or relative `home` declines the
/// two user-global writes rather than guessing a location.
/// Test: `prepare_session_does_not_seed_the_workspace_on_the_managed_path`,
/// `global_hook_cleanup_reaches_the_real_home_under_an_overridden_root`.
/// Shared body for every `prepare_session*` entry point.
///
/// Why: the public entry points differ only in how they resolve `explicit_style`,
/// `native_supported`, and (issue #1605) the cloned-from `repo_url`. Funnelling
/// them through one private body keeps the long preparation sequence in a single
/// place so the variants cannot drift. `repo_url` is the only new degree of
/// freedom: it is threaded to [`maybe_register_palace_alias`] as the
/// authoritative remote and is `None` for the flag-less / style-only entry
/// points (which then fall back to the workspace's own git origin remote).
/// What: identical to the documented [`prepare_session_with_style_and_native`]
/// behaviour, plus it passes `repo_url` to [`maybe_register_palace_alias`].
/// Issue #2149: an agent-deploy or skill-deploy failure is captured into
/// [`PrepReport::roster_errors`] rather than short-circuiting the function via
/// `?` — every step after the roster deploy (CLAUDE.md/instructions, the
/// trusty-mpm output-style write, MCP injection, hooks) still runs
/// unconditionally, so a session ALWAYS launches carrying its trusty-mpm
/// identity even when the roster itself is empty or broken. This function now
/// only returns `Err` for genuinely fatal failures (the instruction pipeline,
/// or the inspection-stash IO).
/// Test: covered by every `prepare_session_*` test plus
/// `prepare_session_continues_after_agent_deploy_failure`,
/// `prepare_session_continues_after_skill_deploy_failure`.
/// Build the project-agnostic `--append-system-prompt` text (no overrides).
///
/// Why: every `claude` session launched by trusty-mpm must be a configured PM
/// instance. trusty-mpm owns its PM instructions: they are assembled IN MEMORY
/// from the compile-time bundled sections and passed to
/// `claude --append-system-prompt-file`. Nothing is read back from an installed
/// `INSTRUCTIONS.md` to produce them (#4752 retired that path — see the note
/// below). This variant is kept for callers that do not know the project
/// directory (e.g. tests); prefer [`build_system_prompt_for`] at launch sites so
/// project-level overrides apply.
/// What: returns [`crate::core::instruction_pipeline::assemble_system_prompt`],
/// trimmed. `Option` is retained for API compatibility and is always `Some`.
///
/// #4752: this used to read `~/.trusty-mpm/framework/instructions/INSTRUCTIONS.md`
/// and regenerate it on disk when missing. That file is retired — nothing writes
/// it, `tm install` deletes a stale copy, and the compiled prompt is now
/// per-project — so the round-trip could only ever have returned either bundled
/// content it already had in memory, or a stale leftover. Composing directly
/// removes the last dependency on the retired path and the home directory.
/// Test: `build_system_prompt_includes_trusty_block`.
/// Build the `--append-system-prompt` text for `project_dir`, applying any
/// project-level instruction overrides.
///
/// Why: `BASE_PM.md` advertises project-level overrides under
/// `<project>/.trusty-mpm/` (issue #381). The *live* prompt delivered to
/// `claude` must reflect them, and it must be resolved with the same
/// [`crate::core::instruction_overrides::resolve_pm_prompt`] function the
/// inspectable stash uses so the two never diverge (the #382 concern). This is
/// the launch-site entry point; it always returns a usable prompt — there is no
/// home-directory dependency because the prompt is composed from compiled-in
/// bundled assets plus the project's own override files.
/// What: delegates to
/// [`crate::core::instruction_overrides::resolve_pm_prompt`], which layers the
/// override files onto the bundled PM prompt and always appends the
/// non-overridable `BASE_PM` floor last, then applies HR-4 output-style
/// version-fallback injection via [`build_system_prompt_for_with_style`] with no
/// explicit style override.
/// Test: `build_system_prompt_for_applies_project_override`.
/// Build the launch prompt for `project_dir`, applying overrides AND HR-4
/// output-style version-fallback injection with an explicit style override.
///
/// Why: on Claude Code builds older than `1.0.83` the native `outputStyle`
/// settings key is ignored, so the active output style only takes effect if its
/// content is folded into the `--append-system-prompt` text. This is the single
/// launch seam where that injection happens, so both the CLI (`tm launch`) and
/// the client (`/connect`) get identical behaviour. The `--style` flag flows in
/// as `explicit_style`.
/// What: resolves the override-layered PM prompt via
/// [`crate::core::instruction_overrides::resolve_pm_prompt`], then calls
/// [`crate::core::output_style::apply_output_style_to_prompt`], which is a no-op
/// on native-capable Claude Code and prepends the active style otherwise. The
/// active style is `explicit_style` > `[style] active` config > professional
/// default; an unknown id falls back to the default.
/// Test: the injection logic is unit-tested in
/// `crate::core::output_style::tests`; this composition is covered by
/// `build_system_prompt_for_applies_project_override` (which asserts the PM
/// prompt is preserved regardless of the version gate).
/// Build the launch prompt with the `native_supported` output-style decision
/// supplied explicitly (no live `claude --version` probe).
///
/// Why: the public [`build_system_prompt_for_with_style`] probes
/// `claude --version`, so any test (or caller) that exercises the launch prompt
/// is silently coupled to whether `claude` is installed on the host — the
/// host-dependence that broke `prepare_session_stash_reflects_override` on CI
/// (issue #1409). This seam pins the decision so the stash/launch invariant can
/// be asserted deterministically under BOTH `native_supported = true` (no
/// injection) and `false` (injection fires). Production code keeps real
/// detection via the wrapper above.
/// What: resolves the override-layered PM prompt via
/// [`crate::core::instruction_overrides::resolve_pm_prompt`], then applies the
/// injection decision with the caller-supplied flag via
/// [`crate::core::output_style::apply_output_style_to_prompt_with_native`].
/// Test: `prepare_session_stash_reflects_override`.
/// Build the launch prompt with the deployed-agent roster supplied by the caller.
///
/// Why (#5544): [`build_system_prompt_for`] rescans the three live agent tiers
/// on every call — `<project>/.claude/agents`, `$CLAUDE_CONFIG_DIR/agents`, and
/// `$HOME/.claude/agents`. Two successive calls can therefore disagree, so any
/// test comparing this prompt against another composition of it is racing
/// machine-global state, and it fails with a message indistinguishable from a
/// genuine regression. The remedy is to give both sides ONE roster value, not
/// to pin `$HOME` — pinning it is a PROCESS-GLOBAL write every sibling test in
/// the same target can observe mid-scan, which is the flake class #5544 tracks.
/// [`crate::core::instruction_overrides::resolve_pm_prompt_with_roster`] is the
/// matching seam one layer down; this is its launch-site counterpart.
/// What: identical to [`build_system_prompt_for`] except the rendered
/// `## Delegation Authority` block comes from `roster` instead of a live scan.
/// Callers build `roster` with
/// [`crate::core::delegation_authority::roster_section_from_dirs`] over tier
/// directories they own.
/// Test: `compose_session_instructions_display_matches_live_prompt` and its
/// `_with_override` sibling (`tests_behavior_b_tests.rs`).