rusty-agent-server 0.12.0

The durable agent runtime built in Rust — HTTP/SSE server: an Agent-Protocol subset with threads, background runs, checkpoints, and resumable streaming.
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
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
//! Governed memory integration tests (R0.8 Rusty Learn, wave 1): the
//! `/memory` HTTP surface over the default JSON-file backend — write
//! gates (scope authorization), content-address dedupe, structured
//! retrieval with the token-bounded assembly, tenant isolation,
//! artifact spill with self-contained reads, restart durability (the
//! wave-1 exit criterion 1a), and route-journaled memory events
//! landing in a run's Flight Recorder journal.
//!
//! Driven in-process via `tower::ServiceExt::oneshot` (no sockets), the
//! `flight_recorder.rs` convention. Live-Postgres coverage of the same
//! semantics (exit criterion 1b) is the gated section at the bottom.
//!
//! The journaled-events test needs a completed run's persisted journal,
//! so one small pipeline graph is registered (the flight-recorder
//! harness's); every other test keeps the registry empty.

use std::path::PathBuf;

use axum::body::{to_bytes, Body, Bytes};
use axum::http::{Request, StatusCode};
use axum::Router;
use rusty_agent_server::{router, GraphRegistry, ServerConfig};
use serde_json::{json, Value};
use tower::ServiceExt;

// --------------------------------------------------------------------- //
// Harness
// --------------------------------------------------------------------- //

/// Unique temp store root, removed at the end of each test (best effort).
fn temp_store() -> PathBuf {
    std::env::temp_dir().join(format!("rusty-server-memory-test-{}", uuid::Uuid::new_v4()))
}

/// Open-mode (single `default` tenant) app over a fresh store.
fn app() -> (Router, PathBuf) {
    let store = temp_store();
    (app_at(store.clone()), store)
}

/// Open-mode app over a given store root (restart tests build it twice).
fn app_at(store: PathBuf) -> Router {
    let config = ServerConfig::new("127.0.0.1:0".parse().unwrap(), store);
    router(GraphRegistry::new(), config)
}

/// Two-tenant app for the isolation tests.
fn multi_tenant_app() -> (Router, PathBuf) {
    let store = temp_store();
    let config = ServerConfig::new("127.0.0.1:0".parse().unwrap(), store.clone())
        .with_tenant_key("acme", "acme-secret")
        .with_tenant_key("globex", "globex-secret");
    (router(GraphRegistry::new(), config), store)
}

/// Send a request; returns `(status, json-body-or-null)`.
async fn call(app: &Router, method: &str, uri: &str, body: Option<Value>) -> (StatusCode, Value) {
    call_as(app, None, method, uri, body).await
}

/// Send a request with an optional auth header.
async fn call_as(
    app: &Router,
    auth: Option<(&str, &str)>,
    method: &str,
    uri: &str,
    body: Option<Value>,
) -> (StatusCode, Value) {
    let mut builder = Request::builder().method(method).uri(uri);
    if let Some((k, v)) = auth {
        builder = builder.header(k, v);
    }
    let body = match body {
        Some(v) => {
            builder = builder.header("content-type", "application/json");
            Body::from(v.to_string())
        }
        None => Body::empty(),
    };
    let response = app
        .clone()
        .oneshot(builder.body(body).unwrap())
        .await
        .unwrap();
    let status = response.status();
    let bytes: Bytes = to_bytes(response.into_body(), usize::MAX).await.unwrap();
    let value = if bytes.is_empty() {
        Value::Null
    } else {
        serde_json::from_slice(&bytes).unwrap_or(Value::Null)
    };
    (status, value)
}

/// A human-authored write payload; fields merge over the defaults.
fn write_payload(overrides: Value) -> Value {
    let mut base = json!({
        "kind": "fact",
        "scope": {"scope": "user", "id": "user-7"},
        "content": {"timezone": "Asia/Dubai"},
        "author": {"type": "human", "human_id": "amjad"},
    });
    let base_map = base.as_object_mut().unwrap();
    for (key, value) in overrides.as_object().unwrap() {
        base_map.insert(key.clone(), value.clone());
    }
    base
}

/// Write a record; asserts 201 and returns the response body.
async fn write(app: &Router, payload: Value) -> Value {
    let (status, v) = call(app, "POST", "/memory", Some(payload)).await;
    assert_eq!(status, StatusCode::CREATED, "write failed: {v}");
    assert_eq!(v["created"], json!(true));
    v
}

// --------------------------------------------------------------------- //
// Round trip, dedupe, restart durability
// --------------------------------------------------------------------- //

#[tokio::test]
async fn memory_write_read_query_round_trip() {
    let (app, store) = app();
    let v = write(
        &app,
        write_payload(json!({"key": "timezone", "tags": ["prefs"]})),
    )
    .await;
    let memory_id = v["memory_id"].as_str().unwrap().to_string();
    // Content addressing: a 64-char hex digest.
    assert_eq!(memory_id.len(), 64);
    // Human-authored confidence defaults to 1.0; provenance is mandatory
    // and travels with the record.
    assert_eq!(v["record"]["confidence"], json!(1.0));
    assert_eq!(
        v["record"]["provenance"]["author"],
        json!({"type": "human", "human_id": "amjad"})
    );
    assert_eq!(
        v["record"]["scope"],
        json!({"scope": "user", "id": "user-7"})
    );

    // GET by content address returns the same record.
    let (status, got) = call(&app, "GET", &format!("/memory/{memory_id}"), None).await;
    assert_eq!(status, StatusCode::OK, "get failed: {got}");
    assert_eq!(got, v["record"]);

    // Structured query by scope + key + tags finds it.
    let (status, v) = call(
        &app,
        "POST",
        "/memory/query",
        Some(json!({
            "scope": {"scope": "user", "id": "user-7"},
            "key": "timezone",
            "tags": ["prefs"],
        })),
    )
    .await;
    assert_eq!(status, StatusCode::OK, "query failed: {v}");
    let records = v["records"].as_array().unwrap();
    assert_eq!(records.len(), 1);
    assert_eq!(records[0]["memory_id"], json!(memory_id));
    // A non-matching tag misses (equality, every listed tag).
    let (_, v) = call(
        &app,
        "POST",
        "/memory/query",
        Some(json!({"tags": ["prefs", "other"]})),
    )
    .await;
    assert_eq!(v["records"].as_array().unwrap().len(), 0);

    let _ = std::fs::remove_dir_all(store);
}

#[tokio::test]
async fn memory_dedupe_returns_created_false() {
    let (app, store) = app();
    // `written_at` is part of provenance, and provenance is part of the
    // content address — so the idempotent-retry case names its learning
    // instant explicitly (the default is per-request `now`, and two
    // genuinely different learnings of the same content are distinct
    // records by design).
    let learned = json!({"written_at": "2026-01-15T10:00:00Z"});
    let first = write(&app, write_payload(learned.clone())).await;
    // The identical write (same content + provenance ⇒ same address) does
    // not create: 200 with `created: false` and the same memory id.
    let (status, second) = call(&app, "POST", "/memory", Some(write_payload(learned))).await;
    assert_eq!(status, StatusCode::OK, "dedupe write failed: {second}");
    assert_eq!(second["created"], json!(false));
    assert_eq!(second["memory_id"], first["memory_id"]);
    // A different provenance is a different record (origin is identity).
    let other = write(
        &app,
        write_payload(json!({
            "written_at": "2026-01-15T10:00:00Z",
            "author": {"type": "human", "human_id": "reviewer"},
        })),
    )
    .await;
    assert_ne!(other["memory_id"], first["memory_id"]);
    let _ = std::fs::remove_dir_all(store);
}

/// Wave-1 exit criterion 1a: memory survives a server restart on the
/// JSON-file backend.
#[tokio::test]
async fn memory_survives_a_server_restart() {
    let (first_app, store) = app();
    let written = write(
        &first_app,
        write_payload(json!({"key": "timezone", "tags": ["prefs"]})),
    )
    .await;
    let memory_id = written["memory_id"].as_str().unwrap().to_string();
    drop(first_app);

    // Rebuild the server over the same store root: the record reads back
    // by address and answers the same query.
    let second_app = app_at(store.clone());
    let (status, got) = call(&second_app, "GET", &format!("/memory/{memory_id}"), None).await;
    assert_eq!(status, StatusCode::OK, "get after restart failed: {got}");
    assert_eq!(got, written["record"]);
    let (status, v) = call(
        &second_app,
        "POST",
        "/memory/query",
        Some(json!({"scope": {"scope": "user", "id": "user-7"}})),
    )
    .await;
    assert_eq!(status, StatusCode::OK, "query after restart failed: {v}");
    assert_eq!(v["records"].as_array().unwrap().len(), 1);
    let _ = std::fs::remove_dir_all(store);
}

// --------------------------------------------------------------------- //
// Write gates (scope authorization)
// --------------------------------------------------------------------- //

#[tokio::test]
async fn memory_write_gates_enforce_scope_authorization() {
    let (app, store) = app();

    // Run scope is runtime-only.
    let (status, v) = call(
        &app,
        "POST",
        "/memory",
        Some(write_payload(
            json!({"scope": {"scope": "run", "id": "run-1"}}),
        )),
    )
    .await;
    assert_eq!(status, StatusCode::BAD_REQUEST, "run scope must 400: {v}");

    // Agent scope: unknown agent → 404.
    let (status, v) = call(
        &app,
        "POST",
        "/memory",
        Some(write_payload(
            json!({"scope": {"scope": "agent", "id": "ghost"}}),
        )),
    )
    .await;
    assert_eq!(status, StatusCode::NOT_FOUND, "unknown agent must 404: {v}");

    // Agent scope: a registered agent whose manifest does NOT declare the
    // private state scope → 403.
    let (status, v) = call(
        &app,
        "POST",
        "/agents",
        Some(json!({
            "agent_id": "unscoped",
            "manifest": {"agent_kind": "researcher", "manifest_version": "researcher/1.0.0"},
        })),
    )
    .await;
    assert_eq!(status, StatusCode::CREATED, "register failed: {v}");
    let (status, v) = call(
        &app,
        "POST",
        "/memory",
        Some(write_payload(
            json!({"scope": {"scope": "agent", "id": "unscoped"}}),
        )),
    )
    .await;
    assert_eq!(
        status,
        StatusCode::FORBIDDEN,
        "undeclared private scope must 403: {v}"
    );

    // Agent scope: with `private` declared the write lands.
    let (status, v) = call(
        &app,
        "POST",
        "/agents",
        Some(json!({
            "agent_id": "researcher-7",
            "manifest": {
                "agent_kind": "researcher",
                "manifest_version": "researcher/1.4.0",
                "scopes": ["private", "team"],
            },
        })),
    )
    .await;
    assert_eq!(status, StatusCode::CREATED, "register failed: {v}");
    let (status, v) = call(
        &app,
        "POST",
        "/memory",
        Some(write_payload(json!({
            "scope": {"scope": "agent", "id": "researcher-7"},
            "author": {"type": "agent", "agent_id": "researcher-7"},
            "confidence": 0.8,
        }))),
    )
    .await;
    assert_eq!(
        status,
        StatusCode::CREATED,
        "declared agent scope must write: {v}"
    );

    // Tenant scope: the scope id must be the caller's own tenant (open
    // mode runs as `default`).
    let (status, v) = call(
        &app,
        "POST",
        "/memory",
        Some(write_payload(
            json!({"scope": {"scope": "tenant", "id": "acme"}}),
        )),
    )
    .await;
    assert_eq!(
        status,
        StatusCode::FORBIDDEN,
        "foreign tenant scope must 403: {v}"
    );
    let (status, v) = call(
        &app,
        "POST",
        "/memory",
        Some(write_payload(
            json!({"scope": {"scope": "tenant", "id": "default"}}),
        )),
    )
    .await;
    assert_eq!(
        status,
        StatusCode::CREATED,
        "own tenant scope must write: {v}"
    );

    // Confidence: required for non-human authors.
    let (status, v) = call(
        &app,
        "POST",
        "/memory",
        Some(write_payload(json!({
            "author": {"type": "distiller", "name": "nightly"},
            "content": {"distilled": true},
        }))),
    )
    .await;
    assert_eq!(
        status,
        StatusCode::BAD_REQUEST,
        "missing confidence must 400: {v}"
    );
    // …and rejected outside (0, 1].
    let (status, v) = call(
        &app,
        "POST",
        "/memory",
        Some(write_payload(
            json!({"confidence": 1.5, "content": {"other": 1}}),
        )),
    )
    .await;
    assert_eq!(
        status,
        StatusCode::BAD_REQUEST,
        "out-of-range confidence must 400: {v}"
    );

    let _ = std::fs::remove_dir_all(store);
}

// --------------------------------------------------------------------- //
// Retrieval semantics: filters, ranking, budget, supersession, expiry
// --------------------------------------------------------------------- //

/// Three user-7 records with distinct ranks, plus one user-8 record:
/// priorities 10 / 0 / 0, confidences 0.5 / 0.9 / 0.3.
async fn seed_ranked(app: &Router) -> (String, String, String) {
    let high_priority = write(
        app,
        write_payload(json!({
            "content": {"fact": "low-confidence-but-prioritized"},
            "priority": 10,
            "confidence": 0.5,
            "tags": ["ranked"],
        })),
    )
    .await;
    let high_confidence = write(
        app,
        write_payload(json!({
            "content": {"fact": "confident"},
            "confidence": 0.9,
            "tags": ["ranked"],
        })),
    )
    .await;
    let low_confidence = write(
        app,
        write_payload(json!({
            "content": {"fact": "unsure"},
            "confidence": 0.3,
            "tags": ["ranked"],
        })),
    )
    .await;
    write(
        app,
        write_payload(json!({
            "scope": {"scope": "user", "id": "user-8"},
            "content": {"fact": "someone-else"},
        })),
    )
    .await;
    (
        high_priority["memory_id"].as_str().unwrap().to_string(),
        high_confidence["memory_id"].as_str().unwrap().to_string(),
        low_confidence["memory_id"].as_str().unwrap().to_string(),
    )
}

#[tokio::test]
async fn memory_query_filters_rank_and_budget() {
    let (app, store) = app();
    let (prioritized, confident, unsure) = seed_ranked(&app).await;

    // Scope + kind filter, no budget: the assembly's total order —
    // priority first, then confidence.
    let (status, v) = call(
        &app,
        "POST",
        "/memory/query",
        Some(json!({"scope": {"scope": "user", "id": "user-7"}, "kinds": ["fact"]})),
    )
    .await;
    assert_eq!(status, StatusCode::OK, "query failed: {v}");
    let ids: Vec<&str> = v["records"]
        .as_array()
        .unwrap()
        .iter()
        .map(|r| r["memory_id"].as_str().unwrap())
        .collect();
    assert_eq!(
        ids,
        vec![prioritized.as_str(), confident.as_str(), unsure.as_str()]
    );

    // min_confidence filters before ranking.
    let (_, v) = call(
        &app,
        "POST",
        "/memory/query",
        Some(json!({
            "scope": {"scope": "user", "id": "user-7"},
            "min_confidence": 0.4,
        })),
    )
    .await;
    let ids: Vec<&str> = v["records"]
        .as_array()
        .unwrap()
        .iter()
        .map(|r| r["memory_id"].as_str().unwrap())
        .collect();
    assert_eq!(ids, vec![prioritized.as_str(), confident.as_str()]);

    // A budget answers the assembly shape: ranked ids, packed records,
    // the accounting the packing applied. Generous budget → all three.
    let (status, v) = call(
        &app,
        "POST",
        "/memory/query",
        Some(json!({
            "scope": {"scope": "user", "id": "user-7"},
            "budget": {"max_tokens": 100000},
        })),
    )
    .await;
    assert_eq!(status, StatusCode::OK, "budgeted query failed: {v}");
    assert_eq!(v["truncated"], json!(false));
    assert_eq!(v["memory_ids"], json!([prioritized, confident, unsure]));
    assert_eq!(v["token_accounting"]["budget_tokens"], json!(100000));
    assert_eq!(v["token_accounting"]["bytes_per_token"], json!(4));
    assert_eq!(v["token_accounting"]["margin_percent"], json!(20));

    // A tight budget truncates honestly: the top-ranked record fits, the
    // rest drop with `truncated: true`.
    let (_, v) = call(
        &app,
        "POST",
        "/memory/query",
        Some(json!({
            "scope": {"scope": "user", "id": "user-7"},
            "budget": {"max_tokens": 15},
        })),
    )
    .await;
    assert_eq!(v["truncated"], json!(true));
    assert_eq!(v["memory_ids"].as_array().unwrap().len(), 1);

    // A hard budget (overflow: fail) refuses loudly → 422.
    let (status, v) = call(
        &app,
        "POST",
        "/memory/query",
        Some(json!({
            "scope": {"scope": "user", "id": "user-7"},
            "budget": {"max_tokens": 15, "overflow": "fail"},
        })),
    )
    .await;
    assert_eq!(
        status,
        StatusCode::UNPROCESSABLE_ENTITY,
        "hard overflow must 422: {v}"
    );

    let _ = std::fs::remove_dir_all(store);
}

#[tokio::test]
async fn memory_supersession_and_expiry_are_retrieval_filters() {
    let (app, store) = app();
    let original = write(&app, write_payload(json!({"key": "timezone"}))).await;
    let replacement = write(
        &app,
        write_payload(json!({
            "content": {"timezone": "Asia/Riyadh"},
            "key": "timezone",
            "supersedes": original["memory_id"],
        })),
    )
    .await;

    // Default retrieval hides the superseded record; it is retained as
    // evidence (still fetchable by address) and explicit on request.
    let (_, v) = call(
        &app,
        "POST",
        "/memory/query",
        Some(json!({"key": "timezone"})),
    )
    .await;
    let ids: Vec<&str> = v["records"]
        .as_array()
        .unwrap()
        .iter()
        .map(|r| r["memory_id"].as_str().unwrap())
        .collect();
    assert_eq!(ids, vec![replacement["memory_id"].as_str().unwrap()]);
    let (_, v) = call(
        &app,
        "POST",
        "/memory/query",
        Some(json!({"key": "timezone", "include_superseded": true})),
    )
    .await;
    assert_eq!(v["records"].as_array().unwrap().len(), 2);
    let (status, _) = call(
        &app,
        "GET",
        &format!("/memory/{}", original["memory_id"].as_str().unwrap()),
        None,
    )
    .await;
    assert_eq!(
        status,
        StatusCode::OK,
        "superseded is retained, not deleted"
    );

    // Expiry: a record past its TTL drops out of default retrieval, is
    // explicit on request. (Expiry evaluates against `as_of`, resolved
    // at read time.)
    let expired = write(
        &app,
        write_payload(json!({
            "content": {"promo": "ended"},
            "expires_at": "2000-01-01T00:00:00Z",
        })),
    )
    .await;
    let (_, v) = call(
        &app,
        "POST",
        "/memory/query",
        Some(json!({"scope": {"scope": "user", "id": "user-7"}})),
    )
    .await;
    let ids: Vec<&str> = v["records"]
        .as_array()
        .unwrap()
        .iter()
        .map(|r| r["memory_id"].as_str().unwrap())
        .collect();
    assert!(!ids.contains(&expired["memory_id"].as_str().unwrap()));
    let (_, v) = call(
        &app,
        "POST",
        "/memory/query",
        Some(json!({"include_expired": true})),
    )
    .await;
    let ids: Vec<&str> = v["records"]
        .as_array()
        .unwrap()
        .iter()
        .map(|r| r["memory_id"].as_str().unwrap())
        .collect();
    assert!(ids.contains(&expired["memory_id"].as_str().unwrap()));

    // Validity-at-time: the window must contain `valid_at`.
    let (_, v) = call(
        &app,
        "POST",
        "/memory/query",
        Some(json!({"key": "timezone", "valid_at": "1990-01-01T00:00:00Z"})),
    )
    .await;
    assert_eq!(
        v["records"].as_array().unwrap().len(),
        0,
        "nothing was true in 1990"
    );

    let _ = std::fs::remove_dir_all(store);
}

/// A summary supersedes the sources it names in
/// `evidence.source_memory_ids` (wave 2): consolidation supersedes what
/// it consolidates, so default retrieval serves the summary alone while
/// the sources stay queryable as evidence.
#[tokio::test]
async fn memory_summary_supersedes_its_sources_in_default_retrieval() {
    let (app, store) = app();
    let a = write(&app, write_payload(json!({"content": {"fact": "alpha"}}))).await;
    let b = write(&app, write_payload(json!({"content": {"fact": "beta"}}))).await;
    let source_ids = vec![
        a["memory_id"].as_str().unwrap().to_string(),
        b["memory_id"].as_str().unwrap().to_string(),
    ];
    let summary = write(
        &app,
        write_payload(json!({
            "kind": "summary",
            "content": {"combined": ["alpha", "beta"]},
            "author": {"type": "distiller", "name": "test-distiller"},
            "confidence": 1.0,
            "evidence": {"source_memory_ids": source_ids},
        })),
    )
    .await;

    let (_, v) = call(
        &app,
        "POST",
        "/memory/query",
        Some(json!({"scope": {"scope": "user", "id": "user-7"}})),
    )
    .await;
    let ids: Vec<&str> = v["records"]
        .as_array()
        .unwrap()
        .iter()
        .map(|r| r["memory_id"].as_str().unwrap())
        .collect();
    assert_eq!(
        ids,
        vec![summary["memory_id"].as_str().unwrap()],
        "default retrieval serves the summary alone"
    );
    let (_, v) = call(
        &app,
        "POST",
        "/memory/query",
        Some(json!({
            "scope": {"scope": "user", "id": "user-7"},
            "include_superseded": true,
        })),
    )
    .await;
    assert_eq!(
        v["records"].as_array().unwrap().len(),
        3,
        "sources stay queryable as evidence"
    );

    let _ = std::fs::remove_dir_all(store);
}

// --------------------------------------------------------------------- //
// Tenant isolation
// --------------------------------------------------------------------- //

#[tokio::test]
async fn memory_is_tenant_isolated() {
    let (app, store) = multi_tenant_app();
    let acme = Some(("x-api-key", "acme-secret"));
    let globex = Some(("x-api-key", "globex-secret"));

    let (status, v) = call_as(
        &app,
        acme,
        "POST",
        "/memory",
        Some(write_payload(json!({}))),
    )
    .await;
    assert_eq!(status, StatusCode::CREATED, "acme write failed: {v}");
    let memory_id = v["memory_id"].as_str().unwrap().to_string();

    // Cross-tenant reads are 404, never 403 — the other tenant's memory
    // simply does not exist here.
    let (status, _) = call_as(&app, globex, "GET", &format!("/memory/{memory_id}"), None).await;
    assert_eq!(status, StatusCode::NOT_FOUND);
    // …and queries never leak across the boundary.
    let (_, v) = call_as(&app, globex, "POST", "/memory/query", Some(json!({}))).await;
    assert_eq!(v["records"].as_array().unwrap().len(), 0);
    let (_, v) = call_as(&app, acme, "POST", "/memory/query", Some(json!({}))).await;
    assert_eq!(v["records"].as_array().unwrap().len(), 1);

    // The default tenant's namespace is the unprefixed one: an open-mode
    // server over the same store sees neither tenant's records.
    let default_app = app_at(store.clone());
    let (_, v) = call(&default_app, "POST", "/memory/query", Some(json!({}))).await;
    assert_eq!(v["records"].as_array().unwrap().len(), 0);

    let _ = std::fs::remove_dir_all(store);
}

// --------------------------------------------------------------------- //
// Artifact spill
// --------------------------------------------------------------------- //

#[tokio::test]
async fn memory_artifact_spill_serves_self_contained_records() {
    let (first_app, store) = app();
    // A body past the 4 KiB inline threshold spills, content-addressed.
    let big_content = json!({"transcript": "x".repeat(9000), "turns": 42});
    let written = write(
        &first_app,
        write_payload(json!({"content": big_content.clone()})),
    )
    .await;
    // The served record is self-contained: the body re-inlines on read
    // (an `inline` payload carrying the full value), indistinguishable
    // from a small record.
    assert_eq!(written["record"]["content"]["kind"], json!("inline"));
    assert_eq!(written["record"]["content"]["value"], big_content);
    // …but on disk it spilled: the blob lives under memory_artifacts/,
    // the record file under memory/ carries only the reference.
    let artifacts = store.join("memory_artifacts");
    assert!(
        artifacts.exists(),
        "spilled body must land in the artifact store"
    );
    let record_file = store
        .join("memory")
        .join(format!("{}.json", written["memory_id"].as_str().unwrap()));
    let on_disk: Value =
        serde_json::from_str(&std::fs::read_to_string(record_file).unwrap()).unwrap();
    assert_eq!(on_disk["content"]["kind"], json!("artifact"));

    // …and the spill survives a restart: reads still re-inline.
    drop(first_app);
    let second_app = app_at(store.clone());
    let (status, got) = call(
        &second_app,
        "GET",
        &format!("/memory/{}", written["memory_id"].as_str().unwrap()),
        None,
    )
    .await;
    assert_eq!(status, StatusCode::OK, "get after restart failed: {got}");
    assert_eq!(got["content"]["kind"], json!("inline"));
    assert_eq!(got["content"]["value"], big_content);

    let _ = std::fs::remove_dir_all(store);
}

// --------------------------------------------------------------------- //
// Route-journaled memory events
// --------------------------------------------------------------------- //

/// `first -> second`, appending to a `log` channel (the flight-recorder
/// harness's minimal pipeline).
fn pipeline_app_at(store: PathBuf) -> Router {
    use rusty_agent_runtime::prelude::*;
    let spec = StateSpec::new().channel("log", Reducer::Append);
    let mut builder = GraphBuilder::new();
    builder.add_node("first", |_ctx: NodeContext| async {
        Ok(NodeOutput::update("log", json!("first")))
    });
    builder.add_node("second", |_ctx: NodeContext| async {
        Ok(NodeOutput::update("log", json!("second")))
    });
    builder.set_entry_point("first");
    builder.add_edge("first", "second");
    let mut registry = GraphRegistry::new();
    registry.register("pipeline", builder.compile().unwrap(), spec);
    let config = ServerConfig::new("127.0.0.1:0".parse().unwrap(), store);
    router(registry, config)
}

#[tokio::test]
async fn journaled_memory_write_and_read_land_in_the_runs_journal() {
    let store = temp_store();
    let app = pipeline_app_at(store.clone());

    // A completed run: its journal is persisted at completion.
    let (status, v) = call(&app, "POST", "/threads", Some(json!({"graph": "pipeline"}))).await;
    assert_eq!(status, StatusCode::CREATED, "thread failed: {v}");
    let thread_id = v["thread_id"].as_str().unwrap().to_string();
    let (status, v) = call(
        &app,
        "POST",
        &format!("/threads/{thread_id}/runs/wait"),
        Some(json!({})),
    )
    .await;
    assert_eq!(status, StatusCode::OK, "run failed: {v}");
    let run_id = v["run_id"].as_str().unwrap().to_string();

    // A write attributed to the run lands in its journal as a
    // `memory_write` event: idempotent effect, derived effect key, the
    // stored record as output, parented to the journal's head.
    let (status, v) = call(
        &app,
        "POST",
        "/memory",
        Some(write_payload(json!({
            "content": {"lesson": "journal me"},
            "run_id": run_id.clone(),
        }))),
    )
    .await;
    assert_eq!(status, StatusCode::CREATED, "journaled write failed: {v}");
    let memory_id = v["memory_id"].as_str().unwrap().to_string();

    // A budgeted read attributed to the run lands as a `memory_read`
    // event: the resolved query + budget as input, the assembly as
    // output.
    let (status, v) = call(
        &app,
        "POST",
        "/memory/query",
        Some(json!({
            "scope": {"scope": "user", "id": "user-7"},
            "budget": {"max_tokens": 100000},
            "run_id": run_id.clone(),
        })),
    )
    .await;
    assert_eq!(status, StatusCode::OK, "journaled read failed: {v}");
    assert_eq!(v["memory_ids"], json!([memory_id.clone()]));

    let (status, v) = call(&app, "GET", &format!("/runs/{run_id}/events"), None).await;
    assert_eq!(status, StatusCode::OK, "events failed: {v}");
    let events = v["events"].as_array().unwrap();
    let write_event = events
        .iter()
        .find(|e| e["kind"] == json!("memory_write"))
        .expect("the memory write is journaled");
    assert_eq!(write_event["effect"], json!("idempotent"));
    assert_eq!(
        write_event["input"]["value"]["effect_key"],
        json!(format!("memory:user:user-7:{memory_id}"))
    );
    assert_eq!(
        write_event["output"]["value"]["memory_id"],
        json!(memory_id)
    );
    let read_event = events
        .iter()
        .find(|e| e["kind"] == json!("memory_read"))
        .expect("the memory read is journaled");
    assert_eq!(read_event["effect"], json!("read_only"));
    assert_eq!(
        read_event["input"]["value"]["query"]["scope"],
        json!({"scope": "user", "id": "user-7"})
    );
    // as_of resolved at read time and journaled with the request.
    assert!(read_event["input"]["value"]["query"]["as_of"].is_string());
    assert_eq!(
        read_event["output"]["value"]["memory_ids"],
        json!([memory_id])
    );
    // Causal parentage: each journaled memory event parents to the
    // journal's head at append time, so the write precedes the read.
    assert_eq!(read_event["parent"], write_event["id"]);

    // A journaled read without a budget is a contract error (400): the
    // journaled request is the resolved query plus its budget.
    let (status, v) = call(
        &app,
        "POST",
        "/memory/query",
        Some(json!({"run_id": run_id.clone()})),
    )
    .await;
    assert_eq!(
        status,
        StatusCode::BAD_REQUEST,
        "unbudgeted journaled read must 400: {v}"
    );

    // Journaling into another tenant's run is refused silently (the write
    // itself lands; the evidence does not cross the boundary).
    let multi = {
        let config = ServerConfig::new("127.0.0.1:0".parse().unwrap(), store.clone())
            .with_tenant_key("acme", "acme-secret");
        use rusty_agent_runtime::prelude::*;
        let spec = StateSpec::new().channel("log", Reducer::Append);
        let mut builder = GraphBuilder::new();
        builder.add_node("first", |_ctx: NodeContext| async {
            Ok(NodeOutput::update("log", json!("first")))
        });
        builder.set_entry_point("first");
        let mut registry = GraphRegistry::new();
        registry.register("pipeline", builder.compile().unwrap(), spec);
        router(registry, config)
    };
    let acme = Some(("x-api-key", "acme-secret"));
    let (status, v) = call_as(
        &multi,
        acme,
        "POST",
        "/memory",
        Some(write_payload(json!({
            "content": {"lesson": "not your run"},
            "run_id": run_id.clone(),
        }))),
    )
    .await;
    assert_eq!(status, StatusCode::CREATED, "the write itself lands: {v}");
    let (status, v) = call(&app, "GET", &format!("/runs/{run_id}/events"), None).await;
    assert_eq!(status, StatusCode::OK);
    let writes = v["events"]
        .as_array()
        .unwrap()
        .iter()
        .filter(|e| e["kind"] == json!("memory_write"))
        .count();
    assert_eq!(writes, 1, "no event journaled across the tenant boundary");

    let _ = std::fs::remove_dir_all(store);
}

// --------------------------------------------------------------------- //
// Postgres backend (live database required)
//
// Every test uses a dedicated tenant (`mempg-<uuid>`) whose records are
// scoped under a per-run prefix, so repeated runs against one scratch
// database never interfere; the database itself is throwaway.
// --------------------------------------------------------------------- //

#[cfg(feature = "postgres")]
mod postgres {
    use super::*;

    fn pg_url() -> Option<String> {
        std::env::var("DATABASE_URL").ok()
    }

    /// A Postgres-backed app with a dedicated tenant for this test run.
    fn pg_app(url: &str, tenant: &str) -> Router {
        let config = ServerConfig::new("127.0.0.1:0".parse().unwrap(), temp_store())
            .with_postgres(url.to_string())
            .with_tenant_key(tenant, "pg-secret");
        router(GraphRegistry::new(), config)
    }

    /// Wave-1 exit criterion 1b: memory survives a server restart on the
    /// Postgres backend — records, spill, and query semantics included.
    #[tokio::test]
    #[ignore = "requires a live Postgres (DATABASE_URL)"]
    async fn postgres_memory_survives_a_restart() {
        let Some(url) = pg_url() else {
            eprintln!("DATABASE_URL unset; skipping");
            return;
        };
        let tenant = format!("mempg-{}", uuid::Uuid::new_v4());
        let auth = Some(("x-api-key", "pg-secret"));

        let first = pg_app(&url, &tenant);
        // One inline record and one spilled record (past the inline
        // threshold — the PostgresArtifactStore path).
        let small = write_payload(json!({"key": "timezone", "tags": ["prefs"]}));
        let (status, v) = call_as(&first, auth, "POST", "/memory", Some(small)).await;
        assert_eq!(status, StatusCode::CREATED, "pg write failed: {v}");
        let small_id = v["memory_id"].as_str().unwrap().to_string();
        let small_record = v["record"].clone();

        let big_content = json!({"transcript": "y".repeat(9000)});
        let (status, v) = call_as(
            &first,
            auth,
            "POST",
            "/memory",
            Some(write_payload(json!({
                "kind": "summary",
                "content": big_content.clone(),
                "confidence": 0.9,
            }))),
        )
        .await;
        assert_eq!(status, StatusCode::CREATED, "pg spill write failed: {v}");
        let big_id = v["memory_id"].as_str().unwrap().to_string();
        drop(first);

        // Restart: a fresh app over the same database serves both
        // records, self-contained.
        let second = pg_app(&url, &tenant);
        let (status, got) =
            call_as(&second, auth, "GET", &format!("/memory/{small_id}"), None).await;
        assert_eq!(status, StatusCode::OK, "pg get after restart failed: {got}");
        assert_eq!(got, small_record);
        let (status, got) = call_as(&second, auth, "GET", &format!("/memory/{big_id}"), None).await;
        assert_eq!(status, StatusCode::OK, "pg spill get failed: {got}");
        assert_eq!(
            got["content"]["value"], big_content,
            "spilled bodies re-inline on Postgres too"
        );

        // The column-mapped query path: kind + key + confidence filters
        // and the rank-ordered response.
        let (status, v) = call_as(
            &second,
            auth,
            "POST",
            "/memory/query",
            Some(json!({"kinds": ["summary"], "min_confidence": 0.5})),
        )
        .await;
        assert_eq!(status, StatusCode::OK, "pg query failed: {v}");
        let records = v["records"].as_array().unwrap();
        assert_eq!(records.len(), 1);
        assert_eq!(records[0]["memory_id"], json!(big_id));
        let (_, v) = call_as(
            &second,
            auth,
            "POST",
            "/memory/query",
            Some(json!({"key": "timezone", "budget": {"max_tokens": 100000}})),
        )
        .await;
        assert_eq!(v["memory_ids"], json!([small_id]));

        // A different tenant sees nothing (the isolation boundary is the
        // tenant column, unchanged).
        let other_tenant = format!("mempg-{}", uuid::Uuid::new_v4());
        let other = pg_app(&url, &other_tenant);
        let (status, _) = call_as(&other, auth, "GET", &format!("/memory/{small_id}"), None).await;
        assert_eq!(status, StatusCode::NOT_FOUND);
    }
}