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
//! Project-trust seeding and stale-entry pruning for the managed CLAUDE_CONFIG_DIR.
//!
//! Why: a managed Claude Code session must not block on "Do you trust the files
//! in this folder?". Claude Code reads per-directory trust from
//! `$CLAUDE_CONFIG_DIR/.claude.json` when `CLAUDE_CONFIG_DIR` is set — NOT from
//! `$HOME/.claude.json` — so managed-path seeding must target
//! `<claude_config_dir>/.claude.json` (WI-3 sub-part 2).
//!
//! ISOLATION INVARIANT: this module NEVER writes to `~/.claude.json` or
//! `~/.claude/`. It writes only under `<claude_config_dir>` (the managed
//! CLAUDE_CONFIG_DIR — typically `~/.trusty-mpm/claude-config/`).
//!
//! What: [`preseed_managed_trust`] sets the three trust keys on
//! `projects.<workspace>` and REMOVES `enabledMcpjsonServers` from that entry.
//! [`prune_stale_project_entries`] deletes `projects` entries that are pure
//! seeder droppings for directories that are definitively gone (#4206).
//!
//! **#4181 / ADR-0042 — this module no longer derives an MCP approval.** It used
//! to write `enabledMcpjsonServers`, computed from the framework builtins gated
//! on four per-run `_pinned` results plus the operator's `tm mcp add` registry.
//! Those four parameters and that derivation went with the injectors that fed
//! them: MCP servers are now declared once in user scope, and a project-scope
//! approval is exactly what lets a workspace `.mcp.json` entry displace that
//! declaration. So the #3918 → #3934 → #3950 hardening chain — excluding a
//! cloned repo's own `.mcp.json` from the approval set, gating the conditional
//! builtins on their manifest toggle, then gating every builtin on its actual
//! per-run write result — hardened a mechanism this module no longer has. The
//! key is REMOVED from the entry rather than merely left unwritten, because
//! ceasing to write it would leave it in place on every machine a prior tm
//! launched; see [`preseed_managed_trust`]'s own doc.
//!
//! Test: `test_preseed_managed_trust_marks_directory`,
//! `test_preseed_managed_trust_is_idempotent`,
//! `test_preseed_managed_trust_writes_no_mcp_approval` (#4181),
//! `test_preseed_managed_trust_strips_a_stale_mcp_approval` (#4181 migration),
//! `test_preseed_managed_trust_preserves_other_keys`,
//! `test_preseed_managed_trust_no_home_write` (isolation guard),
//! `test_preseed_managed_trust_quarantines_malformed_json` (corrupt-file quarantine).
use Path;
/// 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 three keys [`preseed_managed_trust`] writes
/// (`hasTrustDialogAccepted`, `hasCompletedProjectOnboarding`,
/// `projectOnboardingSeenCount`), plus `enabledMcpjsonServers`, which #4181
/// stopped writing but which a dropping left by an older tm still carries — so
/// dropping it from this list would make those legacy entries stop looking pure
/// and never be pruned. 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 into `<claude_config_dir>/.claude.json`, and strip any
/// MCP approval a prior version left behind.
///
/// Why (WI-3 sub-part 2): Claude Code blocks an unfamiliar project on "Do you
/// trust the files in this folder?", keyed to the absolute workspace path under
/// `projects.<workspace>`. Writing the trust keys before launch means managed
/// sessions start immediately without that 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).
///
/// **#4181 / ADR-0042 — why `enabledMcpjsonServers` is REMOVED, not merely left
/// unwritten.** The approval is name-based and content-blind, and an approved
/// name makes the workspace `.mcp.json` entry of that name WIN over the
/// operator's own user-scope declaration — measured, and the whole hinge of the
/// #3918→#3950 name-squatting chain. tm no longer writes MCP config into a
/// workspace, so it approves no project-scope name either, and a repo's
/// colliding entry falls through to Claude Code's own consent dialog. Ceasing to
/// write would leave the key on every machine a prior tm launched, keeping the
/// displacement alive exactly where a cloned repo could reach it.
///
/// This also closes the widening #5398 shipped on the owner's explicit
/// understanding that this change removes the mechanism: this seeder applied no
/// `project_scope_mcp_names` subtraction (#2739), so a repo `[mcp.custom]` name
/// colliding with an operator registry name was pre-approved on `tm launch` /
/// `tm connect`. With no approval written, there is nothing to collide with.
///
/// What: reads `<claude_config_dir>/.claude.json` (starts from `{}` when absent;
/// a malformed file is quarantined to a timestamped path — #4206 — and seeding
/// proceeds from a fresh `{}`), then ensures `projects.<workspace>` carries
/// `hasTrustDialogAccepted: true`, `hasCompletedProjectOnboarding: true` and
/// `projectOnboardingSeenCount >= 1`, and REMOVES `enabledMcpjsonServers`.
/// `workspace` is used only as the `projects.<workspace>` key — this never reads
/// the workspace's own `.mcp.json`. Writes back atomically; idempotent once the
/// entry is trusted and the approval key is gone. All other keys are preserved.
///
/// **Concurrency (issue #4076):** the whole read → mutate → write cycle runs
/// under [`crate::core::claude_json_guard::lock`]. The daemon provisions
/// sessions concurrently and calls this once per session, so two overlapping
/// cycles were a lost update — the slower writer stored a snapshot taken before
/// the faster writer's store, silently dropping that session's whole
/// `projects.<workspace>` entry. This is the third seeder to take the guard;
/// #4072 fixed the two that target `~/.claude.json`, and
/// [`crate::core::mcp_config::seed_builtin_servers`] already held it against
/// the SAME `<claude_config_dir>/.claude.json` this function writes, so leaving
/// this one unguarded also left those two racing each other.
/// Test: `test_preseed_managed_trust_marks_directory`,
/// `test_preseed_managed_trust_is_idempotent`,
/// `test_preseed_managed_trust_writes_no_mcp_approval`,
/// `test_preseed_managed_trust_strips_a_stale_mcp_approval`,
/// `test_preseed_managed_trust_no_home_write`,
/// `test_preseed_managed_trust_quarantines_malformed_json`,
/// `concurrent_managed_seeds_preserve_every_workspace_entry` (#4076).