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
//! Project trust + MCP-server pre-seeding for the managed CLAUDE_CONFIG_DIR.
//!
//! Why: WI-3 (sub-parts 2+3) requires that the managed Claude Code session never
//! sees a blocking "Do you trust this folder?" or "New MCP servers found" dialog.
//! Claude Code reads per-directory trust from `$CLAUDE_CONFIG_DIR/.claude.json` when
//! `CLAUDE_CONFIG_DIR` is set — NOT from `$HOME/.claude.json`. All trust seeding
//! for the managed path MUST target `<claude_config_dir>/.claude.json`.
//!
//! ISOLATION INVARIANT: this module NEVER writes to `~/.claude.json` or
//! `~/.claude/`. It only writes to files under `<claude_config_dir>` (the
//! managed CLAUDE_CONFIG_DIR — typically `~/.trusty-mpm/claude-config/`).
//!
//! What: [`preseed_managed_trust`] merges `projects.<workspace>` trust keys and
//! `enabledMcpjsonServers` into `<claude_config_dir>/.claude.json`. The MCP
//! server list is derived via
//! [`crate::core::mcp_config::managed_mcp_server_names`] — the two
//! UNCONDITIONAL framework builtins (`trusty-mpm`, `trusty-review`) and the
//! two CONDITIONAL framework builtins (`trusty-memory`, `trusty-search`),
//! EACH gated by its own `_pinned` parameter below, UNION any user-scope
//! servers registered via `tm mcp add` (read from the same file's top-level
//! `mcpServers`) — so a `tm mcp add`-ed server is trusted on the next
//! session start with no per-project bookkeeping.
//!
//! **Security note (issue #3918 follow-up):** this derivation deliberately
//! does NOT read the target workspace's own `<workspace>/.mcp.json`. That
//! file is git-tracked content that arrives WITH a cloned repo — an earlier
//! version of this fix read it directly (mirroring
//! `session_launch::settings::preseed_workspace_trust`, the interactive `tm
//! launch` path) and a code-critic review caught that this let a hostile or
//! compromised repo's `.mcp.json` get silently auto-approved and connected in
//! a DAEMON-managed session, with no human present to decline it. See
//! [`crate::core::mcp_config::managed_mcp_server_names`]'s doc for the full
//! reasoning on why its remaining sources (the two unconditional builtins and
//! the operator's own `tm mcp add` registry) are safe against that vector.
//!
//! **Security note (issue #3934 follow-up):** the two CONDITIONAL builtins
//! looked safe to trust unconditionally too, on the assumption their
//! force-overwrite injector always ran this session — but that assumption is
//! controlled by a manifest `[mcp]` toggle that is itself untrusted,
//! project-scope, cloned-with-the-repo content (see
//! [`crate::core::mcp_config::CONDITIONAL_BUILTIN_MCP_SERVERS`]'s doc for the
//! full exploit). [`preseed_managed_trust`] takes the resolved toggle values
//! as explicit parameters instead of assuming them.
//!
//! **Security note (issue #3950 follow-up — fifth instance):** a toggle
//! being on is necessary but not sufficient — the force-overwrite injector's
//! WRITE can itself fail (disk full, permission error, transient I/O fault)
//! while a spoofed or stale `.mcp.json` entry is already present, in which
//! case the name must NOT be approved either, even though its toggle was on.
//! [`preseed_managed_trust`] now takes each of the four builtins' actual
//! per-run pin RESULT (toggle AND write success) — callers MUST supply the
//! value the SAME run's injectors actually observed
//! ([`super::load::load_alias`] reads it off the
//! [`crate::core::session_launch::PrepReport`] its own
//! `prepare_session_with_repo_url` call already produced), never a value
//! re-derived purely from the manifest toggle in isolation.
//! Test: `test_preseed_managed_trust_marks_directory`,
//! `test_preseed_managed_trust_is_idempotent`,
//! `test_preseed_managed_trust_enables_mcp_servers`,
//! `test_preseed_managed_trust_includes_trusty_mpm` (#3918),
//! `test_preseed_managed_trust_excludes_foreign_mcp_json_entries` (#3918 follow-up,
//! hostile-clone regression),
//! `test_preseed_managed_trust_no_home_write` (isolation guard),
//! `test_preseed_managed_trust_quarantines_malformed_json` (corrupt-file quarantine),
//! `test_preseed_managed_trust_excludes_conditional_builtin_when_toggle_off`
//! (#3934 regression — attack reproduction),
//! `test_preseed_managed_trust_legitimate_toggle_disable_is_harmless`
//! (#3934 — legitimate operator toggle still launches cleanly),
//! `test_preseed_managed_trust_excludes_unconditional_builtin_when_pin_failed`
//! (#3950 regression — write-failure reproduction).
use Path;
use cratemanaged_mcp_server_names;
/// The exact set of keys [`preseed_managed_trust`] itself writes into a
/// `projects.<workspace>` entry.
///
/// Why (issue #4206): [`prune_stale_project_entries`] must distinguish a
/// SEEDER DROPPING (an entry this function created for a directory that no
/// longer exists — 2,520 of 2,541 entries in the reporting operator's config)
/// from REAL USER STATE that Claude Code itself accumulated (`lastSessionId`,
/// `lastCost`, `mcpServers`, `history`, …). The observed distribution is
/// sharply bimodal — droppings carry exactly these four keys, real entries
/// carried 15–33 — so "the entry's key set is a subset of what the seeder
/// writes" is a precise, non-heuristic test for "nothing but this function has
/// ever touched this entry".
/// What: the four keys written below (`hasTrustDialogAccepted`,
/// `hasCompletedProjectOnboarding`, `projectOnboardingSeenCount`,
/// `enabledMcpjsonServers`). MUST be kept in sync with the writes at the end
/// of [`preseed_managed_trust`] — adding a key there without adding it here
/// only makes the prune MORE conservative (entries stop looking pure and are
/// kept), never more destructive, so the failure mode of drift is safe.
/// Test: `prune_keeps_entry_with_runtime_fields`.
const SEEDER_WRITTEN_KEYS: & = &;
/// Whether `dir` is DEFINITIVELY absent from the filesystem.
///
/// Why (issue #4206): this is the load-bearing safety predicate of the prune.
/// Deleting an entry because its directory "looks missing" must never fire for
/// a directory that is merely temporarily unreachable — an unmounted volume, a
/// network mount that is down, a permission error, a filesystem returning
/// `EIO`. This project has repeatedly shipped the opposite bug (a failure
/// branch treating an ambiguous observation as a definite negative and
/// advancing state anyway), so the rule here is deliberately asymmetric:
/// `NotFound` is the ONLY error the OS reports that actually means "this path
/// does not exist", and every other outcome — including success — keeps the
/// entry.
/// What: `symlink_metadata` (NOT `metadata`) so a dangling symlink counts as
/// PRESENT: the link itself exists, and its target may simply be an unmounted
/// volume. Returns `true` only on `ErrorKind::NotFound`; any other error kind
/// (`PermissionDenied`, `NotADirectory`, or a platform-specific I/O fault)
/// returns `false` — keep the entry.
/// Test: `prune_keeps_entry_when_path_error_is_ambiguous`,
/// `prune_drops_entry_when_directory_definitively_absent`.
/// Drop `projects` entries that are pure seeder droppings for directories that
/// are definitively gone, returning how many were removed.
///
/// Why (issue #4206): the seeder only ever ADDED entries, so a config that had
/// accumulated 2,541 `projects` keys — 2,445 of them `tempfile::TempDir`
/// paths — had no mechanism to ever shrink. Pruning during the read-modify-
/// write that is already happening makes the file self-healing with no new
/// command, no background job, and no extra I/O beyond one `symlink_metadata`
/// per entry.
/// What: removes an entry only when BOTH conditions hold —
/// (1) [`is_definitively_absent`] for its path key, AND
/// (2) its object carries no key outside [`SEEDER_WRITTEN_KEYS`].
/// The conjunction is the point: either test alone would be unsafe.
/// Condition (1) alone would delete a real, actively-used project sitting on a
/// temporarily-unmounted volume; condition (2) alone would delete a
/// freshly-seeded entry for a directory that still exists. `keep_key` (the
/// workspace being seeded this run) is never pruned. Non-object entries are
/// left untouched — this function only removes what it can positively
/// identify.
/// Test: `prune_drops_entry_when_directory_definitively_absent`,
/// `prune_keeps_entry_when_path_error_is_ambiguous`,
/// `prune_keeps_entry_with_runtime_fields`.
/// Pre-seed project trust and MCP-server approval into `<claude_config_dir>/.claude.json`.
///
/// Why (WI-3 sub-parts 2+3): Claude Code shows two blocking dialogs for unfamiliar
/// projects — (1) "Do you trust the files in this folder?" and (2) "New MCP servers
/// found". Both are keyed to the absolute workspace path under
/// `projects.<workspace>` in `$CLAUDE_CONFIG_DIR/.claude.json`. Writing the trust
/// keys before launch means managed sessions start immediately without any dialog.
///
/// ISOLATION: writes ONLY to `<claude_config_dir>/.claude.json` — never to
/// `$HOME/.claude.json` or anything under `~/.claude/`. This is the central
/// isolation invariant for the managed driver (WI-7 support).
///
/// What: reads `<claude_config_dir>/.claude.json` (starts from `{}` when absent;
/// when the file exists but contains malformed JSON the corrupt file is renamed
/// to `.claude.json.corrupt` (preserving bytes for post-mortem) and seeding
/// proceeds from a fresh `{}`), then ensures `projects.<workspace>` carries
/// `hasTrustDialogAccepted: true`, `hasCompletedProjectOnboarding: true`,
/// `projectOnboardingSeenCount: 1` (if not already ≥ 1), and
/// `enabledMcpjsonServers` set to
/// [`crate::core::mcp_config::managed_mcp_server_names`]`(&config, trusty_mpm_pinned, trusty_review_pinned, trusty_memory_pinned, trusty_search_pinned)`
/// — the two unconditional builtins and the two conditional builtins, EACH
/// gated by the caller-supplied per-name pin result, UNION the `tm mcp add`
/// registry (see that function's doc for why raw `.mcp.json` content is
/// deliberately excluded, issue #3918 follow-up). Note this list does NOT
/// read `workspace`'s own `.mcp.json` or require `session_launch::prepare_session`
/// to have run for it — `workspace` is used only as the
/// `projects.<workspace>` trust key.
///
/// **`trusty_mpm_pinned` / `trusty_review_pinned` / `trusty_memory_pinned` /
/// `trusty_search_pinned` (issues #3934/#3950):** each MUST reflect whether
/// that name's force-overwrite injector actually SUCCEEDED writing the
/// framework-controlled entry for `workspace` this run — not merely that its
/// manifest toggle (where one exists) was on. Passing a hardcoded
/// `true, true, true, true` reopens the exact vulnerability these parameters
/// close: a manifest that disabled a conditional injector, OR a write that
/// failed for any of the four (disk full, permission error, transient I/O
/// fault — issue #3950, the fifth instance of this class), would then have
/// its (possibly attacker-spoofed) `.mcp.json` entry pre-approved anyway.
/// [`super::load::load_alias`] derives all four from the
/// [`crate::core::session_launch::PrepReport`] the SAME run's
/// `prepare_session_with_repo_url` call already produced, rather than
/// re-deriving from the manifest toggle alone.
/// Writes back pretty-printed; idempotent: if all fields already match, the
/// file is NOT rewritten. All other keys in the file are preserved.
/// Test: `test_preseed_managed_trust_marks_directory`,
/// `test_preseed_managed_trust_is_idempotent`,
/// `test_preseed_managed_trust_enables_mcp_servers`,
/// `test_preseed_managed_trust_no_home_write`,
/// `test_preseed_managed_trust_quarantines_malformed_json`,
/// `test_preseed_managed_trust_excludes_conditional_builtin_when_toggle_off`,
/// `test_preseed_managed_trust_excludes_unconditional_builtin_when_pin_failed`
/// (issue #3950 regression).