trusty-memory 0.21.2

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
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
//! Tests for MCP/HTTP drawer creator attribution and hook emit failure isolation.

use super::super::router;
use super::test_state;
use crate::AppState;
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::PalaceId;

/// Why (submission-logging Part A): every hook firing must produce an
/// activity-feed entry tagged `source=hook` so a normal Claude Code
/// session that only triggers hooks no longer leaves the TUI feed
/// empty. The simplest direct check is to POST to the hook ingestion
/// endpoint and confirm the new entry shows up in `GET /api/v1/activity`.
/// What: posts a `HookEventPayload` to `/api/v1/activity/hook`, then
/// queries `/api/v1/activity?source=hook&limit=1` and asserts a row
/// exists with the matching event_type and source.
/// Test: itself.
#[tokio::test]
async fn hook_fired_activity_emit_smoke() {
    let state = test_state();
    let app = router().with_state(state.clone());

    let payload = serde_json::json!({
        "palace_id": "alpha",
        "palace_name": "alpha",
        "hook_type": "UserPromptSubmit",
        "injection_kind": "prompt-context",
        "injection_length": 256,
        "trigger_prompt_excerpt": "test prompt",
        "duration_ms": 12,
    });
    let resp = app
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/api/v1/activity/hook")
                .header("content-type", "application/json")
                .body(Body::from(payload.to_string()))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::NO_CONTENT);
    // Issue #232: the hook handler emits via the fire-and-forget
    // `spawn_blocking` path; wait for the write to settle before
    // reading the activity history endpoint.
    state.flush_activity_writes().await;

    // Read it back through the activity history endpoint.
    let app = router().with_state(state);
    let resp = app
        .oneshot(
            Request::builder()
                .uri("/api/v1/activity?source=hook&limit=10")
                .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 entries = v["entries"].as_array().expect("entries array");
    assert!(
        !entries.is_empty(),
        "expected at least one hook activity row, got {entries:?}"
    );
    let first = &entries[0];
    assert_eq!(first["source"], "hook");
    assert_eq!(first["event_type"], "hook_fired");
    assert_eq!(first["palace_id"], "alpha");
    let body = &first["payload"];
    assert_eq!(body["hook_type"], "UserPromptSubmit");
    assert_eq!(body["injection_kind"], "prompt-context");
}

/// Why (submission-logging Part B): an HTTP drawer write with no
/// client-identifying header must still produce a drawer carrying a
/// `creator:client=unknown-http-client` tag so operators can recognise
/// "writer didn't self-identify" as distinct from "writer is known".
/// What: creates a palace via the registry, POSTs a drawer with no
/// `X-Trusty-Client-Name` header, lists the palace drawers, asserts
/// the new drawer carries the four creator tags with the default
/// client name and `source=http`.
/// Test: itself.
#[tokio::test]
async fn drawer_creator_attribution_http_default() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let root = tmp.path().to_path_buf();
    let state = AppState::new(root);
    let palace = trusty_common::memory_core::Palace {
        id: PalaceId::new("cred-default"),
        name: "cred-default".to_string(),
        description: None,
        created_at: chrono::Utc::now(),
        data_dir: state.data_root.join("cred-default"),
    };
    state
        .registry
        .create_palace(&state.data_root, palace)
        .expect("create palace");

    let app = router().with_state(state.clone());
    let body = serde_json::json!({
        "content": "hello world from anonymous client",
        "tags": ["user-tag"],
    });
    let resp = app
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/api/v1/palaces/cred-default/drawers")
                .header("content-type", "application/json")
                .body(Body::from(body.to_string()))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::OK);

    // Inspect the persisted drawer's tags.
    let app = router().with_state(state);
    let resp = app
        .oneshot(
            Request::builder()
                .uri("/api/v1/palaces/cred-default/drawers?limit=10")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::OK);
    let bytes = to_bytes(resp.into_body(), 8192).await.unwrap();
    let v: Value = serde_json::from_slice(&bytes).unwrap();
    let drawers = v.as_array().expect("drawers array");
    assert_eq!(drawers.len(), 1, "expected one drawer, got {drawers:?}");
    let tags: Vec<&str> = drawers[0]["tags"]
        .as_array()
        .expect("tags array")
        .iter()
        .filter_map(|t| t.as_str())
        .collect();
    assert!(
        tags.contains(&"user-tag"),
        "user-supplied tag must survive; got {tags:?}"
    );
    assert!(
        tags.contains(&"creator:client=unknown-http-client"),
        "expected default client tag; got {tags:?}"
    );
    assert!(
        tags.contains(&"creator:source=http"),
        "expected http source tag; got {tags:?}"
    );
    assert!(
        tags.iter().any(|t| t.starts_with("creator:version=")),
        "expected creator:version tag; got {tags:?}"
    );
}

/// Why (submission-logging Part B): when an HTTP client *does* set
/// `X-Trusty-Client-Name`, the drawer must carry that exact name in
/// its `creator:client=` tag so operators can trace which client wrote
/// which drawer.
/// What: POST with `X-Trusty-Client-Name: qa-curl` and assert the
/// rendered tag matches.
/// Test: itself.
#[tokio::test]
async fn drawer_creator_attribution_http_header() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let root = tmp.path().to_path_buf();
    let state = AppState::new(root);
    let palace = trusty_common::memory_core::Palace {
        id: PalaceId::new("cred-header"),
        name: "cred-header".to_string(),
        description: None,
        created_at: chrono::Utc::now(),
        data_dir: state.data_root.join("cred-header"),
    };
    state
        .registry
        .create_palace(&state.data_root, palace)
        .expect("create palace");

    let app = router().with_state(state.clone());
    let body = serde_json::json!({
        "content": "this is enough content to pass the signal/noise filter applied by remember",
        "tags": [],
    });
    let resp = app
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/api/v1/palaces/cred-header/drawers")
                .header("content-type", "application/json")
                .header("x-trusty-client-name", "qa-curl")
                .header("x-trusty-client-cwd", "/tmp/qa")
                .body(Body::from(body.to_string()))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::OK);

    let app = router().with_state(state);
    let resp = app
        .oneshot(
            Request::builder()
                .uri("/api/v1/palaces/cred-header/drawers?limit=10")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    let bytes = to_bytes(resp.into_body(), 8192).await.unwrap();
    let v: Value = serde_json::from_slice(&bytes).unwrap();
    let tags: Vec<&str> = v[0]["tags"]
        .as_array()
        .expect("tags")
        .iter()
        .filter_map(|t| t.as_str())
        .collect();
    assert!(
        tags.contains(&"creator:client=qa-curl"),
        "expected custom client tag; got {tags:?}"
    );
    assert!(
        tags.contains(&"creator:cwd=/tmp/qa"),
        "expected cwd tag from header; got {tags:?}"
    );
}

/// Why (DOC-53 §4.3): `X-Trusty-Client-Workstream` is the HTTP-transport
/// counterpart of the MCP `args["workstream"]` field — an explicit header
/// value must win over the cwd-derived heuristic and land as both
/// `creator:workstream=` and the bare `ws:` tag.
/// What: POSTs with both `x-trusty-client-workstream` and an unrelated
/// `x-trusty-client-cwd` (one with no `.worktrees` segment, so the cwd
/// heuristic alone would resolve to nothing) and asserts the explicit
/// header's value is what lands.
/// Test: itself.
#[tokio::test]
async fn drawer_creator_attribution_http_workstream_header() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let root = tmp.path().to_path_buf();
    let state = AppState::new(root);
    let palace = trusty_common::memory_core::Palace {
        id: PalaceId::new("cred-ws-header"),
        name: "cred-ws-header".to_string(),
        description: None,
        created_at: chrono::Utc::now(),
        data_dir: state.data_root.join("cred-ws-header"),
    };
    state
        .registry
        .create_palace(&state.data_root, palace)
        .expect("create palace");

    let app = router().with_state(state.clone());
    let body = serde_json::json!({
        "content": "this is enough content to pass the signal/noise filter applied by remember",
        "tags": [],
    });
    let resp = app
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/api/v1/palaces/cred-ws-header/drawers")
                .header("content-type", "application/json")
                .header("x-trusty-client-workstream", "explicit-ws")
                .header("x-trusty-client-cwd", "/tmp/no-worktrees-here")
                .body(Body::from(body.to_string()))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::OK);

    let app = router().with_state(state);
    let resp = app
        .oneshot(
            Request::builder()
                .uri("/api/v1/palaces/cred-ws-header/drawers?limit=10")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    let bytes = to_bytes(resp.into_body(), 8192).await.unwrap();
    let v: Value = serde_json::from_slice(&bytes).unwrap();
    let tags: Vec<&str> = v[0]["tags"]
        .as_array()
        .expect("tags")
        .iter()
        .filter_map(|t| t.as_str())
        .collect();
    assert!(
        tags.contains(&"creator:workstream=explicit-ws"),
        "expected explicit workstream header tag; got {tags:?}"
    );
    assert!(
        tags.contains(&"ws:explicit-ws"),
        "expected bare ws: tag; got {tags:?}"
    );
}

/// Why (submission-logging Part B): drawers written through the MCP
/// tool surface (`memory_remember`) must carry
/// `creator:client=trusty-memory-mcp` and `creator:source=mcp` so
/// operators can tell MCP-origin drawers apart from HTTP / CLI writes.
/// What: dispatches `memory_remember` directly against an in-process
/// `AppState` (no HTTP), then lists the palace drawers and asserts
/// the MCP attribution tags landed.
/// Test: itself.
#[tokio::test]
async fn drawer_creator_attribution_mcp_default() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let root = tmp.path().to_path_buf();
    std::mem::forget(tmp);
    let state = AppState::new(root);
    // Flip to Ready so the issue #911 warming preflight allows dispatch_tool
    // to proceed (the call below goes through the MCP handler path).
    state.set_ready();
    let palace = trusty_common::memory_core::Palace {
        id: PalaceId::new("cred-mcp"),
        name: "cred-mcp".to_string(),
        description: None,
        created_at: chrono::Utc::now(),
        data_dir: state.data_root.join("cred-mcp"),
    };
    state
        .registry
        .create_palace(&state.data_root, palace)
        .expect("create palace");

    let _ = crate::tools::dispatch_tool(
        &state,
        "memory_remember",
        json!({
            "palace": "cred-mcp",
            "text": "remember a sentence with enough tokens to pass filters please",
            "room": "General",
            "tags": ["from-test"],
        }),
    )
    .await
    .expect("memory_remember dispatch");

    let app = router().with_state(state);
    let resp = app
        .oneshot(
            Request::builder()
                .uri("/api/v1/palaces/cred-mcp/drawers?limit=10")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    let bytes = to_bytes(resp.into_body(), 8192).await.unwrap();
    let v: Value = serde_json::from_slice(&bytes).unwrap();
    let drawers = v.as_array().expect("drawers array");
    assert!(!drawers.is_empty(), "expected at least one drawer");
    let tags: Vec<&str> = drawers[0]["tags"]
        .as_array()
        .expect("tags array")
        .iter()
        .filter_map(|t| t.as_str())
        .collect();
    assert!(
        tags.contains(&"creator:client=trusty-memory-mcp"),
        "expected MCP client tag; got {tags:?}"
    );
    assert!(
        tags.contains(&"creator:source=mcp"),
        "expected MCP source tag; got {tags:?}"
    );
}

/// Why (CRITICAL fix, DOC-53 §4.3 — code-critic BLOCK round): the bug this
/// test exists to catch is daemon-vs-caller mis-attribution — a SHARED
/// daemon process serving two concurrently-attached MCP sessions must
/// stamp EACH write with the identity ITS OWN request carried, never a
/// value cached/derived from the daemon process itself (which would be
/// identical for every caller and silently collapse two sessions'
/// attribution into one — the exact epic #3524 slice 5/6 duplication this
/// whole feature exists to prevent). An in-process `dispatch_tool` call (as
/// `drawer_creator_attribution_mcp_default` above uses) cannot exercise
/// this: it never goes through the shared `POST /rpc` surface a real
/// stdio-bridge-mediated caller uses, so it cannot observe cross-request
/// isolation. This test routes two `tools/call` envelopes — the actual MCP
/// wire shape the stdio bridge forwards, each carrying a DIFFERENT
/// `arguments.workstream` (simulating two distinct sessions' bridge
/// processes, each having injected its own resolved identity per
/// DOC-53 §4.3) — through the real `/rpc` HTTP handler against the SAME
/// `AppState`/daemon instance, and asserts the two resulting drawers carry
/// DIFFERENT, correct `ws:`/`creator:workstream=` tags with no cross-leak.
/// What: two POSTs to `/rpc` with `method: "tools/call"`,
/// `params.name: "memory_remember"`, `params.arguments.workstream` set to
/// `"ws-alpha"` and `"ws-beta"` respectively (same palace, same daemon
/// state); lists the palace's drawers and asserts each drawer carries only
/// its own workstream's tags — never the other's.
/// Test: itself.
#[tokio::test]
async fn mcp_writes_carry_distinct_ws_tags_per_caller_over_rpc() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let root = tmp.path().to_path_buf();
    let state = AppState::new(root);
    state.set_ready();
    let palace = trusty_common::memory_core::Palace {
        id: PalaceId::new("cred-multi-caller"),
        name: "cred-multi-caller".to_string(),
        description: None,
        created_at: chrono::Utc::now(),
        data_dir: state.data_root.join("cred-multi-caller"),
    };
    state
        .registry
        .create_palace(&state.data_root, palace)
        .expect("create palace");

    // `force: true` bypasses the rolling near-duplicate gate (issue #220,
    // `helpers::dedup_gate` uses jaro_winkler similarity) -- without it the
    // two writes below (differing only in the "alpha"/"beta" marker word)
    // would be similar enough for the SECOND to be silently skipped rather
    // than stored, which would make this test pass for the wrong reason
    // (one drawer landing) rather than actually exercising two isolated
    // writes.
    let rpc_call = |workstream: &str, marker: &str| {
        serde_json::json!({
            "jsonrpc": "2.0",
            "id": 1,
            "method": "tools/call",
            "params": {
                "name": "memory_remember",
                "arguments": {
                    "palace": "cred-multi-caller",
                    "text": format!(
                        "distinct-caller regression content marker {marker} with enough tokens"
                    ),
                    "room": "General",
                    "workstream": workstream,
                    "force": true,
                }
            }
        })
    };

    for (workstream, marker) in [("ws-alpha", "alpha"), ("ws-beta", "beta")] {
        let app = router().with_state(state.clone());
        let resp = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/rpc")
                    .header("content-type", "application/json")
                    .body(Body::from(rpc_call(workstream, marker).to_string()))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let bytes = to_bytes(resp.into_body(), 8192).await.unwrap();
        let v: Value = serde_json::from_slice(&bytes).unwrap();
        assert!(
            v.get("error").is_none(),
            "tools/call memory_remember for {workstream} must not error; got {v:?}"
        );
        // The MCP result is wrapped `{"content":[{"type":"text","text":"<json>"}]}`
        // (see `transport::rpc::dispatch`'s `tools/call` branch) -- parse the
        // inner text back to JSON and assert it actually stored (not a
        // gate-skip envelope), so a regression in either gate config would
        // fail loudly here rather than downstream as a missing-drawer count.
        let inner_text = v["result"]["content"][0]["text"]
            .as_str()
            .unwrap_or_default();
        let inner: Value = serde_json::from_str(inner_text).unwrap_or_default();
        assert_eq!(
            inner["status"], "stored",
            "expected a stored (not skipped) envelope for {workstream}; got {inner:?}"
        );
    }

    let app = router().with_state(state);
    let resp = app
        .oneshot(
            Request::builder()
                .uri("/api/v1/palaces/cred-multi-caller/drawers?limit=10")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    let bytes = to_bytes(resp.into_body(), 8192).await.unwrap();
    let v: Value = serde_json::from_slice(&bytes).unwrap();
    let drawers = v.as_array().expect("drawers array");
    assert_eq!(drawers.len(), 2, "expected two drawers, got {drawers:?}");

    for drawer in drawers {
        let content = drawer["content"].as_str().unwrap_or_default();
        let tags: Vec<&str> = drawer["tags"]
            .as_array()
            .expect("tags array")
            .iter()
            .filter_map(|t| t.as_str())
            .collect();
        if content.contains("marker alpha") {
            assert!(
                tags.contains(&"ws:ws-alpha") && tags.contains(&"creator:workstream=ws-alpha"),
                "alpha drawer must carry its own ws tags; got {tags:?}"
            );
            assert!(
                !tags.contains(&"ws:ws-beta") && !tags.contains(&"creator:workstream=ws-beta"),
                "alpha drawer must NOT leak the beta caller's ws tags (daemon-vs-caller \
                 mis-attribution); got {tags:?}"
            );
        } else if content.contains("marker beta") {
            assert!(
                tags.contains(&"ws:ws-beta") && tags.contains(&"creator:workstream=ws-beta"),
                "beta drawer must carry its own ws tags; got {tags:?}"
            );
            assert!(
                !tags.contains(&"ws:ws-alpha") && !tags.contains(&"creator:workstream=ws-alpha"),
                "beta drawer must NOT leak the alpha caller's ws tags (daemon-vs-caller \
                 mis-attribution); got {tags:?}"
            );
        } else {
            panic!("drawer content did not match either marker: {content:?}");
        }
    }
}

/// Why (submission-logging Part A, failure isolation): if the daemon
/// is unreachable when the hook fires, the hook command MUST still
/// return `Ok(())` so the user's prompt is not blocked. The activity
/// emit failure is surfaced via a stderr warn-log only.
/// What: pins a tempdir as the data dir (so `read_daemon_addr`
/// returns `Ok(None)` — no http_addr file), runs
/// `handle_prompt_context_with_payload` directly with a fixed empty
/// payload (issue #2079 — avoids spawning a real blocking stdin read
/// that could outlive this test's `Runtime` teardown), and asserts it
/// returns `Ok(())`. Separately verifies the emit helper does not
/// panic — covered by `post_hook_event_no_daemon_is_noop` in
/// `hook_emit::tests`.
/// Test: itself.
#[tokio::test]
async fn hook_emit_failure_isolated() {
    let _guard = crate::commands::env_test_lock().lock().await;
    let tmp = tempfile::tempdir().expect("tempdir");
    // SAFETY: test serialised via env_test_lock.
    unsafe {
        std::env::set_var(trusty_common::DATA_DIR_OVERRIDE_ENV, tmp.path());
    }
    let res =
        crate::commands::prompt_context::handle_prompt_context_with_payload(String::new()).await;
    unsafe {
        std::env::remove_var(trusty_common::DATA_DIR_OVERRIDE_ENV);
    }
    assert!(
        res.is_ok(),
        "hook must complete even when daemon emit fails; got {res:?}"
    );
}