trusty-memory 0.23.1

MCP server (stdio + HTTP/SSE) for trusty-memory
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
//! Tests for status, palace routing, drawer create, and memories alias.

use super::super::router;
use super::test_state;
use axum::body::{to_bytes, Body};
use axum::http::{Request, StatusCode};
use serde_json::{json, Value};
use tower::util::ServiceExt;
use trusty_common::memory_core::palace::{Palace, PalaceId};

#[tokio::test]
async fn status_endpoint_returns_payload() {
    let state = test_state();
    let app = router().with_state(state);
    let resp = app
        .oneshot(
            Request::builder()
                .uri("/api/v1/status")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::OK);
    let bytes = to_bytes(resp.into_body(), 1024).await.unwrap();
    let v: Value = serde_json::from_slice(&bytes).unwrap();
    assert!(v["version"].is_string());
    assert_eq!(v["palace_count"], 0);
}

#[tokio::test]
async fn unknown_api_returns_404() {
    let state = test_state();
    let app = router().with_state(state);
    let resp = app
        .oneshot(
            Request::builder()
                .uri("/api/v1/does-not-exist")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::NOT_FOUND);
}

/// Issue #70 — `…/memories` is a working alias for `…/drawers`.
///
/// Why: Clients that POST/GET against `…/memories` previously hit a 404
/// because only `/drawers` was registered, which silently broke every
/// store call (and pushed callers onto an OOM-prone CLI fallback). The
/// alias must route to the same handler as `/drawers`.
/// What: Creates a real palace via the registry, then GETs the `/memories`
/// alias and asserts a 200 with a JSON array body (the list-drawers shape).
/// Uses GET, not POST, so the test stays embedder-free (no ONNX load).
/// Test: this test.
#[tokio::test]
async fn memories_alias_routes_to_drawers() {
    let state = test_state();
    let palace = Palace {
        id: PalaceId::new("alias-test"),
        name: "alias-test".to_string(),
        description: None,
        created_at: chrono::Utc::now(),
        data_dir: state.data_root.join("alias-test"),
    };
    state
        .registry
        .create_palace(&state.data_root, palace)
        .expect("create_palace");

    let app = router().with_state(state);
    let resp = app
        .oneshot(
            Request::builder()
                .uri("/api/v1/palaces/alias-test/memories")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(
        resp.status(),
        StatusCode::OK,
        "the /memories alias must resolve to list_drawers, not 404"
    );
    let bytes = to_bytes(resp.into_body(), 4096).await.unwrap();
    let v: Value = serde_json::from_slice(&bytes).unwrap();
    assert!(
        v.is_array(),
        "the alias must return the list-drawers array shape, got {v:?}"
    );
}

/// Issue #133 — `POST /api/v1/palaces/{id}/drawers` must trigger the
/// same auto-KG extraction as the MCP `memory_remember` tool.
///
/// Why: PR #106 wired auto-extract only into the MCP path; HTTP-origin
/// writes silently skipped it, leaving every palace populated via the
/// HTTP API with an empty KG. This regression test posts a drawer over
/// HTTP and then queries the KG to confirm the expected `tag:`,
/// `room:`, and `topic:` (`#hashtag`) auto-extracted triples landed.
/// What: creates a palace via the registry, posts a drawer with tags +
/// room + a `#hashtag` over the HTTP endpoint, reads
/// `/api/v1/palaces/{id}/kg/graph`, and asserts the auto-extracted
/// triples (provenance = `auto:remember`) appear.
/// Test: this test.
#[tokio::test]
async fn http_create_drawer_runs_auto_kg_extraction() {
    let state = test_state();
    let palace = Palace {
        id: PalaceId::new("kgauto-http"),
        name: "kgauto-http".to_string(),
        description: None,
        created_at: chrono::Utc::now(),
        data_dir: state.data_root.join("kgauto-http"),
    };
    state
        .registry
        .create_palace(&state.data_root, palace)
        .expect("create_palace");

    let app = router().with_state(state.clone());
    // Why: tag "test" is in the KG extraction deny-list (issue #278), so we
    // use "backend" and "kg" tags to exercise the auto-extraction path
    // without triggering the deny-list skip.
    let body = json!({
        "content": "trusty-memory is a Rust crate that ships an MCP server. \
                    It tracks #mcp and #rust topics with care.",
        "room": "Backend",
        "tags": ["backend", "kg"],
        "importance": 0.5,
    })
    .to_string();
    let resp = app
        .clone()
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/api/v1/palaces/kgauto-http/drawers")
                .header("content-type", "application/json")
                .body(Body::from(body))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(
        resp.status(),
        StatusCode::OK,
        "create_drawer must return 200 OK"
    );

    // Read the KG graph for the same palace and assert auto-extracted
    // triples landed. The exact set is exercised in
    // `tools::tests::auto_kg_extraction_hooks_into_memory_remember`; here
    // we only need to confirm the HTTP path now mirrors the MCP path.
    let resp = app
        .oneshot(
            Request::builder()
                .uri("/api/v1/palaces/kgauto-http/kg/graph")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::OK);
    let bytes = to_bytes(resp.into_body(), 64 * 1024).await.unwrap();
    let v: Value = serde_json::from_slice(&bytes).unwrap();
    let triples = v["triples"].as_array().expect("triples array");
    assert!(
        !triples.is_empty(),
        "HTTP-origin drawer must populate the KG; got empty graph"
    );
    let auto: Vec<&Value> = triples
        .iter()
        .filter(|t| t["provenance"].as_str() == Some(crate::kg_extract::AUTO_PROVENANCE))
        .collect();
    assert!(
        !auto.is_empty(),
        "expected at least one auto-extracted triple in HTTP-populated KG; got: {triples:?}"
    );
    // Spot-check the tag-as-subject encoding survived (matches the MCP
    // path's behaviour and proves the extractor saw the body's tags).
    // Note: "test" is in the deny-list, so we use "backend" in the drawer
    // tags above (issue #278); assert on that tag instead.
    assert!(
        auto.iter()
            .any(|t| t["subject"].as_str() == Some("tag:backend")),
        "expected `tag:backend` auto-extracted edge, got: {auto:?}"
    );
    // Hashtag mention triples (room-aware extractor).
    assert!(
        auto.iter()
            .any(|t| t["predicate"].as_str() == Some("mentioned-in")),
        "expected at least one #hashtag mention triple, got: {auto:?}"
    );
}

/// Issue #3225 — `POST .../drawers` runs the signal/noise QUALITY gate
/// (`trusty_common::memory_core::filter`) on `content` by default, and a
/// JSON-shaped payload is a designed rejection target: `non_alphabetic_ratio`
/// counts braces/quotes/colons/digits as non-alphabetic, and the daemon's own
/// `non_alpha_ratio_detects_json` unit test asserts a small JSON object
/// crosses the 0.5 ratio it checks (well above the gate's 0.80 reject
/// threshold). Without an opt-out, a caller that deliberately wants to store
/// structured content verbatim (e.g. trusty-agents' `TrustyMemoryClient`,
/// which JSON-serializes its payload as `content` for lossless round-tripping)
/// gets a 500 on every write.
///
/// Why: proves the gate is still active (the safe default) for ordinary
/// callers that don't opt in.
/// What: posts a small JSON-object `content` with no `force` field and
/// asserts the response is NOT 200 OK.
/// Test: this test; paired with
/// `create_drawer_force_bypasses_quality_gate_for_json_content` below.
#[tokio::test]
async fn create_drawer_rejects_json_content_without_force() {
    let state = test_state();
    let palace = Palace {
        id: PalaceId::new("force-gate-reject"),
        name: "force-gate-reject".to_string(),
        description: None,
        created_at: chrono::Utc::now(),
        data_dir: state.data_root.join("force-gate-reject"),
    };
    state
        .registry
        .create_palace(&state.data_root, palace)
        .expect("create_palace");

    let app = router().with_state(state.clone());
    let body = json!({
        "content": "{\"score\":0.42,\"id\":\"a1b2\",\"tier\":3}",
    })
    .to_string();
    let resp = app
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/api/v1/palaces/force-gate-reject/drawers")
                .header("content-type", "application/json")
                .body(Body::from(body))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_ne!(
        resp.status(),
        StatusCode::OK,
        "JSON-shaped content without `force` must still be rejected by the quality gate"
    );
}

/// Why: proves `force: true` on `CreateDrawerBody` (issue #3225) reaches
/// `RememberOptions::force` and bypasses the QUALITY gate for the exact
/// content shape the previous test proves is rejected without it.
/// What: posts the same JSON-object `content` with `"force": true` and
/// asserts 200 OK.
/// Test: this test.
#[tokio::test]
async fn create_drawer_force_bypasses_quality_gate_for_json_content() {
    let state = test_state();
    let palace = Palace {
        id: PalaceId::new("force-gate-accept"),
        name: "force-gate-accept".to_string(),
        description: None,
        created_at: chrono::Utc::now(),
        data_dir: state.data_root.join("force-gate-accept"),
    };
    state
        .registry
        .create_palace(&state.data_root, palace)
        .expect("create_palace");

    let app = router().with_state(state.clone());
    let body = json!({
        "content": "{\"score\":0.42,\"id\":\"a1b2\",\"tier\":3}",
        "force": true,
    })
    .to_string();
    let resp = app
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/api/v1/palaces/force-gate-accept/drawers")
                .header("content-type", "application/json")
                .body(Body::from(body))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(
        resp.status(),
        StatusCode::OK,
        "`force: true` must bypass the quality gate for JSON-shaped content"
    );
}

#[tokio::test]
async fn create_then_list_palace() {
    let state = test_state();
    let app = router().with_state(state.clone());
    let body = json!({"name": "web-test", "description": "from test"}).to_string();
    let resp = app
        .clone()
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/api/v1/palaces")
                .header("content-type", "application/json")
                .body(Body::from(body))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::OK);

    let resp = app
        .oneshot(
            Request::builder()
                .uri("/api/v1/palaces")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::OK);
    let bytes = to_bytes(resp.into_body(), 4096).await.unwrap();
    let v: Value = serde_json::from_slice(&bytes).unwrap();
    let arr = v.as_array().expect("array");
    assert!(arr.iter().any(|p| p["id"] == "web-test"));
}

/// Why: Issue #180 — verify the happy path: create an empty palace,
/// `DELETE /api/v1/palaces/{id}` returns 204, and a follow-up
/// `GET /api/v1/palaces/{id}` returns 404 because the directory is gone.
/// What: Drives the router through axum's `oneshot` testing layer; no
/// query parameters are passed so `force` defaults to `false`. A freshly
/// created palace has no drawers, so the conflict guard does not fire.
/// Test: This test itself.
#[tokio::test]
async fn delete_palace_removes_dir_when_empty() {
    let state = test_state();
    let app = router().with_state(state.clone());
    let body = json!({"name": "to-delete"}).to_string();
    let resp = app
        .clone()
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/api/v1/palaces")
                .header("content-type", "application/json")
                .body(Body::from(body))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::OK);

    let resp = app
        .clone()
        .oneshot(
            Request::builder()
                .method("DELETE")
                .uri("/api/v1/palaces/to-delete")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::NO_CONTENT);

    // Confirm the palace is gone from the on-disk registry.
    let resp = app
        .oneshot(
            Request::builder()
                .uri("/api/v1/palaces/to-delete")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::NOT_FOUND);

    // And the on-disk directory itself was removed.
    let palace_dir = state.data_root.join("to-delete");
    assert!(
        !palace_dir.exists(),
        "palace dir should be removed: {}",
        palace_dir.display()
    );
}

/// Why: Issue #180 — without `force=true` we must refuse to drop a
/// palace that still has drawers, otherwise a stray DELETE could nuke
/// hours of memory in one request.
/// What: Create a palace, write a drawer into it, then DELETE without
/// `force`. Expect 409 Conflict and verify the palace and drawer are
/// still on disk.
/// Test: This test itself.
#[tokio::test]
async fn delete_palace_refuses_when_drawers_present() {
    let state = test_state();
    let app = router().with_state(state.clone());
    // Create the palace.
    let resp = app
        .clone()
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/api/v1/palaces")
                .header("content-type", "application/json")
                .body(Body::from(json!({"name": "keep-me"}).to_string()))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::OK);
    // Add a drawer so the conflict guard fires.
    let resp = app
        .clone()
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/api/v1/palaces/keep-me/drawers")
                .header("content-type", "application/json")
                .body(Body::from(
                    json!({
                        "content": "Important fact that should not be deleted accidentally.",
                        "tags": [],
                    })
                    .to_string(),
                ))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::OK);

    let resp = app
        .clone()
        .oneshot(
            Request::builder()
                .method("DELETE")
                .uri("/api/v1/palaces/keep-me")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::CONFLICT);

    // Palace still resolves.
    let resp = app
        .oneshot(
            Request::builder()
                .uri("/api/v1/palaces/keep-me")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::OK);
}