mentra 0.21.0

An agent runtime for tool-using LLM applications
Documentation
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
use std::{path::PathBuf, time::Duration};

use crate::{
    ContentBlock, Message,
    agent::{AgentConfig, AgentStatus},
    memory::MemoryStore,
    memory::journal::{AgentMemoryState, RunMemoryState},
    provider::ProviderId,
    runtime::{
        AgentStore, LeaseStore, PermissionRuleStore, RunStore, RuntimeError, TaskStore,
        store::{PersistedAgentRecord, now_nanos},
    },
    session::{
        PermissionRuleScope,
        permission::{RememberedRule, RuleKey},
    },
    transcript::{AgentTranscript, TranscriptItem},
};

use super::FileRuntimeStore;

fn temp_root(label: &str) -> PathBuf {
    std::env::temp_dir()
        .join("mentra-file-store-tests")
        .join(format!("{label}-{}-{}", std::process::id(), now_nanos()))
}

fn agent_record(id: &str) -> PersistedAgentRecord {
    PersistedAgentRecord {
        id: id.to_string(),
        runtime_identifier: "test-runtime".to_string(),
        name: format!("agent-{id}"),
        model: "test-model".to_string(),
        provider_id: ProviderId::new("test"),
        config: AgentConfig::default(),
        hidden_tools: Default::default(),
        max_rounds: Some(7),
        teammate_identity: None,
        rounds_since_task: 2,
        idle_requested: false,
        status: AgentStatus::default(),
        subagents: Vec::new(),
    }
}

fn user_entry(text: &str) -> TranscriptItem {
    TranscriptItem::user_turn(Message::user(ContentBlock::text(text)))
}

fn transcript_of(texts: &[&str]) -> AgentTranscript {
    let mut transcript = AgentTranscript::default();
    for text in texts {
        transcript.push(user_entry(text));
    }
    transcript
}

fn memory_with(transcript: AgentTranscript) -> AgentMemoryState {
    AgentMemoryState {
        transcript,
        revision: 3,
        resumable_user_message: Some(Message::user(ContentBlock::text("resume me"))),
        ..AgentMemoryState::default()
    }
}

/// The comparison form of a memory state: its serde JSON, which covers every
/// field, entry id, and ordering the store must preserve.
fn state_value(state: &AgentMemoryState) -> serde_json::Value {
    serde_json::to_value(state).expect("serialize state")
}

fn record_value(record: &PersistedAgentRecord) -> serde_json::Value {
    serde_json::to_value(record).expect("serialize record")
}

fn transcript_line_count(store: &FileRuntimeStore, agent_id: &str) -> usize {
    let path = store.agent_dir(agent_id).join("transcript.jsonl");
    std::fs::read_to_string(path)
        .expect("read transcript log")
        .lines()
        .filter(|line| !line.is_empty())
        .count()
}

// -- AgentStore round trips --

#[test]
fn create_agent_then_load_round_trips_exactly() {
    let store = FileRuntimeStore::new(temp_root("round-trip"));
    let record = agent_record("agent-1");
    let memory = memory_with(transcript_of(&["hello", "world"]));

    store.create_agent(&record, &memory).expect("create agent");
    let loaded = store
        .load_agent("agent-1")
        .expect("load agent")
        .expect("agent present");

    assert_eq!(record_value(&loaded.record), record_value(&record));
    assert_eq!(state_value(&loaded.memory), state_value(&memory));
    assert!(
        loaded.created_at.is_some(),
        "a durable store reports when it first wrote"
    );
    assert!(loaded.updated_at.is_some());
}

#[test]
fn a_branched_transcript_round_trips_with_its_archive_and_leaf() {
    let store = FileRuntimeStore::new(temp_root("branch"));
    let record = agent_record("agent-1");

    let mut transcript = transcript_of(&["0", "1", "2"]);
    let first = transcript.items()[0].id.clone();
    let abandoned_leaf = transcript.leaf().expect("a leaf").clone();
    store
        .create_agent(&record, &memory_with(transcript.clone()))
        .expect("create agent");

    // Branch away and continue elsewhere, saving each state as the runtime
    // would.
    transcript.branch_from(&first).expect("branch");
    transcript.push(user_entry("elsewhere"));
    let memory = memory_with(transcript.clone());
    store
        .save_agent_memory("agent-1", &memory)
        .expect("save branched state");

    let loaded = store
        .load_agent("agent-1")
        .expect("load agent")
        .expect("agent present");
    assert_eq!(loaded.memory.transcript, transcript);
    assert_eq!(loaded.memory.transcript.archived().len(), 2);

    // The reloaded tree can still return to the abandoned branch.
    let mut reloaded = loaded.memory.transcript;
    reloaded
        .branch_from(&abandoned_leaf)
        .expect("return to the abandoned branch");
    assert_eq!(reloaded.items().len(), 3);

    // The leaf file names the active leaf, newline-terminated, for tools
    // that read no JSON.
    let leaf = std::fs::read_to_string(store.agent_dir("agent-1").join("leaf")).expect("read leaf");
    assert_eq!(leaf, format!("{}\n", transcript.leaf().expect("a leaf")));
}

#[test]
fn a_run_baseline_round_trips_and_rolls_back_identically() {
    let store = FileRuntimeStore::new(temp_root("baseline"));
    let record = agent_record("agent-1");

    let baseline = transcript_of(&["before"]);
    let mut transcript = baseline.clone();
    transcript.push(user_entry("during the run"));
    let memory = AgentMemoryState {
        transcript,
        run: Some(RunMemoryState {
            run_id: "run-1".to_string(),
            baseline_transcript: baseline.clone(),
            assistant_committed: false,
        }),
        revision: 9,
        ..AgentMemoryState::default()
    };

    store.create_agent(&record, &memory).expect("create agent");
    let loaded = store
        .load_agent("agent-1")
        .expect("load agent")
        .expect("agent present");

    assert_eq!(state_value(&loaded.memory), state_value(&memory));
    assert_eq!(
        loaded
            .memory
            .run
            .as_ref()
            .expect("run state survives")
            .baseline_transcript,
        baseline,
        "an interrupted run recovered from disk rolls back to the same baseline"
    );
}

#[test]
fn a_replaced_transcript_loads_as_replaced_while_the_log_keeps_history() {
    let store = FileRuntimeStore::new(temp_root("compaction"));
    let record = agent_record("agent-1");
    let original = memory_with(transcript_of(&["a", "b", "c"]));
    store
        .create_agent(&record, &original)
        .expect("create agent");

    // What compaction does: install a wholly new transcript.
    let replacement = memory_with(transcript_of(&["summary of a-c", "d"]));
    store
        .save_agent_memory("agent-1", &replacement)
        .expect("save replacement");

    let loaded = store
        .load_agent("agent-1")
        .expect("load agent")
        .expect("agent present");
    assert_eq!(state_value(&loaded.memory), state_value(&replacement));

    // The log is history: the superseded entries are still greppable.
    assert_eq!(transcript_line_count(&store, "agent-1"), 5);
}

#[test]
fn appends_do_not_duplicate_entries_across_reopen() {
    let root = temp_root("reopen");
    let mut transcript = transcript_of(&["one", "two"]);
    {
        let store = FileRuntimeStore::new(&root);
        store
            .create_agent(&agent_record("agent-1"), &memory_with(transcript.clone()))
            .expect("create agent");
    }

    // A fresh process appends the next turn.
    let store = FileRuntimeStore::new(&root);
    transcript.push(user_entry("three"));
    store
        .save_agent_memory("agent-1", &memory_with(transcript.clone()))
        .expect("save third entry");

    assert_eq!(
        transcript_line_count(&store, "agent-1"),
        3,
        "already-logged entries must not be appended again"
    );
    let loaded = store
        .load_agent("agent-1")
        .expect("load agent")
        .expect("agent present");
    assert_eq!(loaded.memory.transcript, transcript);
}

// -- Crash shapes --

#[test]
fn a_truncated_final_line_is_skipped_and_the_next_append_gets_a_fresh_line() {
    let root = temp_root("truncated");
    let mut transcript = transcript_of(&["one", "two"]);
    let store = FileRuntimeStore::new(&root);
    store
        .create_agent(&agent_record("agent-1"), &memory_with(transcript.clone()))
        .expect("create agent");

    // A crash mid-append: half a line, no newline.
    let log_path = store.agent_dir("agent-1").join("transcript.jsonl");
    let mut contents = std::fs::read(&log_path).expect("read log");
    contents.extend_from_slice(br#"{"schema":1,"id":"entry-trunc"#);
    std::fs::write(&log_path, contents).expect("write truncated log");

    // A fresh process reads past the damage and appends on a fresh line.
    let reopened = FileRuntimeStore::new(&root);
    let loaded = reopened
        .load_agent("agent-1")
        .expect("load agent despite the truncated tail")
        .expect("agent present");
    assert_eq!(loaded.memory.transcript, transcript);

    transcript.push(user_entry("three"));
    reopened
        .save_agent_memory("agent-1", &memory_with(transcript.clone()))
        .expect("append after damage");

    let reloaded = reopened
        .load_agent("agent-1")
        .expect("load agent")
        .expect("agent present");
    assert_eq!(reloaded.memory.transcript, transcript);
    // Every surviving line parses: the damaged tail is gone, not entombed.
    assert_eq!(transcript_line_count(&reopened, "agent-1"), 3);
    for line in std::fs::read_to_string(&log_path)
        .expect("read log")
        .lines()
        .filter(|line| !line.is_empty())
    {
        serde_json::from_str::<serde_json::Value>(line).expect("every kept line parses");
    }
}

#[test]
fn leftover_temp_files_and_stray_entries_are_ignored() {
    let store = FileRuntimeStore::new(temp_root("strays"));
    let record = agent_record("agent-1");
    store
        .create_agent(&record, &memory_with(transcript_of(&["hello"])))
        .expect("create agent");

    // The shapes a crash between write and rename can leave behind.
    let agent_dir = store.agent_dir("agent-1");
    std::fs::write(agent_dir.join(".agent.json.tmp-999-1"), b"{ partial").expect("plant temp file");
    std::fs::write(store.agents_dir().join("not-a-directory"), b"stray").expect("plant stray file");
    std::fs::create_dir_all(store.agents_dir().join("half-created"))
        .expect("plant record-less directory");

    let agents = store.list_agents().expect("list agents");
    assert_eq!(agents.len(), 1, "only the real agent is listed");
    assert_eq!(agents[0].record.id, "agent-1");
    let loaded = store
        .load_agent("agent-1")
        .expect("load agent")
        .expect("agent present");
    assert_eq!(record_value(&loaded.record), record_value(&record));
}

// -- Record lifecycle parity with the other stores --

#[test]
fn save_agent_record_without_memory_errors_on_load() {
    let store = FileRuntimeStore::new(temp_root("no-memory"));
    store
        .save_agent_record(&agent_record("agent-1"))
        .expect("save record");

    let error = store
        .load_agent("agent-1")
        .expect_err("memory is missing until it is saved");
    assert!(matches!(error, RuntimeError::Store(_)));
}

#[test]
fn resaving_a_record_moves_updated_at_and_keeps_created_at() {
    let store = FileRuntimeStore::new(temp_root("timestamps"));
    let mut record = agent_record("agent-1");
    store
        .create_agent(&record, &AgentMemoryState::default())
        .expect("create agent");
    let first = store
        .load_agent("agent-1")
        .expect("load agent")
        .expect("agent present");

    record.name = "renamed".to_string();
    store
        .save_agent_record(&record)
        .expect("save renamed record");
    let second = store
        .load_agent("agent-1")
        .expect("load agent")
        .expect("agent present");

    assert_eq!(second.record.name, "renamed");
    assert_eq!(
        second.created_at, first.created_at,
        "the first write settles created_at for good"
    );
    assert!(second.updated_at >= first.updated_at);
}

#[test]
fn delete_agent_removes_everything_and_deleting_absent_succeeds() {
    let store = FileRuntimeStore::new(temp_root("delete"));
    store
        .create_agent(
            &agent_record("agent-1"),
            &memory_with(transcript_of(&["x"])),
        )
        .expect("create agent");

    store.delete_agent("agent-1").expect("delete agent");

    assert!(store.load_agent("agent-1").expect("load agent").is_none());
    assert!(store.list_agents().expect("list agents").is_empty());
    assert!(!store.agent_dir("agent-1").exists());
    store
        .delete_agent("agent-1")
        .expect("deleting an absent agent succeeds: the goal is that it be gone");
}

#[test]
fn a_crashed_delete_leaves_the_shape_readers_already_ignore() {
    let store = FileRuntimeStore::new(temp_root("partial-delete"));
    let memory = AgentMemoryState::default();
    store
        .create_agent(
            &agent_record("agent-1"),
            &memory_with(transcript_of(&["x"])),
        )
        .expect("create agent-1");
    store
        .create_agent(&agent_record("agent-2"), &memory)
        .expect("create agent-2");

    // The state a delete interrupted between its two steps leaves behind:
    // agent.json gone, the rest of the directory still there.
    std::fs::remove_file(store.agent_dir("agent-1").join("agent.json"))
        .expect("simulate the crash point");

    assert!(
        store
            .load_agent("agent-1")
            .expect("load half-deleted agent")
            .is_none(),
        "a record-less directory is not an agent"
    );
    let ids: Vec<_> = store
        .list_agents()
        .expect("listing survives a half-deleted agent")
        .into_iter()
        .map(|loaded| loaded.record.id)
        .collect();
    assert_eq!(ids, vec!["agent-2".to_string()]);

    // Deleting the remains finishes the job.
    store.delete_agent("agent-1").expect("finish the delete");
    assert!(!store.agent_dir("agent-1").exists());
}

#[test]
fn list_agents_orders_by_creation_and_filters_by_runtime() {
    let store = FileRuntimeStore::new(temp_root("list"));
    let memory = AgentMemoryState::default();
    let mut second = agent_record("agent-b");
    second.runtime_identifier = "other-runtime".to_string();
    store
        .create_agent(&agent_record("agent-a"), &memory)
        .expect("create first");
    store.create_agent(&second, &memory).expect("create second");

    let ids: Vec<_> = store
        .list_agents()
        .expect("list agents")
        .into_iter()
        .map(|loaded| loaded.record.id)
        .collect();
    assert_eq!(ids, vec!["agent-a".to_string(), "agent-b".to_string()]);

    let by_runtime: Vec<_> = store
        .list_agents_by_runtime("other-runtime")
        .expect("list by runtime")
        .into_iter()
        .map(|loaded| loaded.record.id)
        .collect();
    assert_eq!(by_runtime, vec!["agent-b".to_string()]);
}

#[test]
fn an_id_needing_encoding_still_round_trips() {
    let store = FileRuntimeStore::new(temp_root("encoding"));
    let record = agent_record("agent/one two");
    store
        .create_agent(&record, &AgentMemoryState::default())
        .expect("create agent");

    let loaded = store
        .load_agent("agent/one two")
        .expect("load agent")
        .expect("agent present");
    assert_eq!(loaded.record.id, "agent/one two");
    assert_eq!(store.list_agents().expect("list agents").len(), 1);
}

#[test]
fn ids_differing_only_by_case_get_distinct_directories() {
    // macOS and Windows fold case in filenames, so `Agent` and `agent`
    // sharing a directory would silently merge two agents. Mixed case
    // routes to the hex encoding instead.
    let store = FileRuntimeStore::new(temp_root("case"));
    assert_ne!(store.agent_dir("Agent"), store.agent_dir("agent"));

    store
        .create_agent(&agent_record("Agent"), &AgentMemoryState::default())
        .expect("create Agent");
    store
        .create_agent(&agent_record("agent"), &AgentMemoryState::default())
        .expect("create agent");

    assert_eq!(
        store
            .load_agent("Agent")
            .expect("load Agent")
            .expect("Agent present")
            .record
            .id,
        "Agent"
    );
    assert_eq!(
        store
            .load_agent("agent")
            .expect("load agent")
            .expect("agent present")
            .record
            .id,
        "agent"
    );
    assert_eq!(store.list_agents().expect("list agents").len(), 2);
}

#[test]
fn hazardous_names_route_to_the_encoded_form() {
    let store = FileRuntimeStore::new(temp_root("hazard"));
    // Windows device names (with or without extension), a trailing dot,
    // anything shaped like an encoded name, mixed case, and dotfiles all
    // take the hex path.
    for id in [
        "con", "con.log", "com1", "lpt9", "foo.", "x-6162", "Agent", ".hidden",
    ] {
        let dir_name = store
            .agent_dir(id)
            .file_name()
            .and_then(|name| name.to_str())
            .expect("dir name")
            .to_string();
        assert!(
            dir_name.starts_with("x-"),
            "'{id}' must be encoded, got '{dir_name}'"
        );
    }
    // A tame id stays readable on disk, and com0/lpt0 are not reserved.
    for id in ["agent-1", "com0", "lpt0", "foo.log", "conx"] {
        let dir_name = store
            .agent_dir(id)
            .file_name()
            .and_then(|name| name.to_str())
            .expect("dir name")
            .to_string();
        assert_eq!(dir_name, id, "'{id}' needs no encoding");
    }
}

#[test]
fn a_file_from_a_newer_schema_is_refused_not_misread() {
    let store = FileRuntimeStore::new(temp_root("schema"));
    store
        .create_agent(&agent_record("agent-1"), &AgentMemoryState::default())
        .expect("create agent");

    let path = store.agent_dir("agent-1").join("agent.json");
    let rewritten = std::fs::read_to_string(&path)
        .expect("read agent.json")
        .replacen("\"schema\": 1", "\"schema\": 99", 1);
    std::fs::write(&path, rewritten).expect("write future schema");

    let error = store
        .load_agent("agent-1")
        .expect_err("a future schema must be refused");
    assert!(error.to_string().contains("schema"), "{error}");
}

// -- Permission rules --

fn rule(tool_name: &str, allow: bool, scope: PermissionRuleScope) -> RememberedRule {
    RememberedRule {
        key: RuleKey {
            tool_name: tool_name.to_string(),
            pattern: None,
        },
        allow,
        scope,
        reason: None,
    }
}

#[test]
fn permission_rules_round_trip_across_scopes_and_reopen() {
    let root = temp_root("rules");
    {
        let store = FileRuntimeStore::new(&root);
        store
            .save_rules(
                "session-1",
                Some("proj-x"),
                &[
                    rule("shell", true, PermissionRuleScope::Session),
                    rule("read", false, PermissionRuleScope::Project),
                    rule("write", false, PermissionRuleScope::Global),
                ],
            )
            .expect("save rules");
    }

    // A restarted process sees the same rules.
    let store = FileRuntimeStore::new(&root);
    let with_project = store
        .load_rules("session-1", Some("proj-x"))
        .expect("load with project");
    assert_eq!(with_project.len(), 3);

    let other_session = store
        .load_rules("session-2", None)
        .expect("load other session");
    assert_eq!(
        other_session.len(),
        1,
        "only the global rule crosses sessions"
    );
    assert_eq!(other_session[0].key.tool_name, "write");

    store.clear_rules("session-1").expect("clear session");
    assert!(
        store
            .load_rules("session-1", Some("proj-x"))
            .expect("load after clear")
            .is_empty()
    );
}

#[test]
fn repeated_saves_keep_one_copy_of_each_rule() {
    let store = FileRuntimeStore::new(temp_root("rules-dedup"));
    let remembered = [
        rule("shell", true, PermissionRuleScope::Session),
        rule("read", false, PermissionRuleScope::Project),
        rule("write", false, PermissionRuleScope::Global),
    ];

    // Every save carries the session's whole remembered set, project and
    // global rules included — this used to duplicate the non-session rows
    // once per save.
    for _ in 0..4 {
        store
            .save_rules("session-1", Some("proj-x"), &remembered)
            .expect("save rules");
    }

    let loaded = store
        .load_rules("session-1", Some("proj-x"))
        .expect("load rules");
    assert_eq!(loaded.len(), 3, "each rule loads exactly once: {loaded:?}");

    let on_disk: serde_json::Value = serde_json::from_str(
        &std::fs::read_to_string(store.rules_path()).expect("read rules.json"),
    )
    .expect("parse rules.json");
    assert_eq!(
        on_disk["rules"].as_array().expect("rules array").len(),
        3,
        "the file holds one copy of each rule"
    );
}

#[test]
fn saving_rules_replaces_only_that_sessions_session_scope() {
    let store = FileRuntimeStore::new(temp_root("rules-replace"));
    store
        .save_rules(
            "session-1",
            Some("proj-x"),
            &[
                rule("shell", true, PermissionRuleScope::Session),
                rule("read", false, PermissionRuleScope::Project),
            ],
        )
        .expect("save initial");

    store
        .save_rules(
            "session-1",
            Some("proj-x"),
            &[rule("write", false, PermissionRuleScope::Session)],
        )
        .expect("save replacement");

    let loaded = store
        .load_rules("session-1", Some("proj-x"))
        .expect("load rules");
    let mut tools: Vec<_> = loaded
        .iter()
        .map(|rule| rule.key.tool_name.as_str())
        .collect();
    tools.sort_unstable();
    assert_eq!(
        tools,
        vec!["read", "write"],
        "the project rule survives a session-scope replacement"
    );
}

// -- Runs --

#[test]
fn run_lifecycle_is_an_append_only_event_log() {
    let store = FileRuntimeStore::new(temp_root("runs"));
    let run_id = store.start_run("agent-1").expect("start run");
    store.finish_run(&run_id).expect("finish run");
    store
        .fail_run("run-from-a-previous-process", "interrupted")
        .expect("a transition for an unseen run id is still recorded");

    let contents = std::fs::read_to_string(store.runs_path()).expect("read runs.jsonl");
    let events: Vec<serde_json::Value> = contents
        .lines()
        .filter(|line| !line.is_empty())
        .map(|line| serde_json::from_str(line).expect("event line parses"))
        .collect();
    assert_eq!(events.len(), 3);
    assert_eq!(events[0]["run_id"], serde_json::json!(run_id));
    assert_eq!(events[0]["state"], serde_json::json!("running"));
    assert_eq!(events[0]["agent_id"], serde_json::json!("agent-1"));
    assert_eq!(events[1]["state"], serde_json::json!("finished"));
    assert_eq!(events[2]["state"], serde_json::json!("failed"));
    assert_eq!(events[2]["error"], serde_json::json!("interrupted"));
}

// -- The deliberately-not-persisted subsystems --

#[test]
fn long_term_memory_is_refused_with_the_fix_named() {
    let store = FileRuntimeStore::new(temp_root("memory"));
    let error = store
        .upsert_records(&[])
        .expect_err("the file store refuses long-term memory");
    assert!(error.to_string().contains("store-sqlite"), "{error}");
    assert!(
        store.search_records("agent-1", "anything", 5).is_err(),
        "search is refused the same way"
    );
}

#[test]
fn leases_exclude_independent_stores_until_released() {
    let root = temp_root("leases");
    let first = FileRuntimeStore::new(&root);
    // An independently constructed store on the same root holds the OS
    // lock the way another process would.
    let second = FileRuntimeStore::new(&root);
    let ttl = Duration::from_secs(3600);

    assert!(
        first
            .acquire_lease("agent:x", "runtime-1", ttl)
            .expect("acquire")
    );
    assert!(
        !first
            .acquire_lease("agent:x", "runtime-1", ttl)
            .expect("re-acquire"),
        "a held lease refuses even its own owner, as the SQLite store does"
    );
    assert!(
        !second
            .acquire_lease("agent:x", "runtime-2", ttl)
            .expect("contended acquire"),
        "the file lock excludes an independent store on the same root"
    );

    // Releasing under the wrong owner changes nothing.
    first
        .release_lease("agent:x", "runtime-9")
        .expect("mismatched release");
    assert!(
        !second
            .acquire_lease("agent:x", "runtime-2", ttl)
            .expect("still held")
    );

    first
        .release_lease("agent:x", "runtime-1")
        .expect("release");
    assert!(
        second
            .acquire_lease("agent:x", "runtime-2", ttl)
            .expect("acquire after release"),
        "a released lease is immediately acquirable elsewhere"
    );
}

#[test]
fn tasks_work_in_process() {
    let store = FileRuntimeStore::new(temp_root("volatile"));
    let namespace = std::path::Path::new("/tasks/example");
    store
        .replace_tasks(namespace, &[])
        .expect("task board is usable");
    assert!(store.load_tasks(namespace).expect("load tasks").is_empty());
}

#[cfg(not(feature = "store-sqlite"))]
#[test]
fn an_existing_sqlite_store_is_diagnosed_not_shadowed() {
    // A root that holds runtime.sqlite is a workspace whose sessions live
    // in a database this build cannot read. Starting an empty file store
    // beside it would look exactly like data loss; the build must fail
    // with the diagnosis instead.
    let root = temp_root("migration");
    std::fs::create_dir_all(&root).expect("create root");
    std::fs::write(root.join("runtime.sqlite"), b"SQLite format 3\0").expect("plant database");

    let store = FileRuntimeStore::new(&root);
    let error = store
        .prepare_recovery()
        .expect_err("an unreadable existing store must be named, not shadowed");
    let message = error.to_string();
    assert!(message.contains("runtime.sqlite"), "{message}");
    assert!(message.contains("store-sqlite"), "{message}");
}

#[test]
fn prepare_recovery_creates_the_store_home() {
    let root = temp_root("recovery");
    let store = FileRuntimeStore::new(&root);
    assert!(!root.exists(), "construction alone touches nothing");

    store.prepare_recovery().expect("prepare recovery");
    assert!(store.agents_dir().is_dir());
}