Skip to content

Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors

Rust

test(admin,lint): adversarial scope tests for the scoped status and the broken_link finding

Caminharae60310abbe8
diff --git a/crates/ai-memory-consolidate/tests/suite/typed_edges.rs b/crates/ai-memory-consolidate/tests/suite/typed_edges.rs
index d48c5f1e..bc89ff7f 100644
--- a/crates/ai-memory-consolidate/tests/suite/typed_edges.rs
+++ b/crates/ai-memory-consolidate/tests/suite/typed_edges.rs
@@ -144,6 +144,76 @@ async fn a_declared_contradiction_is_a_lint_finding_without_an_llm() {
);
}
+#[tokio::test]
+async fn an_unresolved_same_project_link_is_a_broken_link_finding() {
+ let tmp = TempDir::new().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let (ws, proj) = scope(&store).await;
+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();
+
+ wiki.write_page(req(
+ ws,
+ proj,
+ "notes/dangling.md",
+ "points at [[notes/missing.md]]",
+ serde_json::json!({}),
+ ))
+ .await
+ .unwrap();
+ // Control: a link that resolves is not reported.
+ wiki.write_page(req(
+ ws,
+ proj,
+ "notes/present.md",
+ "the target",
+ serde_json::json!({}),
+ ))
+ .await
+ .unwrap();
+ wiki.write_page(req(
+ ws,
+ proj,
+ "notes/resolved.md",
+ "see [[notes/present.md]]",
+ serde_json::json!({}),
+ ))
+ .await
+ .unwrap();
+
+ let report = run_lint(
+ &store.reader,
+ &wiki,
+ None,
+ ws,
+ proj,
+ LintOptions {
+ dry_run: true,
+ use_llm: false,
+ decay_lambda: 0.02,
+ embedding: None,
+ },
+ )
+ .await
+ .unwrap();
+
+ let broken: Vec<_> = report
+ .findings
+ .iter()
+ .filter(|f| f.kind == "broken_link")
+ .collect();
+ assert_eq!(
+ broken.len(),
+ 1,
+ "only the unresolved same-project link is reported: {broken:?}"
+ );
+ assert_eq!(broken[0].pages, vec!["notes/dangling.md"]);
+ assert!(
+ broken[0].message.contains("notes/missing.md"),
+ "{}",
+ broken[0].message
+ );
+}
+
#[tokio::test]
async fn a_contradiction_to_a_deleted_page_reports_the_stale_declaration() {
let tmp = TempDir::new().unwrap();
diff --git a/crates/ai-memory-mcp/tests/suite/admin_status_search.rs b/crates/ai-memory-mcp/tests/suite/admin_status_search.rs
index a23a36b3..4f9931dd 100644
--- a/crates/ai-memory-mcp/tests/suite/admin_status_search.rs
+++ b/crates/ai-memory-mcp/tests/suite/admin_status_search.rs
@@ -71,6 +71,52 @@ async fn seed_page(store: &Store, title: &str, path: &str, body: &str) {
store.writer.upsert_page(page).await.unwrap();
}
+/// Seed one page (with the given outgoing same-project links) into an explicit
+/// scope, so a test can drive the scoped `links` figures that
+/// `GET /admin/status?workspace=&project=` reports.
+async fn seed_linked_page(
+ store: &Store,
+ workspace: &str,
+ project: &str,
+ path: &str,
+ links: &[&str],
+) {
+ let ws = store
+ .writer
+ .get_or_create_workspace(workspace.to_string())
+ .await
+ .unwrap();
+ let proj = store
+ .writer
+ .get_or_create_project(ws, project.to_string(), None)
+ .await
+ .unwrap();
+ let page = NewPage {
+ workspace_id: ws,
+ project_id: proj,
+ path: PagePath::new(path).unwrap(),
+ title: path.to_string(),
+ body: "seeded".to_string(),
+ tier: Tier::Semantic,
+ frontmatter_json: serde_json::json!({}),
+ pinned: false,
+ links: links
+ .iter()
+ .map(|target| ai_memory_core::LinkTarget {
+ workspace: None,
+ project: None,
+ path: PagePath::new(*target).unwrap(),
+ relation: None,
+ })
+ .collect(),
+ author_id: None,
+ expires_at: None,
+ entities: Vec::new(),
+ evidence: Vec::new(),
+ };
+ store.writer.upsert_page(page).await.unwrap();
+}
+
async fn body_bytes(resp: axum::response::Response) -> Vec<u8> {
use axum::body::to_bytes;
to_bytes(resp.into_body(), 1_000_000)
@@ -198,6 +244,198 @@ async fn list_projects_returns_workspace_project_pairs() {
);
}
+/// A partial scope pair is refused on `/admin/status` too, and the full pair
+/// answers with this project's figures (adversarial + control, per `AGENTS.md`
+/// "Security-boundary tests are adversarial and mandatory").
+#[tokio::test]
+async fn status_scoped_links_rejects_partial_scope() {
+ let tmp = TempDir::new().unwrap();
+ let (state, store) = make_admin_state(&tmp).await;
+ seed_linked_page(&store, "default", "app", "notes/one.md", &["notes/missing.md"]).await;
+ let app = admin_router(state);
+
+ for uri in [
+ "/admin/status?workspace=default",
+ "/admin/status?project=app",
+ ] {
+ let resp = app
+ .clone()
+ .oneshot(
+ Request::builder()
+ .method("GET")
+ .uri(uri)
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(resp.status(), StatusCode::BAD_REQUEST, "{uri}");
+ let body: serde_json::Value = serde_json::from_slice(&body_bytes(resp).await).unwrap();
+ assert!(
+ body["error"]
+ .as_str()
+ .unwrap_or("")
+ .contains("workspace and project must be provided together"),
+ "unexpected error body for {uri}: {body}"
+ );
+ }
+
+ // Control: the full pair is answered and carries the scoped object.
+ let resp = app
+ .oneshot(
+ Request::builder()
+ .method("GET")
+ .uri("/admin/status?workspace=default&project=app")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(resp.status(), StatusCode::OK);
+ let body: serde_json::Value = serde_json::from_slice(&body_bytes(resp).await).unwrap();
+ assert_eq!(
+ body["links_scope"]["links_from_latest_pages"].as_u64(),
+ Some(1),
+ "{body}"
+ );
+ assert_eq!(
+ body["links_scope"]["unresolved_links_from_latest_pages"].as_u64(),
+ Some(1),
+ "{body}"
+ );
+}
+
+/// An unknown scope is refused and stays refused: the route resolves through
+/// the no-create lookup, so the first 404 cannot have minted the scope.
+#[tokio::test]
+async fn status_scoped_links_fails_closed_on_an_unknown_scope() {
+ let tmp = TempDir::new().unwrap();
+ let (state, store) = make_admin_state(&tmp).await;
+ seed_linked_page(&store, "default", "app", "notes/one.md", &["notes/missing.md"]).await;
+ let app = admin_router(state);
+
+ for uri in [
+ "/admin/status?workspace=default&project=ghost",
+ "/admin/status?workspace=ghost&project=app",
+ ] {
+ let resp = app
+ .clone()
+ .oneshot(
+ Request::builder()
+ .method("GET")
+ .uri(uri)
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(resp.status(), StatusCode::NOT_FOUND, "{uri}");
+ }
+
+ // Adversarial half: a creating path would answer 200 on this retry.
+ let resp = app
+ .clone()
+ .oneshot(
+ Request::builder()
+ .method("GET")
+ .uri("/admin/status?workspace=default&project=ghost")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ resp.status(),
+ StatusCode::NOT_FOUND,
+ "the refused scope must not have been created"
+ );
+
+ // Control: the scope that does exist answers.
+ let resp = app
+ .oneshot(
+ Request::builder()
+ .method("GET")
+ .uri("/admin/status?workspace=default&project=app")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(resp.status(), StatusCode::OK);
+}
+
+/// Same-named projects in two workspaces stay isolated in the scoped figures.
+#[tokio::test]
+async fn status_scoped_links_do_not_leak_across_workspaces() {
+ let tmp = TempDir::new().unwrap();
+ let (state, store) = make_admin_state(&tmp).await;
+ seed_linked_page(&store, "default", "app", "notes/one.md", &["notes/missing.md"]).await;
+ seed_linked_page(&store, "other", "app", "notes/one.md", &[]).await;
+ seed_linked_page(
+ &store,
+ "other",
+ "app",
+ "notes/two.md",
+ &["notes/missing.md", "notes/also-missing.md"],
+ )
+ .await;
+ let app = admin_router(state);
+
+ let resp = app
+ .clone()
+ .oneshot(
+ Request::builder()
+ .method("GET")
+ .uri("/admin/status?workspace=default&project=app")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(resp.status(), StatusCode::OK);
+ let body: serde_json::Value = serde_json::from_slice(&body_bytes(resp).await).unwrap();
+ assert_eq!(
+ body["links_scope"]["links_from_latest_pages"].as_u64(),
+ Some(1),
+ "default/app must not include the same-named project in `other`: {body}"
+ );
+ assert_eq!(
+ body["links_scope"]["unresolved_links_from_latest_pages"].as_u64(),
+ Some(1),
+ "{body}"
+ );
+ // Store-wide both workspaces count, so the scoped figure is a real subset.
+ assert_eq!(
+ body["derived"]["links_from_latest_pages"].as_u64(),
+ Some(3),
+ "{body}"
+ );
+
+ // Control: the other workspace's own figures (2 links, both unresolved).
+ let resp = app
+ .oneshot(
+ Request::builder()
+ .method("GET")
+ .uri("/admin/status?workspace=other&project=app")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(resp.status(), StatusCode::OK);
+ let body: serde_json::Value = serde_json::from_slice(&body_bytes(resp).await).unwrap();
+ assert_eq!(
+ body["links_scope"]["links_from_latest_pages"].as_u64(),
+ Some(2),
+ "{body}"
+ );
+ assert_eq!(
+ body["links_scope"]["unresolved_links_from_latest_pages"].as_u64(),
+ Some(2),
+ "{body}"
+ );
+}
+
#[tokio::test]
async fn search_returns_matching_hits() {
let tmp = TempDir::new().unwrap();
diff --git a/docs/security-boundaries.md b/docs/security-boundaries.md
index 0d9ccce7..48a24bf8 100644
--- a/docs/security-boundaries.md
+++ b/docs/security-boundaries.md
@@ -35,7 +35,7 @@ boundary not yet built.
| 8b | Messaging: cancel-own-only | `ai-memory-store/src/ops.rs` `cancel_messages` (AND-gated on `from_*` sender coordinate) | `agent_messages.rs` — whole-outbox **and** a foreign **specific-id** cancel refused | STRONG |
| 8c | Messaging: pop-exactly-once | `ai-memory-store/src/ops.rs` `pop_message_in_transaction` atomic CAS `WHERE state='pending'` | `agent_messages.rs` — sequential **and** `tokio::join!` concurrent double-pop yields exactly one `Some` | STRONG |
| 8d | Messaging: inferred-scope read is diagnosed (#854) | `scope.rs` `is_inferred`; `server.rs` `inferred_scope_hint` on empty pop/list | `agent_messages_briefing.rs` `no_scope_pop_that_misses_the_mail_is_diagnosed_not_a_silent_null` | STRONG |
-| 9 | Scope resolution fail-closed | `ai-memory-store/src/scope.rs` no-create `lookup_existing_*`; create only via `create_explicit_scope` | `scope.rs` no-auto-create + `unscoped_write_with_unresolvable_coordinate_errors` | STRONG |
+| 9 | Scope resolution fail-closed | `ai-memory-store/src/scope.rs` no-create `lookup_existing_*`; create only via `create_explicit_scope`; `ai-memory-mcp/src/admin.rs` `handle_status` resolves an optional `?workspace=&project=` pair through `lookup_ws_proj_no_create` (never `create_ws_proj`), so a scoped status read cannot mint a scope | `scope.rs` no-auto-create + `unscoped_write_with_unresolvable_coordinate_errors`; `admin_status_search.rs` `status_scoped_links_rejects_partial_scope`, `status_scoped_links_fails_closed_on_an_unknown_scope`, `status_scoped_links_do_not_leak_across_workspaces` | STRONG |
| 10 | Destructive-op live-process refusal + confirm flags (invariant #9) | `ai-memory-cli/src/commands/process_guard.rs` `sibling_processes` + confirm flags in `reset`/`restore`/`reindex`/`uninstall --purge-data`/`purge_project` | `admin_purge.rs` confirm→400; `removal.rs` — injected live-sibling makes each destructive command bail before touching the data dir | STRONG |
| 10b | Session purge is scope+owner-bound (no cross-session/project over-delete) | `ai-memory-store/src/ops.rs` `purge_session` — selection scoped to `(workspace_id, project_id)` and keyed on this session's own `summary_page_id` **or** `path='sessions/<sid>.md'` + `json_extract(frontmatter_json,'$.session_id')=<sid>` (frontmatter owner, not the recursive latest-chain); `in_scope==0 → NotFound` fail-closed; whole op in one transaction | `ops.rs` `purge_session_leaves_a_sibling_session_in_the_same_project_intact`, `…refuses_a_session_from_another_project_and_deletes_nothing`, `…refuses_a_session_from_another_workspace`, `…does_not_delete_an_identically_pathed_page_in_another_project`, `…removes_older_summary_versions_without_deleting_prior_manual_page` (#862) | STRONG |
| 11a | Hook backpressure (202/429) + bounded fan-out (invariant #5) | `ai-memory-hooks/src/router.rs` semaphore→429, 202 immediately, `MAX_HOOK_BATCH_ITEMS`, bounded LRU limiter | `router.rs` `handle_hook_returns_429_when_ingest_saturated`, `ingest_rate_limiter_is_bounded` | STRONG |