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
//! 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 BTreeSet;
use ;
use PrepError;
/// 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
}
]
}
]
}"#;
/// Build the `trusty-memory` MCP server definition injected into a project's
/// `.mcp.json`, optionally pinned to a project palace (issue #1605).
///
/// Why (issue #1270): Claude Code reads MCP servers from `<project>/.mcp.json`;
/// a launched trusty-mpm session needs the `trusty-memory` server registered
/// there so the memory tools (`memory_recall`, `memory_remember`, …) are
/// available. The canonical stdio MCP invocation (per `trusty-memory setup`) is
/// `serve --stdio`. Issue #1605: a bare stub leaves palace selection to
/// trusty-memory's cwd-based derivation, which for a repo_url-cloned managed
/// session resolves to the session-id directory basename — the WRONG palace.
/// Pinning `env.TRUSTY_MEMORY_PALACE` to the project's derived `owner-repo` slug
/// makes the spawned trusty-memory resolve the correct project-scoped palace
/// regardless of the throwaway workspace path (the env var is the
/// highest-precedence palace override read by `derive_palace_id`). No
/// trusty-memory CLI/protocol change — the env var is the agreed seam.
/// What: returns the JSON `Value` for a stdio MCP server running
/// `trusty-memory serve --stdio` — with `"env": { "TRUSTY_MEMORY_PALACE": <slug> }`
/// when `palace_slug` is `Some` (non-empty), else the bare stub (no `env` key,
/// byte-identical to the pre-#1605 block). Pure: callers resolve the slug.
/// Test: `trusty_memory_mcp_value_pins_palace`, `trusty_memory_mcp_value_bare`.
pub
/// 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
/// 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`], 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.
/// Test: `prepare_session_sets_output_style`,
/// `write_output_style_preserves_existing_keys`,
/// `write_output_style_sets_spinner_tips`,
/// `write_output_style_sets_active_style`.
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.
/// 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`.
pub
/// 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.
/// The guard itself fails open (ALLOW) on any error, so a slow/absent binary
/// never blocks the PM.
/// Test: `write_project_hooks_registers_pm_guard`.
pub
/// Inject (or update) a named stdio MCP server into the project's `.mcp.json`.
///
/// Why: trusty-mpm needs to register multiple MCP servers (`trusty-memory`,
/// `trusty-search`) into the workspace `.mcp.json` with identical merge/idempotency
/// semantics. Factoring the read-merge-write logic into one helper keeps the two
/// public wrappers thin and guarantees they behave consistently (issue #1270).
/// What: reads an existing `<project_path>/.mcp.json` (starting from `{}` when
/// absent or malformed), adds/updates `mcpServers.<name>` to `server`, and
/// writes the merged JSON back pretty-printed — preserving all other MCP
/// servers. Idempotent: if the entry already matches, the file is left
/// untouched and no write occurs. `server` is a `serde_json::Value` object
/// built by the caller (a const for `trusty-memory`, a dynamically-pinned value
/// for `trusty-search`, #1373).
/// Test: exercised via `inject_trusty_memory_mcp_*` and `inject_trusty_search_mcp_*`.
///
/// Visibility: `pub(super)` (rather than private) because the sibling
/// `search_index` module's `inject_trusty_search_mcp` also calls this shared
/// read-merge-write helper (issue #610 split).
pub
/// Inject the `trusty-memory` MCP server into the project's `.mcp.json`,
/// pinned to the project's palace when one can be derived (issue #1605).
///
/// Why: `prepare_session` configures hooks and instructions but, without this,
/// the launched `claude` process has no access to the memory tools because the
/// `trusty-memory` MCP server is never registered in `<project>/.mcp.json`.
/// Issue #1605: the stub must additionally PIN the session to its project's
/// palace via `env.TRUSTY_MEMORY_PALACE`, because a repo_url-cloned managed
/// session lives under a throwaway `<owner>/<repo>/<session-id>/` workspace
/// whose basename is the session-id — so trusty-memory's cwd-based derivation
/// would resolve the wrong palace. The slug is derived from project identity
/// (operator override > git `owner/repo` > parent/dir) so it matches the slug
/// trusty-memory itself would compute for the canonical project root.
/// What: resolves the palace slug via [`resolve_palace_slug`] (passing the
/// explicit `git_remote` from `LaunchParams`/`SessionRecord` when known, else
/// best-effort `git remote get-url origin` in `project_path`), builds the
/// (optionally pinned) server value via [`trusty_memory_mcp_value`], and
/// registers it under the key `trusty-memory`. When no slug can be derived the
/// bare stub is injected — byte-identical to the pre-#1605 behaviour, so the
/// session still gets the memory tools (no regression).
/// Test: `inject_trusty_memory_mcp_adds_server`,
/// `inject_trusty_memory_mcp_preserves_existing`,
/// `inject_trusty_memory_mcp_is_idempotent`,
/// `inject_trusty_memory_mcp_uses_serve_stdio`,
/// `inject_trusty_memory_mcp_pins_palace_from_repo_url`,
/// `inject_trusty_memory_mcp_pins_palace_from_git_remote`.
pub
/// Resolve the trusty-memory palace slug to pin 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.
/// What: reads the `TRUSTY_MEMORY_PALACE` env override (highest precedence),
/// resolves the git remote (explicit arg, else best-effort `git -C
/// <project_path> config --get remote.origin.url`), and returns
/// `trusty_common::derive_palace_id(project_path, git_remote, override)`. Returns
/// `None` when nothing usable can be derived (no override, no remote, root-less
/// path) so the caller injects the bare stub. Best-effort and side-effect-free
/// beyond the read-only `git config` probe; never panics.
/// Test: covered via `inject_trusty_memory_mcp_pins_palace_from_repo_url`
/// (explicit remote) and `resolve_palace_slug_*` (override / git-fallback / none).
/// Read `remote.origin.url` for the repo containing `start` (best-effort).
///
/// Why: a local-path managed session (no `repo_url` in `LaunchParams`) should
/// still pin its palace by the repo's GitHub identity rather than the directory
/// basename. Shelling out to `git config` (rather than parsing `.git/config`)
/// transparently handles worktrees, mirroring trusty-memory's own
/// `git_remote_origin` so the two derive the same slug.
/// What: runs `git -C <start> config --get remote.origin.url`; returns the
/// trimmed URL on success, `None` when there is no origin remote, git is
/// absent, or `start` is not in a repo. No network.
/// Test: exercised indirectly via `resolve_palace_slug_falls_back_to_git_remote`
/// (a temp git repo) and the daemon-less paths in `inject_trusty_memory_mcp_*`.
pub
/// Collect the MCP server names declared in a workspace's `.mcp.json`.
///
/// Why (issue #1296): Claude Code blocks a freshly-spawned session on a "new MCP
/// servers found" approval dialog whenever `<workspace>/.mcp.json` registers a
/// server the project entry has not yet approved. [`preseed_workspace_trust`]
/// pre-approves them via `enabledMcpjsonServers`, and to do that it needs the
/// list of server names the project actually ships. The list is derived from the
/// on-disk `.mcp.json` (rather than a hard-coded set) so it covers BOTH the
/// servers trusty-mpm injects (`trusty-memory`, `trusty-search`) AND any servers
/// the cloned project shipped of its own — every one of which would otherwise
/// trigger the dialog.
/// What: reads `<workspace>/.mcp.json`, parses it, and returns the sorted keys of
/// its `mcpServers` object. A missing, unreadable, malformed, or server-less file
/// yields an empty vector — this never fails, so a degenerate `.mcp.json` cannot
/// crash launch preparation. Sorting makes the result deterministic so the
/// written settings are stable across runs (supporting idempotency).
/// Test: covered via `preseed_trust_enables_mcp_servers_from_mcp_json` and
/// `preseed_trust_enables_empty_when_no_mcp_json`.
/// Pre-seed per-directory trust acceptance for `workspace` in `~/.claude.json`.
///
/// 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. Issue #1296 extends this: trust
/// acceptance alone is not enough — a project shipping a `.mcp.json` triggers a
/// SECOND blocking "new MCP servers found" dialog, so this also pre-approves the
/// project's MCP servers via `enabledMcpjsonServers`.
/// What: reads `~/.claude.json` (the JSON config; starts from `{}` when absent
/// or malformed — 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`, `projectOnboardingSeenCount >= 1`, and
/// `enabledMcpjsonServers` listing every server name from
/// `<workspace>/.mcp.json` (see [`mcp_server_names`]; an empty array when the
/// project ships none), then writes it back pretty-printed preserving every
/// other key. Idempotent. The OAuth fields elsewhere in the file are never
/// touched.
/// `exclude_mcp_names` (issue #2739 follow-up security fix) removes names from
/// the auto-approved `enabledMcpjsonServers` list even though they are present
/// in `.mcp.json` — used to keep project-scope-bridged custom MCP servers
/// (which ship with the cloned repo, not the operator's own registry) behind
/// Claude Code's normal "new MCP servers found" consent dialog rather than
/// silently pre-approved. Pass an empty set to preserve the pre-#2739-fix
/// behaviour of approving every name in `.mcp.json`.
/// Test: `preseed_trust_marks_directory`, `preseed_trust_preserves_other_keys`,
/// `preseed_trust_is_idempotent`, `preseed_trust_leaves_malformed_file`,
/// `preseed_trust_enables_mcp_servers_from_mcp_json`,
/// `preseed_trust_enables_empty_when_no_mcp_json`,
/// `preseed_trust_excludes_project_scope_names_from_approval`.
pub
/// Pre-seed workspace trust in the operator's real `~/.claude.json`.
///
/// Why: thin home-resolving 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.
/// What: resolves `~/.claude.json` and delegates, forwarding `exclude_mcp_names`
/// unchanged (see [`preseed_workspace_trust`]'s doc — issue #2739 follow-up
/// security fix). A missing home directory is a soft failure (logged,
/// non-fatal) so launch still proceeds.
/// Test: covered by the inner `preseed_trust_*` tests.
pub
/// 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).
/// What: reads `~/.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`.
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.
const STATUSLINE_BIN_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.
/// 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
/// `has_prior_conversation_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_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