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
//! `tm repair` command handler — recover from corrupt deploy state.
//!
//! Why: a crash between atomic stages (write-temp / rename) or a disk-full
//! during manifest serialisation can leave stale `.tmp` orphans or a malformed
//! manifest. Without a repair path the user sees confusing deploy failures and
//! must manually poke at `~/.claude/agents/`. This command provides a single,
//! safe recovery entry point.
//! What: `repair_deploy` removes `.tmp` orphans from the AGENT deploy tier
//! (`FrameworkPaths::agent_deploy_dir()` — the tm-managed `CLAUDE_CONFIG_DIR`
//! since #4409, not `~/.claude/agents/`) and from skill subdirs under
//! `~/.claude/skills/`, validates both manifests, and — with `--force` —
//! resets a corrupt agent manifest to a clean empty state so the next
//! `tm install` performs a full re-deploy. The agent half MUST follow the
//! deploy tier: every "run `tm repair deploy` to recover" message the deployer
//! and retraction emit is about the ledger in THAT directory, so repairing the
//! old location would leave the operator with no way out of a corrupt ledger.
//! Test: `cli_parses_repair_deploy` covers argument parsing; the integration
//! test `repair_deploy_removes_stale_tmps` exercises the full flow.
use std::path::{Path, PathBuf};
use trusty_mpm::core::agent_manifest::{AgentManifest, MANIFEST_FILE, ManifestLoad};
use trusty_mpm::core::paths::FrameworkPaths;
use trusty_mpm::core::skill_manifest::{SKILL_MANIFEST_FILE, SkillManifest};
use crate::cli::RepairAction;
/// Routes a parsed `tm repair` subcommand to its handler.
///
/// Why: #5007 added a third repair subcommand and the inline `match` in
/// `main.rs` crossed the 500-SLOC production cap. Dispatch lives beside the
/// handlers it selects, so a fourth subcommand costs `main.rs` nothing.
///
/// What: maps each `RepairAction` variant onto the module that implements it.
///
/// Test: `cli_parses_repair_deploy`, `cli_parses_repair_push_guard`, and the
/// `tests_behavior_repair_tests.rs` behaviour suite exercise the handlers this
/// routes to.
pub(crate) async fn dispatch(
client: &reqwest::Client,
url: &str,
action: RepairAction,
) -> anyhow::Result<()> {
match action {
// #7602: the only arm that needs the daemon — the delegation map lives
// there and nowhere else.
// #8257: a listing, or a repair by delegation id or by agent id.
RepairAction::Delegation {
agent_id,
delegation_id,
list,
force,
} => match (list, delegation_id, agent_id) {
(Some(dir), _, _) => super::repair_delegation_list::list(client, url, &dir).await,
(None, Some(id), _) => {
let path = format!("/api/v1/delegations/by-id/{id}/repair");
repair_delegation(&path, &format!("delegation {id}"), force).await
}
(None, None, Some(agent_id)) => {
let path = format!("/api/v1/delegations/{agent_id}/repair");
repair_delegation(&path, &format!("agent {agent_id}"), force).await
}
(None, None, None) => anyhow::bail!("name an agent id, --delegation-id, or --list"),
},
RepairAction::Deploy { force } => repair_deploy(force),
RepairAction::PushGuard { path, dry_run } => {
super::push_guard::repair_push_guard(path, dry_run)
}
RepairAction::SessionStore {
path,
dry_run,
force,
} => super::repair_session_store::repair_session_store(path, dry_run, force),
// #7569: quarantine the ledger rows #7514 let unit tests write.
RepairAction::SavingsLedger {
root,
apply,
dry_run: _,
markers,
} => super::repair_savings_ledger::repair_savings_ledger(root, apply, markers),
}
}
/// `tm repair delegation <agent-id> [--force]` (#7602).
///
/// Why: the daemon owns the decision — it holds the delegation map and the
/// session registry, and it is the only process that can write the record. This
/// function's whole job is to carry the answer back without softening it: a
/// refusal exits NONZERO so a script cannot read it as a repair.
/// What: POSTs the agent id and the `force` assertion, then prints one line per
/// outcome. `no_record` and `refused` both exit nonzero — the first because the
/// operator named an agent nothing knows, which is a fact they must see rather
/// than a success; the second because the gate declined.
/// #8531: always over the daemon socket, which proves this process's pid to
/// the daemon; the owning session is established from it. No caller id is
/// sent — the daemon would ignore one.
/// Test: `cli_parses_repair_delegation`, `cli_parses_repair_delegation_force`,
/// `cli_rejects_a_caller_session_argument_8257`; the outcomes themselves in
/// `delegation_repair_tests.rs`.
async fn repair_delegation(path: &str, target: &str, force: bool) -> anyhow::Result<()> {
// #8257: `path` is the agent-id or the delegation-id endpoint; `target`
// names which in every line printed below.
// #8531: socket only, never HTTP — HTTP cannot prove the caller, so an
// owning session's own clear would be refused there.
let daemon = trusty_mpm::client::DaemonClient::from_resolved_socket()?;
let resp = daemon
.post(path)
.json(&serde_json::json!({ "force": force }))
.send()
.await?;
let status = resp.status();
let body = resp.text().await.unwrap_or_default();
if !status.is_success() {
anyhow::bail!("repair delegation failed ({status}): {body}");
}
let outcome: trusty_mpm::daemon::services::delegation_repair::RepairOutcome =
serde_json::from_str(&body)
.map_err(|e| anyhow::anyhow!("could not read the daemon's answer ({e}): {body}"))?;
use trusty_mpm::daemon::services::delegation_repair::RepairOutcome;
match outcome {
RepairOutcome::Ended { records } => {
println!("ended {records} stuck delegation record(s) for {target} (cancelled)");
Ok(())
}
RepairOutcome::AlreadyEnded { records } => {
println!("nothing to repair: all {records} record(s) for {target} have ended");
Ok(())
}
// The gate's own words — paraphrasing them would hide which arm fired,
// which is the only thing that says what to do next.
RepairOutcome::Refused { reason } => anyhow::bail!("repair refused: {reason}"),
RepairOutcome::NoRecord => anyhow::bail!(
"no delegation names {target}. The daemon's delegation map is rebuilt empty \
at every start, so this is undeterminable rather than proof the agent is gone \
(ADR-0045)"
),
}
}
/// `tm repair deploy` handler.
///
/// Why: one safe, user-facing entry point to recover from the two crash
/// scenarios: a stale `.tmp` left after an interrupted atomic rename, and a
/// corrupt manifest left by an interrupted or truncated JSON write.
///
/// What: removes `*.tmp` orphans from the agent deploy tier and all skill
/// subdirs under `~/.claude/skills/`, then validates both manifests. With
/// `--force`, resets a corrupt manifest to empty so the next `tm install`
/// performs a full re-deploy. Prints a line per action; exits 0 even when
/// only reporting corruption (so the caller can decide next steps).
///
/// Test: `cli_parses_repair_deploy`, integration `repair_removes_stale_tmps`.
pub(crate) fn repair_deploy(force: bool) -> anyhow::Result<()> {
let home =
dirs::home_dir().ok_or_else(|| anyhow::anyhow!("could not resolve home directory"))?;
let claude_dir = home.join(".claude");
// #4409: the agent ledger this command repairs lives in the tm-managed
// deploy tier now. Skills are unchanged by that issue and stay here.
let agents_dir = FrameworkPaths::default().agent_deploy_dir();
let skills_dir = claude_dir.join("skills");
// ── Step 1: remove stale .tmp files from agents directory ──────────────
let agents_tmps = remove_tmp_orphans(&agents_dir)?;
if agents_tmps.is_empty() {
println!("agents: no stale .tmp files found");
} else {
for p in &agents_tmps {
println!("agents: removed stale temp file {}", p.display());
}
}
// ── Step 2: validate the agent manifest ────────────────────────────────
let agent_manifest_path = agents_dir.join(MANIFEST_FILE);
if agent_manifest_path.exists() {
match AgentManifest::load_checked(&agents_dir) {
ManifestLoad::Ok(_) => {
println!("agents: manifest OK");
}
ManifestLoad::Corrupt(detail) => {
eprintln!("agents: manifest CORRUPT — {detail}");
if force {
// Write an empty, valid manifest so the next `tm install`
// performs a full re-deploy from the bundle source.
let empty = AgentManifest::default();
empty
.save(&agents_dir)
.map_err(|e| anyhow::anyhow!("failed to reset agent manifest: {e}"))?;
println!(
"agents: manifest reset to empty (--force). Run `tm install` to re-deploy."
);
} else {
println!(
"agents: run `tm repair deploy --force` to reset and re-deploy, \
or `tm install --force` to force a full re-install."
);
}
}
}
} else {
println!("agents: no manifest found (first deploy not yet run)");
}
// ── Step 3: remove stale .tmp files from skill subdirs ─────────────────
let skill_tmps = remove_skill_tmp_orphans(&skills_dir)?;
if skill_tmps.is_empty() {
println!("skills: no stale .tmp files found");
} else {
for p in &skill_tmps {
println!("skills: removed stale temp file {}", p.display());
}
}
// ── Step 4: validate the skill manifest ────────────────────────────────
let skill_manifest_path = skills_dir.join(SKILL_MANIFEST_FILE);
if skill_manifest_path.exists() {
match validate_skill_manifest(&skills_dir) {
Ok(()) => println!("skills: manifest OK"),
Err(detail) => {
eprintln!("skills: manifest CORRUPT — {detail}");
if force {
let empty = SkillManifest::default();
empty
.save(&skills_dir)
.map_err(|e| anyhow::anyhow!("failed to reset skill manifest: {e}"))?;
println!(
"skills: manifest reset to empty (--force). Run `tm install` to re-deploy."
);
} else {
println!(
"skills: run `tm repair deploy --force` to reset and re-deploy, \
or `tm install --force` to force a full re-install."
);
}
}
}
} else {
println!("skills: no manifest found (first deploy not yet run)");
}
Ok(())
}
/// Remove `*.tmp` orphans from `dir`, returning the paths that were removed.
///
/// Why: `atomic_write` stages via a scratch sibling; a crash after `fs::write`
/// but before `fs::rename` leaves it behind. This is the cleaner for those
/// orphans.
/// What: reads `dir` (non-error if absent), removes any regular file whose name
/// ends with `.tmp`, and returns the paths it ACTUALLY unlinked.
///
/// Removes `entry.path()` directly rather than round-tripping through a derived
/// "base" path (issue #4409). The previous implementation computed
/// `path.with_extension("")` and handed that to `repair_stale_tmp`, which
/// re-derived `base.with_extension("tmp")` — a round-trip that only reconstructs
/// the OLD fixed `<name>.tmp` naming. Against the per-attempt
/// `<name>.<pid>.<nanos>.tmp` scratch names `atomic_write` writes now,
/// `with_extension` strips only the last dot-segment, so the reconstruction
/// never matched, nothing was unlinked — and the path was pushed onto `removed`
/// regardless, so `tm repair deploy` reported cleaning files it had left on
/// disk. A repair command that reports work it did not do is worse than one
/// that does nothing. The exact path is already in hand; the indirection bought
/// nothing and hid that bug.
/// Test: `repair_deploy_removes_stale_tmps`,
/// `repair_removes_per_attempt_temp_orphans`,
/// `remove_tmp_orphans_reports_only_what_it_unlinked`.
fn remove_tmp_orphans(dir: &Path) -> anyhow::Result<Vec<PathBuf>> {
let mut removed = Vec::new();
if !dir.is_dir() {
return Ok(removed);
}
for entry in std::fs::read_dir(dir)? {
let entry = entry?;
let name = entry.file_name();
let name_str = name.to_string_lossy();
if name_str.ends_with(".tmp") && entry.file_type()?.is_file() {
let path = entry.path();
match std::fs::remove_file(&path) {
// Only a real unlink counts as removed.
Ok(()) => removed.push(path),
// Raced by another repair run or by the writer's own cleanup.
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
Err(e) => {
return Err(anyhow::anyhow!(
"failed to remove stale temp file {}: {e}",
path.display()
));
}
}
}
}
Ok(removed)
}
/// Remove `*.tmp` orphans from all per-skill subdirs under `skills_dir`.
///
/// Why: skill files live under `<skills_dir>/<name>/SKILL.md`, and the
/// staging temp is `<skills_dir>/<name>/SKILL.tmp`. This helper walks one
/// level of subdirectory to cover all skill subdirs.
/// What: for each subdirectory of `skills_dir`, calls `remove_tmp_orphans`.
/// Test: covered by `repair_removes_stale_tmps`.
fn remove_skill_tmp_orphans(skills_dir: &Path) -> anyhow::Result<Vec<PathBuf>> {
let mut all_removed = Vec::new();
if !skills_dir.is_dir() {
return Ok(all_removed);
}
// Also check the skills dir itself (top-level `.tmp` orphan from manifest write).
let mut top = remove_tmp_orphans(skills_dir)?;
all_removed.append(&mut top);
for entry in std::fs::read_dir(skills_dir)? {
let entry = entry?;
if entry.file_type()?.is_dir() {
let mut sub = remove_tmp_orphans(&entry.path())?;
all_removed.append(&mut sub);
}
}
Ok(all_removed)
}
/// Validate the skill manifest in `skills_dir`, returning `Err(detail)` if corrupt.
///
/// Why: `SkillManifest::load` silently defaults to empty on parse errors; for
/// the repair command we need to detect corruption explicitly.
/// What: reads the manifest file directly; a missing file is `Ok(())`; a
/// present but unparseable file is `Err(detail)`.
/// Test: covered by `repair_deploy_corrupt_skill_manifest_is_reported`.
fn validate_skill_manifest(skills_dir: &Path) -> Result<(), String> {
let path = skills_dir.join(SKILL_MANIFEST_FILE);
match std::fs::read_to_string(&path) {
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(e) => Err(format!("{}: {e}", path.display())),
Ok(raw) => serde_json::from_str::<SkillManifest>(&raw)
.map(|_| ())
.map_err(|e| format!("{}: {e}", path.display())),
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
use tempfile::TempDir;
use trusty_mpm::core::agent_manifest::MANIFEST_FILE;
/// Helper: create a minimal agent directory with a stale .tmp file.
fn setup_agents_dir_with_stale_tmp(agents_dir: &Path) {
fs::create_dir_all(agents_dir).unwrap();
// Simulate a stale .tmp orphan from a crashed atomic write.
fs::write(agents_dir.join("engineer.tmp"), "incomplete content").unwrap();
}
#[test]
fn repair_removes_per_attempt_temp_orphans() {
// #4409 regression: `atomic_write` stages through
// `<name>.<pid>.<nanos>.tmp`, and the old cleaner derived a "base" via
// `with_extension("")` then re-derived `base.with_extension("tmp")` —
// which only reconstructs the OLD fixed `<name>.tmp`. Nothing was
// unlinked, yet the path was still reported as removed, so
// `tm repair deploy` claimed a directory was clean while the orphans
// sat there.
//
// The orphans here are produced by the REAL `temp_path`, so this test
// cannot drift from the naming the writer actually emits.
let dir = TempDir::new().unwrap();
let manifest_orphan =
trusty_mpm::core::agent_manifest::temp_path(&dir.path().join(MANIFEST_FILE));
let agent_orphan =
trusty_mpm::core::agent_manifest::temp_path(&dir.path().join("engineer.md"));
fs::write(&manifest_orphan, "half-written json").unwrap();
fs::write(&agent_orphan, "half-written agent").unwrap();
// A real deployed agent that must survive.
fs::write(dir.path().join("engineer.md"), "real agent").unwrap();
let removed = remove_tmp_orphans(dir.path()).unwrap();
assert!(
!manifest_orphan.exists() && !agent_orphan.exists(),
"both per-attempt orphans must actually be unlinked"
);
assert_eq!(
removed.len(),
2,
"the report must name exactly what was unlinked: {removed:?}"
);
assert!(
dir.path().join("engineer.md").exists(),
"a real deployed agent must never be removed"
);
}
#[test]
fn remove_tmp_orphans_reports_only_what_it_unlinked() {
// The count is the other half of the bug: the old code pushed onto
// `removed` unconditionally, so the report was true by construction
// regardless of what happened on disk.
let dir = TempDir::new().unwrap();
fs::write(dir.path().join("engineer.md"), "real agent").unwrap();
let removed = remove_tmp_orphans(dir.path()).unwrap();
assert!(
removed.is_empty(),
"a directory with no orphans must report none removed: {removed:?}"
);
}
#[test]
fn remove_tmp_orphans_removes_only_tmp_files() {
// Only .tmp files must be removed; .md files must be left intact.
let tmp = TempDir::new().unwrap();
fs::write(tmp.path().join("engineer.md"), "good content").unwrap();
fs::write(tmp.path().join("engineer.tmp"), "stale").unwrap();
fs::write(tmp.path().join("other.tmp"), "stale2").unwrap();
let removed = remove_tmp_orphans(tmp.path()).unwrap();
assert_eq!(removed.len(), 2, "expected 2 .tmp files removed");
assert!(
tmp.path().join("engineer.md").exists(),
".md file must survive"
);
assert!(
!tmp.path().join("engineer.tmp").exists(),
".tmp file must be removed"
);
}
#[test]
fn remove_tmp_orphans_is_no_op_on_missing_dir() {
// A non-existent directory must not error — first deploy has no agents dir.
let removed = remove_tmp_orphans(Path::new("/nonexistent/dir/agents")).unwrap();
assert!(removed.is_empty());
}
#[test]
fn validate_skill_manifest_ok_on_missing_file() {
let tmp = TempDir::new().unwrap();
assert!(validate_skill_manifest(tmp.path()).is_ok());
}
#[test]
fn validate_skill_manifest_err_on_corrupt_file() {
let tmp = TempDir::new().unwrap();
fs::write(tmp.path().join(SKILL_MANIFEST_FILE), b"not valid json{{{").unwrap();
assert!(validate_skill_manifest(tmp.path()).is_err());
}
#[test]
fn repair_deploy_removes_stale_tmps() {
// repair_deploy (via remove_tmp_orphans) must remove stale .tmp files
// from the agents dir. We simulate a minimal environment by building
// a temp tree with the expected directory layout.
// NOTE: repair_deploy currently uses dirs::home_dir() directly, so
// it cannot be pointed at a temp directory in a unit test. Instead,
// we test the underlying helpers (remove_tmp_orphans, etc.) directly,
// which is the appropriate unit-test boundary.
let agents_dir = TempDir::new().unwrap();
setup_agents_dir_with_stale_tmp(agents_dir.path());
assert!(agents_dir.path().join("engineer.tmp").exists());
let removed = remove_tmp_orphans(agents_dir.path()).unwrap();
assert_eq!(removed.len(), 1);
assert!(!agents_dir.path().join("engineer.tmp").exists());
}
#[test]
fn repair_deploy_corrupt_manifest_is_reported_without_force() {
// Without --force, a corrupt manifest must not be reset. We verify
// the detection logic via AgentManifest::load_checked.
let tmp = TempDir::new().unwrap();
fs::write(tmp.path().join(MANIFEST_FILE), b"garbage{{{").unwrap();
let result = AgentManifest::load_checked(tmp.path());
assert!(
matches!(result, ManifestLoad::Corrupt(_)),
"corrupt manifest must be detected"
);
// File must still exist (not auto-reset without --force).
assert!(tmp.path().join(MANIFEST_FILE).exists());
}
}