trusty-mpm 1.8.2

trusty-mpm: unified multi-agent orchestration platform (core, daemon, CLI, TUI, Telegram)
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
//! Tests for the `auto_memory` doctor check and its `--fix` repair (#7685).
//!
//! Why: split into a sibling file so `doctor_auto_memory.rs` stays well under
//! the 500-SLOC production cap, the same pattern every other `doctor_*_tests.rs`
//! in this directory uses.
//! What: all three verdicts of [`super::check_auto_memory`] — the same
//! configuration graded against a live and a dead trusty-memory — plus tier
//! precedence, the index half of the directive, and the four repair states.
//! Reachability and the config dir are INJECTED, so no test depends on whether
//! the host happens to be running trusty-memory.
//! Test: this is the test module.

use std::path::{Path, PathBuf};

use super::*;
use crate::core::auto_memory_import::{INDEX_FILE, auto_memory_dir};
use crate::core::doctor::CheckStatus;
use crate::core::memory_reachable::MemoryReachability;

/// Write `<root>/<rel>` with `body`, creating parents.
fn write_settings(root: &Path, rel: &str, body: &str) {
    let path = root.join(rel);
    std::fs::create_dir_all(path.parent().unwrap()).unwrap();
    std::fs::write(path, body).unwrap();
}

/// Seed a Claude config dir whose auto-memory index for `project` holds `body`.
fn write_index(config_dir: &Path, project: &Path, body: &str) -> PathBuf {
    let memory = auto_memory_dir(config_dir, project);
    std::fs::create_dir_all(&memory).unwrap();
    std::fs::write(memory.join(INDEX_FILE), body).unwrap();
    memory.join(INDEX_FILE)
}

/// A home + project pair with `settings` written into the project tier.
fn fixture(settings: Option<&str>) -> (tempfile::TempDir, PathBuf, PathBuf) {
    let tmp = tempfile::TempDir::new().unwrap();
    let home = tmp.path().join("home");
    let project = tmp.path().join("project");
    std::fs::create_dir_all(&home).unwrap();
    std::fs::create_dir_all(&project).unwrap();
    if let Some(body) = settings {
        write_settings(&project, ".claude/settings.json", body);
    }
    (tmp, home, project)
}

const OFF: &str = r#"{"autoMemoryEnabled": false}"#;
const ON: &str = r#"{"autoMemoryEnabled": true}"#;

#[test]
fn auto_memory_fails_when_on_beside_a_healthy_trusty_memory() {
    // 🔴: trusty-memory is up and IS the memory, so auto memory being on is the
    // directive unmet.
    let (_tmp, home, project) = fixture(Some(ON));

    let check = check_auto_memory(Some(&project), &home, None, &MemoryReachability::Reachable);

    assert_eq!(check.status, CheckStatus::Fail, "{}", check.message);
    assert!(
        check.message.contains("project tier"),
        "the row must name the tier it resolved from: {}",
        check.message
    );
    assert!(
        check.message.contains(DISABLE_ENV_VAR),
        "the row must name the env-var lever too: {}",
        check.message
    );
}

#[test]
fn auto_memory_fails_when_unset_beside_a_healthy_trusty_memory() {
    // A settings file that exists and is silent on the key is not a pass —
    // Claude Code defaults auto memory ON.
    let (_tmp, home, project) = fixture(Some(r#"{"outputStyle": "x"}"#));

    let check = check_auto_memory(Some(&project), &home, None, &MemoryReachability::Reachable);

    assert_eq!(check.status, CheckStatus::Fail, "{}", check.message);
    assert!(check.message.contains("unset"), "{}", check.message);
}

#[test]
fn auto_memory_is_ok_when_on_while_trusty_memory_is_down() {
    // ✅: the SAME configuration as the first test. With trusty-memory down,
    // auto memory carrying the project IS the posture the directive asks for —
    // there is nothing here for an operator to do.
    let (_tmp, home, project) = fixture(Some(ON));

    let check = check_auto_memory(
        Some(&project),
        &home,
        None,
        &MemoryReachability::Unreachable,
    );

    assert_eq!(check.status, CheckStatus::Ok, "{}", check.message);
    assert!(
        check.message.contains("FALLBACK"),
        "the row must say why this is the correct state: {}",
        check.message
    );
}

#[test]
fn auto_memory_warns_when_off_while_trusty_memory_is_down() {
    // ⚠️ #7685 r3: the double-loss state. trusty-memory is not answering and the
    // fallback is disabled, so this project has NO memory — and before the
    // two-way write that state was unreachable from `--fix` and reported as a
    // clean `Ok`.
    let (_tmp, home, project) = fixture(Some(OFF));

    let check = check_auto_memory(
        Some(&project),
        &home,
        None,
        &MemoryReachability::Unreachable,
    );

    assert_eq!(check.status, CheckStatus::Warn, "{}", check.message);
    assert!(
        check.message.contains("NO memory"),
        "the row must name the loss: {}",
        check.message
    );
    assert!(
        check.message.contains("tm doctor --fix"),
        "the row must name the repair that restores it: {}",
        check.message
    );
}

#[test]
fn auto_memory_names_a_wedged_trusty_memory_apart_from_a_dead_one() {
    // #7685: a wedged daemon answers its health call, so it is not "down" — but
    // it reports itself unhealthy, so it should not be trusted as the memory
    // either. The row must keep the fallback posture AND say which of the two
    // an operator is looking at.
    let (_tmp, home, project) = fixture(Some(OFF));
    let wedged =
        MemoryReachability::Unhealthy(trusty_common::memory_rpc::MemoryHealthStatus::Wedged);

    let check = check_auto_memory(Some(&project), &home, None, &wedged);
    let dead = check_auto_memory(
        Some(&project),
        &home,
        None,
        &MemoryReachability::Unreachable,
    );

    assert_eq!(check.status, CheckStatus::Warn, "{}", check.message);
    assert!(check.message.contains("WEDGED"), "{}", check.message);
    assert!(!dead.message.contains("WEDGED"), "{}", dead.message);
    assert!(dead.message.contains("unreachable"), "{}", dead.message);
}

#[test]
fn auto_memory_ok_when_off_and_the_index_is_empty() {
    // ✅: off, and nothing stranded in the store it turned off.
    let (_tmp, home, project) = fixture(Some(OFF));
    let config = tempfile::TempDir::new().unwrap();
    write_index(config.path(), &project, "   \n");

    let check = check_auto_memory(
        Some(&project),
        &home,
        Some(config.path()),
        &MemoryReachability::Reachable,
    );

    assert_eq!(check.status, CheckStatus::Ok, "{}", check.message);
    assert!(
        check.message.contains("project tier"),
        "the row must name the tier it resolved from: {}",
        check.message
    );
}

#[test]
fn auto_memory_ok_when_the_project_has_no_auto_memory_store() {
    // An absent store is the same end state as an emptied one.
    let (_tmp, home, project) = fixture(Some(OFF));
    let config = tempfile::TempDir::new().unwrap();

    let check = check_auto_memory(
        Some(&project),
        &home,
        Some(config.path()),
        &MemoryReachability::Reachable,
    );

    assert_eq!(check.status, CheckStatus::Ok, "{}", check.message);
}

#[test]
fn auto_memory_fails_when_the_index_still_holds_facts() {
    // 🔴: the key says off, but the facts are in neither memory — they are
    // sitting in a `MEMORY.md` nothing reads any more.
    let (_tmp, home, project) = fixture(Some(OFF));
    let config = tempfile::TempDir::new().unwrap();
    let index = write_index(config.path(), &project, "- [a fact](a-fact.md) — text\n");

    let check = check_auto_memory(
        Some(&project),
        &home,
        Some(config.path()),
        &MemoryReachability::Reachable,
    );

    assert_eq!(check.status, CheckStatus::Fail, "{}", check.message);
    assert!(
        check.message.contains("tm memory import-auto-memory"),
        "the row must name the migration, which --fix does not run: {}",
        check.message
    );
    assert!(
        check.message.contains(&index.display().to_string()),
        "the row must name the index it read: {}",
        check.message
    );
}

#[test]
fn auto_memory_warns_when_the_index_holds_facts_and_memory_is_down() {
    // Same stranded facts, but nothing can migrate them right now. The disabled
    // fallback is the headline — a project with no memory outranks a migration
    // that cannot run — and the stranded index is named alongside it.
    let (_tmp, home, project) = fixture(Some(OFF));
    let config = tempfile::TempDir::new().unwrap();
    let index = write_index(config.path(), &project, "- [a fact](a-fact.md) — text\n");

    let check = check_auto_memory(
        Some(&project),
        &home,
        Some(config.path()),
        &MemoryReachability::Unreachable,
    );

    assert_eq!(check.status, CheckStatus::Warn, "{}", check.message);
    assert!(check.message.contains("NO memory"), "{}", check.message);
    assert!(
        check.message.contains(&index.display().to_string()),
        "the row must still name the stranded index: {}",
        check.message
    );
}

#[test]
fn auto_memory_project_local_overrides_project() {
    let (_tmp, home, project) = fixture(Some(OFF));
    // The layer Claude Code actually reads first. A project tier tm wrote does
    // not make the setting effective when this one contradicts it.
    write_settings(&project, ".claude/settings.local.json", ON);

    let check = check_auto_memory(Some(&project), &home, None, &MemoryReachability::Reachable);

    assert_eq!(check.status, CheckStatus::Fail, "{}", check.message);
    assert!(
        check.message.contains("project-local"),
        "the row must name the winning tier: {}",
        check.message
    );
}

#[test]
fn auto_memory_falls_back_to_the_user_tier() {
    let (_tmp, home, project) = fixture(None);
    write_settings(&home, ".claude/settings.json", OFF);

    let check = check_auto_memory(Some(&project), &home, None, &MemoryReachability::Reachable);

    assert_eq!(check.status, CheckStatus::Ok, "{}", check.message);
    assert!(
        check.message.contains("user tier"),
        "the row must name the tier it resolved from: {}",
        check.message
    );
}

#[test]
fn auto_memory_fails_on_malformed_json() {
    let (_tmp, home, project) = fixture(Some("not json{{{"));

    // A settings file Claude Code cannot parse is a finding either way round.
    for reachable in [
        MemoryReachability::Reachable,
        MemoryReachability::Unreachable,
    ] {
        let check = check_auto_memory(Some(&project), &home, None, &reachable);
        assert_eq!(check.status, CheckStatus::Fail, "{}", check.message);
        assert!(
            check.message.contains("not valid JSON"),
            "{}",
            check.message
        );
    }
}

#[test]
fn auto_memory_repair_applies_when_absent() {
    let tmp = tempfile::TempDir::new().unwrap();
    let project = tmp.path();
    write_settings(project, ".claude/settings.json", r#"{"outputStyle": "x"}"#);

    let steps = repair_auto_memory(project, RepairMode::Apply, true);

    assert_eq!(steps.len(), 1);
    assert!(steps[0].changed(), "{:?}", steps[0].status);
    let written: serde_json::Value = serde_json::from_str(
        &std::fs::read_to_string(project.join(".claude").join("settings.json")).unwrap(),
    )
    .unwrap();
    assert_eq!(written[AUTO_MEMORY_KEY], serde_json::Value::Bool(false));
    assert_eq!(
        written["outputStyle"], "x",
        "the repair must preserve every other key"
    );
}

#[test]
fn auto_memory_repair_restores_the_fallback_when_memory_is_down() {
    // #7685 r3: the recovery path. A project left `false` by an earlier launch
    // beside a healthy trusty-memory had NO route back once trusty-memory went
    // down — `--fix` only ever wrote `false`, so the double loss was permanent.
    let tmp = tempfile::TempDir::new().unwrap();
    let project = tmp.path();
    write_settings(project, ".claude/settings.json", OFF);

    let steps = repair_auto_memory(project, RepairMode::Apply, false);

    assert_eq!(steps.len(), 1, "a `false` beside a dead daemon is a repair");
    assert!(steps[0].changed(), "{:?}", steps[0].status);
    assert!(
        steps[0].what.contains("restoring the fallback"),
        "the step must say what it is doing: {}",
        steps[0].what
    );
    let written: serde_json::Value = serde_json::from_str(
        &std::fs::read_to_string(project.join(".claude").join("settings.json")).unwrap(),
    )
    .unwrap();
    assert_eq!(
        written[AUTO_MEMORY_KEY],
        serde_json::Value::Bool(true),
        "the fallback must come back on: {written}"
    );

    // And the repair is idempotent in this direction too.
    assert!(repair_auto_memory(project, RepairMode::Apply, false).is_empty());
}

#[test]
fn auto_memory_repair_never_migrates() {
    // #7685: `--fix` writes ONE boolean key. Moving facts between two stores is
    // an operator-run data migration, so a repair must leave the auto-memory
    // store byte-identical — index included.
    let tmp = tempfile::TempDir::new().unwrap();
    let project = tmp.path().join("project");
    std::fs::create_dir_all(&project).unwrap();
    write_settings(&project, ".claude/settings.json", r#"{"outputStyle": "x"}"#);
    let config = tempfile::TempDir::new().unwrap();
    let body = "- [a fact](a-fact.md) — text\n";
    let index = write_index(config.path(), &project, body);
    let fact = index.parent().unwrap().join("a-fact.md");
    std::fs::write(&fact, "---\nname: a-fact\n---\nbody\n").unwrap();

    let steps = repair_auto_memory(&project, RepairMode::Apply, true);

    assert_eq!(steps.len(), 1, "the repair writes the key and nothing else");
    assert_eq!(
        std::fs::read_to_string(&index).unwrap(),
        body,
        "--fix must not empty the index"
    );
    assert!(fact.is_file(), "--fix must not move a fact file");
}

#[test]
fn auto_memory_repair_dry_run_writes_nothing() {
    let tmp = tempfile::TempDir::new().unwrap();
    let project = tmp.path();
    let body = r#"{"outputStyle": "x"}"#;
    write_settings(project, ".claude/settings.json", body);

    let steps = repair_auto_memory(project, RepairMode::DryRun, true);

    assert_eq!(steps.len(), 1);
    assert_eq!(steps[0].status, StepStatus::Planned);
    assert_eq!(
        std::fs::read_to_string(project.join(".claude").join("settings.json")).unwrap(),
        body,
        "a dry run must leave the file byte-identical"
    );
}

#[test]
fn auto_memory_repair_is_silent_when_already_false() {
    let tmp = tempfile::TempDir::new().unwrap();
    let project = tmp.path();
    write_settings(project, ".claude/settings.json", OFF);

    assert!(repair_auto_memory(project, RepairMode::Apply, true).is_empty());
}

#[test]
fn auto_memory_repair_reports_a_write_failure() {
    // Fail-open guard: a repair that could not write must never come back as a
    // success. A DIRECTORY where `settings.json` belongs makes the write fail
    // deterministically without depending on permission bits.
    let tmp = tempfile::TempDir::new().unwrap();
    let project = tmp.path();
    std::fs::create_dir_all(project.join(".claude").join("settings.json")).unwrap();

    let steps = repair_auto_memory(project, RepairMode::Apply, true);

    assert_eq!(steps.len(), 1);
    assert!(
        matches!(steps[0].status, StepStatus::Failed(_)),
        "a failed write must report Failed, not Applied: {:?}",
        steps[0].status
    );
    assert!(
        !steps[0].changed(),
        "a failed write must never count as a change"
    );
}