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
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
//! Output-style, spinner-tip, hook, and MCP-injection helpers.
//!
//! Why: `prepare_session` must configure several Claude Code settings files
//! before launching a session. Grouping all the settings-file mutations here
//! keeps `mod.rs` focused on the top-level preparation sequence and makes
//! each individual helper easy to test in isolation.
//! What: constants and functions for writing the output style, spinner tips,
//! `trusty-memory` project hooks, `trusty-memory` MCP server injection, and
//! global-hook cleanup.
//! Test: each public(super) function is covered by a dedicated test in `tests.rs`.
use ;
use PrepError;
use cratebackup;
/// The `tm hook` sub-flag the PM enforcement guard is invoked with.
///
/// Why: [`pm_guard_hook_value`] writes this shape and
/// [`super::project_hooks::is_project_managed_hook_command`] must recognise
/// exactly what was written, or the replace-by-identity strip stops matching
/// and every relaunch appends a duplicate group (#2948). #7262 added a third
/// reader — the build-tree classifier — so the literal now lives in the lower
/// layer beside the other argv tails and is re-exported here rather than
/// spelled out in each module, mirroring
/// [`super::divert_hooks::DIVERT_CHECK_SUFFIX`].
/// What: the literal suffix, including its leading space.
/// Test: `pm_guard_and_divert_commands_end_in_a_known_argv_tail`.
pub use cratePM_GUARD_SUFFIX;
/// Default Claude Code output style applied to launched sessions.
///
/// Why: the Claude Code status bar renders `style:<outputStyle>`; when no style
/// is configured, launched trusty-mpm sessions advertise the professional
/// default `trusty-mpm`. HR-4 lets the operator select a different bundled style
/// (teaching/research); [`write_output_style`] takes the resolved active id and
/// falls back to this constant when none is supplied. `pub(crate)` (rather than
/// `pub(super)`) so `core::standalone::settings_defaults::ensure_settings_defaults`
/// can seed the SAME default id into the tm-owned `CLAUDE_CONFIG_DIR` settings.json
/// (issue #2214), re-exported via `session_launch::OUTPUT_STYLE`.
pub const OUTPUT_STYLE: &str = crateDEFAULT_OUTPUT_STYLE_ID;
/// trusty-mpm-specific spinner tips shown during Claude Code loading.
///
/// Why: Claude Code's loading spinner renders tips from
/// `spinnerTipsOverride.tips`; the operator's global settings carry generic
/// claude-mpm tips, so trusty-mpm sessions override them with project-relevant
/// guidance (the `tm` CLI, the `make check` gate, the API-first layering rule).
pub const SPINNER_TIPS: & = &;
/// The `trusty-memory` hook block written into the project's
/// `.claude/settings.json`.
///
/// Why (issue #1270): the previous block invoked `trusty-memory hooks fire
/// <event>`, but the installed `trusty-memory` binary has **no `hooks`
/// subcommand** — that invocation exits non-zero with "unrecognized subcommand
/// 'hooks'". A non-zero `UserPromptSubmit` hook *hard-blocks the prompt*, so
/// every trusty-mpm-spawned session was dead on arrival: the injected task was
/// rejected before Claude ever saw it. This block now mirrors the canonical
/// hooks that `trusty-memory setup` installs (see
/// `crates/trusty-memory/src/commands/setup.rs`): `UserPromptSubmit` runs
/// `trusty-memory prompt-context` (documented to always exit 0 so it can never
/// block a prompt) and `SessionStart` runs `trusty-memory inbox-check` (also
/// fail-silent). There is intentionally no `PostToolUse` or `Stop` hook because
/// `trusty-memory` ships no corresponding CLI surface; memory writes during a
/// session flow through the MCP tools instead.
/// What: a `UserPromptSubmit` → `trusty-memory prompt-context` hook and a
/// `SessionStart` → `trusty-memory inbox-check` hook, scoped to the project so
/// they fire only for trusty-mpm sessions.
/// Test: `write_project_hooks_uses_canonical_commands`,
/// `write_project_hooks_writes_all_event_types`.
pub const TRUSTY_MEMORY_HOOKS: &str = r#"{
"UserPromptSubmit": [
{
"matcher": "",
"hooks": [
{
"type": "command",
"command": "trusty-memory prompt-context",
"timeout": 60
}
]
}
],
"SessionStart": [
{
"matcher": "",
"hooks": [
{
"type": "command",
"command": "trusty-memory inbox-check",
"timeout": 60
}
]
}
]
}"#;
/// Hook event types the global `trusty-memory` entries may have been registered
/// under (across current and legacy trusty-mpm builds).
///
/// Why: [`clean_global_trusty_memory_hooks`] strips trusty-mpm's
/// `trusty-memory` hook entries from `~/.claude/settings.json` so they stop
/// firing for unrelated sessions. It must cover every event trusty-mpm has ever
/// written globally: the new canonical pair (`UserPromptSubmit`, `SessionStart`)
/// AND the legacy `hooks fire` events (`PostToolUse`, `Stop`) so an upgrade
/// cleans up the old entries too.
/// What: the union of current and legacy global hook event keys.
pub const GLOBAL_TRUSTY_MEMORY_EVENTS: & =
&;
/// Deploy ALL bundled output styles under `<root>/.claude/output-styles/`.
///
/// Why: [`write_output_style`] sets `"outputStyle": "<active>"` in the project
/// settings; Claude Code honours that name only when a matching style file
/// exists under a `.claude/output-styles/` directory that is actually loaded
/// by the running session's `--setting-sources`. HR-4 bundles three styles
/// (professional / teaching / research) and the operator may select any of
/// them, so ALL of them must be on disk for the selection to resolve. `root`
/// is passed in (rather than resolved here) so callers can target either the
/// operator's `$HOME`/`CLAUDE_CONFIG_DIR` (the `user` tier) or, since issue
/// #2125 item 2, the PROJECT directory itself (the `project` tier) — the
/// daemon managed-spawn path launches `claude --setting-sources project,local`,
/// which EXCLUDES the `user` tier, so without a project-tier copy the
/// `outputStyle` id written into the project's `settings.json` cannot resolve
/// and Claude Code silently falls back to its own default. `prepare_session`
/// calls this for BOTH roots; it is a plain additive deploy either way.
/// What: creates `<root>/.claude/output-styles/` if absent, then writes every
/// entry in [`crate::core::bundle::OUTPUT_STYLES`] to its `file_name`, always
/// overwriting so framework upgrades to the styles propagate on the next launch.
/// Returns the path of the default (professional) style for the [`PrepReport`].
/// Test: `deploy_output_style_writes_file`, `deploy_output_style_overwrites`,
/// `deploy_output_style_writes_all_styles`,
/// `deploy_output_style_writes_under_project_root`.
pub
/// The Claude Code settings key that turns auto memory off (#7685).
///
/// Why: the owner directive is that Claude Code's own auto memory (`MEMORY.md`)
/// is not used in tm sessions — `trusty-memory` is the memory. The key name is
/// Claude Code's, documented at
/// <https://code.claude.com/docs/en/memory#enable-or-disable-auto-memory>:
/// "To turn it off for a single project, set `autoMemoryEnabled` in that
/// project's settings". One constant, because `tm doctor`'s `auto_memory` check
/// and its `--fix` repair must read and write exactly what this launch path
/// writes.
/// What: the literal key name.
/// Test: `write_auto_memory_off_disables_auto_memory`.
pub const AUTO_MEMORY_KEY: &str = "autoMemoryEnabled";
/// Read-merge-write the project's `.claude/settings.json` under one mutation.
///
/// Why (#7685): [`write_output_style`] was the only project-settings writer and
/// carried the read/merge/write body inline, so every new key would have copied
/// it. The merge discipline it encodes is the part worth sharing: an existing
/// file is parsed and every key it already carries is preserved, a missing file
/// starts from an empty object rather than aborting the launch, and the result
/// is written back pretty-printed. Taking a closure rather than a single key
/// keeps a multi-key writer at one read and one write.
/// What: creates `<project_dir>/.claude/`, then — holding the cross-process
/// settings lock across the WHOLE cycle — loads the settings object through
/// [`super::malformed_backup::load_settings_object`], hands it to `mutate`, and
/// publishes it back pretty-printed via [`crate::core::settings_lock::publish`].
///
/// #7780: a file that is not a JSON object is no longer silently coerced to
/// `{}` and overwritten. Its bytes are copied to a
/// `settings.json.malformed-<stamp>` sibling first (the owner's
/// backup-then-rewrite ruling, 2026-09-13), and a copy that cannot be made
/// refuses the rewrite outright — see [`PrepError::SettingsBackup`]. The write
/// became atomic in the same change, so a crash mid-rewrite can no longer
/// CREATE the torn file this function exists to survive.
///
/// #7762: atomicity was never the whole problem. `tm doctor --fix` repairs this
/// same file from another PROCESS, so a read here and a write there interleave
/// into a lost update that no in-process guard can see. The lock now spans the
/// read and the write, and the publish dropped `write_json_atomic`'s `<path>.bak`
/// — a copy taken on every launch is litter in the operator's project, not a
/// recovery artifact.
///
/// # Contract
///
/// - **`mutate` must be pure** — it edits the `Value` it is handed and does no
/// I/O of its own on a settings file. It runs INSIDE the lock, and
/// `settings_lock` is not reentrant (#7762): a `mutate` that reached another
/// settings writer — `merge_settings` itself, `add_exclude`,
/// `write_skill_overrides` — would block forever on a lock its own caller
/// holds. No current closure does anything but assign keys.
///
/// Test: `write_output_style_preserves_existing_keys`,
/// `write_auto_memory_off_preserves_existing_keys`,
/// `merge_settings_backs_up_a_malformed_file_before_rewriting_it`,
/// `merge_settings_refuses_when_the_copy_cannot_be_written`,
/// `concurrent_merges_of_distinct_keys_never_lose_an_update`,
/// `merge_settings_refuses_when_the_lock_cannot_be_acquired`.
pub
/// Set one key in the project's `.claude/settings.json`, preserving the rest.
///
/// Why (#7685): the common case of [`merge_settings`] — one scalar key, every
/// other key carried through untouched. `tm doctor --fix`'s `auto_memory` repair
/// writes through this same function rather than re-implementing the merge, so
/// the repair and the launch path cannot drift.
/// What: [`merge_settings`] with a closure that assigns `value` to `key`.
/// Test: `write_auto_memory_off_disables_auto_memory`,
/// `auto_memory_repair_applies_when_absent`.
pub
/// Write `autoMemoryEnabled` into the project's `.claude/settings.json` (#7685).
///
/// Why: the owner directive — `trusty-memory` is the memory, and Claude Code's
/// own auto memory is a FALLBACK that stays on only while trusty-memory is
/// unavailable (ruling 2026-09-12). This is the project-tier half; the
/// managed-spawn half is the `CLAUDE_CODE_DISABLE_AUTO_MEMORY=1` assignment in
/// [`crate::runtime::claude_code::env_bin_prefix`]. Both, for the reason
/// [`write_output_style`]'s `attribution` seed gives: the env var reaches only
/// the `claude` child tm spawns, whereas a bare `claude` launched in this
/// project reads the project tier regardless.
///
/// The write is TWO-WAY, and that is the whole contract: the key is ALWAYS
/// written, in the direction reachability dictates. "Leave it alone" was the
/// first shape of this function and it could never recover — a project whose key
/// a healthy-trusty-memory launch set `false` kept that `false` forever once
/// trusty-memory went down, leaving the session with neither memory. `true` is
/// therefore written explicitly, through this same helper, so the fallback comes
/// back on by itself.
/// What: [`merge_settings_key`] with [`AUTO_MEMORY_KEY`] and `enabled`.
/// [`super::prepare_session_inner`] derives `enabled` as `!memory_reachable`.
/// Test: `write_auto_memory_off_disables_auto_memory`,
/// `write_auto_memory_off_preserves_existing_keys`,
/// `write_auto_memory_off_overrides_an_enabled_value`,
/// `write_auto_memory_on_reverts_a_prior_disable`,
/// `prepare_session_disables_auto_memory_when_trusty_memory_is_reachable`,
/// `prepare_session_restores_auto_memory_when_trusty_memory_is_down`.
pub
/// Merge trusty-mpm output-style and spinner-tip settings into the project's
/// `.claude/settings.json`.
///
/// Why: Claude Code reads the output style from `.claude/settings.json` under
/// the `outputStyle` key (there is no `--style` CLI flag); writing it in the
/// project directory makes every `claude` launched there show
/// `style:trusty-mpm` without disturbing the operator's global settings. The
/// same file drives the loading-spinner tips, so trusty-mpm-specific tips are
/// written alongside to override the operator's generic claude-mpm tips.
/// What: reads an existing `<project>/.claude/settings.json` (preserving all
/// other keys), sets `outputStyle` to `active_style` (the resolved active id;
/// `None` → [`OUTPUT_STYLE`] default), enables `spinnerTipsEnabled`, sets
/// `spinnerTipsOverride.tips` to [`SPINNER_TIPS`], seeds `attribution` when
/// absent (#6807, see below), and writes it back pretty-printed. Creates the
/// file and `.claude/` directory when absent. The caller resolves+validates the
/// id (via [`crate::core::output_style::resolve_active_style`]); an
/// empty/whitespace id is treated as "unset" and falls back to the default here
/// defensively.
///
/// The `attribution` seed is deliberately duplicated from
/// [`crate::core::standalone::settings_defaults::ensure_settings_defaults`],
/// which writes the same key into the tm-owned `CLAUDE_CONFIG_DIR`. That copy
/// reaches only the `claude` child tm spawns — `CLAUDE_CONFIG_DIR` is set
/// per-command and never exported — whereas the project tier is read by any
/// `claude` launched in this directory, tm-orchestrated or not. Both seeds are
/// absent-only and share one constant, so an operator-set value survives either
/// path.
/// Test: `prepare_session_sets_output_style`,
/// `write_output_style_preserves_existing_keys`,
/// `write_output_style_sets_spinner_tips`,
/// `write_output_style_sets_active_style`,
/// `write_output_style_seeds_attribution`,
/// `write_output_style_preserves_operator_attribution`.
pub
/// Write the project-tier `enabledPlugins` allowlist into the project's
/// `.claude/settings.json` (#7422).
///
/// Why: a Claude Code plugin installed into the tm-managed `CLAUDE_CONFIG_DIR`
/// loads its whole skill catalog into every session on the host, and there is
/// no per-invocation flag to scope it — `enabledPlugins` is settings-only. The
/// project tier outranks the user tier, so writing the map here is the one
/// lever that turns a host-wide install into a per-project decision. Sits
/// beside [`write_output_style`] because it is the same kind of write to the
/// same file, on the same launch path.
/// What: enumerates every plugin the managed config dir knows about
/// ([`crate::core::session_plugin_scope::known_plugins`]), maps each to `true`
/// when the project's committed `[session] plugins` list names it and `false`
/// otherwise, and merges that map into the existing `enabledPlugins` object.
/// The opt-in list reaches this function through
/// [`crate::core::session_mcp_scope::granted_plugins`], so an UNTRUSTED project
/// grants nothing and every enumerated key is written `false`. Since #7892 the
/// plugin half of `[session]` is the ONLY half trust gates: the server half
/// follows Claude Code's own scoping, and `[session] mcp_servers` is parsed and
/// ignored. Plugins keep the gate because Claude Code has no per-project plugin
/// approval to defer to, and the file ships with the clone.
/// tm owns ONLY the keys it enumerated: a key for a plugin tm cannot see is the
/// operator's and is carried through untouched, the same merge discipline
/// [`write_output_style`]'s `attribution` seed and
/// [`write_project_hooks`]'s entry-level strip already use. Returns without
/// writing when the merged object equals what is on disk, so an unchanged
/// project takes no write on every launch.
///
/// `config_dir` is the tm-managed `CLAUDE_CONFIG_DIR`. `None` — an
/// unresolvable home — enumerates nothing and writes nothing, rather than
/// writing an empty map that would disable plugins tm never saw.
///
/// #7678 moved the composition itself into
/// [`crate::core::session_scope_drift::plan_enabled_plugins`] so that
/// `tm doctor`'s `session_scope` check and `tm doctor --fix` read and repair
/// through this same writer instead of a second implementation.
/// Test: `write_enabled_plugins_denies_a_non_opted_plugin`,
/// `write_enabled_plugins_denies_an_opt_in_from_an_untrusted_project`,
/// `write_enabled_plugins_enables_an_opted_in_plugin`,
/// `write_enabled_plugins_preserves_foreign_keys`,
/// `write_enabled_plugins_skips_without_a_config_dir`.
pub
/// [`write_enabled_plugins`] against an explicit trust decision (#7678).
///
/// Why: the trust bit lives under the operator's `$HOME`, so `tm doctor --fix`
/// could not be tested end-to-end against a TRUSTED project without redirecting
/// it. Splitting the lookup from the write mirrors
/// [`crate::core::session_mcp_scope::granted_plugins_with_trust`], which already
/// does exactly this for the same `[session] plugins` list.
/// What: see [`write_enabled_plugins`]. Writes nothing when `config_dir` is
/// `None`, when the managed config dir knows about no plugins, or when the
/// merged object already equals what is on disk — so a `--fix` against an
/// in-sync project leaves the file, and its mtime, untouched. #7780: when it
/// does write over a file that is not a JSON object, the original bytes are
/// copied to a `settings.json.malformed-<stamp>` sibling first.
///
/// #7762: the plan is computed TWICE and that is deliberate. The first pass is
/// an unlocked pre-check whose only job is to return early for the in-sync case,
/// because taking the lock would create a `.claude/` and a lock sidecar in a
/// project this writer is not going to touch. The pass that decides what to
/// write is the one inside the lock, so the bytes published are always derived
/// from a read no other process could have raced.
/// Test: `write_enabled_plugins_enables_an_opted_in_plugin`,
/// `session_scope_repair_writes_nothing_when_the_settings_already_match`,
/// `write_enabled_plugins_backs_up_a_malformed_file_before_rewriting_it`.
pub
/// Write the project-tier trusty-mpm-owned hooks into the project's
/// `.claude/settings.json`.
///
/// Why (issue #2003): the daemon's managed-launch path spawns `claude
/// --setting-sources project,local`, excluding the `user` tier where
/// [`crate::core::standalone::hooks::ensure_managed_hooks`] provisions the
/// lifecycle triad (circuit breaker / audit log / dashboard). A managed
/// session therefore never fired those events — only the `trusty-memory` +
/// PM-guard entries this function previously wrote (by REPLACING the entire
/// `hooks` key, which also clobbered any pre-existing hooks the project itself
/// carried). [`super::project_hooks::project_managed_hook_additions`] now
/// folds the SAME triad definition the user-tier writer uses into this
/// project-tier write, and the entry-level replace-by-identity strip (issue
/// #2948's [`crate::core::standalone::hooks::strip_hook_entries_matching_for_events`])
/// removes only OUR OWN prior entries before merging, so a foreign/hand-added
/// hook — even one sharing a matcher group with one of ours — survives.
/// Since #2969 this writes the full lifecycle triad on every managed-session
/// launch, so a crash mid-write has a larger blast radius than before; issue
/// #2972 switched the final write from a plain `fs::write` to
/// [`trusty_common::claude_config::write_json_atomic`] (temp-file + rename) for
/// parity with the sibling `tm hooks clean` mutation path, so a crash or `^C`
/// mid-write can never leave a torn/truncated `settings.json`.
/// What: reads an existing `<project>/.claude/settings.json` (preserving all
/// other keys), strips any existing entry recognised by
/// [`super::project_hooks::is_project_managed_hook_command`] for the events
/// about to be (re)written, deep-merges in
/// [`super::project_hooks::project_managed_hook_additions`] via
/// [`trusty_common::claude_config::merge_hook_entries`], and atomically writes
/// the result back pretty-printed via
/// [`trusty_common::claude_config::write_json_atomic`]. Creates the file and
/// `.claude/` directory when absent. #7780: a file that is not a JSON object is
/// copied to a `settings.json.malformed-<stamp>` sibling before it is replaced,
/// and a copy that cannot be written refuses the write.
///
/// `inject_prompt_context` carries the `[hooks] prompt_context` config key
/// (#5034). It gates ONE entry — `UserPromptSubmit` → `trusty-memory
/// prompt-context`. The strip is deliberately NOT narrowed with it (see
/// [`super::project_hooks::project_managed_hook_events`]), so turning the key
/// off also removes the entry a prior launch wrote. Note the write is
/// framework-owned either way: a hand-deleted entry is re-added on the next
/// launch when the key is `true`. The config key, not a manual edit, is the
/// supported off switch.
/// `divert_enabled` carries the `[divert] enabled` manifest key (#6887) and
/// behaves the same way: `true` writes the two bulk-read diversion
/// `PreToolUse` groups, `false` writes none AND removes any a prior launch
/// wrote (the strip domain covers them either way).
/// Test: `write_project_hooks_writes_all_event_types`,
/// `write_project_hooks_registers_pm_guard`,
/// `write_project_hooks_replaces_existing`,
/// `project_hooks_tests::write_project_hooks_writes_lifecycle_triad`,
/// `project_hooks_tests::write_project_hooks_preserves_foreign_hooks`,
/// `project_hooks_tests::write_project_hooks_writes_via_atomic_path`,
/// `project_hooks_tests::write_project_hooks_omits_prompt_context_when_disabled`,
/// `project_hooks_tests::write_project_hooks_strips_stale_prompt_context_when_disabled`,
/// `project_hooks_tests::write_project_hooks_enabled_output_is_unchanged_by_the_toggle`,
/// `project_hooks_tests::write_project_hooks_writes_divert_groups_when_enabled`,
/// `project_hooks_tests::write_project_hooks_strips_stale_divert_when_disabled`,
/// `write_project_hooks_backs_up_a_malformed_file_and_installs_the_pm_guard`.
///
/// `exe_override` (#7244) pins the binary the hook commands name; production
/// passes `None` and lets the resolver find the running installed binary. A
/// test passes an installed-looking path so its assertions do not depend on
/// whether the host running them has `tm` installed — without which every
/// assertion here would read the resolver's refusal instead of the write.
///
/// #7244 (round 3), two additions in front of the write. A merge that equals
/// the file as read returns without writing — every managed launch calls this
/// and almost none of them change anything. A merge that does differ first
/// copies the file to `<path>.<YYYYMMDDTHHMMSSZ>.bak` via
/// [`backup::snapshot_then_prune`], keeping the newest
/// [`backup::HOOK_SETTINGS_SNAPSHOTS_KEPT`] and raising
/// [`PrepError::HookSnapshot`] — which abandons the rewrite — if that copy
/// fails. The refusal at the top still precedes both, so a refused write takes
/// no snapshot either.
/// Test: `project_hooks_tests::write_project_hooks_snapshots_the_file_it_replaces`,
/// `project_hooks_tests::write_project_hooks_prunes_snapshots_to_three`,
/// `project_hooks_tests::write_project_hooks_takes_no_snapshot_when_nothing_changes`,
/// `project_hooks_tests::write_project_hooks_takes_no_snapshot_when_the_exe_is_refused`,
/// `project_hooks_tests::write_project_hooks_aborts_when_the_snapshot_fails`.
/// #7849: production no longer reaches this four-argument form — the resume
/// merge, its last caller, now resolves every toggle (the #7688 flag included)
/// through [`super::hook_group_diff::project_hook_additions_for`]. It survives
/// as the pre-#7688 REFERENCE its own tests assert against, exactly as
/// [`super::project_hooks::project_managed_hook_additions`] does one layer down.
pub
/// [`write_project_hooks`], with the #7688 prompt-feedback capture toggled.
///
/// Why: an ADDITIVE seam rather than a fifth parameter on
/// [`write_project_hooks`], because that function has ~28 call sites and every
/// one of them is asserting a shape this flag does not change. Widening it
/// would have edited all of them to say `false` — pure churn over a default,
/// and a diff in which the one call site that matters is invisible. Same
/// convention as [`write_project_hooks_with`] and
/// `build_system_prompt_for_with_style`.
/// What: identical to [`write_project_hooks`], except
/// `prompt_feedback_enabled = true` registers the `Stop` / `SubagentStop`
/// capture groups. #9018: the launch now builds its additions with
/// `[pm_guard] enabled` resolved too and calls [`write_project_hooks_with`]; this
/// form survives as the guard-on reference its tests assert against.
/// Test: `project_hooks_tests::write_project_hooks_writes_prompt_feedback_when_enabled`,
/// `project_hooks_tests::write_project_hooks_strips_stale_prompt_feedback_when_disabled`.
pub
/// [`write_project_hooks`] with the resolved additions supplied by the caller.
///
/// Why (#7244, round 3): the fail-closed rules this writer owes — a refusal
/// writes nothing and snapshots nothing — cannot be exercised through
/// [`write_project_hooks`] on a machine that has `tm` installed, because
/// `resolve_stable_hook_exe`'s PATH fallback rescues even a refused
/// `exe_override`. Taking the already-computed `Result` lets a test hand in the
/// refusal directly. Mirrors the seam
/// [`crate::core::standalone::hooks::write_project_hooks`] grew in round 1, so
/// the two writers stay testable the same way.
/// What: returns `additions`'s error as [`PrepError::HookExe`] before touching
/// the filesystem; otherwise performs the read / strip / merge / no-op check /
/// snapshot / atomic-write exactly as [`write_project_hooks`] documents.
/// Test: `project_hooks_tests::write_project_hooks_takes_no_snapshot_when_the_exe_is_refused`.
pub
/// The read / strip / merge / no-op / snapshot / publish body of
/// [`write_project_hooks_with`], run under the settings lock.
///
/// Why (#7762): the whole cycle has to sit inside one closure for the lock to
/// span it, and a closure this long inline made the acquisition itself hard to
/// see. Split out rather than nested so the lock is the only thing
/// [`write_project_hooks_with`] does.
/// What: exactly what [`write_project_hooks_with`] documents, minus the
/// `additions` refusal and the directory creation its caller has already done.
/// Test: see [`write_project_hooks_with`].
/// Build the `PreToolUse` PM-enforcement guard hook entry (issue #1977).
///
/// Why: the deployed PM instructions' P1–P11 prohibitions ("delegate all file
/// edits", "never run builds/tests yourself") are prompt-only and unenforced.
/// Claude Code's `PreToolUse` hook is the one seam that can *block* a tool call
/// before it runs, so managed PM sessions register `tm hook --pm-guard` there
/// (see `crate::bin::tm::commands::pm_guard`) to turn those prohibitions into
/// enforcement. The command is resolved to an ABSOLUTE binary path via
/// [`resolve_statusline_binary`] — the same PATH-robustness fix #1914 applied to
/// the statusLine command — because a bare `tm hook --pm-guard` would silently
/// no-op under Claude Code's minimal `PATH`, leaving the guard un-fired.
/// What: returns the `PreToolUse` handler-group array with `matcher: ""` (fires
/// for every tool) invoking `<abs-path> hook --pm-guard` with a short timeout.
/// An absent binary is a non-blocking hook error, so it never blocks the PM; a
/// stdin payload the guard cannot read denies (#7975).
/// Test: `write_project_hooks_registers_pm_guard`.
pub
/// Resolve the trusty-memory palace slug for a managed session (#1605).
///
/// Why: the slug must match what trusty-memory itself would derive for the
/// project's canonical identity, so memory written/read in the managed session
/// lands in the project-scoped palace rather than a session-id-named one. The
/// explicit `git_remote` (threaded from `LaunchParams`/`SessionRecord.repo_url`)
/// is the authoritative identity for repo_url-cloned sessions; for local-path
/// sessions where it is `None` we fall back to the workspace's own
/// `git remote get-url origin`, exactly as trusty-memory's `cwd_palace_slug_at`
/// does. The operator `TRUSTY_MEMORY_PALACE` override still wins over both, per
/// `derive_palace_id` precedence.
///
/// // #4181: this used to feed the `.mcp.json` `env` block the memory injector
/// wrote. ADR-0042 deleted that injector; the slug now becomes the
/// `TRUSTY_MEMORY_PALACE` variable the spawn exports, resolved through
/// [`crate::core::mcp_session_env::session_mcp_env`].
///
/// // #5811: this called `derive_palace_id` — the PURE three-level core, which
/// never reads the committed `.trusty-tools/trusty-memory.yaml` pin. The value
/// it produced then became `TRUSTY_MEMORY_PALACE`, which is precedence level 1,
/// so a derived slug outranked the pin it was supposed to lose to: this repo's
/// sessions resolved `bobmatnyc-trusty-tools` while its pin said `trusty-tools`.
/// Routing through [`trusty_common::palace_resolve::resolve_palace_with_remote`]
/// means the exported variable already carries the pinned answer.
///
/// What: returns the resolved palace id, or `None` when no level yields one OR
/// when a pin file exists but cannot be trusted. `None` means the spawn exports
/// no palace variable and the session's trusty-memory resolves for itself —
/// through the same entry point, so it reaches the same verdict rather than
/// papering over the failure. Read-only; never panics.
///
/// #7712: `TRUSTY_MEMORY_PALACE` in the process env dominates BOTH the
/// explicit `git_remote` argument and the workspace's own `origin` fallback —
/// it is precedence level 1 ahead of either path-derived level. A test that
/// wants to exercise git-remote or path derivation must clear
/// `TRUSTY_MEMORY_PALACE` first (`EnvVarGuard::clear("TRUSTY_MEMORY_PALACE")`
/// in this crate's tests), or a value left over from the ambient environment
/// silently wins and the test exercises the override path instead.
/// Test: `resolve_palace_slug_*` (override / git-fallback / pin / none), plus
/// `session_mcp_env_exports_palace_when_memory_enabled`.
pub
/// Pre-seed per-directory trust acceptance for `workspace` in `~/.claude.json`,
/// and strip any MCP approval a prior version left behind.
///
/// Why (issue #1269): trusty-mpm launches Claude Code inside an *interactive*
/// tmux pane (so the session can be observed and driven). For a directory it has
/// never trusted, Claude Code blocks on the "Do you trust the files in this
/// folder?" dialog before it will accept any input — so the task prompt that tm
/// injects via `send-keys` is swallowed and the session stalls. Trust is keyed
/// by absolute directory path in the config dir (`~/.claude.json`), which
/// `--setting-sources` does NOT govern, so we must seed it directly. Because tm
/// clones each repo into its OWN throwaway workspace under
/// `~/trusty-mpm-projects/<owner>/<repo>/<id>/`, marking that path trusted is
/// safe — no real user project is affected.
///
/// **#4181 / ADR-0042 — why the `enabledMcpjsonServers` key is REMOVED, not
/// merely left unwritten.** Claude Code's `enabledMcpjsonServers` approval is
/// name-based and content-blind, and a name that appears in it makes the
/// workspace `.mcp.json` entry of that name WIN over the operator's own
/// user-scope declaration. That displacement is what made the #3918→#3950
/// name-squatting chain possible, and it is the mechanism ADR-0042 removes:
/// tm no longer writes MCP config into a workspace, so it approves no project-
/// scope name either. Ceasing to write would leave the key in place on every
/// machine a prior tm ever launched, keeping the displacement alive exactly
/// where a repo could exploit it, so the key is deleted from the entry.
/// What: reads `~/.claude.json` (the JSON config; starts from `{}` when absent
/// — but a malformed *existing* file is left untouched to avoid clobbering the
/// operator's OAuth/login data), ensures `projects.<workspace>` carries
/// `hasTrustDialogAccepted: true`, `hasCompletedProjectOnboarding: true` and
/// `projectOnboardingSeenCount >= 1`, removes `enabledMcpjsonServers`, then
/// writes it back pretty-printed (ATOMICALLY, temp file + rename) preserving
/// every other key. Idempotent — an entry already trusted and already free of
/// the approval key is not rewritten. The OAuth fields are never touched.
///
/// **Concurrency (issue #4072):** the whole read → mutate → write cycle runs
/// under [`crate::core::claude_json_guard::lock`], because
/// `core::home_trust_seed::preseed_home_trust` load-mutate-stores the SAME file
/// and the daemon runs both concurrently, once per session it provisions.
/// Unsynchronised, the slower writer stored a snapshot taken before the faster
/// writer's store, silently deleting that session's whole
/// `projects.<workspace>` entry.
/// Test: `preseed_trust_marks_directory`, `preseed_trust_preserves_other_keys`,
/// `preseed_trust_is_idempotent`, `preseed_trust_leaves_malformed_file`,
/// `concurrent_seeds_preserve_every_workspace_entry`,
/// `concurrent_home_and_workspace_seeds_preserve_both_entries`. The two
/// `enabledMcpjsonServers` claims above are proven end to end, through this
/// function, in `tests_launch_trust_3926.rs`:
/// `prepare_session_writes_no_approval_for_a_builtin_name_in_workspace_mcp_json`
/// (nothing is written, even for a name a repo squats) and
/// `prepare_session_strips_a_stale_enabled_mcp_approval` (an approval a prior
/// version left is removed while the entry's other keys survive).
pub
/// Pre-seed workspace trust in the user's `~/.claude.json`.
///
/// Why: thin wrapper over [`preseed_workspace_trust`] so `prepare_session` can
/// call it without knowing the config-dir layout; tests target a temp file via
/// the inner function directly.
///
/// #5544: the home arrives as a PARAMETER rather than being read from `fw`.
/// `FrameworkPaths` describes where a session's framework and `.claude/` tiers
/// live, and the managed constructors deliberately relocate those onto the
/// workspace — so every accessor on it answers a question this function is not
/// asking. `~/.claude.json` belongs to the USER, under every root. Production
/// passes `dirs::home_dir()`, exactly as before this change; only tests pass
/// anything else.
/// What: resolves `<home>/.claude.json` and delegates. An absent or relative
/// home is a soft skip (logged) — seeding a trust record beside the process's
/// working directory would be worse than not seeding one.
/// Test: `prepare_session_does_not_seed_the_workspace_on_the_managed_path`,
/// `home_writes_are_skipped_when_the_home_is_unusable`; the seeding behaviour
/// itself by the inner `preseed_trust_*` tests.
pub
/// The supplied home, when it is usable for a user-global write.
///
/// Why (#5544): `dirs::home_dir()` returns `None` on a stripped environment, and
/// a caller that substituted a relative fallback would send the write beside the
/// process's working directory — the stray-file outcome this change exists to
/// prevent. Declining is the correct answer; both callers are best-effort side
/// effects.
/// What: passes an absolute path through, logging at `warn!` otherwise so a
/// declined write is visible rather than silent.
/// Test: `home_writes_are_skipped_when_the_home_is_unusable`.
/// Remove the `trusty-memory` hook entries from `~/.claude/settings.json`.
///
/// Why: `trusty-memory` hooks were previously registered globally, so they
/// fired for every Claude Code session. Now that [`write_project_hooks`]
/// scopes them to trusty-mpm projects, the global entries must be removed to
/// stop them double-firing (and firing for unrelated sessions like claude-mpm).
///
/// #5544: the home arrives as a PARAMETER — see [`preseed_workspace_trust_home`]
/// for why it is not read off `FrameworkPaths`. Pointing this at a managed
/// workspace was the worse half of that bug: the file does not exist there, a
/// missing file is success by contract, so the operator's REAL global hooks were
/// never removed and kept double-firing with nothing to show for it. No second
/// implementation of this cleanup exists to catch it.
/// What: reads `<home>/.claude/settings.json`, and for each event in
/// [`GLOBAL_TRUSTY_MEMORY_EVENTS`] filters out handler groups whose `hooks`
/// array contains a command matching `trusty-memory hooks fire`. An event key
/// whose array becomes empty is removed entirely. Writes the file back. A
/// missing or malformed file is treated as success (nothing to clean up).
/// Test: `remove_global_hooks_removes_trusty_memory_entries`,
/// `global_hook_cleanup_reaches_the_real_home_under_an_overridden_root`.
pub
/// Filter `trusty-memory` hook entries out of the settings file at `settings_path`.
///
/// Why: split from [`remove_global_trusty_memory_hooks`] so tests can target a
/// temp file instead of the operator's real `~/.claude/settings.json`.
/// What: see [`remove_global_trusty_memory_hooks`]. A missing or malformed
/// file is a no-op success.
/// Test: `remove_global_hooks_removes_trusty_memory_entries`.
pub
/// Inject `"statusLine": {"type":"command","command":"<abs-path> statusline","padding":0}`
/// into `<project>/.claude/settings.json` when the key is absent, or upgrade a
/// stale bare `tm`/`trusty-mpm statusline` default already on disk to the
/// resolved absolute path.
///
/// Why (#1914, same risk class as #1298's `claude_code.rs::resolve_claude`): a
/// bare `tm statusline` command relies on the spawning shell's `PATH`
/// containing wherever `tm` is installed (e.g. `~/.cargo/bin`); under launchd
/// or Claude Code's minimal environment that PATH omission silently drops the
/// statusline segment with no error surfaced anywhere. Resolving an absolute
/// path via [`resolve_statusline_command`] closes that gap the same way
/// `crate::runtime::claude_code::ClaudeCodeAdapter::resolve_claude` already
/// does for the `claude` runtime binary. Because every prior version
/// of this function wrote the exact literal bare string, [`ensure_status_line`]'s
/// resume self-heal (#1913) can recognise that EXACT fingerprint via
/// [`is_stale_bare_statusline_command`] and safely upgrade it in place —
/// without ever touching a genuinely user-customized `statusLine.command`.
/// What: reads the existing `.claude/settings.json` (or `{}` when absent/invalid).
/// When `statusLine` is absent, inserts it with the resolved absolute command.
/// When present and it matches [`is_stale_statusline_command`] (a bare default,
/// OR a `"<binary> statusline"` command whose absolute binary is ephemeral or
/// no longer on disk — #2229), rewrites ONLY its `command` field in place. Any
/// other existing `statusLine` value — a genuine user customization pointing at
/// an existing binary — is left completely untouched. The file is written back
/// pretty-printed only when a change was actually made.
/// Test: `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`.
pub
/// The literal `statusLine.command` strings this module has ever auto-injected.
///
/// Why: a single source of truth for [`is_stale_bare_statusline_command`] and
/// its tests keeps the "what counts as our own stale default" fingerprint from
/// drifting between the two call sites.
/// What: the bare (no absolute path) commands written before #1914 introduced
/// path resolution — one per `[[bin]]` name the `trusty-mpm` crate produces.
pub const KNOWN_BARE_STATUSLINE_COMMANDS: & =
&;
/// Whether an existing `statusLine` entry is our own previously-injected bare
/// default, safe for [`write_status_line`] to upgrade in place.
///
/// Why (#1914): [`write_status_line`] must never clobber a genuinely
/// user-customized `statusLine.command`, but a bare `tm statusline` /
/// `trusty-mpm statusline` written by a pre-#1914 build of this module is not
/// a user customization — it is stale output of this exact function that
/// silently breaks under a minimal PATH. Matching the EXACT literal fingerprint
/// (rather than e.g. "starts with tm") keeps the heuristic conservative: any
/// command with extra flags, an already-absolute path, or a different binary
/// name is left alone.
/// What: returns `true` when `entry.type == "command"` and `entry.command` is
/// exactly one of [`KNOWN_BARE_STATUSLINE_COMMANDS`] (case-sensitive, no extra
/// arguments).
/// Test: `is_stale_bare_statusline_command_matches_known_defaults`,
/// `is_stale_bare_statusline_command_ignores_custom_command`,
/// `is_stale_bare_statusline_command_ignores_non_command_type`.
pub
/// Whether an existing `statusLine` entry is a broken/stale trusty-mpm default
/// that [`write_status_line`] / `ensure_settings_defaults` may safely re-resolve
/// — a strict superset of [`is_stale_bare_statusline_command`].
///
/// Why (#2229): the original heal recognised ONLY the exact pre-#1914 bare
/// literals; every other absolute `statusLine.command` was treated as an
/// untouchable user customization. But a command baked from an ephemeral
/// `current_exe()` (`.../target/debug/deps/tm statusline`, or a worktree path)
/// is NOT a customization — it is our own output pointing at a build artifact
/// that no longer exists on disk, so the statusline silently breaks and never
/// self-heals. This predicate additionally flags a `"<binary> statusline"`
/// command whose absolute binary path is ephemeral or missing on disk, while
/// still leaving a genuine customization that points at an EXISTING,
/// non-ephemeral binary completely alone.
/// What: returns `true` when `entry.type == "command"` and either (a) the
/// command is one of [`KNOWN_BARE_STATUSLINE_COMMANDS`], or (b) the command has
/// our managed `"<binary> statusline"` shape AND the binary token is an
/// absolute path that is either an ephemeral build path
/// ([`trusty_common::bin_resolve::is_ephemeral_build_path`]) or does not exist.
/// A command not ending in ` statusline`, or whose absolute binary still exists
/// and is non-ephemeral, is left untouched.
/// Test: `is_stale_statusline_command_flags_missing_and_ephemeral`,
/// `is_stale_statusline_command_respects_existing_custom_binary`.
pub
/// Resolve the absolute `<binary> statusline` command to write into
/// `statusLine.command`.
///
/// Why (#1914): see [`write_status_line`]'s doc comment for the full
/// PATH-resolution motivation. `pub(crate)` (rather than private) so
/// `core::standalone::settings_defaults::ensure_settings_defaults` can reuse the
/// SAME absolute-path resolution when seeding `statusLine` into the tm-owned
/// `CLAUDE_CONFIG_DIR` settings.json (issue #2214), re-exported via
/// `session_launch::resolve_statusline_command`.
/// What: appends the `statusline` subcommand to [`resolve_statusline_binary`].
/// Test: exercised indirectly by `write_status_line_injects_when_absent`
/// (asserts the written command is an absolute path ending in ` statusline`).
pub
/// The `[[bin]]` names this crate's `Cargo.toml` produces, in fallback order.
///
/// Why (#1914 review, trusty-review PR #1925 finding 1): a machine that only
/// has `trusty-mpm` on `PATH` (not the `tm` alias) must still resolve when
/// `current_exe()` is unavailable — falling back to a single hardcoded "tm"
/// PATH lookup reproduced the exact bug this module fixes for that installed
/// name. Both entries are tried, in order, before degrading to the bare
/// literal.
///
/// #4058: sourced from [`crate::core::own_binary_names::OWN_BINARY_NAMES`]
/// rather than a second hand-copy of the two names, so the SET can't drift
/// out of sync with `daemon::discovery` and the `find_daemon_pids` daemon-PID
/// scan again. `OWN_BINARY_NAMES` is deliberately ordered `tm` before
/// `trusty-mpm` for exactly this call site's fallback order — see that
/// constant's module doc. (`core::standalone::hooks::MPM_BIN_NAMES` needs the
/// opposite order for a different lookup, so it keeps its own array rather
/// than aliasing this one; a test pins the two to the same set.)
const STATUSLINE_BIN_NAMES: & = crateOWN_BINARY_NAMES;
/// Resolve the absolute path to the running `tm`/`trusty-mpm` binary.
///
/// Why (#1914): [`write_status_line`] always runs INSIDE the `tm`/`trusty-mpm`
/// process itself — the CLI launch path (`tm session start`) and the daemon
/// resume path (`ensure_status_line`) are both compiled into that same binary
/// — so `std::env::current_exe()` is the single most reliable source of truth:
/// no PATH search needed, the running binary IS the answer. `current_exe()`
/// does not guarantee a canonical (symlink-free) path, so the result is
/// canonicalized best-effort — falling back to the raw path when
/// canonicalization fails (e.g. the exe was deleted/moved since spawn) rather
/// than losing the resolution entirely. This mirrors, but is even more direct
/// than, the `bin_resolve::resolve_binary("claude")` pattern `claude_code.rs`
/// uses for a DIFFERENT binary it does not control.
/// What: thin wrapper over [`resolve_statusline_binary_with`] using the real
/// `std::env::current_exe` (canonicalized best-effort) and
/// [`trusty_common::bin_resolve::resolve_binary`].
/// Test: exercised indirectly by `write_status_line_injects_when_absent`; the
/// resolution priority itself is covered by the `resolve_statusline_binary_with_*`
/// unit tests, which inject fake sources.
pub
/// Testable core of [`resolve_statusline_binary`] with its I/O sources injected.
///
/// Why: separating the resolution PRIORITY from the actual `current_exe()` /
/// PATH syscalls lets each branch (current-exe hit, PATH-lookup fallback, bare
/// last resort) be exercised deterministically, mirroring the
/// `session_id_exists_in` injected-I/O-root pattern used elsewhere in
/// this crate (`crate::runtime::claude_code`).
/// What: returns `current_exe()`'s path as a `String` when it resolves to
/// valid UTF-8 AND is not an ephemeral build/worktree path (#2229 — a
/// `target/debug` or worktree exe would bake a path that 404s after a rebuild);
/// else the first hit of `path_lookup` over [`STATUSLINE_BIN_NAMES`]
/// (`"tm"` then `"trusty-mpm"` — #1914 review finding 1: a bare single-name
/// PATH lookup reproduces the original bug on a `trusty-mpm`-only install);
/// else the literal `"tm"` so the statusline segment degrades to pre-#1914
/// behaviour rather than disappearing outright.
/// Test: `resolve_statusline_binary_with_prefers_current_exe`,
/// `resolve_statusline_binary_with_rejects_ephemeral_current_exe`,
/// `resolve_statusline_binary_with_rejects_system_temp_current_exe`,
/// `resolve_statusline_binary_with_falls_back_to_path_lookup`,
/// `resolve_statusline_binary_with_falls_back_to_trusty_mpm_name`,
/// `resolve_statusline_binary_with_falls_back_to_bare_name`.
pub
/// Whether a hook handler group is a `trusty-memory` entry.
///
/// Why: identifies the groups [`clean_global_trusty_memory_hooks`] must drop.
/// Matching on the broad `trusty-memory` prefix (rather than the old, narrow
/// `trusty-memory hooks fire` substring) cleans up BOTH the legacy global
/// entries and the canonical `prompt-context` / `inbox-check` entries should
/// either ever have been written globally (issue #1270).
/// What: returns `true` when any command in the group's `hooks` array invokes
/// the `trusty-memory` binary (the command string starts with `trusty-memory `
/// or is exactly `trusty-memory`).
/// Test: covered indirectly by `remove_global_hooks_removes_trusty_memory_entries`.
pub