trusty-memory 0.24.0

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
//! Tests for prompt-context, add-alias, list-prompt-facts, remove-prompt-fact.

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;
use trusty_common::memory_core::store::kg::Triple;

/// Why (issue #42): `GET /api/v1/kg/prompt-context` must serve the
/// formatted Markdown block from the in-memory cache (or a placeholder
/// when empty). Mirrors the MCP `get_prompt_context` tool but over HTTP.
#[tokio::test]
async fn prompt_context_endpoint_returns_formatted_block() {
    let state = test_state();

    // Empty cache returns the placeholder text.
    let app = router().with_state(state.clone());
    let resp = app
        .oneshot(
            Request::builder()
                .uri("/api/v1/kg/prompt-context")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::OK);
    let bytes = to_bytes(resp.into_body(), 4096).await.unwrap();
    let text = String::from_utf8(bytes.to_vec()).unwrap();
    assert_eq!(text, "No prompt facts stored yet.");

    // Populate the cache and re-fetch.
    {
        let mut guard = state.prompt_context_cache.write().await;
        let triples = vec![(
            "tga".to_string(),
            "is_alias_for".to_string(),
            "trusty-git-analytics".to_string(),
        )];
        let formatted = crate::prompt_facts::build_prompt_context(&triples);
        *guard = crate::prompt_facts::PromptFactsCache { triples, formatted };
    }
    let app = router().with_state(state);
    let resp = app
        .oneshot(
            Request::builder()
                .uri("/api/v1/kg/prompt-context")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::OK);
    let bytes = to_bytes(resp.into_body(), 4096).await.unwrap();
    let text = String::from_utf8(bytes.to_vec()).unwrap();
    assert!(text.contains("tga → trusty-git-analytics"), "got: {text}");
}

/// Why (issue #42): `POST /api/v1/kg/aliases` must assert the alias as
/// an `is_alias_for` triple AND refresh the prompt cache so subsequent
/// reads see the new alias.
#[tokio::test]
async fn add_alias_endpoint_asserts_triple_and_refreshes_cache() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let root = tmp.path().to_path_buf();
    std::mem::forget(tmp);
    let state = AppState::new(root).with_default_palace(Some("aliases".to_string()));
    let palace = trusty_common::memory_core::Palace {
        id: PalaceId::new("aliases"),
        name: "aliases".to_string(),
        description: None,
        created_at: chrono::Utc::now(),
        data_dir: state.data_root.join("aliases"),
    };
    state
        .registry
        .create_palace(&state.data_root, palace)
        .expect("create palace");

    let body = json!({"short": "tm", "full": "trusty-memory"});
    let app = router().with_state(state.clone());
    let resp = app
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/api/v1/kg/aliases")
                .header("content-type", "application/json")
                .body(Body::from(serde_json::to_vec(&body).unwrap()))
                .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();
    assert_eq!(v["subject"], "tm");
    assert_eq!(v["object"], "trusty-memory");

    // The prompt cache must reflect the new alias.
    let guard = state.prompt_context_cache.read().await;
    assert!(
        guard.formatted.contains("tm → trusty-memory"),
        "cache missing alias; got: {}",
        guard.formatted
    );
}

/// Build an `AppState` with one created palace, for the direct HTTP KG routes.
fn state_with_palace(name: &str) -> AppState {
    let tmp = tempfile::tempdir().expect("tempdir");
    let root = tmp.path().to_path_buf();
    std::mem::forget(tmp);
    let state = AppState::new(root).with_default_palace(Some(name.to_string()));
    let palace = trusty_common::memory_core::Palace {
        id: PalaceId::new(name),
        name: name.to_string(),
        description: None,
        created_at: chrono::Utc::now(),
        data_dir: state.data_root.join(name),
    };
    state
        .registry
        .create_palace(&state.data_root, palace)
        .expect("create palace");
    state
}

/// Regression for [#5524](https://github.com/bobmatnyc/trusty-tools/issues/5524):
/// a hot fact asserted through `POST /api/v1/palaces/{id}/kg` must be visible
/// in the prompt context, not merely stored.
///
/// Before the fix `MemoryService::kg_assert` returned 204 without touching the
/// prompt cache, so this assertion on `formatted` found an empty string — the
/// fact was in the KG and invisible to every later turn. Its sibling
/// `add_alias_endpoint_asserts_triple_and_refreshes_cache` had to seed hot
/// facts through the alias endpoint precisely because this route could not.
#[tokio::test]
async fn http_kg_assert_endpoint_refreshes_prompt_cache() {
    let state = state_with_palace("httpassert");
    let body = json!({
        "subject": "trusty-tools",
        "predicate": "has_convention",
        "object": "thiserror for libraries, anyhow for binaries",
    });
    let app = router().with_state(state.clone());
    let resp = app
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/api/v1/palaces/httpassert/kg")
                .header("content-type", "application/json")
                .body(Body::from(serde_json::to_vec(&body).unwrap()))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::NO_CONTENT);

    let guard = state.prompt_context_cache.read().await;
    assert!(
        guard
            .formatted
            .contains("thiserror for libraries, anyhow for binaries"),
        "HTTP kg_assert did not reach the prompt cache; got: {:?}",
        guard.formatted
    );
}

/// Error arm for the same route: a Tier S refusal must answer 400 and leave
/// both the graph and the prompt cache untouched.
///
/// Why this is here and not only in `kg_write::tests`: consolidation moved the
/// gate behind a shared function, and the thing that could regress is the
/// variant→status mapping in the handler, which only an HTTP-level test sees.
#[tokio::test]
async fn http_kg_assert_endpoint_rejects_over_long_tier_s_object() {
    let state = state_with_palace("httpreject");
    let over_long = "x".repeat(crate::prompt_facts::TIER_S_MAX_OBJECT_CHARS + 1);
    let body = json!({
        "subject": "trusty-tools",
        "predicate": "has_convention",
        "object": over_long,
    });
    let app = router().with_state(state.clone());
    let resp = app
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/api/v1/palaces/httpreject/kg")
                .header("content-type", "application/json")
                .body(Body::from(serde_json::to_vec(&body).unwrap()))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::BAD_REQUEST);

    let handle = state
        .registry
        .get(&PalaceId::new("httpreject"))
        .expect("palace handle");
    let stored = handle.kg.query_active("trusty-tools").await.expect("query");
    assert!(
        stored.is_empty(),
        "refused write reached storage: {stored:?}"
    );
    assert!(
        state.prompt_context_cache.read().await.triples.is_empty(),
        "refused write reached the prompt cache"
    );
}

/// Why (issue #42): `GET /api/v1/kg/prompt-facts` returns the structured
/// JSON array of every hot-predicate triple across the registry (so a
/// dashboard can render its own table).
#[tokio::test]
async fn list_prompt_facts_endpoint_returns_hot_triples() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let root = tmp.path().to_path_buf();
    std::mem::forget(tmp);
    let state = AppState::new(root).with_default_palace(Some("listfacts".to_string()));
    let palace = trusty_common::memory_core::Palace {
        id: PalaceId::new("listfacts"),
        name: "listfacts".to_string(),
        description: None,
        created_at: chrono::Utc::now(),
        data_dir: state.data_root.join("listfacts"),
    };
    let handle = state
        .registry
        .create_palace(&state.data_root, palace)
        .expect("create palace");

    // Insert one hot triple and one non-hot triple; only the hot one
    // should surface.
    handle
        .kg
        .assert(Triple {
            subject: "ts".to_string(),
            predicate: "is_alias_for".to_string(),
            object: "trusty-search".to_string(),
            valid_from: chrono::Utc::now(),
            valid_to: None,
            confidence: 1.0,
            provenance: None,
        })
        .await
        .expect("assert alias");
    handle
        .kg
        .assert(Triple {
            subject: "alice".to_string(),
            predicate: "works_at".to_string(),
            object: "Acme".to_string(),
            valid_from: chrono::Utc::now(),
            valid_to: None,
            confidence: 1.0,
            provenance: None,
        })
        .await
        .expect("assert works_at");

    let app = router().with_state(state);
    let resp = app
        .oneshot(
            Request::builder()
                .uri("/api/v1/kg/prompt-facts")
                .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(|r| r["subject"] == "ts"
            && r["predicate"] == "is_alias_for"
            && r["object"] == "trusty-search"),
        "missing ts alias; got {arr:?}"
    );
    // The non-hot `works_at` triple must not be present.
    assert!(
        !arr.iter().any(|r| r["predicate"] == "works_at"),
        "non-hot triple leaked into prompt facts: {arr:?}"
    );

    // #4890: this endpoint is what `trusty-memory doctor`'s Tier S
    // re-affirmation check reads, and it decodes the body straight into
    // `Vec<TierSFact>`. Decoding it the same way here pins the wire contract the
    // check depends on — a dropped or renamed `affirmed_at` would leave the
    // check permanently reporting "could not determine" against a healthy
    // daemon, which is exactly the kind of silent degradation nothing else
    // would catch.
    let facts: Vec<crate::prompt_facts::TierSFact> =
        serde_json::from_slice(&bytes).expect("body must decode as the doctor decodes it");
    let alias = facts
        .iter()
        .find(|f| f.subject == "ts")
        .expect("ts alias present");
    assert!(
        (chrono::Utc::now() - alias.affirmed_at).num_seconds() < 60,
        "affirmed_at must be the write time, got {}",
        alias.affirmed_at,
    );
}

/// Why (issue #42): `DELETE /api/v1/kg/prompt-facts` must retract the
/// interval and refresh the cache; the next list call must omit it.
#[tokio::test]
async fn remove_prompt_fact_endpoint_soft_deletes_and_refreshes_cache() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let root = tmp.path().to_path_buf();
    std::mem::forget(tmp);
    let state = AppState::new(root).with_default_palace(Some("rmfacts".to_string()));
    let palace = trusty_common::memory_core::Palace {
        id: PalaceId::new("rmfacts"),
        name: "rmfacts".to_string(),
        description: None,
        created_at: chrono::Utc::now(),
        data_dir: state.data_root.join("rmfacts"),
    };
    let handle = state
        .registry
        .create_palace(&state.data_root, palace)
        .expect("create palace");

    handle
        .kg
        .assert(Triple {
            subject: "ta".to_string(),
            predicate: "is_alias_for".to_string(),
            object: "trusty-analyze".to_string(),
            valid_from: chrono::Utc::now(),
            valid_to: None,
            confidence: 1.0,
            provenance: None,
        })
        .await
        .expect("assert alias");
    // Prime the cache so we can observe the removal effect.
    crate::prompt_facts::rebuild_prompt_cache(&state)
        .await
        .expect("rebuild prompt cache");

    let app = router().with_state(state.clone());
    let resp = app
        .oneshot(
            Request::builder()
                .method("DELETE")
                .uri("/api/v1/kg/prompt-facts?subject=ta&predicate=is_alias_for")
                .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();
    assert_eq!(v["removed"], true);
    assert!(v["closed"].as_u64().unwrap_or(0) >= 1);

    // Cache must no longer contain the alias.
    {
        let guard = state.prompt_context_cache.read().await;
        assert!(
            !guard.formatted.contains("ta → trusty-analyze"),
            "alias still in cache after delete: {}",
            guard.formatted
        );
    }

    // Removing a non-existent fact returns removed=false.
    let app = router().with_state(state);
    let resp = app
        .oneshot(
            Request::builder()
                .method("DELETE")
                .uri("/api/v1/kg/prompt-facts?subject=nope&predicate=is_alias_for")
                .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();
    assert_eq!(v["removed"], false);
}

// ---------------------------------------------------------------------------
// #4888 — Tier S admission control over HTTP (ADR-0028 D2 / D8)
//
// The MCP tools are not the only way to write a hot predicate. These two
// endpoints can each create one, so a gate that covered only the MCP surface
// would read as protection while leaving the surface writable.
// ---------------------------------------------------------------------------

/// Build a palace named `name` and fill Tier S to the cap with conventions.
async fn state_with_full_tier_s(name: &str) -> AppState {
    let tmp = tempfile::tempdir().expect("tempdir");
    let root = tmp.path().to_path_buf();
    std::mem::forget(tmp);
    let state = AppState::new(root).with_default_palace(Some(name.to_string()));
    let palace = trusty_common::memory_core::Palace {
        id: PalaceId::new(name),
        name: name.to_string(),
        description: None,
        created_at: chrono::Utc::now(),
        data_dir: state.data_root.join(name),
    };
    let handle = state
        .registry
        .create_palace(&state.data_root, palace)
        .expect("create palace");
    for i in 0..crate::prompt_facts::TIER_S_MAX_FACTS {
        handle
            .kg
            .assert(Triple {
                subject: format!("rule-{i}"),
                predicate: "has_convention".to_string(),
                object: format!("standing rule number {i}"),
                valid_from: chrono::Utc::now(),
                valid_to: None,
                confidence: 1.0,
                provenance: None,
            })
            .await
            .expect("seed convention");
    }
    state
}

/// Why (#4888): `POST /api/v1/kg/aliases` writes `is_alias_for` directly, so
/// it consumes a Tier S slot and must refuse the write past the cap with an
/// actionable 400 rather than silently growing the always-injected surface.
#[tokio::test]
async fn add_alias_endpoint_enforces_tier_s_cap() {
    let state = state_with_full_tier_s("httpcap").await;

    let body = json!({"short": "tga", "full": "trusty-git-analytics"});
    let app = router().with_state(state.clone());
    let resp = app
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/api/v1/kg/aliases")
                .header("content-type", "application/json")
                .body(Body::from(serde_json::to_vec(&body).unwrap()))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    let bytes = to_bytes(resp.into_body(), 8192).await.unwrap();
    let text = String::from_utf8(bytes.to_vec()).unwrap();
    assert!(text.contains("Tier S is full"), "got: {text}");
    assert!(text.contains("remove_prompt_fact"), "got: {text}");

    // Fail-closed: the alias is absent from the surface.
    let facts = crate::prompt_facts::gather_hot_triples(&state)
        .await
        .expect("gather");
    assert_eq!(facts.len(), crate::prompt_facts::TIER_S_MAX_FACTS);
    assert!(!facts.iter().any(|(s, _, _)| s == "tga"), "{facts:?}");
}

/// Why (#4888): `POST /api/v1/palaces/{id}/kg` takes an arbitrary predicate,
/// so it can write a hot one. This is the path `trusty-mpm`'s provisioner
/// uses to seed its identity `is_fact`, which makes it a real bypass rather
/// than a hypothetical one. The form constraint must hold here too.
#[tokio::test]
async fn kg_assert_endpoint_enforces_tier_s_form_constraint() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let root = tmp.path().to_path_buf();
    std::mem::forget(tmp);
    let state = AppState::new(root);
    let palace = trusty_common::memory_core::Palace {
        id: PalaceId::new("httpform"),
        name: "httpform".to_string(),
        description: None,
        created_at: chrono::Utc::now(),
        data_dir: state.data_root.join("httpform"),
    };
    state
        .registry
        .create_palace(&state.data_root, palace)
        .expect("create palace");

    let body = json!({
        "subject": "trusty-mpm",
        "predicate": "is_fact",
        "object": "z".repeat(crate::prompt_facts::TIER_S_MAX_OBJECT_CHARS + 1),
    });
    let app = router().with_state(state.clone());
    let resp = app
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/api/v1/palaces/httpform/kg")
                .header("content-type", "application/json")
                .body(Body::from(serde_json::to_vec(&body).unwrap()))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    let bytes = to_bytes(resp.into_body(), 8192).await.unwrap();
    let text = String::from_utf8(bytes.to_vec()).unwrap();
    assert!(text.contains("81 characters"), "got: {text}");
    assert!(text.contains("limit is 80"), "got: {text}");

    let facts = crate::prompt_facts::gather_hot_triples(&state)
        .await
        .expect("gather");
    assert!(facts.is_empty(), "rejected write must not land: {facts:?}");
}

/// Why (#4888): the HTTP KG endpoint must stay usable for ordinary
/// (non-hot) triples regardless of Tier S occupancy — the gate is scoped to
/// the always-injected surface, not to the knowledge graph as a whole.
#[tokio::test]
async fn kg_assert_endpoint_allows_cold_predicates_at_cap() {
    let state = state_with_full_tier_s("httpcold").await;

    let body = json!({
        "subject": "alice",
        "predicate": "works_at",
        "object": "z".repeat(crate::prompt_facts::TIER_S_MAX_OBJECT_CHARS + 40),
    });
    let app = router().with_state(state);
    let resp = app
        .oneshot(
            Request::builder()
                .method("POST")
                .uri("/api/v1/palaces/httpcold/kg")
                .header("content-type", "application/json")
                .body(Body::from(serde_json::to_vec(&body).unwrap()))
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(resp.status(), StatusCode::NO_CONTENT);
}