Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(read_page): include_related only walks pages the caller may read
luisfnicolauec65a6d90c38
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 439e4426..11a45e27 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Fixed+- `memory_read_page` with `include_related` no longer returns pages in projects+ the caller cannot read under per-project authorization, nor walks through+ them to reach others. `page_links` and the graph already hid them; the+ multi-hop related walk now filters every hop the same way. Installs without+ authorization, and root, are unchanged. (#NNN)+## [2.5.0] - 2026-09-30### Addeddiff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rsindex cd15657a..25375ef5 100644--- a/crates/ai-memory-mcp/src/server.rs+++ b/crates/ai-memory-mcp/src/server.rs@@ -4041,7 +4041,13 @@ impl AiMemoryServer {let depth = args.related_depth.unwrap_or(1);Some(self.reader- .related_walk(ws, proj, page_path.to_string(), depth)+ .related_walk(+ ws,+ proj,+ page_path.to_string(),+ depth,+ Self::viewer_from_parts(Some(&parts)),+ ).await.map_err(|e| McpError::internal_error(e.to_string(), None))?,)diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rsindex 81329e31..40136c20 100644--- a/crates/ai-memory-store/src/reader.rs+++ b/crates/ai-memory-store/src/reader.rs@@ -7444,6 +7444,12 @@ impl ReaderPool {////// Returns an empty vec when the seed is missing or has no neighbours.///+ /// `viewer` filters every hop the way [`Self::page_links`] filters its far+ /// end: a page in a project the viewer cannot read is neither returned+ /// nor walked through, so nothing reachable only through it is returned+ /// either. `None` (root, or per-repository authorization off) walks every+ /// latest page.+ ////// # Errors/// Propagates any SQL or pool error.pub async fn related_walk(@@ -7452,6 +7458,7 @@ impl ReaderPool {project_id: ProjectId,path: String,depth: u8,+ viewer: Option<UserId>,) -> StoreResult<Vec<RelatedNode>> {let depth = depth.clamp(1, RELATED_WALK_MAX_DEPTH);self.with_conn(move |conn| {@@ -7472,13 +7479,14 @@ impl ReaderPool {// (latest-only, cross-project) but also selects `pg.id` so the walk// can continue from each neighbour.let kind_expr = page_kind_expr("pg.path", "pg.frontmatter_json");+ let visible = readable_repository_predicate("pg.project_id", viewer);let outgoing = format!("SELECT DISTINCT pg.id, pg.path, pg.title, {kind_expr}, ws.name, pr.name \FROM links l \JOIN pages pg ON pg.id = l.to_page_id \JOIN projects pr ON pr.id = pg.project_id \JOIN workspaces ws ON ws.id = pg.workspace_id \- WHERE l.from_page_id = ?1 AND pg.is_latest = 1 \+ WHERE l.from_page_id = ?1 AND pg.is_latest = 1{visible} \ORDER BY ws.name, pr.name, pg.path");let incoming = format!(@@ -7487,7 +7495,7 @@ impl ReaderPool {JOIN pages pg ON pg.id = l.from_page_id \JOIN projects pr ON pr.id = pg.project_id \JOIN workspaces ws ON ws.id = pg.workspace_id \- WHERE l.to_page_id = ?1 AND pg.is_latest = 1 \+ WHERE l.to_page_id = ?1 AND pg.is_latest = 1{visible} \ORDER BY ws.name, pr.name, pg.path");let mut out_stmt = conn.prepare(&outgoing)?;diff --git a/crates/ai-memory-store/tests/suite/related_walk.rs b/crates/ai-memory-store/tests/suite/related_walk.rsindex fff2121d..60fe2534 100644--- a/crates/ai-memory-store/tests/suite/related_walk.rs+++ b/crates/ai-memory-store/tests/suite/related_walk.rs@@ -14,9 +14,13 @@//! result.//! - **A total-node cap** bounds the response regardless of depth.//! - **Cross-project links resolve** and carry their real workspace/project.+//! - **The walk honours per-project authorization (#708):** a viewer never+//! sees, nor walks through, a page in a project they cannot read.-use ai_memory_core::{NewPage, PagePath, ProjectId, Tier, WorkspaceId};-use ai_memory_store::{RELATED_WALK_MAX_DEPTH, RELATED_WALK_MAX_NODES, Store};+use ai_memory_core::{NewPage, NewUser, PagePath, ProjectId, Tier, UserId, WorkspaceId};+use ai_memory_store::{+ AccessMode, GrantLevel, RELATED_WALK_MAX_DEPTH, RELATED_WALK_MAX_NODES, Store,+};fn page_with_links(ws: WorkspaceId,@@ -150,7 +154,7 @@ async fn depth_one_returns_only_direct_neighbours() {let nodes = store.reader- .related_walk(ws, app, "notes/a.md".into(), 1)+ .related_walk(ws, app, "notes/a.md".into(), 1, None).await.unwrap();@@ -179,7 +183,7 @@ async fn depth_two_adds_second_hop_including_cross_project() {let nodes = store.reader- .related_walk(ws, app, "notes/a.md".into(), 2)+ .related_walk(ws, app, "notes/a.md".into(), 2, None).await.unwrap();@@ -209,13 +213,13 @@ async fn depth_is_clamped_to_the_hard_cap() {let capped = store.reader- .related_walk(ws, app, "notes/a.md".into(), RELATED_WALK_MAX_DEPTH)+ .related_walk(ws, app, "notes/a.md".into(), RELATED_WALK_MAX_DEPTH, None).await.unwrap();// Anything past the cap must behave exactly like the cap, not walk further.let over = store.reader- .related_walk(ws, app, "notes/a.md".into(), 100)+ .related_walk(ws, app, "notes/a.md".into(), 100, None).await.unwrap();@@ -239,7 +243,7 @@ async fn walk_is_dedup_and_cycle_safe() {// seed, and never return a page twice.let nodes = store.reader- .related_walk(ws, app, "notes/a.md".into(), RELATED_WALK_MAX_DEPTH)+ .related_walk(ws, app, "notes/a.md".into(), RELATED_WALK_MAX_DEPTH, None).await.unwrap();@@ -292,7 +296,7 @@ async fn total_node_cap_bounds_a_dense_hub() {let nodes = store.reader- .related_walk(ws, app, "hub.md".into(), 1)+ .related_walk(ws, app, "hub.md".into(), 1, None).await.unwrap();@@ -314,8 +318,122 @@ async fn missing_seed_returns_empty() {let (_tmp, store, ws, app) = seeded_graph().await;let nodes = store.reader- .related_walk(ws, app, "notes/does-not-exist.md".into(), 2)+ .related_walk(ws, app, "notes/does-not-exist.md".into(), 2, None).await.unwrap();assert!(nodes.is_empty(), "a missing seed yields no related pages");}++/// Under per-project authorization the walk shows only what the viewer may+/// read and never walks through what they may not, in either direction: a+/// page in a restricted project without a grant is absent, and so is a+/// readable page reachable only through it.+///+/// ```text+/// app:a ──▶ lib:x (lib restricted, viewer holds a grant)+/// app:a ──▶ secret:s ──▶ lib:y (secret restricted, no grant; lib:y only via s)+/// secret:t ──▶ app:a (incoming edge from the unreadable project)+/// ```+#[tokio::test]+async fn the_walk_hides_and_does_not_cross_projects_the_viewer_cannot_read() {+ let tmp = tempfile::tempdir().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let ws = store+ .writer+ .get_or_create_workspace("default".to_string())+ .await+ .unwrap();+ let mut projects = Vec::new();+ for name in ["app", "lib", "secret"] {+ projects.push(+ store+ .writer+ .get_or_create_project(ws, name.to_string(), None)+ .await+ .unwrap(),+ );+ }+ let (app, lib, secret) = (projects[0], projects[1], projects[2]);+ for page in [+ page_with_links(ws, lib, "notes/x.md", vec![]),+ page_with_links(ws, lib, "notes/y.md", vec![]),+ page_with_links(+ ws,+ secret,+ "notes/s.md",+ vec![cross_project_link("lib", "notes/y.md")],+ ),+ page_with_links(+ ws,+ app,+ "notes/a.md",+ vec![+ cross_project_link("lib", "notes/x.md"),+ cross_project_link("secret", "notes/s.md"),+ ],+ ),+ page_with_links(+ ws,+ secret,+ "notes/t.md",+ vec![cross_project_link("app", "notes/a.md")],+ ),+ ] {+ store.writer.upsert_page(page).await.unwrap();+ }+ for project in [lib, secret] {+ store+ .writer+ .set_access_mode(project, AccessMode::Restricted)+ .await+ .unwrap();+ }+ let viewer = store+ .writer+ .create_user(+ NewUser {+ username: "vera".into(),+ name: None,+ email: None,+ },+ [7; ai_memory_store::TOKEN_HASH_LEN],+ )+ .await+ .unwrap();+ store+ .writer+ .grant_memory(viewer, lib, GrantLevel::Read, None)+ .await+ .unwrap();++ let walk = |who: Option<UserId>| {+ let reader = store.reader.clone();+ async move {+ let mut seen: Vec<String> = reader+ .related_walk(ws, app, "notes/a.md".into(), RELATED_WALK_MAX_DEPTH, who)+ .await+ .unwrap()+ .into_iter()+ .map(|n| format!("{}:{}", n.page.project, n.page.path))+ .collect();+ seen.sort();+ seen+ }+ };++ assert_eq!(+ walk(Some(viewer)).await,+ vec!["lib:notes/x.md".to_string()],+ "secret:s and secret:t are unreadable, and lib:y is reachable only through s"+ );+ // Control: no viewer (root, or authorization off) walks the whole graph.+ assert_eq!(+ walk(None).await,+ vec![+ "lib:notes/x.md".to_string(),+ "lib:notes/y.md".to_string(),+ "secret:notes/s.md".to_string(),+ "secret:notes/t.md".to_string(),+ ]+ );+}diff --git a/docs/security-boundaries.md b/docs/security-boundaries.mdindex a842ed85..a66155e3 100644--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@ -59,6 +59,7 @@ boundary not yet built.| 14 | Per-project authorization (#708) | `ai-memory-store/src/project_authz.rs` `authorize_project` / `ProjectAuthz::authorize` choke point (V68 `project_grants` + `projects.access_mode`, default `open`; V69 `projects.created_by` feeds `is_creator`); `scope.rs` `ScopeResolver::with_project_authz` (reader pool for reads, writer actor for writes) and its free forms `authorize_scope_for` / `*_guarded`, attached for every DB user by `ai-memory-mcp` `scope_resolver_as`, `ai-memory-web` `authorize_read` / `lookup_project`, and `ai-memory-hooks` (`grants.rs` `authorize_resolved` for run/workstream ids, the capture check in `router.rs`); read-shaped mutations resolve at `ProjectAccess::Write` (`resolve_existing_args(.., need)`); unscoped reads filtered before `LIMIT` by `reader.rs` `readable_repository_sql`; `WriterHandle::authorize_project` as defense in depth. Page ids are never taken from a caller (only derived from already-authorized hits), so there is no page-id entry point to guard | `tests/suite/project_authz.rs` (decision matrix, ship-inert, resolver gate); `tests/suite/access_mode.rs` `every_caller_against_both_modes`, `a_restricted_project_admits_the_team_and_refuses_the_outsider`, `new_projects_follow_the_server_default_and_admit_their_creator`; `scope.rs` `the_argument_shape_does_not_decide_the_level`, `a_user_reaches_only_what_they_were_granted`, `creating_authorizes_against_a_project_that_already_exists`, `a_refused_scope_fails_the_search_instead_of_shortening_it`; `grants.rs` `search_finds_only_what_the_viewer_may_read`, `the_limit_counts_only_what_the_viewer_may_see`, `the_workspace_handoff_comes_only_from_readable_repositories`; `ai-memory-mcp` `server.rs` `a_reader_may_read_everything_and_change_nothing`, `bob_cannot_read_alices_page_in_a_restricted_project`, `bob_cannot_find_alices_page_by_searching_in_a_restricted_project`, `bob_cannot_consolidate_a_session_in_alices_repository`, `a_restricted_projects_queues_need_write`; `ai-memory-hooks` `a_capture_needs_writer_on_the_repository_it_lands_in`, `session_start_delivers_nothing_from_a_repository_the_viewer_cannot_read`, `run_and_workstream_ids_only_answer_someone_who_may_reach_the_repository`; `ai-memory-web` `web_reads_honour_grants_in_a_restricted_project`, `metadata_shows_only_what_the_viewer_may_read` — each with a granted or open-project control, and proven to fail with the choke point (18 tests) or the SQL filter (9 tests) neutralized | STRONG — slice 3 closed both bypass classes (unscoped reads, raw-id entry points) and added the root-only management surface. Out of scope by design: per-project administrators (granting/restricting is root-only), and access modes, creators and grants live only in SQLite, so `reindex` resets them || 14b | Repository identity routing (#708) | `ai-memory-store/src/ops.rs` `resolve_project_by_identity` — one transaction; an identity already on a project is never overwritten; an unclaimed project is claimed only when the capturing user may write it (the choke point's `resolve_project_authz` on the same transaction), otherwise it is returned unclaimed; a different identity under the same name splits into a new project with no shared `repo_path`; `ai-memory-hooks/src/router.rs` `cache_key_for` keys the path cache by identity too; `ai-memory-core/src/repository_identity.rs` strips credentials from remote URLs client-side, and the server accepts only the routing rungs (`explicit`, `git_remote`) from the wire | `tests/suite/identity_resolution.rs` `an_outsider_cannot_take_an_unclaimed_projects_identity` (control: `an_existing_project_is_claimed_in_place`), `two_unrelated_repositories_with_one_folder_name_stay_apart`, `a_created_or_split_project_admits_its_creator`; `router.rs` `one_path_with_two_remotes_is_two_projects`, `two_api_checkouts_with_different_remotes_get_two_projects` (a manifest rung on the wire is ignored); `repository_identity.rs` credential and normalisation tables — the claim guard and the cache key each proven to fail their test when removed | STRONG — first claimant wins: in a restricted workspace a user who creates a project under a remote identity first holds it until root grants others || 14c | Client-supplied event time is bounded and self-scoped (#919) | `ai-memory-hooks/src/payload.rs` `HookEnvelope::occurred_at_micros` — a `/hook` caller's optional `occurred_at` must be `> 0` and `<= now + 5min`; it only sets the caller's *own* admitted session's `started_at`/`ended_at`/`created_at`, never another session/project/user, and the ingest dedup `seen_at`/TTL stays on `now` | `payload.rs` `occurred_at_micros_rejects_a_far_future_timestamp`, `…_rejects_non_positive_values`, `…_rejects_garbage_strings` | MEDIUM — self-scoped numeric bound; no cross-tenant surface (a client already controls its own content) |+| 14d | `include_related` shows and walks only readable projects (#708) | `ai-memory-store/src/reader.rs` `related_walk(.., viewer)` — both the outgoing and incoming hop queries carry `readable_repository_predicate("pg.project_id", viewer)`, the same far-end filter `page_links` applies, so a page in a project the viewer cannot read is neither returned nor expanded; `ai-memory-mcp/src/server.rs` `memory_read_page` passes `viewer_from_parts`, and the access bump only touches the filtered nodes | `related_walk.rs` `the_walk_hides_and_does_not_cross_projects_the_viewer_cannot_read` (an outgoing and an incoming neighbour in an ungranted restricted project are absent, and so is a granted page reachable only through one; control: a granted restricted project is shown, and no viewer walks the whole graph) — fails with the predicate removed | STRONG |## Keeping this current (the standing protocol)