Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(store): per-project creator, grant storage and guarded resolution (#708)
luisfnicolau84cc8f334797
diff --git a/crates/ai-memory-store/migrations/V69__project_created_by.sql b/crates/ai-memory-store/migrations/V69__project_created_by.sqlnew file mode 100644index 00000000..98f8901c--- /dev/null+++ b/crates/ai-memory-store/migrations/V69__project_created_by.sql@@ -0,0 +1,15 @@+-- Per-project authorization: the project creator (#708, slice 3).+--+-- A `restricted` project admits root, its creator, and matching grants. V68+-- left the creator to the caller (`ProjectPrincipal::is_creator`); this column+-- lets the choke point derive it from the project row instead, so it cannot+-- disagree with who actually created the project.+--+-- Additive and nullable: every project that exists on upgrade has no recorded+-- creator, and so admits only root and grants once restricted. A project+-- created by the root token or on an install with no database users has none+-- either — nobody but root could have been its creator. Deleting the user+-- clears the column rather than the project.++ALTER TABLE projects+ ADD COLUMN created_by BLOB REFERENCES users(id) ON DELETE SET NULL;diff --git a/crates/ai-memory-store/src/api_credentials.rs b/crates/ai-memory-store/src/api_credentials.rsindex 1cc4780b..f354a240 100644--- a/crates/ai-memory-store/src/api_credentials.rs+++ b/crates/ai-memory-store/src/api_credentials.rs@@ -411,7 +411,7 @@ mod tests {|row| row.get(0),).unwrap();- assert_eq!(version, 68, "update the pin when adding a migration");+ assert_eq!(version, 69, "update the pin when adding a migration");let cols: i64 = conn.query_row("SELECT COUNT(*) FROM pragma_table_info('users') WHERE name = 'token_hash'",diff --git a/crates/ai-memory-store/src/grants.rs b/crates/ai-memory-store/src/grants.rsnew file mode 100644index 00000000..e5645c13--- /dev/null+++ b/crates/ai-memory-store/src/grants.rs@@ -0,0 +1,1153 @@+//! Per-project grants and access modes: storage (#708).+//!+//! The decision lives in [`crate::project_authz`]; this module keeps what it+//! reads — `project_grants` rows and `projects.access_mode` — and the+//! root-only management that changes them, each change recorded in+//! `audit_log`.++use ai_memory_core::{ProjectId, UserId, WorkspaceId};+use jiff::Timestamp;+use rusqlite::{Connection, OptionalExtension, params};++use crate::error::StoreResult;+use crate::project_authz::{AccessMode, GrantLevel};++fn ts(micros: i64) -> Timestamp {+ Timestamp::from_microsecond(micros).unwrap_or(Timestamp::UNIX_EPOCH)+}++/// One user's access to one project's memory — a row of `project_grants`.+///+/// What is granted is access to the project's *memory*, not to the code it+/// may describe: whoever hosts the repository decides that, and ai-memory+/// neither checks nor implies it.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct ProjectGrant {+ /// The workspace the project lives in.+ pub workspace_id: WorkspaceId,+ /// Which project's memory.+ pub project_id: ProjectId,+ /// Who may reach it. A person, not a device: revoking one laptop's key+ /// must not cost them access from another.+ pub user_id: UserId,+ /// What this grant permits.+ pub level: GrantLevel,+ /// Who granted it; `None` for the root bearer token, which authenticates+ /// from configuration and has no `users` row to name.+ pub granted_by: Option<UserId>,+ /// When it was granted, or last changed level.+ pub granted_at: Timestamp,+}++/// The access mode of a repository, or `None` when there is no such project.+///+/// A stored value this build does not recognise reads as `open`, as it does at+/// the choke point ([`AccessMode::from_db`]).+///+/// # Errors+/// Propagates SQL errors.+pub fn access_mode_of(+ conn: &Connection,+ repository_id: ProjectId,+) -> StoreResult<Option<AccessMode>> {+ let stored: Option<Option<String>> = conn+ .query_row(+ "SELECT access_mode FROM projects WHERE id = ?1",+ params![repository_id.as_bytes()],+ |row| row.get(0),+ )+ .optional()?;+ Ok(stored.map(|mode| AccessMode::from_db(mode.as_deref())))+}++/// Set a repository's access mode, returning the mode it had. `None` when the+/// repository does not exist.+///+/// # Errors+/// Propagates SQL errors.+pub fn set_access_mode(+ conn: &Connection,+ repository_id: ProjectId,+ mode: AccessMode,+) -> StoreResult<Option<AccessMode>> {+ let Some(previous) = access_mode_of(conn, repository_id)? else {+ return Ok(None);+ };+ conn.execute(+ "UPDATE projects SET access_mode = ?1 WHERE id = ?2",+ params![mode.as_str(), repository_id.as_bytes()],+ )?;+ Ok(Some(previous))+}++/// Users who have written to `repository_id` and would not be admitted if it+/// were restricted: enabled, not root, not its creator, and holding no grant+/// on it.+///+/// What an operator needs to see when restricting a project — the people who+/// were working in it and are about to be refused — so they can grant the ones+/// who should stay. "Written to" is page authorship, the attribution upstream+/// already records.+///+/// # Errors+/// Propagates SQL errors.+pub fn authors_without_grant(+ conn: &Connection,+ repository_id: ProjectId,+) -> StoreResult<Vec<String>> {+ let mut stmt = conn.prepare(+ "SELECT DISTINCT u.username FROM pages p \+ JOIN users u ON u.id = p.author_id \+ WHERE p.project_id = ?1 \+ AND u.role <> 'root' AND u.disabled_at IS NULL \+ AND NOT EXISTS (SELECT 1 FROM projects pr \+ WHERE pr.id = ?1 AND pr.created_by = u.id) \+ AND NOT EXISTS (SELECT 1 FROM project_grants pg \+ WHERE pg.user_id = u.id AND pg.project_id = ?1) \+ ORDER BY u.username",+ )?;+ let names = stmt+ .query_map(params![repository_id.as_bytes()], |row| row.get(0))?+ .collect::<Result<Vec<String>, _>>()?;+ Ok(names)+}++/// The grant this user holds on this project, if any — at most one, the+/// table's primary key being `(workspace, project, user)`.+///+/// A row that cannot be parsed is **skipped and logged**, never repaired into+/// something plausible. Fabricating a level for a malformed row in an+/// authorization table risks inventing access that nobody granted; dropping it+/// can only ever deny, which is the safe direction to fail.+///+/// # Errors+/// Propagates any SQL error.+pub fn grants_for(+ conn: &Connection,+ user_id: UserId,+ project_id: ProjectId,+) -> StoreResult<Vec<ProjectGrant>> {+ let mut stmt = conn.prepare(+ "SELECT workspace_id, level, granted_by, granted_at \+ FROM project_grants WHERE user_id = ?1 AND project_id = ?2",+ )?;+ let rows = stmt.query_map(params![user_id.as_bytes(), project_id.as_bytes()], |row| {+ Ok((+ row.get::<_, Vec<u8>>(0)?,+ row.get::<_, String>(1)?,+ row.get::<_, Option<Vec<u8>>>(2)?,+ row.get::<_, i64>(3)?,+ ))+ })?;+ let mut grants = Vec::new();+ for row in rows {+ let (workspace, level, by, at) = row?;+ // An ABSENT granter is the root-token case and parses fine. One that+ // is present but unreadable does not: a value we cannot read is never+ // guessed at, and skipping can only ever deny.+ let granter = match &by {+ None => Some(None),+ Some(raw) => UserId::from_slice(raw).ok().map(Some),+ };+ let parsed = WorkspaceId::from_slice(&workspace)+ .ok()+ .zip(granter)+ .zip(GrantLevel::from_db(&level));+ let Some(((workspace_id, granted_by), level)) = parsed else {+ tracing::error!(+ %level,+ "skipping a malformed project_grants row; access will be denied \+ as though it were absent",+ );+ continue;+ };+ grants.push(ProjectGrant {+ workspace_id,+ project_id,+ user_id,+ level,+ granted_by,+ granted_at: ts(at),+ });+ }+ Ok(grants)+}++/// What a call to [`grant`] actually did.+///+/// Returned rather than inferred so an operator's tooling can say "already had+/// that" instead of reporting a change it did not make.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum GrantOutcome {+ /// There was no grant; one was created.+ Granted,+ /// A grant existed at a different level and was changed.+ LevelChanged {+ /// The level held before this call.+ from: GrantLevel,+ },+ /// A grant at exactly this level already existed. Nothing written.+ Unchanged,+}++/// Record a grant change in `audit_log`, the durable answer to "who could+/// reach this, since when, and who decided". The grant table itself only+/// holds what is in force now.+fn audit_grant(+ conn: &Connection,+ op: &str,+ workspace_id: WorkspaceId,+ project_id: ProjectId,+ by: Option<UserId>,+ detail: &serde_json::Value,+ now: i64,+) -> StoreResult<()> {+ conn.execute(+ "INSERT INTO audit_log (at, op, workspace_id, project_id, page_id, author_id, detail) \+ VALUES (?1, ?2, ?3, ?4, NULL, ?5, ?6)",+ params![+ now,+ op,+ workspace_id.as_bytes(),+ project_id.as_bytes(),+ by.map(|by| by.as_bytes().to_vec()),+ detail.to_string(),+ ],+ )?;+ Ok(())+}++/// Grant `user_id` `level` on `project_id`, or change the level they hold.+///+/// `granted_by` is `None` for the root bearer token. Every change is recorded in `audit_log` (`grant_access`, with the previous+/// level when there was one).+///+/// # Errors+/// [`crate::StoreError::NotFound`] when the project does not exist; otherwise+/// propagates any SQL error.+pub fn grant(+ conn: &Connection,+ user_id: UserId,+ project_id: ProjectId,+ level: GrantLevel,+ granted_by: Option<UserId>,+ now: i64,+) -> StoreResult<GrantOutcome> {+ let held = grants_for(conn, user_id, project_id)?.into_iter().next();+ let outcome = match &held {+ Some(held) if held.level == level => return Ok(GrantOutcome::Unchanged),+ Some(held) => GrantOutcome::LevelChanged { from: held.level },+ None => GrantOutcome::Granted,+ };+ let workspace_id: Option<Vec<u8>> = conn+ .query_row(+ "SELECT workspace_id FROM projects WHERE id = ?1",+ params![project_id.as_bytes()],+ |row| row.get(0),+ )+ .optional()?;+ let workspace_id = workspace_id+ .and_then(|bytes| WorkspaceId::from_slice(&bytes).ok())+ .ok_or_else(|| crate::StoreError::NotFound(format!("project {project_id}")))?;+ conn.execute(+ "INSERT INTO project_grants \+ (workspace_id, project_id, user_id, level, granted_by, granted_at) \+ VALUES (?1, ?2, ?3, ?4, ?5, ?6) \+ ON CONFLICT (workspace_id, project_id, user_id) DO UPDATE SET \+ level = excluded.level, granted_by = excluded.granted_by, \+ granted_at = excluded.granted_at",+ params![+ workspace_id.as_bytes(),+ project_id.as_bytes(),+ user_id.as_bytes(),+ level.as_str(),+ granted_by.map(|by| by.as_bytes().to_vec()),+ now,+ ],+ )?;+ let previous = held.map(|held| held.level.as_str());+ audit_grant(+ conn,+ "grant_access",+ workspace_id,+ project_id,+ granted_by,+ &serde_json::json!({+ "user_id": user_id.to_string(),+ "level": level.as_str(),+ "previous": previous,+ }),+ now,+ )?;+ Ok(outcome)+}++/// Take away whatever `user_id` holds on `project_id`.+///+/// Returns whether anything was actually revoked, so revoking twice is+/// harmless and still reports honestly. The revocation is recorded in+/// `audit_log` (`revoke_access`); `revoked_by` is `None` for the root bearer+/// token, and must never be able to prevent a revocation — taking access away+/// is what most needs to work when something has gone wrong.+///+/// # Errors+/// Propagates any SQL error.+pub fn revoke(+ conn: &Connection,+ user_id: UserId,+ project_id: ProjectId,+ revoked_by: Option<UserId>,+ now: i64,+) -> StoreResult<bool> {+ let Some(held) = grants_for(conn, user_id, project_id)?.into_iter().next() else {+ return Ok(false);+ };+ conn.execute(+ "DELETE FROM project_grants WHERE user_id = ?1 AND project_id = ?2",+ params![user_id.as_bytes(), project_id.as_bytes()],+ )?;+ audit_grant(+ conn,+ "revoke_access",+ held.workspace_id,+ project_id,+ revoked_by,+ &serde_json::json!({+ "user_id": user_id.to_string(),+ "level": held.level.as_str(),+ }),+ now,+ )?;+ Ok(true)+}++/// One row of the operator's grant listing, resolved to names.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct GrantListing {+ /// Who holds it.+ pub username: String,+ /// The workspace the project lives in.+ pub workspace: String,+ /// The project, by the name an operator would type.+ pub project: String,+ /// What they hold.+ pub level: GrantLevel,+}++/// Which grants a listing covers.+#[derive(Debug, Clone, Copy)]+pub enum GrantFilter {+ /// Every grant on the server.+ All,+ /// What one user reaches.+ User(UserId),+ /// Who reaches one project.+ Project(ProjectId),+}++/// Grants matching `filter`, ordered for human reading.+///+/// Names rather than ids: a listing an operator cannot read without three+/// further queries is not a listing.+///+/// # Errors+/// Propagates any SQL error.+pub fn list_grants(conn: &Connection, filter: GrantFilter) -> StoreResult<Vec<GrantListing>> {+ let (predicate, bound): (&str, Option<Vec<u8>>) = match filter {+ GrantFilter::All => ("1 = 1", None),+ GrantFilter::User(user) => (+ "project_grants.user_id = ?1",+ Some(user.as_bytes().to_vec()),+ ),+ GrantFilter::Project(project) => (+ "project_grants.project_id = ?1",+ Some(project.as_bytes().to_vec()),+ ),+ };+ let mut stmt = conn.prepare(&format!(+ "SELECT users.username, workspaces.name, projects.name, project_grants.level \+ FROM project_grants \+ JOIN users ON users.id = project_grants.user_id \+ JOIN projects ON projects.id = project_grants.project_id \+ JOIN workspaces ON workspaces.id = project_grants.workspace_id \+ WHERE {predicate} \+ ORDER BY workspaces.name, projects.name, users.username"+ ))?;+ let map = |row: &rusqlite::Row<'_>| {+ Ok((+ row.get::<_, String>(0)?,+ row.get::<_, String>(1)?,+ row.get::<_, String>(2)?,+ row.get::<_, String>(3)?,+ ))+ };+ let rows = match bound {+ Some(id) => stmt+ .query_map(params![id], map)?+ .collect::<Result<Vec<_>, _>>()?,+ None => stmt.query_map([], map)?.collect::<Result<Vec<_>, _>>()?,+ };+ let mut out = Vec::new();+ for (username, workspace, project, level) in rows {+ let Some(level) = GrantLevel::from_db(&level) else {+ // Same rule as `grants_for`: a row we cannot read is not repaired+ // into something plausible, even for display.+ tracing::error!(%username, %project, "skipping a malformed project_grants row in listing");+ continue;+ };+ out.push(GrantListing {+ username,+ workspace,+ project,+ level,+ });+ }+ Ok(out)+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::Store;+ use ai_memory_core::{NewUser, UserRole};++ struct Fixture {+ _tmp: tempfile::TempDir,+ store: Store,+ ws: ai_memory_core::WorkspaceId,+ alice: UserId,+ bob: UserId,+ client: ProjectId,+ personal: ProjectId,+ }++ async fn human(store: &Store, name: &str, role: UserRole) -> UserId {+ store+ .writer+ .create_human_user(+ NewUser {+ username: name.to_owned(),+ name: None,+ email: None,+ },+ role,+ None,+ false,+ )+ .await+ .unwrap()+ }++ async fn fixture() -> Fixture {+ let tmp = tempfile::TempDir::new().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ // Grants only decide anything in a restricted project; every project+ // these tests create starts restricted.+ store+ .writer+ .set_new_project_mode(AccessMode::Restricted)+ .await+ .unwrap();+ let ws = store+ .writer+ .get_or_create_workspace("default")+ .await+ .unwrap();+ let client = store+ .writer+ .get_or_create_project(ws, "client-work", None)+ .await+ .unwrap();+ let personal = store+ .writer+ .get_or_create_project(ws, "personal", None)+ .await+ .unwrap();+ let alice = human(&store, "alice", UserRole::User).await;+ let bob = human(&store, "bob", UserRole::User).await;+ Fixture {+ _tmp: tmp,+ store,+ ws,+ alice,+ bob,+ client,+ personal,+ }+ }++ fn all_rows(store: &Store, user: UserId, project: ProjectId) -> Vec<ProjectGrant> {+ let conn = Connection::open(store.db_path()).unwrap();+ grants_for(&conn, user, project).unwrap()+ }++ /// `(author_id, detail)` of every audit row with this `op`, oldest first.+ fn audit_rows(store: &Store, op: &str) -> Vec<(Option<Vec<u8>>, serde_json::Value)> {+ let conn = Connection::open(store.db_path()).unwrap();+ let mut stmt = conn+ .prepare("SELECT author_id, detail FROM audit_log WHERE op = ?1 ORDER BY id")+ .unwrap();+ stmt.query_map(params![op], |row| {+ let detail: String = row.get(1)?;+ Ok((row.get(0)?, serde_json::from_str(&detail).unwrap()))+ })+ .unwrap()+ .collect::<Result<_, _>>()+ .unwrap()+ }++ /// One row per user and project: a level change updates it, and every+ /// change — not a repeat — lands in the audit log with who made it.+ #[tokio::test]+ async fn granting_reports_what_it_did_and_every_change_is_audited() {+ let f = fixture().await;+ let w = &f.store.writer;++ assert_eq!(+ w.grant_memory(f.alice, f.client, GrantLevel::Read, Some(f.bob))+ .await+ .unwrap(),+ GrantOutcome::Granted+ );+ assert_eq!(+ w.grant_memory(f.alice, f.client, GrantLevel::Read, Some(f.bob))+ .await+ .unwrap(),+ GrantOutcome::Unchanged,+ "the same level again is not a change"+ );+ assert_eq!(+ w.grant_memory(f.alice, f.client, GrantLevel::Write, Some(f.bob))+ .await+ .unwrap(),+ GrantOutcome::LevelChanged {+ from: GrantLevel::Read+ }+ );++ let rows = all_rows(&f.store, f.alice, f.client);+ assert_eq!(rows.len(), 1);+ assert_eq!(rows[0].level, GrantLevel::Write);+ assert_eq!(rows[0].granted_by, Some(f.bob));++ let audit = audit_rows(&f.store, "grant_access");+ assert_eq!(audit.len(), 2, "grant and level change, not the repeat");+ assert_eq!(audit[0].0, Some(f.bob.as_bytes().to_vec()));+ assert_eq!(audit[0].1["level"], "read");+ assert_eq!(audit[1].1["level"], "write");+ assert_eq!(audit[1].1["previous"], "read");+ assert_eq!(audit[1].1["user_id"], f.alice.to_string());+ }++ /// Revoking deletes the grant and records it; revoking again is honest+ /// about there being nothing to take. A revoked user reads exactly like one+ /// never granted.+ #[tokio::test]+ async fn revoking_is_honest_and_audited() {+ let f = fixture().await;+ let w = &f.store.writer;+ w.grant_memory(f.alice, f.client, GrantLevel::Write, Some(f.bob))+ .await+ .unwrap();++ assert!(+ w.revoke_memory(f.alice, f.client, Some(f.bob))+ .await+ .unwrap()+ );+ assert!(+ !w.revoke_memory(f.alice, f.client, Some(f.bob))+ .await+ .unwrap()+ );++ assert!(all_rows(&f.store, f.alice, f.client).is_empty());+ assert!(+ f.store+ .reader+ .authorize_project(+ f.ws,+ f.client,+ crate::ProjectPrincipal::user(f.alice),+ true,+ crate::ProjectAccess::Read,+ )+ .await+ .unwrap()+ .is_err(),+ "a revoked user reads like one never granted"+ );+ let audit = audit_rows(&f.store, "revoke_access");+ assert_eq!(audit.len(), 1, "the no-op second revoke writes nothing");+ assert_eq!(audit[0].1["level"], "write");+ }++ #[tokio::test]+ async fn the_root_token_can_grant_and_revoke_without_a_users_row() {+ // The operator on a bearer-token install has no `users` row. They must+ // still be able to take access away — that is the operation that most+ // needs to work when something has gone wrong.+ let f = fixture().await;+ let w = &f.store.writer;+ w.grant_memory(f.alice, f.client, GrantLevel::Write, None)+ .await+ .unwrap();+ assert_eq!(all_rows(&f.store, f.alice, f.client)[0].granted_by, None);+ assert!(w.revoke_memory(f.alice, f.client, None).await.unwrap());+ assert!(all_rows(&f.store, f.alice, f.client).is_empty());+ for op in ["grant_access", "revoke_access"] {+ assert_eq!(+ audit_rows(&f.store, op)[0].0,+ None,+ "{op} by the root token"+ );+ }+ }++ async fn page(store: &Store, repository: ProjectId, path: &str, body: &str) {+ let workspace = store+ .writer+ .get_or_create_workspace("default")+ .await+ .unwrap();+ store+ .writer+ .upsert_page(ai_memory_core::NewPage {+ workspace_id: workspace,+ project_id: repository,+ path: ai_memory_core::PagePath::new(path).unwrap(),+ title: path.to_owned(),+ body: body.to_owned(),+ tier: ai_memory_core::Tier::Semantic,+ frontmatter_json: serde_json::json!({}),+ pinned: false,+ links: Vec::new(),+ author_id: None,+ expires_at: None,+ entities: Vec::new(),+ evidence: Vec::new(),+ })+ .await+ .unwrap();+ }++ fn paths<T>(hits: &[T], path: impl Fn(&T) -> &str) -> Vec<String> {+ let mut out: Vec<String> = hits.iter().map(|h| path(h).to_owned()).collect();+ out.sort();+ out+ }++ /// The search filter is written in SQL as "any grant"; the choke point on+ /// every other path is `authorize_project(.., ProjectAccess::Read)`. They+ /// agree only because every level admits a read. This pins that, so adding+ /// a level that cannot read breaks a test rather than quietly widening+ /// search.+ #[test]+ fn every_grant_level_can_read_which_is_what_the_search_filter_assumes() {+ for level in [GrantLevel::Read, GrantLevel::Write] {+ let ctx = crate::ProjectAuthz {+ distinguishes_operators: true,+ access_mode: AccessMode::Restricted,+ is_root: false,+ is_creator: false,+ grant: Some(level),+ };+ assert!(+ crate::authorize_project(&ctx, crate::ProjectAccess::Read).is_ok(),+ "{level:?}"+ );+ }+ }++ #[tokio::test]+ async fn search_finds_only_what_the_viewer_may_read() {+ let f = fixture().await;+ let r = &f.store.reader;+ page(+ &f.store,+ f.client,+ "secrets/rates.md",+ "confidential day rate",+ )+ .await;+ page(&f.store, f.personal, "notes/rates.md", "personal day rate").await;+ let global = crate::create_global_scope(&f.store.writer).await.unwrap();+ page(+ &f.store,+ global.project_id,+ "prefs/rates.md",+ "shared day rate",+ )+ .await;+ f.store+ .writer+ .grant_memory(f.alice, f.client, GrantLevel::Read, None)+ .await+ .unwrap();++ let as_viewer = |viewer| async move {+ (+ paths(+ &r.search_pages("rate".into(), 10, viewer).await.unwrap(),+ |h| h.path.as_str(),+ ),+ paths(+ &r.search_pages_with_meta("rate".into(), 10, None, viewer)+ .await+ .unwrap(),+ |h| h.path.as_str(),+ ),+ paths(&r.recent_pages_global(10, viewer).await.unwrap(), |h| {+ h.path.as_str()+ }),+ )+ };++ // Alice holds a grant on the client project: she finds it, plus the+ // shared global scope, and nothing from the project she was never+ // given.+ let alice = vec!["prefs/rates.md".to_owned(), "secrets/rates.md".to_owned()];+ assert_eq!(+ as_viewer(Some(f.alice)).await,+ (alice.clone(), alice.clone(), alice)+ );++ // Bob holds nothing: only the global scope, which is shared by design.+ let bob = vec!["prefs/rates.md".to_owned()];+ assert_eq!(+ as_viewer(Some(f.bob)).await,+ (bob.clone(), bob.clone(), bob)+ );++ // No viewer — an install with no database users, or root — sees everything, as before.+ let all = vec![+ "notes/rates.md".to_owned(),+ "prefs/rates.md".to_owned(),+ "secrets/rates.md".to_owned(),+ ];+ assert_eq!(as_viewer(None).await, (all.clone(), all.clone(), all));++ // A revoked grant hides the repository again.+ f.store+ .writer+ .revoke_memory(f.alice, f.client, None)+ .await+ .unwrap();+ let revoked = vec!["prefs/rates.md".to_owned()];+ assert_eq!(+ as_viewer(Some(f.alice)).await,+ (revoked.clone(), revoked.clone(), revoked)+ );+ }++ #[tokio::test]+ async fn the_limit_counts_only_what_the_viewer_may_see() {+ // Filtering after LIMIT would hand bob a short page: of the first ten+ // matches, most are alice's. Filtering in the query fills his limit+ // from what he can read, and does not tell him how much was hidden.+ //+ // The hidden pages are built to win every ordering these queries use —+ // more of them than the 40 candidates a limit of 10 over-fetches,+ // ranked higher (the needle repeated) and written more recently — so a+ // filter applied after the LIMIT would leave bob with nothing at all.+ let f = fixture().await;+ let r = &f.store.reader;+ for n in 0..12 {+ page(+ &f.store,+ f.personal,+ &format!("visible/{n:02}.md"),+ "needle visible",+ )+ .await;+ }+ for n in 0..60 {+ page(+ &f.store,+ f.client,+ &format!("hidden/{n:02}.md"),+ "needle needle needle needle hidden",+ )+ .await;+ }+ // Without a viewer the hidden pages crowd out every visible one, which+ // is what makes the assertions below mean something.+ let unfiltered = r.search_pages("needle".into(), 10, None).await.unwrap();+ assert!(+ unfiltered+ .iter()+ .all(|h| h.path.as_str().starts_with("hidden/"))+ );+ let unfiltered = r.recent_pages_global(10, None).await.unwrap();+ assert!(unfiltered.iter().all(|h| h.project_name == "client-work"));++ f.store+ .writer+ .grant_memory(f.bob, f.personal, GrantLevel::Read, None)+ .await+ .unwrap();++ let hits = r+ .search_pages("needle".into(), 10, Some(f.bob))+ .await+ .unwrap();+ assert_eq!(hits.len(), 10);+ assert!(hits.iter().all(|h| h.path.as_str().starts_with("visible/")));++ let hits = r+ .search_pages_with_meta("needle".into(), 10, None, Some(f.bob))+ .await+ .unwrap();+ assert_eq!(hits.len(), 10);+ assert!(hits.iter().all(|h| h.project_name == "personal"));++ let hits = r.recent_pages_global(10, Some(f.bob)).await.unwrap();+ assert_eq!(hits.len(), 10);+ assert!(hits.iter().all(|h| h.project_name == "personal"));+ }++ #[tokio::test]+ async fn the_listing_shows_names_and_only_what_is_in_force() {+ let f = fixture().await;+ let w = &f.store.writer;+ w.grant_memory(f.alice, f.client, GrantLevel::Write, None)+ .await+ .unwrap();+ w.grant_memory(f.bob, f.personal, GrantLevel::Read, None)+ .await+ .unwrap();+ w.revoke_memory(f.bob, f.personal, None).await.unwrap();++ let listing = f.store.reader.list_grants(GrantFilter::All).await.unwrap();+ assert_eq!(+ listing,+ vec![GrantListing {+ username: "alice".into(),+ workspace: "default".into(),+ project: "client-work".into(),+ level: GrantLevel::Write,+ }]+ );++ // Filtered: what one user reaches, and who reaches one project.+ w.grant_memory(f.bob, f.client, GrantLevel::Read, None)+ .await+ .unwrap();+ let alice = f+ .store+ .reader+ .list_grants(GrantFilter::User(f.alice))+ .await+ .unwrap();+ assert_eq!(alice.len(), 1);+ assert_eq!(alice[0].username, "alice");+ let on_client = f+ .store+ .reader+ .list_grants(GrantFilter::Project(f.client))+ .await+ .unwrap();+ let names: Vec<_> = on_client.iter().map(|g| g.username.as_str()).collect();+ assert_eq!(names, ["alice", "bob"]);+ assert!(+ f.store+ .reader+ .list_grants(GrantFilter::Project(f.personal))+ .await+ .unwrap()+ .is_empty()+ );+ }++ /// A grant never outlives its project: purging it takes the grants too, as+ /// the design's CASCADE says, and the audit log still says who had access.+ #[tokio::test]+ async fn purging_a_project_takes_its_grants_and_keeps_the_audit_trail() {+ let f = fixture().await;+ f.store+ .writer+ .grant_memory(f.alice, f.client, GrantLevel::Write, None)+ .await+ .unwrap();+ f.store+ .writer+ .purge_project(+ f.ws,+ f.client,+ "default/client-work",+ None,+ false,+ crate::Compaction::Skip,+ )+ .await+ .expect("a grant in force does not stand in a purge's way");+ let conn = Connection::open(f.store.db_path()).unwrap();+ let left: i64 = conn+ .query_row(+ "SELECT COUNT(*) FROM project_grants WHERE project_id = ?1",+ params![f.client.as_bytes()],+ |row| row.get(0),+ )+ .unwrap();+ assert_eq!(left, 0);+ assert_eq!(audit_rows(&f.store, "grant_access").len(), 1);+ }++ /// Deleting a workspace cascades through its projects to their grants.+ #[tokio::test]+ async fn deleting_a_workspace_takes_its_grants() {+ let f = fixture().await;+ let w = &f.store.writer;+ let team = w.get_or_create_workspace("team-b").await.unwrap();+ let api = w.get_or_create_project(team, "api", None).await.unwrap();+ w.grant_memory(f.alice, api, GrantLevel::Write, None)+ .await+ .unwrap();+ w.delete_workspace(team, true, crate::Compaction::Skip)+ .await+ .unwrap();+ assert!(all_rows(&f.store, f.alice, api).is_empty());+ }++ /// The hollow-project sweep is upstream's, unchanged: an empty project is+ /// swept after its age cutoff whether or not someone holds a grant on it,+ /// and the grant goes with it.+ #[tokio::test]+ async fn an_empty_project_is_swept_even_when_someone_holds_a_grant() {+ let f = fixture().await;+ let w = &f.store.writer;+ let probe = w.get_or_create_project(f.ws, "probe", None).await.unwrap();+ w.grant_memory(f.alice, probe, GrantLevel::Write, None)+ .await+ .unwrap();+ let mut conn = Connection::open(f.store.db_path()).unwrap();+ conn.execute(+ "UPDATE projects SET created_at = 0 WHERE id = ?1",+ params![probe.as_bytes()],+ )+ .unwrap();+ let swept = crate::ops::sweep_hollow_projects(&mut conn, 1).unwrap();+ assert!(swept.contains(&"probe".to_owned()), "{swept:?}");+ assert!(all_rows(&f.store, f.alice, probe).is_empty());+ }++ #[tokio::test]+ async fn rename_and_a_true_move_keep_the_grants_with_the_project() {+ // Both keep the project id, so the grants stay attached to the same+ // content — the id, not the name, is the key. A move to another+ // workspace carries the grant's workspace along with it.+ let f = fixture().await;+ let w = &f.store.writer;+ w.grant_memory(f.alice, f.client, GrantLevel::Write, None)+ .await+ .unwrap();++ w.rename_project(f.ws, f.client, "client-renamed", None)+ .await+ .unwrap();+ let elsewhere = w.get_or_create_workspace("elsewhere").await.unwrap();+ w.move_project_workspace(f.client, f.ws, elsewhere)+ .await+ .unwrap();++ let grants = all_rows(&f.store, f.alice, f.client);+ assert_eq!(grants[0].workspace_id, elsewhere);+ assert!(+ f.store+ .reader+ .authorize_project(+ elsewhere,+ f.client,+ crate::ProjectPrincipal::user(f.alice),+ true,+ crate::ProjectAccess::Write,+ )+ .await+ .unwrap()+ .is_ok()+ );+ let listing = f.store.reader.list_grants(GrantFilter::All).await.unwrap();+ assert_eq!(listing[0].workspace, "elsewhere");+ assert_eq!(listing[0].project, "client-renamed");++ // And deleting the workspace it left does not take it.+ w.delete_workspace(f.ws, true, crate::Compaction::Skip)+ .await+ .unwrap();+ assert_eq!(all_rows(&f.store, f.alice, f.client).len(), 1);+ }++ /// Both forms of "may read" are built from one SQL template, but they+ /// reach it by different routes — bound parameters and spliced literals —+ /// and a quoting or numbering slip in either would silently widen or+ /// narrow one set of surfaces. This runs both against the same data.+ #[tokio::test]+ async fn the_spliced_predicate_and_the_bound_filter_admit_the_same_repositories() {+ let f = fixture().await;+ let w = &f.store.writer;+ let global = crate::create_global_scope(w).await.unwrap();+ w.grant_memory(f.alice, f.client, GrantLevel::Read, None)+ .await+ .unwrap();+ w.grant_memory(f.bob, f.personal, GrantLevel::Write, None)+ .await+ .unwrap();+ w.revoke_memory(f.bob, f.personal, None).await.unwrap();++ let conn = Connection::open(f.store.db_path()).unwrap();+ let ids = |sql: String, binds: Vec<rusqlite::types::Value>| -> Vec<ProjectId> {+ let mut stmt = conn.prepare(&sql).unwrap();+ let mut out: Vec<ProjectId> = stmt+ .query_map(rusqlite::params_from_iter(binds.iter()), |row| {+ row.get::<_, Vec<u8>>(0)+ })+ .unwrap()+ .map(|id| ProjectId::from_slice(&id.unwrap()).unwrap())+ .collect();+ out.sort_by_key(|id| *id.as_bytes());+ out+ };+ let sorted = |mut v: Vec<ProjectId>| {+ v.sort_by_key(|id| *id.as_bytes());+ v+ };+ for (viewer, expected) in [+ (f.alice, sorted(vec![f.client, global.project_id])),+ // bob's only grant was revoked: the shared scope is all that is left.+ (f.bob, vec![global.project_id]),+ ] {+ let (bound, binds) =+ crate::reader::readable_repository_filter("projects.id", Some(viewer), 1);+ let spliced = crate::reader::readable_repository_predicate("projects.id", Some(viewer));+ let via_binds = ids(format!("SELECT id FROM projects WHERE 1 = 1{bound}"), binds);+ let via_splice = ids(+ format!("SELECT id FROM projects WHERE 1 = 1{spliced}"),+ Vec::new(),+ );+ assert_eq!(via_binds, expected, "bound filter");+ assert_eq!(via_splice, via_binds, "the two forms disagree");+ }+ assert!(+ crate::reader::readable_repository_predicate("projects.id", None).is_empty(),+ "no viewer must leave the query exactly as it was"+ );+ }++ fn unowned_handoff(+ workspace_id: ai_memory_core::WorkspaceId,+ project_id: ProjectId,+ summary: &str,+ ) -> ai_memory_core::NewHandoff {+ ai_memory_core::NewHandoff {+ workspace_id,+ project_id,+ from_session_id: None,+ from_agent: ai_memory_core::AgentKind::ClaudeCode,+ to_agent: None,+ cwd: None,+ summary: summary.into(),+ open_questions: Vec::new(),+ next_steps: Vec::new(),+ files_touched: Vec::new(),+ owner_user: None,+ }+ }++ /// An unowned handoff is visible to everyone who can see its repository —+ /// which is exactly why it must not reach someone who cannot. The query+ /// keeps its `LIMIT 1`, so a newer handoff in a hidden repository must not+ /// shadow an older one the viewer is entitled to either.+ #[tokio::test]+ async fn the_workspace_handoff_comes_only_from_readable_repositories() {+ let f = fixture().await;+ let w = &f.store.writer;+ w.grant_memory(f.alice, f.client, GrantLevel::Read, None)+ .await+ .unwrap();+ w.grant_memory(f.bob, f.personal, GrantLevel::Read, None)+ .await+ .unwrap();+ w.insert_handoff(unowned_handoff(f.ws, f.personal, "bob's older baton"))+ .await+ .unwrap();+ w.insert_handoff(unowned_handoff(f.ws, f.client, "alice's client baton"))+ .await+ .unwrap();+ let latest = |viewer| {+ let reader = f.store.reader.clone();+ let ws = f.ws;+ async move {+ reader+ .latest_open_handoff_for_workspace(ws, ai_memory_core::OwnerFilter::Any, viewer)+ .await+ .unwrap()+ .map(|h| h.content.summary)+ }+ };+ assert_eq!(+ latest(Some(f.alice)).await.as_deref(),+ Some("alice's client baton")+ );+ assert_eq!(+ latest(Some(f.bob)).await.as_deref(),+ Some("bob's older baton"),+ "the newer, hidden handoff shadowed the one bob may read"+ );+ assert_eq!(+ latest(None).await.as_deref(),+ Some("alice's client baton"),+ "no viewer is unchanged"+ );+ }++ /// Health's duplicate list compares titles through an inner query. If only+ /// the outer query were filtered, a hidden page sharing a title would still+ /// make the visible one show up as a duplicate — confirming, by its+ /// presence, a page the viewer cannot see.+ #[tokio::test]+ async fn a_hidden_page_does_not_make_a_visible_one_a_duplicate() {+ let f = fixture().await;+ f.store+ .writer+ .grant_memory(f.alice, f.client, GrantLevel::Read, None)+ .await+ .unwrap();+ for repo in [f.client, f.personal] {+ f.store+ .writer+ .upsert_page(ai_memory_core::NewPage {+ workspace_id: f.ws,+ project_id: repo,+ path: ai_memory_core::PagePath::new("notes/plan.md").unwrap(),+ title: "Plan".into(),+ body: "same title in two repositories".into(),+ tier: ai_memory_core::Tier::Semantic,+ frontmatter_json: serde_json::json!({}),+ pinned: false,+ links: Vec::new(),+ author_id: None,+ expires_at: None,+ entities: Vec::new(),+ evidence: Vec::new(),+ })+ .await+ .unwrap();+ }+ let r = &f.store.reader;+ let (_, dups, _) = r+ .memory_health_for_workspace(f.ws, Some(f.alice))+ .await+ .unwrap();+ assert_eq!(dups, 0, "alice's count includes a page she cannot see");+ let detail = r+ .health_detail_for_workspace(f.ws, 10, Some(f.alice))+ .await+ .unwrap();+ assert!(detail.duplicates.is_empty(), "{:?}", detail.duplicates);++ let (_, dups, _) = r.memory_health_for_workspace(f.ws, None).await.unwrap();+ assert_eq!(dups, 1, "no viewer still sees the pair");+ let detail = r.health_detail_for_workspace(f.ws, 10, None).await.unwrap();+ assert_eq!(detail.duplicates.len(), 2);+ }+}diff --git a/crates/ai-memory-store/src/lib.rs b/crates/ai-memory-store/src/lib.rsindex 5b08c775..d547448c 100644--- a/crates/ai-memory-store/src/lib.rs+++ b/crates/ai-memory-store/src/lib.rs@@ -20,6 +20,7 @@ pub mod belief;pub mod decay;mod error;mod fts_query;+mod grants;mod maintenance;mod migrations;mod ops;@@ -53,6 +54,7 @@ pub use decay::{salience_after_feedback,};pub use error::{StoreError, StoreResult};+pub use grants::{GrantFilter, GrantListing, GrantOutcome, ProjectGrant};pub use maintenance::MaintenanceJob;pub use ops::{AdmittedSession, BootstrapChunkRecord, CompactSummary, Compaction, DeleteWorkspaceSummary,@@ -83,9 +85,10 @@ pub use reader::{pub use retrieval_tuning::{RetrievalTuning, is_session_recall_query};pub use scope::{ResolvedScope, ScopeName, ScopeResolutionError, ScopeResolver, ScopeSource,- WORKSPACE_PROJECT_PAIR_REQUIRED, create_explicit_scope, create_global_scope,- lookup_existing_scope, lookup_existing_workspace, lookup_global_scope,- resolve_many_existing_scopes,+ WORKSPACE_PROJECT_PAIR_REQUIRED, authorize_scope_for, create_explicit_scope,+ create_explicit_scope_guarded, create_global_scope, lookup_existing_scope,+ lookup_existing_scope_guarded, lookup_existing_workspace, lookup_global_scope,+ resolve_many_existing_scopes, resolve_many_existing_scopes_guarded,};pub use session_consolidation::{SESSION_CONSOLIDATION_MAX_ATTEMPTS, SessionConsolidationJob};pub use users::{@@ -1946,7 +1949,7 @@ mod tests {store.writer.upsert_page(dep).await.unwrap();// Graph: exactly one resolved cross-project edge, app -> infra.- let edges = store.reader.cross_project_edges(None).await.unwrap();+ let edges = store.reader.cross_project_edges(None, None).await.unwrap();assert_eq!(edges.len(), 1, "one resolved cross-project edge");assert_eq!(edges[0].from_project, "app");assert_eq!(edges[0].to_project, "infra");@@ -2242,7 +2245,11 @@ mod tests {.await.unwrap();- let hits = store.reader.search_pages("quick".into(), 10).await.unwrap();+ let hits = store+ .reader+ .search_pages("quick".into(), 10, None)+ .await+ .unwrap();assert_eq!(hits.len(), 1);assert_eq!(hits[0].path.as_str(), "alpha.md");assert!(hits[0].snippet.contains("<mark>quick</mark>"));@@ -2264,7 +2271,11 @@ mod tests {assert_eq!(counts.pages_latest, 1);assert_eq!(counts.pages_all, 2);- let hits = store.reader.search_pages("quick".into(), 10).await.unwrap();+ let hits = store+ .reader+ .search_pages("quick".into(), 10, None)+ .await+ .unwrap();assert_eq!(hits.len(), 1);assert!(hits[0].snippet.contains("different"),@@ -2360,7 +2371,7 @@ mod tests {let global = store.reader- .search_pages_with_meta(query.into(), 10, None)+ .search_pages_with_meta(query.into(), 10, None, None).await.unwrap();assert_eq!(global[0].path.as_str(), "decisions/embedding-policy.md");@@ -2421,7 +2432,7 @@ mod tests {let hits = store.reader- .search_pages("pick: handoff bootstrap".into(), 10)+ .search_pages("pick: handoff bootstrap".into(), 10, None).await.unwrap();assert!(@@ -2458,7 +2469,7 @@ mod tests {let hits = store.reader- .search_pages("descricao sessao".into(), 10)+ .search_pages("descricao sessao".into(), 10, None).await.unwrap();assert!(@@ -2489,7 +2500,7 @@ mod tests {let hits = store.reader- .search_pages("quick OR slow".into(), 10)+ .search_pages("quick OR slow".into(), 10, None).await.unwrap();assert!(!hits.is_empty(), "OR must remain an FTS5 operator");@@ -4474,7 +4485,7 @@ mod tests {.await.unwrap();- let summaries = store.reader.list_projects_with_stats().await.unwrap();+ let summaries = store.reader.list_projects_with_stats(None).await.unwrap();assert_eq!(summaries.len(), 1);let s = &summaries[0];assert_eq!(s.workspace_name, "default");@@ -4610,7 +4621,7 @@ mod tests {assert_briefing_kinds(&store.reader- .briefing_for_workspace(ws, 100, ai_memory_core::OwnerFilter::Any)+ .briefing_for_workspace(ws, 100, ai_memory_core::OwnerFilter::Any, None).await.unwrap().recent_pages,@@ -4664,13 +4675,13 @@ mod tests {let source_links = store.reader- .page_links(ws, proj, "notes/source.md".into())+ .page_links(ws, proj, "notes/source.md".into(), None).await.unwrap();assert_eq!(source_links.links[0].kind, "session");let target_links = store.reader- .page_links(ws, proj, "sessions/session.md".into())+ .page_links(ws, proj, "sessions/session.md".into(), None).await.unwrap();assert_eq!(target_links.backlinks[0].kind, "note");diff --git a/crates/ai-memory-store/src/ops.rs b/crates/ai-memory-store/src/ops.rsindex 4d57cfb8..cd368e1e 100644--- a/crates/ai-memory-store/src/ops.rs+++ b/crates/ai-memory-store/src/ops.rs@@ -250,12 +250,65 @@ fn warn_project_name_in_other_workspaces(name: &str, also_in: &[String]) {/// Resolve a project by `(workspace_id, name)`, creating it if missing./// Atomic.+///+/// Test-only: the writer creates through [`get_or_create_project_as`], which+/// applies the server's new-project access mode. This keeps the plain shape+/// the store's own tests build fixtures with; a new project here is `open`.+#[cfg(test)]pub fn get_or_create_project(conn: &mut Connection,workspace_id: &ai_memory_core::WorkspaceId,name: &str,repo_path: Option<&str>,) -> StoreResult<ai_memory_core::ProjectId> {+ get_or_create_project_as(+ conn,+ workspace_id,+ name,+ repo_path,+ None,+ crate::AccessMode::Open,+ )+ .map(|(id, _)| id)+}++/// The access mode a newly created project starts in.+///+/// `default` is the server's `[auth] new_projects_restricted` setting. The+/// two reserved projects are always open whatever it says: `scratch` is where+/// every cwd-less event lands, and the global preferences scope is shared by+/// construction and unioned into everybody's reads.+pub(crate) fn initial_access_mode(name: &str, default: crate::AccessMode) -> crate::AccessMode {+ if name == ai_memory_core::DEFAULT_PROJECT_NAME || name == ai_memory_core::GLOBAL_SCOPE_PROJECT+ {+ crate::AccessMode::Open+ } else {+ default+ }+}++/// [`get_or_create_project`] on behalf of a user, reporting whether this call+/// created the row.+///+/// When it does, `creator` is recorded in `projects.created_by` (V69) in the+/// same transaction as the insert, and the new project starts in the server's+/// new-project access mode. The choke point admits a project's creator+/// unconditionally, so a creator can always read back what they just made —+/// including a hook capture that opens a new restricted project. A caller that+/// finds the row already there gets no such standing: the choke point then+/// decides against whoever created it, which is what closes the race between+/// two users naming the same new project.+///+/// # Errors+/// Propagates SQLite failures.+pub fn get_or_create_project_as(+ conn: &mut Connection,+ workspace_id: &ai_memory_core::WorkspaceId,+ name: &str,+ repo_path: Option<&str>,+ creator: Option<ai_memory_core::UserId>,+ new_project_mode: crate::AccessMode,+) -> StoreResult<(ai_memory_core::ProjectId, bool)> {let repo_path = repo_path.map(normalize_repo_path_key);let tx = conn.transaction()?;let mut also_in = Vec::new();@@ -283,6 +336,20 @@ pub fn get_or_create_project(Timestamp::now().as_microsecond()],)?;+ // `open` and no creator are the column defaults, so the insert above+ // is the one upstream always ran; only what differs needs a write.+ if initial_access_mode(name, new_project_mode) == crate::AccessMode::Restricted {+ tx.execute(+ "UPDATE projects SET access_mode = 'restricted' WHERE id = ?1",+ params![id.as_bytes()],+ )?;+ }+ if let Some(creator) = creator {+ tx.execute(+ "UPDATE projects SET created_by = ?1 WHERE id = ?2",+ params![creator.as_bytes(), id.as_bytes()],+ )?;+ }created = true;id};@@ -293,7 +360,7 @@ pub fn get_or_create_project(if created {warn_project_name_in_other_workspaces(name, &also_in);}- Ok(id)+ Ok((id, created))}/// Delete "hollow" project rows: zero pages (any version), zero sessions,@@ -4425,37 +4492,6 @@ pub fn purge_session(})}-/// Delete a project's rows inside one transaction.-///-/// This is a *logical* delete unless `compaction` is [`Compaction::Reclaim`].-/// The rows are gone and nothing reaches them through the API or search, but-/// their bytes remain in free pages of the database file until it is-/// rewritten — as with any SQLite delete. Neither mode is forensic erasure:-/// the wiki git history and any earlier backup still hold the content.-///-/// Execution order:-/// 1. Count rows in each dependent table (pages/all versions, sessions,-/// observations, handoffs, embeddings) before the delete so we can-/// report how many rows were removed.-/// 2. Collect all distinct page paths stored under the project — these are-/// the on-disk files the caller must clean up after this function returns.-/// 3. DELETE FROM projects WHERE id = ? — the ON DELETE CASCADE clauses in-/// V01 + V02 propagate the delete to pages, sessions, observations,-/// handoffs, and page_embeddings automatically.-/// 4. Commit and return the [`PurgeSummary`].-///-/// The `workspace_project_label` string is passed in by the caller (the-/// admin handler has the human-readable names; the writer only has IDs) and-/// forwarded verbatim into [`PurgeSummary::label`] for logging.-///-/// `force` overrides the live-managed-run guard (step 0): `workstreams`-/// cascades out of `projects`, so purging a scope whose lease is still live-/// would delete the lease row out from under a running agent.-///-/// # Errors-/// Returns [`StoreError::ManagedRunActive`] when a managed run's lease is-/// still live and `force` is false, or [`StoreError`] if any SQL statement-/// fails. The transaction is rolled back automatically on error./// Whether `(workspace_id, project_id)` — or the whole workspace — was purged/// and tombstoned by [`purge_project`] / [`delete_workspace`] (#607).///@@ -4589,6 +4625,37 @@ pub fn clear_bootstrap_progress(conn: &Connection, fingerprint: &str) -> StoreReOk(())}+/// Delete a project's rows inside one transaction.+///+/// This is a *logical* delete unless `compaction` is [`Compaction::Reclaim`].+/// The rows are gone and nothing reaches them through the API or search, but+/// their bytes remain in free pages of the database file until it is+/// rewritten — as with any SQLite delete. Neither mode is forensic erasure:+/// the wiki git history and any earlier backup still hold the content.+///+/// Execution order:+/// 1. Count rows in each dependent table (pages/all versions, sessions,+/// observations, handoffs, embeddings) before the delete so we can+/// report how many rows were removed.+/// 2. Collect all distinct page paths stored under the project — these are+/// the on-disk files the caller must clean up after this function returns.+/// 3. DELETE FROM projects WHERE id = ? — the ON DELETE CASCADE clauses in+/// V01 + V02 propagate the delete to pages, sessions, observations,+/// handoffs, and page_embeddings automatically.+/// 4. Commit and return the [`PurgeSummary`].+///+/// The `workspace_project_label` string is passed in by the caller (the+/// admin handler has the human-readable names; the writer only has IDs) and+/// forwarded verbatim into [`PurgeSummary::label`] for logging.+///+/// `force` overrides the live-managed-run guard (step 0): `workstreams`+/// cascades out of `projects`, so purging a scope whose lease is still live+/// would delete the lease row out from under a running agent.+///+/// # Errors+/// Returns [`StoreError::ManagedRunActive`] when a managed run's lease is+/// still live and `force` is false, or [`StoreError`] if any SQL statement+/// fails. The transaction is rolled back automatically on error.pub fn purge_project(conn: &mut Connection,workspace_id: &WorkspaceId,@@ -4975,6 +5042,13 @@ pub fn move_project_workspace("UPDATE handoffs SET workspace_id = ?1 WHERE project_id = ?2",params![&to[..], &pid[..]],)? as u64;+ // Grants carry the workspace in their key (#708). A grant left on the old+ // workspace would point at a pair that no longer exists, and deleting that+ // workspace would cascade it away from a project that still exists.+ tx.execute(+ "UPDATE project_grants SET workspace_id = ?1 WHERE project_id = ?2",+ params![&to[..], &pid[..]],+ )?;let audit_log_moved = tx.execute("UPDATE audit_log SET workspace_id = ?1 WHERE project_id = ?2 AND workspace_id = ?3",params![&to[..], &pid[..], &from[..]],diff --git a/crates/ai-memory-store/src/project_authz.rs b/crates/ai-memory-store/src/project_authz.rsindex 16c6eee8..3255621f 100644--- a/crates/ai-memory-store/src/project_authz.rs+++ b/crates/ai-memory-store/src/project_authz.rs@@ -7,12 +7,12 @@//! (the one place every scoped MCP/API/web path funnels through) and by the//! writer actor as defense in depth for writes.//!-//! ## Ship inert (slice 2)+//! ## Open until an operator restricts//!//! The V68 schema is additive and every project defaults to `open`, so this is a-//! pure pass-through until an operator opts a project into `restricted` (a-//! follow-up slice adds the management surface). The gate short-circuits to-//! ALLOW for:+//! pure pass-through until the root operator opts a project into `restricted`+//! (`ai-memory project access`), or sets `[auth] new_projects_restricted`. The+//! gate short-circuits to ALLOW for://! - a deployment that does not distinguish operators (single-user / loopback),//! where there is no notion of "another user" to gate against, and//! - any `open` project.@@ -114,10 +114,11 @@ pub enum ProjectAccess {/// The caller, reduced to the facts the gate needs.///-/// Root and creator are supplied by the auth layer; the grant is looked up from-/// `project_grants` by [`Self::user_id`]. No `projects.created_by` column exists-/// yet, so `is_creator` is threaded through the type for complete, testable-/// semantics and populated by the management surface in a follow-up slice.+/// Root is supplied by the auth layer; the grant is looked up from+/// `project_grants` by [`Self::user_id`]. The creator is derived per project+/// from `projects.created_by` (V69) when [`resolve_project_authz`] runs, so a+/// principal built once per request is right for every project it reaches;+/// [`Self::is_creator`] only forces it on.#[derive(Debug, Clone, PartialEq, Eq)]pub struct ProjectPrincipal {/// Authenticated as the configured root operator.@@ -149,6 +150,17 @@ impl ProjectPrincipal {user_id: None,}}++ /// A database user: not root, and the creator only of the projects whose+ /// `created_by` names them.+ #[must_use]+ pub fn user(user_id: UserId) -> Self {+ Self {+ is_root: false,+ is_creator: false,+ user_id: Some(user_id),+ }+ }}/// A project's authorization state, fully resolved from SQL, ready to decide.@@ -211,22 +223,31 @@ pub fn authorize_project(ctx: &ProjectAuthz, need: ProjectAccess) -> Result<(),ctx.authorize(need)}-/// Read `projects.access_mode`, degrading to [`AccessMode::Open`] on any read-/// failure and for an unknown project. Never fails closed.-fn read_access_mode(conn: &Connection, project_id: ProjectId) -> AccessMode {+/// Read `projects.access_mode` and `projects.created_by`, degrading to+/// [`AccessMode::Open`] with no creator on any read failure and for an unknown+/// project. Never fails closed.+fn read_project_row(conn: &Connection, project_id: ProjectId) -> (AccessMode, Option<UserId>) {match conn.query_row(- "SELECT access_mode FROM projects WHERE id = ?1",+ "SELECT access_mode, created_by FROM projects WHERE id = ?1",params![project_id.as_bytes()],- |row| row.get::<_, Option<String>>(0),+ |row| {+ Ok((+ row.get::<_, Option<String>>(0)?,+ row.get::<_, Option<Vec<u8>>>(1)?,+ ))+ },) {- Ok(value) => AccessMode::from_db(value.as_deref()),- Err(rusqlite::Error::QueryReturnedNoRows) => AccessMode::Open,+ Ok((mode, creator)) => (+ AccessMode::from_db(mode.as_deref()),+ creator.and_then(|raw| UserId::from_slice(&raw).ok()),+ ),+ Err(rusqlite::Error::QueryReturnedNoRows) => (AccessMode::Open, None),Err(err) => {tracing::warn!(error = %err,"could not read projects.access_mode; degrading project authz to open",);- AccessMode::Open+ (AccessMode::Open, None)}}}@@ -257,7 +278,9 @@ fn read_grant(/// Resolve the full [`ProjectAuthz`] for a project from a live connection.///-/// `open` short-circuits without touching `project_grants`. A `restricted`+/// `open` short-circuits without touching `project_grants`. The caller is the+/// creator when [`ProjectPrincipal::is_creator`] says so or the project's+/// `created_by` is their [`ProjectPrincipal::user_id`]. A `restricted`/// project whose grants cannot be read degrades to `open` with a warning rather/// than denying every caller (#678).///@@ -271,7 +294,8 @@ pub fn resolve_project_authz(principal: &ProjectPrincipal,distinguishes_operators: bool,) -> StoreResult<ProjectAuthz> {- let mut access_mode = read_access_mode(conn, project_id);+ let (mut access_mode, creator) = read_project_row(conn, project_id);+ let is_creator = principal.is_creator || (creator.is_some() && creator == principal.user_id);let grant = if access_mode == AccessMode::Restricted {match principal.user_id {Some(user_id) => match read_grant(conn, workspace_id, project_id, user_id) {@@ -296,7 +320,7 @@ pub fn resolve_project_authz(distinguishes_operators,access_mode,is_root: principal.is_root,- is_creator: principal.is_creator,+ is_creator,grant,})}diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rsindex 7345c38f..2f9da0dc 100644--- a/crates/ai-memory-store/src/reader.rs+++ b/crates/ai-memory-store/src/reader.rs@@ -75,6 +75,113 @@ fn now_us() -> i64 {Timestamp::now().as_microsecond()}+/// Restrict `project_column` to the repositories `viewer` may read (#708).+///+/// Returns a fragment to append to a `WHERE` clause and the values it binds,+/// numbered from `?{first_param}`. For `None` the fragment is empty and binds+/// nothing, so a query built with no viewer is exactly the query it was before+/// authorization existed — which is what an install with no database users and+/// the root operator both need.+///+/// "May read" is what [`crate::authorize_project`] admits for+/// [`crate::ProjectAccess::Read`]: a project that is not `restricted` (an+/// unrecognised mode reads as open there too), one the viewer created, or one+/// they hold any grant on — every level admits a read, and a test pins the two+/// together. The global+/// preferences scope is always readable: it is shared by construction (see+/// `lookup_global_scope`).+///+/// This belongs in the query, before `LIMIT`, not applied to the rows after.+/// Filtering afterwards hands a user three results out of ten because seven+/// were somebody else's: search that quietly gets worse, and a count that+/// tells them how much is being hidden.+pub(crate) fn readable_repository_filter(+ project_column: &str,+ viewer: Option<UserId>,+ first_param: usize,+) -> (String, Vec<Value>) {+ let Some(viewer) = viewer else {+ return (String::new(), Vec::new());+ };+ let (user, workspace, project) = (first_param, first_param + 1, first_param + 2);+ let fragment = readable_repository_sql(+ project_column,+ &format!("?{user}"),+ &format!("?{workspace}"),+ &format!("?{project}"),+ );+ let bound = vec![+ Value::Blob(viewer.as_bytes().to_vec()),+ Value::Text(ai_memory_core::DEFAULT_WORKSPACE_NAME.to_owned()),+ Value::Text(ai_memory_core::GLOBAL_SCOPE_PROJECT.to_owned()),+ ];+ (fragment, bound)+}++/// [`readable_repository_filter`] with its three values written into the SQL+/// instead of bound.+///+/// For statements that cannot take extra parameters without renumbering the+/// ones they already have: the workspace briefing alone runs a dozen, mixing+/// numbered and anonymous placeholders, and threading three more binds through+/// each would rewrite upstream SQL for no gain in safety. Splicing a fragment+/// in, the way [`not_expired`] already is, leaves them untouched.+///+/// Nothing here comes from a caller. The user id is a 16-byte UUID the store+/// generated, rendered as a hex blob literal, and the other two values are+/// compile-time constants, quoted defensively all the same. Both helpers build+/// from [`readable_repository_sql`], so they cannot disagree about who may+/// read what.+///+/// The cost is one distinct SQL string per user, so a `prepare_cached`+/// statement using this caches one entry per viewer. The cache is a bounded+/// LRU and the callers are operator views, not the per-call agent path; a hot+/// query should take [`readable_repository_filter`] instead.+pub(crate) fn readable_repository_predicate(+ project_column: &str,+ viewer: Option<UserId>,+) -> String {+ let Some(viewer) = viewer else {+ return String::new();+ };+ let hex: String = viewer+ .as_bytes()+ .iter()+ .map(|byte| format!("{byte:02x}"))+ .collect();+ let text = |value: &str| format!("'{}'", value.replace('\'', "''"));+ readable_repository_sql(+ project_column,+ &format!("X'{hex}'"),+ &text(ai_memory_core::DEFAULT_WORKSPACE_NAME),+ &text(ai_memory_core::GLOBAL_SCOPE_PROJECT),+ )+}++/// The one definition of "a repository this user may read", as SQL.+///+/// Callers supply how the user id and the global scope's workspace and project+/// names are referenced — placeholders or literals — and nothing else.+fn readable_repository_sql(+ project_column: &str,+ user: &str,+ workspace: &str,+ project: &str,+) -> String {+ // Aliased so the subqueries cannot bind to a `projects` / `workspaces`+ // already joined by the query this is appended to.+ format!(+ " AND ({project_column} IN (SELECT op.id FROM projects op \+ WHERE op.access_mode <> 'restricted' \+ OR op.created_by = {user}) \+ OR {project_column} IN (SELECT pg.project_id FROM project_grants pg \+ WHERE pg.user_id = {user}) \+ OR {project_column} IN (SELECT gp.id FROM projects gp \+ JOIN workspaces gw ON gw.id = gp.workspace_id \+ WHERE gw.name = {workspace} AND gp.name = {project}))"+ )+}+fn page_kind_expr(path_column: &str, frontmatter_column: &str) -> String {format!("COALESCE( \@@ -1656,6 +1763,44 @@ impl ReaderPool {self.tuning}+ /// The grant this user holds on this repository, if any (at most one).+ ///+ /// # Errors+ /// Propagates any SQL or pool error.+ pub async fn grants_for(+ &self,+ user_id: ai_memory_core::UserId,+ repository_id: ProjectId,+ ) -> StoreResult<Vec<crate::ProjectGrant>> {+ self.with_conn(move |conn| crate::grants::grants_for(conn, user_id, repository_id))+ .await+ }++ /// Page authors who would be refused if this repository were restricted;+ /// see [`crate::grants::authors_without_grant`].+ ///+ /// # Errors+ /// Propagates store failures.+ pub async fn authors_without_grant(+ &self,+ repository_id: ProjectId,+ ) -> StoreResult<Vec<String>> {+ self.with_conn(move |conn| crate::grants::authors_without_grant(conn, repository_id))+ .await+ }++ /// Grants matching `filter`, resolved to names for display.+ ///+ /// # Errors+ /// Propagates any SQL or pool error.+ pub async fn list_grants(+ &self,+ filter: crate::grants::GrantFilter,+ ) -> StoreResult<Vec<crate::grants::GrantListing>> {+ self.with_conn(move |conn| crate::grants::list_grants(conn, filter))+ .await+ }+/// Run a synchronous closure against a pooled read-only connection.////// The closure runs on the tokio blocking pool so it never starves the@@ -1681,6 +1826,49 @@ impl ReaderPool {.map_err(|e| StoreError::PoolPanic(e.to_string()))?}+ /// The repository a managed run belongs to, or `None` when no such run+ /// exists.+ ///+ /// The workstream routes take a run id in the URL rather than a+ /// workspace/project pair, so they never pass through scope resolution and+ /// the grant check with it. This is what they authorize against.+ ///+ /// # Errors+ /// Propagates any SQL or pool error.+ pub async fn managed_run_scope(+ &self,+ run_id: ai_memory_core::ManagedRunId,+ ) -> StoreResult<Option<(WorkspaceId, ProjectId)>> {+ self.with_conn(move |conn| {+ scope_row(+ conn,+ "SELECT w.workspace_id, w.project_id FROM managed_runs r \+ JOIN workstreams w ON w.id = r.workstream_id WHERE r.id = ?1",+ run_id.as_bytes(),+ )+ })+ .await+ }++ /// The repository a workstream belongs to, or `None` when it does not+ /// exist. See [`Self::managed_run_scope`] for why the routes need it.+ ///+ /// # Errors+ /// Propagates any SQL or pool error.+ pub async fn workstream_scope(+ &self,+ workstream_id: ai_memory_core::WorkstreamId,+ ) -> StoreResult<Option<(WorkspaceId, ProjectId)>> {+ self.with_conn(move |conn| {+ scope_row(+ conn,+ "SELECT workspace_id, project_id FROM workstreams WHERE id = ?1",+ workstream_id.as_bytes(),+ )+ })+ .await+ }+/// Return the current state of one `ai-memory run` invocation.pub async fn managed_run_status(&self,@@ -1739,15 +1927,25 @@ impl ReaderPool {/// Run a full-text search against the FTS5 index, apply the bounded page/// authority adjustment, and return the top `is_latest = 1` matches.///+ /// `viewer` restricts the hits to repositories that user may read — see+ /// [`readable_repository_filter`]. `None` searches every repository.+ ////// # Errors/// Propagates any SQL or pool error.- pub async fn search_pages(&self, query: String, limit: usize) -> StoreResult<Vec<PageHit>> {+ pub async fn search_pages(+ &self,+ query: String,+ limit: usize,+ viewer: Option<UserId>,+ ) -> StoreResult<Vec<PageHit>> {let fts_query = normalize_fts_query(&query);if fts_query.is_empty() || limit == 0 {return Ok(Vec::new());}self.with_conn(move |conn| {let kind_expr = page_kind_expr("pages.path", "pages.frontmatter_json");+ let (visible, visible_params) =+ readable_repository_filter("pages.project_id", viewer, 4);let sql = format!("SELECT pages.id, pages.path, pages.title, \snippet(pages_fts, 1, '<mark>', '</mark>', '…', 24) AS snip, \@@ -1755,38 +1953,41 @@ impl ReaderPool {pages.frontmatter_json, {kind_expr} AS kind \FROM pages_fts \JOIN pages ON pages.rowid = pages_fts.rowid \- WHERE pages_fts MATCH ?1 AND pages.is_latest = 1{not_expired} \+ WHERE pages_fts MATCH ?1 AND pages.is_latest = 1{not_expired}{visible} \ORDER BY pages_fts.rank \LIMIT ?2",not_expired = not_expired("pages", "?3"),);let mut stmt = conn.prepare(&sql)?;#[allow(clippy::cast_possible_wrap)]- let rows = stmt.query_map(- params![fts_query, authority_candidate_limit(limit) as i64, now_us()],- |row| {- let id_bytes: Vec<u8> = row.get(0)?;- let path: String = row.get(1)?;- let title: String = row.get(2)?;- let snippet: String = row.get(3)?;- let rank: f64 = row.get(4)?;- let tier: String = row.get(5)?;- let pinned = row.get::<_, i64>(6)? != 0;- let frontmatter_json: String = row.get(7)?;- let kind: String = row.get(8)?;- Ok((- id_bytes,- path,- title,- snippet,- rank,- tier,- pinned,- frontmatter_json,- kind,- ))- },- )?;+ let mut bound = vec![+ Value::Text(fts_query),+ Value::Integer(authority_candidate_limit(limit) as i64),+ Value::Integer(now_us()),+ ];+ bound.extend(visible_params);+ let rows = stmt.query_map(params_from_iter(bound.iter()), |row| {+ let id_bytes: Vec<u8> = row.get(0)?;+ let path: String = row.get(1)?;+ let title: String = row.get(2)?;+ let snippet: String = row.get(3)?;+ let rank: f64 = row.get(4)?;+ let tier: String = row.get(5)?;+ let pinned = row.get::<_, i64>(6)? != 0;+ let frontmatter_json: String = row.get(7)?;+ let kind: String = row.get(8)?;+ Ok((+ id_bytes,+ path,+ title,+ snippet,+ rank,+ tier,+ pinned,+ frontmatter_json,+ kind,+ ))+ })?;let mut candidates = Vec::new();for row in rows {@@ -1817,6 +2018,9 @@ impl ReaderPool {/// to one SQLite query instead of one search query plus a metadata lookup/// per hit.///+ /// `viewer` restricts the hits to repositories that user may read — see+ /// [`readable_repository_filter`]. `None` searches every repository.+ ////// # Errors/// Propagates any SQL or pool error.pub async fn search_pages_with_meta(@@ -1824,6 +2028,7 @@ impl ReaderPool {query: String,limit: usize,expiry_cutoff_us: Option<i64>,+ viewer: Option<UserId>,) -> StoreResult<Vec<PageHitWithMeta>> {let fts_query = normalize_fts_query(&query);if fts_query.is_empty() || limit == 0 {@@ -1832,6 +2037,8 @@ impl ReaderPool {let cutoff = expiry_cutoff_us.unwrap_or_else(now_us);self.with_conn(move |conn| {let kind_expr = page_kind_expr("pages.path", "pages.frontmatter_json");+ let (visible, visible_params) =+ readable_repository_filter("pages.project_id", viewer, 4);let sql = format!("SELECT workspaces.name, projects.name, pages.path, pages.title, \snippet(pages_fts, 1, '<mark>', '</mark>', '…', 24) AS snip, \@@ -1841,40 +2048,43 @@ impl ReaderPool {JOIN pages ON pages.rowid = pages_fts.rowid \JOIN projects ON projects.id = pages.project_id \JOIN workspaces ON workspaces.id = pages.workspace_id \- WHERE pages_fts MATCH ?1 AND pages.is_latest = 1{not_expired} \+ WHERE pages_fts MATCH ?1 AND pages.is_latest = 1{not_expired}{visible} \ORDER BY pages_fts.rank \LIMIT ?2",not_expired = not_expired("pages", "?3"),);let mut stmt = conn.prepare(&sql)?;#[allow(clippy::cast_possible_wrap)]- let rows = stmt.query_map(- params![fts_query, authority_candidate_limit(limit) as i64, cutoff],- |row| {- let workspace_name: String = row.get(0)?;- let project_name: String = row.get(1)?;- let path: String = row.get(2)?;- let title: String = row.get(3)?;- let snippet: String = row.get(4)?;- let rank: f64 = row.get(5)?;- let tier: String = row.get(6)?;- let pinned = row.get::<_, i64>(7)? != 0;- let frontmatter_json: String = row.get(8)?;- let kind: String = row.get(9)?;- Ok((- workspace_name,- project_name,- path,- title,- snippet,- rank,- tier,- pinned,- frontmatter_json,- kind,- ))- },- )?;+ let mut bound = vec![+ Value::Text(fts_query),+ Value::Integer(authority_candidate_limit(limit) as i64),+ Value::Integer(cutoff),+ ];+ bound.extend(visible_params);+ let rows = stmt.query_map(params_from_iter(bound.iter()), |row| {+ let workspace_name: String = row.get(0)?;+ let project_name: String = row.get(1)?;+ let path: String = row.get(2)?;+ let title: String = row.get(3)?;+ let snippet: String = row.get(4)?;+ let rank: f64 = row.get(5)?;+ let tier: String = row.get(6)?;+ let pinned = row.get::<_, i64>(7)? != 0;+ let frontmatter_json: String = row.get(8)?;+ let kind: String = row.get(9)?;+ Ok((+ workspace_name,+ project_name,+ path,+ title,+ snippet,+ rank,+ tier,+ pinned,+ frontmatter_json,+ kind,+ ))+ })?;let mut candidates = Vec::new();for row in rows {@@ -2544,10 +2754,19 @@ impl ReaderPool {/// REAL) — larger still means "ranks first", callers must not read it/// as an FTS rank.///+ /// `viewer` restricts the pages to repositories that user may read — see+ /// [`readable_repository_filter`]. `None` lists every repository.+ ////// # Errors/// Propagates any SQL or pool error.- pub async fn recent_pages_global(&self, limit: usize) -> StoreResult<Vec<PageHitWithMeta>> {+ pub async fn recent_pages_global(+ &self,+ limit: usize,+ viewer: Option<UserId>,+ ) -> StoreResult<Vec<PageHitWithMeta>> {self.with_conn(move |conn| {+ let (visible, visible_params) =+ readable_repository_filter("pages.project_id", viewer, 3);let sql = format!("SELECT workspaces.name, projects.name, pages.path, pages.title, \{descriptor} AS snip, \@@ -2555,7 +2774,7 @@ impl ReaderPool {FROM pages \JOIN projects ON projects.id = pages.project_id \JOIN workspaces ON workspaces.id = pages.workspace_id \- WHERE pages.is_latest = 1{not_expired} \+ WHERE pages.is_latest = 1{not_expired}{visible} \ORDER BY pages.updated_at DESC \LIMIT ?1",descriptor = page_descriptor_expr("pages.body", "pages.frontmatter_json"),@@ -2563,7 +2782,9 @@ impl ReaderPool {);let mut stmt = conn.prepare_cached(&sql)?;#[allow(clippy::cast_possible_wrap)]- let rows = stmt.query_map(params![limit as i64, now_us()], |row| {+ let mut bound = vec![Value::Integer(limit as i64), Value::Integer(now_us())];+ bound.extend(visible_params);+ let rows = stmt.query_map(params_from_iter(bound.iter()), |row| {let workspace_name: String = row.get(0)?;let project_name: String = row.get(1)?;let path: String = row.get(2)?;@@ -6381,13 +6602,22 @@ impl ReaderPool {/// Return the latest open handoff for the workspace, aggregating/// across all of its projects (no project filter).///+ /// `viewer` confines "all of its projects" to those that user may read. A+ /// handoff with no owner is visible to everyone who can see its+ /// repository, which is exactly why it must not be visible to someone who+ /// cannot: its summary, next steps and project name are the repository's+ /// content. Filtered in SQL for the same reason as the owner predicate —+ /// the query keeps its `LIMIT 1`.+ ////// # Errors/// Propagates any SQL or pool error.pub async fn latest_open_handoff_for_workspace(&self,workspace_id: WorkspaceId,owner_filter: OwnerFilter,+ viewer: Option<UserId>,) -> StoreResult<Option<Handoff>> {+ let visible = readable_repository_predicate("project_id", viewer);self.with_conn(move |conn| {// The owner predicate is pushed into SQL (rather than filtered after// the fact like the project-scoped lookup) because this query keeps@@ -6405,7 +6635,7 @@ impl ReaderPool {created_at, accepted_by, accepted_at, accepted_by_session, \owner_user, accepted_by_user \FROM handoffs \- WHERE workspace_id = ?1 AND state = 'open'{owner_clause} \+ WHERE workspace_id = ?1 AND state = 'open'{owner_clause}{visible} \ORDER BY created_at DESC LIMIT 1");let row_opt = match &owner_filter {@@ -6477,6 +6707,12 @@ impl ReaderPool {/// Mirrors [`ReaderPool::briefing_for_project`] but scopes every query/// to the workspace only (no `project_id` filter).///+ /// `viewer` narrows "all projects" to the ones that user may read (#708):+ /// every count, window, rule, slot and recent page below is taken over+ /// those alone, so an aggregate cannot be used to learn how much is+ /// happening in repositories they cannot open. `None` aggregates the whole+ /// workspace, as before.+ ////// # Errors/// Propagates any SQL or pool error.pub async fn briefing_for_workspace(@@ -6484,27 +6720,34 @@ impl ReaderPool {workspace_id: WorkspaceId,recent_pages_limit: usize,owner_filter: OwnerFilter,+ viewer: Option<UserId>,) -> StoreResult<BriefingSnapshot> {self.briefing_for_workspace_with_slot_visibility(workspace_id,recent_pages_limit,owner_filter,&ai_memory_core::SlotVisibility::All,+ viewer,).await}/// Assemble a workspace briefing while filtering operator-owned slots.+ /// `viewer` as for [`Self::briefing_for_workspace`].pub async fn briefing_for_workspace_with_slot_visibility(&self,workspace_id: WorkspaceId,recent_pages_limit: usize,owner_filter: OwnerFilter,slot_visibility: &ai_memory_core::SlotVisibility,+ viewer: Option<UserId>,) -> StoreResult<BriefingSnapshot> {let recent_limit = recent_pages_limit.clamp(1, 100) as i64;let slot_visibility = slot_visibility.clone();let (recent_slot_sql, recent_glob) = slot_exclusion_sql(&slot_visibility, 4);+ // Spliced rather than bound: this function runs a dozen statements+ // with their own parameter numbering. See `readable_repository_predicate`.+ let visible = readable_repository_predicate("project_id", viewer);self.with_conn(move |conn| {let kind_expr = page_kind_expr("path", "frontmatter_json");let now_us = jiff::Timestamp::now().as_microsecond();@@ -6515,22 +6758,24 @@ impl ReaderPool {let counts = StatusCounts {pages_latest: count_workspace(conn,- "SELECT COUNT(*) FROM pages WHERE workspace_id = ?1 AND is_latest = 1",+ &format!(+ "SELECT COUNT(*) FROM pages WHERE workspace_id = ?1 AND is_latest = 1{visible}"+ ),workspace_id,)?,pages_all: count_workspace(conn,- "SELECT COUNT(*) FROM pages WHERE workspace_id = ?1",+ &format!("SELECT COUNT(*) FROM pages WHERE workspace_id = ?1{visible}"),workspace_id,)?,sessions: count_workspace(conn,- "SELECT COUNT(*) FROM sessions WHERE workspace_id = ?1",+ &format!("SELECT COUNT(*) FROM sessions WHERE workspace_id = ?1{visible}"),workspace_id,)?,observations: count_workspace(conn,- "SELECT COUNT(*) FROM observations WHERE workspace_id = ?1",+ &format!("SELECT COUNT(*) FROM observations WHERE workspace_id = ?1{visible}"),workspace_id,)?,evidence_rows: count_workspace(@@ -6542,12 +6787,16 @@ impl ReaderPool {)?,};- let activity_7d = window_activity_workspace(conn, 7, cutoff_7d, workspace_id)?;- let activity_30d = window_activity_workspace(conn, 30, cutoff_30d, workspace_id)?;+ let activity_7d =+ window_activity_workspace(conn, 7, cutoff_7d, workspace_id, &visible)?;+ let activity_30d =+ window_activity_workspace(conn, 30, cutoff_30d, workspace_id, &visible)?;let last_observation_at: Option<i64> = conn.query_row(- "SELECT MAX(created_at) FROM observations WHERE workspace_id = ?1",+ &format!(+ "SELECT MAX(created_at) FROM observations WHERE workspace_id = ?1{visible}"+ ),params![workspace_id.as_bytes()],|row| row.get::<_, Option<i64>>(0),)@@ -6566,7 +6815,7 @@ impl ReaderPool {conn,&format!("SELECT COUNT(*) FROM handoffs \- WHERE workspace_id = ?1 AND state = 'open'{owner_clause}"+ WHERE workspace_id = ?1 AND state = 'open'{owner_clause}{visible}"),&owner_binds,)?;@@ -6575,7 +6824,7 @@ impl ReaderPool {"SELECT path, title, {kind_expr} AS kind, \updated_at \FROM pages \- WHERE workspace_id = ?1 AND is_latest = 1 AND path GLOB '_rules/*'{not_expired} \+ WHERE workspace_id = ?1 AND is_latest = 1 AND path GLOB '_rules/*'{not_expired}{visible} \ORDER BY updated_at DESC",not_expired = not_expired("pages", "?2"),))?;@@ -6592,7 +6841,7 @@ impl ReaderPool {"SELECT path, title, {kind_expr} AS kind, \updated_at \FROM pages \- WHERE workspace_id = ?1 AND is_latest = 1 AND path GLOB '_slots/*'{not_expired} \+ WHERE workspace_id = ?1 AND is_latest = 1 AND path GLOB '_slots/*'{not_expired}{visible} \ORDER BY path ASC",not_expired = not_expired("pages", "?2"),))?;@@ -6609,7 +6858,7 @@ impl ReaderPool {"SELECT path, title, {kind_expr} AS kind, \updated_at \FROM pages \- WHERE workspace_id = ?1 AND is_latest = 1 AND ({recent_slot_sql}){not_expired} \+ WHERE workspace_id = ?1 AND is_latest = 1 AND ({recent_slot_sql}){not_expired}{visible} \ORDER BY updated_at DESC \LIMIT ?2",not_expired = not_expired("pages", "?3"),@@ -6661,13 +6910,17 @@ impl ReaderPool {/// - `duplicates`: extra latest pages that share a title./// - `orphans`: latest pages with no inbound or outbound links.///+ /// `viewer` counts only repositories that user may read; `None` counts+ /// the whole workspace.+ ////// # Errors/// Propagates any SQL or pool error.pub async fn memory_health_for_workspace(&self,workspace_id: WorkspaceId,+ viewer: Option<UserId>,) -> StoreResult<(u64, u64, u64)> {- self.memory_health_scoped(workspace_id, None).await+ self.memory_health_scoped(workspace_id, None, viewer).await}/// Per-project variant of [`ReaderPool::memory_health_for_workspace`]:@@ -6680,7 +6933,8 @@ impl ReaderPool {workspace_id: WorkspaceId,project_id: ProjectId,) -> StoreResult<(u64, u64, u64)> {- self.memory_health_scoped(workspace_id, Some(project_id))+ // A single project is already authorized by whoever resolved it.+ self.memory_health_scoped(workspace_id, Some(project_id), None).await}@@ -6688,6 +6942,7 @@ impl ReaderPool {&self,workspace_id: WorkspaceId,project_id: Option<ProjectId>,+ viewer: Option<UserId>,) -> StoreResult<(u64, u64, u64)> {self.with_conn(move |conn| {let now_us = jiff::Timestamp::now().as_microsecond();@@ -6695,17 +6950,27 @@ impl ReaderPool {let proj = project_id.map(|p| Value::Blob(p.as_bytes().to_vec()));let ws = || Value::Blob(workspace_id.as_bytes().to_vec());// Optional project filter, anonymous-`?` style. The orphan query- // aliases pages as `p`, so it needs its own qualified clause.- let clause = if proj.is_some() {- " AND project_id = ?"- } else {- ""- };- let clause_p = if proj.is_some() {- " AND p.project_id = ?"- } else {- ""- };+ // aliases pages as `p`, so it needs its own qualified clause. The+ // readable-repository predicate binds nothing, so it can follow+ // either without disturbing the anonymous parameter order.+ let clause = format!(+ "{}{}",+ if proj.is_some() {+ " AND project_id = ?"+ } else {+ ""+ },+ readable_repository_predicate("project_id", viewer),+ );+ let clause_p = format!(+ "{}{}",+ if proj.is_some() {+ " AND p.project_id = ?"+ } else {+ ""+ },+ readable_repository_predicate("p.project_id", viewer),+ );let stale: i64 = conn.query_row(@@ -6765,7 +7030,8 @@ impl ReaderPool {/// Drill-down lists behind [`ReaderPool::memory_health_for_workspace`]'s/// counters: the actual stale / duplicate / orphan pages, each capped at/// `limit`. Definitions mirror the counters exactly so the lists explain- /// the headline numbers.+ /// the headline numbers — including `viewer`, which lists only pages in+ /// repositories that user may read, before the `LIMIT`.////// # Errors/// Propagates any SQL or pool error.@@ -6773,8 +7039,10 @@ impl ReaderPool {&self,workspace_id: WorkspaceId,limit: usize,+ viewer: Option<UserId>,) -> StoreResult<HealthDetail> {- self.health_detail_scoped(workspace_id, None, limit).await+ self.health_detail_scoped(workspace_id, None, limit, viewer)+ .await}/// Per-project variant of [`ReaderPool::health_detail_for_workspace`].@@ -6787,7 +7055,8 @@ impl ReaderPool {project_id: ProjectId,limit: usize,) -> StoreResult<HealthDetail> {- self.health_detail_scoped(workspace_id, Some(project_id), limit)+ // A single project is already authorized by whoever resolved it.+ self.health_detail_scoped(workspace_id, Some(project_id), limit, None).await}@@ -6796,6 +7065,7 @@ impl ReaderPool {workspace_id: WorkspaceId,project_id: Option<ProjectId>,limit: usize,+ viewer: Option<UserId>,) -> StoreResult<HealthDetail> {let limit = i64::try_from(limit).unwrap_or(i64::MAX);self.with_conn(move |conn| {@@ -6803,16 +7073,27 @@ impl ReaderPool {let cutoff_30d = now_us - 30 * 86_400 * 1_000_000;let proj = project_id.map(|p| Value::Blob(p.as_bytes().to_vec()));let ws = || Value::Blob(workspace_id.as_bytes().to_vec());- let clause = if proj.is_some() {- " AND pg.project_id = ?"- } else {- ""- };- let inner_clause = if proj.is_some() {- " AND project_id = ?"- } else {- ""- };+ // The duplicate list's inner query must see the same repositories+ // as the outer one, or a hidden page sharing a title would still+ // make a visible one show up as a duplicate.+ let clause = format!(+ "{}{}",+ if proj.is_some() {+ " AND pg.project_id = ?"+ } else {+ ""+ },+ readable_repository_predicate("pg.project_id", viewer),+ );+ let inner_clause = format!(+ "{}{}",+ if proj.is_some() {+ " AND project_id = ?"+ } else {+ ""+ },+ readable_repository_predicate("project_id", viewer),+ );// Shared SELECT prefix: identity + path-inferred `kind`.let kind_expr = page_kind_expr("pg.path", "pg.frontmatter_json");@@ -6961,7 +7242,8 @@ impl ReaderPool {////// Both ends are constrained to `is_latest = 1`, so superseded versions/// never leak into the link panel. Returns empty lists when the page is- /// missing or has no links.+ /// missing or has no links. `viewer` drops links whose far end is in a+ /// repository that user may not read; `None` keeps them all.////// # Errors/// Propagates any SQL or pool error.@@ -6970,6 +7252,7 @@ impl ReaderPool {workspace_id: WorkspaceId,project_id: ProjectId,path: String,+ viewer: Option<UserId>,) -> StoreResult<PageLinks> {self.with_conn(move |conn| {let id_opt: Option<Vec<u8>> = conn@@ -6989,6 +7272,10 @@ impl ReaderPool {// pages that link here. Both reuse the path-inference `kind`// fallback so untagged pages still classify.let kind_expr = page_kind_expr("pg.path", "pg.frontmatter_json");+ // A link into a repository the viewer cannot read would show them+ // its name and a page title and path inside it — the same leak as a+ // graph edge — so the far end is filtered like one.+ let visible = readable_repository_predicate("pg.project_id", viewer);let outgoing = format!("SELECT DISTINCT pg.path, pg.title, {kind_expr}, \ws.name, pr.name \@@ -6996,7 +7283,7 @@ impl ReaderPool {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!(@@ -7006,7 +7293,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");@@ -7266,14 +7553,27 @@ impl ReaderPool {/// that project (as source or target) are returned; `None` returns the/// whole cross-project graph. Powers `/api/v1/graph`.///+ /// `viewer` keeps only edges whose *both* endpoints the user may read+ /// (#708). One readable end is not enough: an edge carries the other end's+ /// workspace, project and path, so a link from a page bob can read into a+ /// repository he cannot would hand him the hidden repository's name and a+ /// page path inside it. `None` returns the graph unfiltered.+ ////// # Errors/// Propagates any SQL or pool error.pub async fn cross_project_edges(&self,scope: Option<(WorkspaceId, ProjectId)>,+ viewer: Option<UserId>,) -> StoreResult<Vec<CrossProjectEdge>> {self.with_conn(move |conn| {- let base = "SELECT fw.name, fpr.name, fp.path, tw.name, tpr.name, tp.path \+ let visible = format!(+ "{}{}",+ readable_repository_predicate("fp.project_id", viewer),+ readable_repository_predicate("tp.project_id", viewer),+ );+ let base = format!(+ "SELECT fw.name, fpr.name, fp.path, tw.name, tpr.name, tp.path \FROM links l \JOIN pages fp ON fp.id = l.from_page_id AND fp.is_latest = 1 \JOIN pages tp ON tp.id = l.to_page_id AND tp.is_latest = 1 \@@ -7281,7 +7581,8 @@ impl ReaderPool {JOIN workspaces fw ON fw.id = fp.workspace_id \JOIN projects tpr ON tpr.id = tp.project_id \JOIN workspaces tw ON tw.id = tp.workspace_id \- WHERE fp.project_id != tp.project_id";+ WHERE fp.project_id != tp.project_id{visible}"+ );let map_row = |row: &rusqlite::Row<'_>| {Ok(CrossProjectEdge {from_workspace: row.get(0)?,@@ -7317,34 +7618,46 @@ impl ReaderPool {/// Return one row per (workspace, project) with page-count and/// last-updated aggregates. Used by the web UI project-list view.///- /// Only `is_latest = 1` pages are counted.+ /// Only `is_latest = 1` pages are counted. `viewer` lists only the+ /// repositories that user may read — see [`readable_repository_filter`];+ /// `None` lists every one.////// # Errors/// Propagates any SQL or pool error.- pub async fn list_projects_with_stats(&self) -> StoreResult<Vec<ProjectSummary>> {- self.list_projects_with_stats_filtered(None).await+ pub async fn list_projects_with_stats(+ &self,+ viewer: Option<UserId>,+ ) -> StoreResult<Vec<ProjectSummary>> {+ self.list_projects_with_stats_filtered(None, viewer).await}/// Return one row per project within one workspace.///- /// Only `is_latest = 1` pages are counted.+ /// Only `is_latest = 1` pages are counted. `viewer` as for+ /// [`Self::list_projects_with_stats`].////// # Errors/// Propagates any SQL or pool error.pub async fn list_projects_with_stats_for_workspace(&self,workspace: String,+ viewer: Option<UserId>,) -> StoreResult<Vec<ProjectSummary>> {- self.list_projects_with_stats_filtered(Some(workspace))+ self.list_projects_with_stats_filtered(Some(workspace), viewer).await}async fn list_projects_with_stats_filtered(&self,workspace: Option<String>,+ viewer: Option<UserId>,) -> StoreResult<Vec<ProjectSummary>> {self.with_conn(move |conn| {- let mut stmt = conn.prepare(+ // A repository's name is itself the leak here — client work from+ // three organisations listed by name — so the filter is on the+ // project row, not only on the pages counted beside it.+ let visible = readable_repository_predicate("p.id", viewer);+ let mut stmt = conn.prepare(&format!("SELECT w.name AS workspace_name, \p.name AS project_name, \COUNT(pg.id) AS page_count, \@@ -7352,10 +7665,10 @@ impl ReaderPool {FROM workspaces w \JOIN projects p ON p.workspace_id = w.id \LEFT JOIN pages pg ON pg.project_id = p.id AND pg.is_latest = 1 \- WHERE (?1 IS NULL OR w.name = ?1) \+ WHERE (?1 IS NULL OR w.name = ?1){visible} \GROUP BY w.id, p.id \- ORDER BY last_updated_us DESC NULLS LAST",- )?;+ ORDER BY last_updated_us DESC NULLS LAST"+ ))?;let rows = stmt.query_map(params![workspace], |row| {let workspace_name: String = row.get(0)?;let project_name: String = row.get(1)?;@@ -7538,21 +7851,40 @@ impl ReaderPool {////// Only `is_latest = 1` pages are counted.///+ /// With a `viewer`, a workspace is listed only when it holds at least one+ /// repository that user may read, and its counts cover only those. A+ /// workspace name is often an organisation's name, so listing an empty+ /// shell of somebody else's workspace would leak exactly what the project+ /// filter hides. `None` lists every workspace, empty ones included, as+ /// before.+ ////// # Errors/// Propagates any SQL or pool error.- pub async fn list_workspaces_with_stats(&self) -> StoreResult<Vec<WorkspaceSummary>> {- self.with_conn(|conn| {- let mut stmt = conn.prepare(+ pub async fn list_workspaces_with_stats(+ &self,+ viewer: Option<UserId>,+ ) -> StoreResult<Vec<WorkspaceSummary>> {+ self.with_conn(move |conn| {+ // In the join, not the WHERE: unreadable projects drop out of the+ // counts while the LEFT JOIN still yields the workspace row, and+ // the HAVING then removes workspaces left with nothing readable.+ let visible = readable_repository_predicate("p.id", viewer);+ let only_readable = if viewer.is_some() {+ " HAVING COUNT(DISTINCT p.id) > 0"+ } else {+ ""+ };+ let mut stmt = conn.prepare(&format!("SELECT w.name AS workspace_name, \COUNT(DISTINCT p.id) AS project_count, \COUNT(pg.id) AS page_count, \MAX(pg.updated_at) AS last_updated_us \FROM workspaces w \- LEFT JOIN projects p ON p.workspace_id = w.id \+ LEFT JOIN projects p ON p.workspace_id = w.id{visible} \LEFT JOIN pages pg ON pg.project_id = p.id AND pg.is_latest = 1 \- GROUP BY w.id \- ORDER BY w.name ASC",- )?;+ GROUP BY w.id{only_readable} \+ ORDER BY w.name ASC"+ ))?;let rows = stmt.query_map([], |row| {let workspace_name: String = row.get(0)?;let project_count: i64 = row.get(1)?;@@ -10121,6 +10453,26 @@ fn cross_project_degree())}+/// Run a one-row `SELECT workspace_id, project_id ... WHERE id = ?1` lookup.+fn scope_row(+ conn: &Connection,+ sql: &str,+ id: &[u8; 16],+) -> StoreResult<Option<(WorkspaceId, ProjectId)>> {+ let row = conn+ .query_row(sql, params![id], |row| {+ Ok((row.get::<_, Vec<u8>>(0)?, row.get::<_, Vec<u8>>(1)?))+ })+ .optional()?;+ match row {+ Some((ws, proj)) => Ok(Some((+ WorkspaceId::from_slice(&ws)?,+ ProjectId::from_slice(&proj)?,+ ))),+ None => Ok(None),+ }+}+fn count_workspace(conn: &Connection, sql: &str, workspace_id: WorkspaceId) -> StoreResult<u64> {let n: Option<i64> = conn.query_row(sql, params![workspace_id.as_bytes()], |row| row.get(0))@@ -10186,11 +10538,14 @@ fn window_activity_project(})}+/// `visible` is a [`readable_repository_predicate`] over `project_id`, or+/// empty; every table counted here carries that column.fn window_activity_workspace(conn: &Connection,days: u32,cutoff_us: i64,workspace_id: WorkspaceId,+ visible: &str,) -> StoreResult<ActivityWindow> {let count_since = |sql: &str| -> StoreResult<u64> {let n: Option<i64> = conn@@ -10202,15 +10557,16 @@ fn window_activity_workspace(};Ok(ActivityWindow {days,- sessions: count_since(- "SELECT COUNT(*) FROM sessions WHERE workspace_id = ?1 AND started_at > ?2",- )?,- observations: count_since(- "SELECT COUNT(*) FROM observations WHERE workspace_id = ?1 AND created_at > ?2",- )?,- pages_updated: count_since(- "SELECT COUNT(*) FROM pages WHERE workspace_id = ?1 AND is_latest = 1 AND updated_at > ?2",- )?,+ sessions: count_since(&format!(+ "SELECT COUNT(*) FROM sessions WHERE workspace_id = ?1 AND started_at > ?2{visible}"+ ))?,+ observations: count_since(&format!(+ "SELECT COUNT(*) FROM observations WHERE workspace_id = ?1 AND created_at > ?2{visible}"+ ))?,+ pages_updated: count_since(&format!(+ "SELECT COUNT(*) FROM pages WHERE workspace_id = ?1 AND is_latest = 1 \+ AND updated_at > ?2{visible}"+ ))?,})}diff --git a/crates/ai-memory-store/src/scope.rs b/crates/ai-memory-store/src/scope.rsindex 2e88d2aa..3448f1d7 100644--- a/crates/ai-memory-store/src/scope.rs+++ b/crates/ai-memory-store/src/scope.rs@@ -10,11 +10,11 @@ use std::collections::HashSet;use std::fmt;use ai_memory_core::{- ActiveProject, ActiveProjectLookup, ActorKey, ProjectId, ReadPointer, WorkspaceId,+ ActiveProject, ActiveProjectLookup, ActorKey, ProjectId, ReadPointer, UserId, WorkspaceId,};use crate::error::StoreError;-use crate::project_authz::{ProjectAccess, ProjectPrincipal};+use crate::project_authz::{GrantLevel, ProjectAccess, ProjectPrincipal};use crate::{ReaderPool, WriterHandle};/// Canonical error for partial explicit scope arguments.@@ -341,12 +341,196 @@ pub async fn create_explicit_scope(})}+/// Run a resolved scope through the per-project choke point (#708).+///+/// A read is decided on the read pool; a write on the writer actor's own+/// connection when a writer is given, so the check cannot race a concurrent+/// grant change against the write it guards.+async fn decide_scope(+ reader: &ReaderPool,+ writer: Option<&WriterHandle>,+ scope: ResolvedScope,+ principal: &ProjectPrincipal,+ distinguishes_operators: bool,+ need: ProjectAccess,+) -> Result<(), ScopeResolutionError> {+ let decision = match (need, writer) {+ (ProjectAccess::Write, Some(writer)) => {+ writer+ .authorize_project(+ scope.workspace_id,+ scope.project_id,+ principal.clone(),+ distinguishes_operators,+ need,+ )+ .await?+ }+ _ => {+ reader+ .authorize_project(+ scope.workspace_id,+ scope.project_id,+ principal.clone(),+ distinguishes_operators,+ need,+ )+ .await?+ }+ };+ if decision.is_ok() {+ return Ok(());+ }+ // A refusal names the project and both levels, so it says what to ask+ // for and can never be mistaken for an empty or missing project. Built on+ // the denial path only, where the extra lookups cost nothing that matters.+ let held = reader+ .resolve_project_authz(+ scope.workspace_id,+ scope.project_id,+ principal.clone(),+ distinguishes_operators,+ )+ .await?+ .grant;+ let name = reader+ .project_name_by_id(scope.workspace_id, scope.project_id)+ .await?+ .unwrap_or_else(|| "the resolved project".to_owned());+ Err(ScopeResolutionError::Forbidden(refusal_message(+ &name, held, need,+ )))+}++fn refusal_message(project: &str, held: Option<GrantLevel>, need: ProjectAccess) -> String {+ let need = match need {+ ProjectAccess::Read => "read",+ ProjectAccess::Write => "write",+ };+ match held {+ Some(held) => format!(+ "not authorized for {project}: you have {} access and this needs {need}. \+ Ask the server operator to raise your access.",+ held.as_str()+ ),+ None => format!(+ "not authorized for {project}. This is an access problem, not an empty \+ memory — ask the server operator to grant you {need} access on it."+ ),+ }+}++/// Authorize a scope resolved outside a [`ScopeResolver`] for `viewer` (#708).+///+/// For routes that name a project directly — admin, web, hook captures — and+/// so have no current-project default to resolve through. `viewer` is the+/// database user the request authenticated as; `None` (the root token, or an+/// install with no database users) skips the check, as a resolver with no+/// principal attached does.+///+/// # Errors+/// [`ScopeResolutionError::Forbidden`] when a restricted project refuses the+/// viewer; store failures otherwise.+pub async fn authorize_scope_for(+ reader: &ReaderPool,+ writer: Option<&WriterHandle>,+ scope: ResolvedScope,+ viewer: Option<UserId>,+ need: ProjectAccess,+) -> Result<ResolvedScope, ScopeResolutionError> {+ let Some(viewer) = viewer else {+ return Ok(scope);+ };+ decide_scope(+ reader,+ writer,+ scope,+ &ProjectPrincipal::user(viewer),+ true,+ need,+ )+ .await?;+ Ok(scope)+}++/// [`lookup_existing_scope`], authorized for `viewer` at `need`.+///+/// # Errors+/// As [`lookup_existing_scope`] and [`authorize_scope_for`].+pub async fn lookup_existing_scope_guarded(+ reader: &ReaderPool,+ workspace: &str,+ project: &str,+ viewer: Option<UserId>,+ need: ProjectAccess,+) -> Result<ResolvedScope, ScopeResolutionError> {+ let scope = lookup_existing_scope(reader, workspace, project).await?;+ authorize_scope_for(reader, None, scope, viewer, need).await+}++/// [`create_explicit_scope`] on behalf of `viewer`, authorized for a write.+///+/// A project this call creates records `viewer` as its creator in the same+/// transaction, and the choke point admits a creator, so they can write to and+/// read back what they just made. A project that already existed is decided+/// like any other write — "create" is never a way into somebody else's+/// restricted project, and because the writer decides which case applies,+/// there is no window between a lookup and a create for another user to win.+///+/// # Errors+/// As [`create_explicit_scope`] and [`authorize_scope_for`].+pub async fn create_explicit_scope_guarded(+ reader: &ReaderPool,+ writer: &WriterHandle,+ workspace: &str,+ project: &str,+ viewer: Option<UserId>,+) -> Result<ResolvedScope, ScopeResolutionError> {+ let workspace_id = writer.get_or_create_workspace(workspace.to_owned()).await?;+ let (project_id, _) = writer+ .get_or_create_project_as(workspace_id, project.to_owned(), None, viewer)+ .await?;+ let scope = ResolvedScope {+ workspace_id,+ project_id,+ };+ authorize_scope_for(reader, Some(writer), scope, viewer, ProjectAccess::Write).await+}++/// [`resolve_many_existing_scopes`], every scope authorized for `viewer`.+///+/// A refused scope fails the whole call rather than being dropped: silently+/// returning the permitted subset would answer a cross-project search with a+/// short list that looks like "nothing was found there", and a refusal must+/// never read as empty memory.+///+/// # Errors+/// As [`resolve_many_existing_scopes`] and [`authorize_scope_for`].+pub async fn resolve_many_existing_scopes_guarded(+ reader: &ReaderPool,+ scopes: &[ScopeName],+ max: usize,+ viewer: Option<UserId>,+ need: ProjectAccess,+) -> Result<Vec<ResolvedScope>, ScopeResolutionError> {+ let resolved = resolve_many_existing_scopes(reader, scopes, max).await?;+ for scope in &resolved {+ authorize_scope_for(reader, None, *scope, viewer, need).await?;+ }+ Ok(resolved)+}+/// Look up the reserved global preferences scope/// ([`ai_memory_core::GLOBAL_SCOPE_PROJECT`] in the default workspace)/// without creating it. Returns `Ok(None)` when it doesn't exist yet — the/// scope participates in default reads by existence, so an absent scope/// means "nothing to union in", never an error (issue #154).///+/// Unauthorized by design, together with [`create_global_scope`]: the global+/// scope is unioned into everybody's default reads, and the unscoped-read+/// filters admit it for every viewer (#708). Per-project authorization is+/// about project scopes; the global preferences scope is common ground.+////// # Errors/// Propagates store failures only; a missing workspace or project is `None`.pub async fn lookup_global_scope(@@ -476,31 +660,15 @@ impl<'a> ScopeResolver<'a> {let Some(principal) = self.authz.as_ref() else {return Ok(());};- let decision = match (need, self.writer) {- (ProjectAccess::Write, Some(writer)) => {- writer- .authorize_project(- scope.workspace_id,- scope.project_id,- principal.clone(),- self.distinguishes_operators,- need,- )- .await?- }- _ => {- self.reader- .authorize_project(- scope.workspace_id,- scope.project_id,- principal.clone(),- self.distinguishes_operators,- need,- )- .await?- }- };- decision.map_err(|err| ScopeResolutionError::Forbidden(err.message().to_owned()))+ decide_scope(+ self.reader,+ self.writer,+ scope,+ principal,+ self.distinguishes_operators,+ need,+ )+ .await}/// Attach the active-project map used for current-project defaults.@@ -529,9 +697,13 @@ impl<'a> ScopeResolver<'a> {explicit_project: Option<&str>,actor: &ActorKey,) -> Result<ResolvedScope, ScopeResolutionError> {- self.resolve_read_args_traced(explicit_workspace, explicit_project, actor)- .await- .map(|(scope, _)| scope)+ self.resolve_existing_args(+ explicit_workspace,+ explicit_project,+ actor,+ ProjectAccess::Read,+ )+ .await}/// [`Self::resolve_read_args`], plus where the scope came from.@@ -540,6 +712,44 @@ impl<'a> ScopeResolver<'a> {explicit_workspace: Option<&str>,explicit_project: Option<&str>,actor: &ActorKey,+ ) -> Result<(ResolvedScope, ScopeSource), ScopeResolutionError> {+ self.resolve_existing_args_traced(+ explicit_workspace,+ explicit_project,+ actor,+ ProjectAccess::Read,+ )+ .await+ }++ /// Resolve read-shaped arguments naming an EXISTING scope, authorized at+ /// `need` (#708).+ ///+ /// The argument shape is not the access level. Tools that delete a page,+ /// record feedback, sweep, lint, accept a handoff or pop a message take the+ /// same arguments as a read and all mutate; resolving them as a read would+ /// let a `read` grant do each of those. The shape says which scope; `need`+ /// says what the caller may do to it. Never creates — that is+ /// [`Self::resolve_write_args`].+ pub async fn resolve_existing_args(+ &self,+ explicit_workspace: Option<&str>,+ explicit_project: Option<&str>,+ actor: &ActorKey,+ need: ProjectAccess,+ ) -> Result<ResolvedScope, ScopeResolutionError> {+ self.resolve_existing_args_traced(explicit_workspace, explicit_project, actor, need)+ .await+ .map(|(scope, _)| scope)+ }++ /// [`Self::resolve_existing_args`], plus where the scope came from.+ pub async fn resolve_existing_args_traced(+ &self,+ explicit_workspace: Option<&str>,+ explicit_project: Option<&str>,+ actor: &ActorKey,+ need: ProjectAccess,) -> Result<(ResolvedScope, ScopeSource), ScopeResolutionError> {match (trimmed_opt(explicit_workspace),@@ -547,11 +757,14 @@ impl<'a> ScopeResolver<'a> {) {(Some(workspace), Some(project)) => {let scope = self.lookup_existing(workspace, project).await?;- self.authorize_scope(scope, ProjectAccess::Read).await?;+ self.authorize_scope(scope, need).await?;Ok((scope, ScopeSource::Explicit))}(Some(_), None) => Err(ScopeResolutionError::WorkspaceProjectPairRequired),- (None, project) => self.resolve_current_or_project_traced(project, actor).await,+ (None, project) => {+ self.resolve_current_or_project_traced(project, actor, need)+ .await+ }}}@@ -562,7 +775,7 @@ impl<'a> ScopeResolver<'a> {explicit_project: Option<&str>,actor: &ActorKey,) -> Result<ResolvedScope, ScopeResolutionError> {- self.resolve_current_or_project_traced(explicit_project, actor)+ self.resolve_current_or_project_traced(explicit_project, actor, ProjectAccess::Read).await.map(|(scope, _)| scope)}@@ -571,6 +784,7 @@ impl<'a> ScopeResolver<'a> {&self,explicit_project: Option<&str>,actor: &ActorKey,+ need: ProjectAccess,) -> Result<(ResolvedScope, ScopeSource), ScopeResolutionError> {// Read path, so `read_pointer`: it adds the startup seed for a caller// the pointer knows nothing about, which is every caller in the window@@ -600,7 +814,7 @@ impl<'a> ScopeResolver<'a> {workspace_id: active_ws,project_id,};- self.authorize_scope(scope, ProjectAccess::Read).await?;+ self.authorize_scope(scope, need).await?;return Ok((scope, ScopeSource::Explicit));}if active.map(|(ws, _)| ws) != Some(self.default_workspace_id)@@ -613,7 +827,7 @@ impl<'a> ScopeResolver<'a> {workspace_id: self.default_workspace_id,project_id,};- self.authorize_scope(scope, ProjectAccess::Read).await?;+ self.authorize_scope(scope, need).await?;return Ok((scope, ScopeSource::Explicit));}return Err(ScopeResolutionError::ProjectNotFoundInActiveOrDefault {@@ -626,7 +840,7 @@ impl<'a> ScopeResolver<'a> {workspace_id,project_id,};- self.authorize_scope(scope, ProjectAccess::Read).await?;+ self.authorize_scope(scope, need).await?;Ok((scope, source))}@@ -676,8 +890,12 @@ impl<'a> ScopeResolver<'a> {.map(|(workspace_id, _)| workspace_id).unwrap_or(self.default_workspace_id),};- let project_id = writer- .get_or_create_project(workspace_id, project.to_owned(), None)+ // A project this call creates records the caller as its creator, whom+ // the choke point below then admits; one that already existed is+ // decided like any other write, so "create" is never a way in.+ let creator = self.authz.as_ref().and_then(|principal| principal.user_id);+ let (project_id, _) = writer+ .get_or_create_project_as(workspace_id, project.to_owned(), None, creator).await?;let scope = ResolvedScope {workspace_id,@@ -687,13 +905,21 @@ impl<'a> ScopeResolver<'a> {Ok(scope)}- /// Resolve and de-duplicate an explicit multi-scope list.+ /// Resolve and de-duplicate an explicit multi-scope list, every scope+ /// authorized for a read.+ ///+ /// A refused scope fails the whole call rather than being dropped — see+ /// [`resolve_many_existing_scopes_guarded`].pub async fn resolve_many_existing(&self,scopes: &[ScopeName],max: usize,) -> Result<Vec<ResolvedScope>, ScopeResolutionError> {- resolve_many_existing_scopes(self.reader, scopes, max).await+ let resolved = resolve_many_existing_scopes(self.reader, scopes, max).await?;+ for scope in &resolved {+ self.authorize_scope(*scope, ProjectAccess::Read).await?;+ }+ Ok(resolved)}}@@ -705,6 +931,331 @@ fn trimmed_opt(value: Option<&str>) -> Option<&str> {mod tests {use super::*;use crate::Store;+ use ai_memory_core::NewUser;++ use crate::{AccessMode, GrantLevel};++ async fn user_named(store: &Store, username: &str, byte: u8) -> UserId {+ store+ .writer+ .create_user(+ NewUser {+ username: username.to_owned(),+ name: None,+ email: None,+ },+ [byte; crate::TOKEN_HASH_LEN],+ )+ .await+ .unwrap()+ }++ /// A restricted project plus two users, neither holding anything on it.+ async fn guard_fixture(store: &Store) -> (WorkspaceId, ProjectId, UserId, UserId) {+ // Grants only decide anything in a restricted project; every project+ // these tests create starts restricted.+ store+ .writer+ .set_new_project_mode(AccessMode::Restricted)+ .await+ .unwrap();+ let ws = store+ .writer+ .get_or_create_workspace("default")+ .await+ .unwrap();+ let project = store+ .writer+ .get_or_create_project(ws, "client-work", None)+ .await+ .unwrap();+ let alice = user_named(store, "alice", 1).await;+ let bob = user_named(store, "bob", 2).await;+ (ws, project, alice, bob)+ }++ async fn grant(store: &Store, user: UserId, project: ProjectId, level: GrantLevel) {+ store+ .writer+ .grant_memory(user, project, level, None)+ .await+ .unwrap();+ }++ fn created_by(store: &Store, project: ProjectId) -> Option<UserId> {+ let conn = rusqlite::Connection::open(store.db_path()).unwrap();+ conn.query_row(+ "SELECT created_by FROM projects WHERE id = ?1",+ rusqlite::params![project.as_bytes()],+ |row| row.get::<_, Option<Vec<u8>>>(0),+ )+ .unwrap()+ .map(|raw| UserId::from_slice(&raw).unwrap())+ }++ fn as_user<'a>(+ store: &'a Store,+ ws: WorkspaceId,+ project: ProjectId,+ user: UserId,+ ) -> ScopeResolver<'a> {+ ScopeResolver::new(&store.reader, ws, project)+ .with_writer(&store.writer)+ .with_project_authz(ProjectPrincipal::user(user), true)+ }++ /// The argument shape and the level are independent, and must stay so.+ ///+ /// Mutating tools take the same arguments as reads. Resolving those as a+ /// read is what would let a `read` grant delete pages, so the level is the+ /// caller's to state — on the explicit-pair branch and on the+ /// current-project fallback alike.+ #[tokio::test]+ async fn the_argument_shape_does_not_decide_the_level() {+ let tmp = tempfile::TempDir::new().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let (ws, project, alice, _) = guard_fixture(&store).await;+ grant(&store, alice, project, GrantLevel::Read).await;+ let resolver = as_user(&store, ws, project, alice);+ let actor = ActorKey::default();++ for (label, workspace, name) in [+ ("explicit pair", Some("default"), Some("client-work")),+ ("current-project fallback", None, None),+ ] {+ resolver+ .resolve_existing_args(workspace, name, &actor, ProjectAccess::Read)+ .await+ .unwrap_or_else(|e| panic!("{label}: a reader may read: {e}"));+ let err = resolver+ .resolve_existing_args(workspace, name, &actor, ProjectAccess::Write)+ .await+ .unwrap_err();+ assert!(+ err.is_forbidden(),+ "{label}: a reader must not reach a write: {err:?}"+ );+ }+ }++ /// Root and an install with no database users both arrive as no viewer,+ /// and neither may change behaviour.+ #[tokio::test]+ async fn no_viewer_resolves_exactly_as_before() {+ let tmp = tempfile::TempDir::new().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let (ws, project, _, _) = guard_fixture(&store).await;++ let scope = lookup_existing_scope_guarded(+ &store.reader,+ "default",+ "client-work",+ None,+ ProjectAccess::Write,+ )+ .await+ .unwrap();+ assert_eq!(+ scope,+ ResolvedScope {+ workspace_id: ws,+ project_id: project+ }+ );+ }++ #[tokio::test]+ async fn a_user_reaches_only_what_they_were_granted() {+ let tmp = tempfile::TempDir::new().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let (_, project, alice, bob) = guard_fixture(&store).await;+ grant(&store, alice, project, GrantLevel::Read).await;+ let lookup = |user, need| {+ lookup_existing_scope_guarded(&store.reader, "default", "client-work", Some(user), need)+ };++ lookup(alice, ProjectAccess::Read).await.unwrap();+ assert!(+ lookup(alice, ProjectAccess::Write)+ .await+ .unwrap_err()+ .is_forbidden()+ );+ // Bob holds nothing. The refusal must say so — not resolve to an+ // empty project, which would read as "there is nothing here".+ let err = lookup(bob, ProjectAccess::Read).await.unwrap_err();+ assert!(err.is_forbidden(), "{err:?}");+ assert!(!err.is_not_found());+ }++ #[tokio::test]+ async fn creating_authorizes_against_a_project_that_already_exists() {+ let tmp = tempfile::TempDir::new().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let (ws, project, alice, bob) = guard_fixture(&store).await;+ grant(&store, alice, project, GrantLevel::Read).await;+ let create = |name: &'static str, user| {+ create_explicit_scope_guarded(&store.reader, &store.writer, "default", name, Some(user))+ };++ // "Create" is not a way around the choke point: the project is already+ // there, so Bob's write is refused exactly as a read would be, and+ // Alice's read grant does not cover a write.+ assert!(create("client-work", bob).await.unwrap_err().is_forbidden());+ assert!(+ create("client-work", alice)+ .await+ .unwrap_err()+ .is_forbidden()+ );+ assert_eq!(created_by(&store, project), None);++ // A project that does not exist yet is created with Bob as its+ // creator, who is admitted without any grant.+ let fresh = create("brand-new", bob).await.unwrap();+ assert_eq!(fresh.workspace_id, ws);+ assert_eq!(created_by(&store, fresh.project_id), Some(bob));+ assert!(+ store+ .reader+ .grants_for(bob, fresh.project_id)+ .await+ .unwrap()+ .is_empty(),+ "the creator needs no grant"+ );+ lookup_existing_scope_guarded(+ &store.reader,+ "default",+ "brand-new",+ Some(bob),+ ProjectAccess::Write,+ )+ .await+ .expect("the creator reaches what they created");++ // A second "create" of the same name by someone else is a write to an+ // existing project: refused, and it does not make them its creator.+ assert!(create("brand-new", alice).await.unwrap_err().is_forbidden());+ assert_eq!(created_by(&store, fresh.project_id), Some(bob));+ }++ /// With no viewer — root, or an install with no database users — a created+ /// project records no creator: there is no user to attribute it to.+ #[tokio::test]+ async fn creating_without_a_viewer_records_no_creator() {+ let tmp = tempfile::TempDir::new().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ guard_fixture(&store).await;+ let fresh = create_explicit_scope_guarded(+ &store.reader,+ &store.writer,+ "default",+ "unattributed",+ None,+ )+ .await+ .unwrap();+ assert_eq!(created_by(&store, fresh.project_id), None);+ }++ /// The MCP write path creates through the resolver, not the free function,+ /// and must behave the same.+ #[tokio::test]+ async fn write_args_record_the_creator_and_check_everyone_else() {+ let tmp = tempfile::TempDir::new().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let (ws, project, alice, bob) = guard_fixture(&store).await;+ let actor = ActorKey::default();++ let as_bob = as_user(&store, ws, project, bob);+ let created = as_bob+ .resolve_write_args(Some("default"), Some("bobs-repo"), &actor)+ .await+ .unwrap();+ assert_eq!(created_by(&store, created.project_id), Some(bob));+ as_bob+ .resolve_write_args(Some("default"), Some("bobs-repo"), &actor)+ .await+ .expect("the creator writes to it again");++ let err = as_user(&store, ws, project, alice)+ .resolve_write_args(Some("default"), Some("bobs-repo"), &actor)+ .await+ .unwrap_err();+ assert!(err.is_forbidden(), "{err:?}");+ }++ #[tokio::test]+ async fn a_refused_scope_fails_the_search_instead_of_shortening_it() {+ let tmp = tempfile::TempDir::new().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let (ws, granted, alice, _) = guard_fixture(&store).await;+ let refused = store+ .writer+ .get_or_create_project(ws, "other-team", None)+ .await+ .unwrap();+ grant(&store, alice, granted, GrantLevel::Read).await;+ let names = [+ ScopeName::new("default", "client-work"),+ ScopeName::new("default", "client-work"),+ ScopeName::new("default", "other-team"),+ ];++ let err = resolve_many_existing_scopes_guarded(+ &store.reader,+ &names,+ 25,+ Some(alice),+ ProjectAccess::Read,+ )+ .await+ .unwrap_err();+ assert!(err.is_forbidden(), "{err:?}");+ let err = as_user(&store, ws, granted, alice)+ .resolve_many_existing(&names, 25)+ .await+ .unwrap_err();+ assert!(err.is_forbidden(), "the resolver agrees: {err:?}");++ // Every scope granted: the call succeeds, still de-duplicated.+ grant(&store, alice, refused, GrantLevel::Read).await;+ let resolved = as_user(&store, ws, granted, alice)+ .resolve_many_existing(&names, 25)+ .await+ .unwrap();+ assert_eq!(resolved.len(), 2);+ }++ #[tokio::test]+ async fn a_revoked_grant_denies_like_one_never_granted() {+ let tmp = tempfile::TempDir::new().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let (_, project, alice, bob) = guard_fixture(&store).await;+ store+ .writer+ .grant_memory(alice, project, GrantLevel::Write, Some(bob))+ .await+ .unwrap();+ assert!(+ store+ .writer+ .revoke_memory(alice, project, Some(bob))+ .await+ .unwrap()+ );+ let err = lookup_existing_scope_guarded(+ &store.reader,+ "default",+ "client-work",+ Some(alice),+ ProjectAccess::Read,+ )+ .await+ .unwrap_err();+ assert!(err.is_forbidden(), "{err:?}");+ }#[tokio::test]async fn read_args_reject_partial_scope() {diff --git a/crates/ai-memory-store/src/writer.rs b/crates/ai-memory-store/src/writer.rsindex 7aae7210..74ced4df 100644--- a/crates/ai-memory-store/src/writer.rs+++ b/crates/ai-memory-store/src/writer.rs@@ -61,6 +61,22 @@ pub(crate) enum WriteCmd {repo_path: Option<String>,reply: oneshot::Sender<StoreResult<ProjectId>>,},+ GetOrCreateProjectAs {+ workspace_id: WorkspaceId,+ name: String,+ repo_path: Option<String>,+ creator: Option<ai_memory_core::UserId>,+ reply: oneshot::Sender<StoreResult<(ProjectId, bool)>>,+ },+ SetNewProjectMode {+ mode: crate::AccessMode,+ reply: oneshot::Sender<StoreResult<()>>,+ },+ SetAccessMode {+ project_id: ProjectId,+ mode: crate::AccessMode,+ reply: oneshot::Sender<StoreResult<Option<crate::AccessMode>>>,+ },EnsureProjectWorkspace {workspace_id: WorkspaceId,project_id: ProjectId,@@ -487,6 +503,19 @@ pub(crate) enum WriteCmd {token_hash: [u8; TOKEN_HASH_LEN],reply: oneshot::Sender<StoreResult<UserId>>,},+ GrantMemory {+ user_id: UserId,+ repository_id: ProjectId,+ role: crate::GrantLevel,+ granted_by: Option<UserId>,+ reply: oneshot::Sender<StoreResult<crate::grants::GrantOutcome>>,+ },+ RevokeMemory {+ user_id: UserId,+ repository_id: ProjectId,+ revoked_by: Option<UserId>,+ reply: oneshot::Sender<StoreResult<bool>>,+ },RotateUserToken {user_id: UserId,token_hash: [u8; TOKEN_HASH_LEN],@@ -774,6 +803,67 @@ impl WriterHandle {rx.await.map_err(|_| StoreError::WriterClosed)?}+ /// [`Self::get_or_create_project`] on behalf of `creator`, who is recorded+ /// as the project's `created_by` in the same transaction when this call+ /// creates the row. Returns whether it did — see+ /// [`ops::get_or_create_project_as`].+ ///+ /// # Errors+ /// Returns [`StoreError::WriterClosed`] if the actor has shut down, or+ /// propagates the SQL error.+ pub async fn get_or_create_project_as(+ &self,+ workspace_id: WorkspaceId,+ name: impl Into<String>,+ repo_path: Option<String>,+ creator: Option<ai_memory_core::UserId>,+ ) -> StoreResult<(ProjectId, bool)> {+ let (tx, rx) = oneshot::channel();+ self.send(WriteCmd::GetOrCreateProjectAs {+ workspace_id,+ name: name.into(),+ repo_path,+ creator,+ reply: tx,+ })+ .await?;+ rx.await.map_err(|_| StoreError::WriterClosed)?+ }++ /// Set the access mode newly created projects start in — the server's+ /// `[auth] new_projects_restricted`. Called once at startup; until then,+ /// and on every install that never calls it, new projects are open.+ ///+ /// # Errors+ /// Returns [`StoreError::WriterClosed`] if the actor has shut down.+ pub async fn set_new_project_mode(&self, mode: crate::AccessMode) -> StoreResult<()> {+ let (tx, rx) = oneshot::channel();+ self.send(WriteCmd::SetNewProjectMode { mode, reply: tx })+ .await?;+ rx.await.map_err(|_| StoreError::WriterClosed)?+ }++ /// Set one project's access mode, returning the mode it had, or `None` when+ /// there is no such project.+ ///+ /// # Errors+ /// Returns [`StoreError::WriterClosed`] if the actor has shut down, or+ /// propagates the SQL error.+ pub async fn set_access_mode(+ &self,+ project_id: ProjectId,+ mode: crate::AccessMode,+ ) -> StoreResult<Option<crate::AccessMode>> {+ let (tx, rx) = oneshot::channel();+ self.send(WriteCmd::SetAccessMode {+ project_id,+ mode,+ reply: tx,+ })+ .await?;+ rx.await.map_err(|_| StoreError::WriterClosed)?+ }+/// Assert that a project still belongs to the supplied workspace.////// # Errors@@ -2181,6 +2271,56 @@ impl WriterHandle {rx.await.map_err(|_| StoreError::WriterClosed)?}+ /// Grant `user_id` `role` on `repository_id` (#708).+ ///+ /// `granted_by` is the operator making the change, or `None` when they+ /// act through the root bearer token (no `users` row).+ ///+ /// # Errors+ /// Writer closed or SQL.+ pub async fn grant_memory(+ &self,+ user_id: UserId,+ repository_id: ProjectId,+ role: crate::GrantLevel,+ granted_by: Option<UserId>,+ ) -> StoreResult<crate::grants::GrantOutcome> {+ let (tx, rx) = oneshot::channel();+ self.send(WriteCmd::GrantMemory {+ user_id,+ repository_id,+ role,+ granted_by,+ reply: tx,+ })+ .await?;+ rx.await.map_err(|_| StoreError::WriterClosed)?+ }++ /// Revoke whatever `user_id` actively holds on `repository_id`.+ ///+ /// Returns whether anything was in force to revoke, so calling it twice is+ /// harmless and still reports honestly.+ ///+ /// # Errors+ /// Writer closed or SQL.+ pub async fn revoke_memory(+ &self,+ user_id: UserId,+ repository_id: ProjectId,+ revoked_by: Option<UserId>,+ ) -> StoreResult<bool> {+ let (tx, rx) = oneshot::channel();+ self.send(WriteCmd::RevokeMemory {+ user_id,+ repository_id,+ revoked_by,+ reply: tx,+ })+ .await?;+ rx.await.map_err(|_| StoreError::WriterClosed)?+ }+/// Insert a token-only compatibility identity.////// # Errors@@ -2772,8 +2912,25 @@ fn send_or_warn<T>(reply: oneshot::Sender<T>, result: T, op: &'static str) {}fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {+ // The mode a newly created project starts in — the server's+ // `[auth] new_projects_restricted`, set once at startup. Held here because+ // this actor performs every project insert, so no creation path can+ // forget to apply it.+ let mut new_project_mode = crate::AccessMode::Open;while let Some(cmd) = rx.blocking_recv() {match cmd {+ WriteCmd::SetNewProjectMode { mode, reply } => {+ new_project_mode = mode;+ send_or_warn(reply, Ok(()), "set_new_project_mode");+ }+ WriteCmd::SetAccessMode {+ project_id,+ mode,+ reply,+ } => {+ let result = crate::grants::set_access_mode(&conn, project_id, mode);+ send_or_warn(reply, result, "set_access_mode");+ }WriteCmd::Shutdown => break,WriteCmd::AuthorizeProject {workspace_id,@@ -2803,14 +2960,36 @@ fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {repo_path,reply,} => {- let result = ops::get_or_create_project(+ // Through the creator-aware path with no creator, so the+ // server's new-project mode applies here too.+ let result = ops::get_or_create_project_as(&mut conn,&workspace_id,&name,repo_path.as_deref(),- );+ None,+ new_project_mode,+ )+ .map(|(id, _)| id);send_or_warn(reply, result, "get_or_create_project");}+ WriteCmd::GetOrCreateProjectAs {+ workspace_id,+ name,+ repo_path,+ creator,+ reply,+ } => {+ let result = ops::get_or_create_project_as(+ &mut conn,+ &workspace_id,+ &name,+ repo_path.as_deref(),+ creator,+ new_project_mode,+ );+ send_or_warn(reply, result, "get_or_create_project_as");+ }WriteCmd::EnsureProjectWorkspace {workspace_id,project_id,@@ -3480,6 +3659,38 @@ fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {let result = users::insert_user(&conn, &new_user, &token_hash);send_or_warn(reply, result, "create_user");}+ WriteCmd::GrantMemory {+ user_id,+ repository_id,+ role,+ granted_by,+ reply,+ } => {+ let result = crate::grants::grant(+ &conn,+ user_id,+ repository_id,+ role,+ granted_by,+ jiff::Timestamp::now().as_microsecond(),+ );+ send_or_warn(reply, result, "grant_memory");+ }+ WriteCmd::RevokeMemory {+ user_id,+ repository_id,+ revoked_by,+ reply,+ } => {+ let result = crate::grants::revoke(+ &conn,+ user_id,+ repository_id,+ revoked_by,+ jiff::Timestamp::now().as_microsecond(),+ );+ send_or_warn(reply, result, "revoke_memory");+ }WriteCmd::RotateUserToken {user_id,token_hash,diff --git a/crates/ai-memory-store/tests/suite/access_mode.rs b/crates/ai-memory-store/tests/suite/access_mode.rsnew file mode 100644index 00000000..79eadeb6--- /dev/null+++ b/crates/ai-memory-store/tests/suite/access_mode.rs@@ -0,0 +1,358 @@+//! Per-project access mode (#708, `docs/design-per-project-authz.md`).+//!+//! A project is `open` — any authenticated user, which is what every project+//! was before this existed — or `restricted` — root, its creator and grant+//! holders only.+//! These follow the design's verification plan: every caller shape against+//! both modes, the multi-session shape that single-session tests cannot see+//! (a teammate admitted while an outsider is refused, pages still shared+//! within the project), and the upgrade path.++use ai_memory_core::{NewPage, NewUser, PagePath, ProjectId, Tier, UserId, WorkspaceId};+use ai_memory_store::{+ AccessMode, GrantLevel, ProjectAccess, ProjectPrincipal, Store, lookup_existing_scope_guarded,+};++/// Whether the choke point admits `user` to `project` for `need`.+async fn admits(+ store: &Store,+ ws: WorkspaceId,+ project: ProjectId,+ user: UserId,+ need: ProjectAccess,+) -> bool {+ store+ .reader+ .authorize_project(ws, project, ProjectPrincipal::user(user), true, need)+ .await+ .unwrap()+ .is_ok()+}++fn page(+ ws: WorkspaceId,+ proj: ProjectId,+ path: &str,+ body: &str,+ author: Option<UserId>,+) -> NewPage {+ NewPage {+ workspace_id: ws,+ project_id: proj,+ path: PagePath::new(path).unwrap(),+ title: path.to_string(),+ body: body.into(),+ tier: Tier::Semantic,+ frontmatter_json: serde_json::json!({}),+ pinned: false,+ links: Vec::new(),+ author_id: author,+ expires_at: None,+ entities: Vec::new(),+ evidence: Vec::new(),+ }+}++async fn user(store: &Store, name: &str, byte: u8) -> UserId {+ store+ .writer+ .create_user(+ NewUser {+ username: name.to_owned(),+ name: None,+ email: None,+ },+ [byte; ai_memory_store::TOKEN_HASH_LEN],+ )+ .await+ .unwrap()+}++struct Fixture {+ _tmp: tempfile::TempDir,+ store: Store,+ ws: WorkspaceId,+ project: ProjectId,+ reader: UserId,+ writer: UserId,+ outsider: UserId,+}++async fn fixture() -> Fixture {+ let tmp = tempfile::TempDir::new().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let ws = store+ .writer+ .get_or_create_workspace("default".to_string())+ .await+ .unwrap();+ let project = store+ .writer+ .get_or_create_project(ws, "client-work", None)+ .await+ .unwrap();+ let reader = user(&store, "ray", 1).await;+ let writer = user(&store, "wren", 2).await;+ let outsider = user(&store, "otto", 3).await;+ store+ .writer+ .grant_memory(reader, project, GrantLevel::Read, None)+ .await+ .unwrap();+ store+ .writer+ .grant_memory(writer, project, GrantLevel::Write, None)+ .await+ .unwrap();+ Fixture {+ _tmp: tmp,+ store,+ ws,+ project,+ reader,+ writer,+ outsider,+ }+}++/// Every caller shape against both modes, at both levels.+///+/// Root arrives with no viewer and is never checked. In an open project every+/// database user is admitted at every level — grants or not, which is how+/// every project behaved before this existed. In a restricted one the grant+/// decides, and holding less than the operation needs is its own refusal.+#[tokio::test]+async fn every_caller_against_both_modes() {+ let f = fixture().await;+ for mode in [AccessMode::Open, AccessMode::Restricted] {+ f.store+ .writer+ .set_access_mode(f.project, mode)+ .await+ .unwrap();+ let open = mode == AccessMode::Open;+ for (who, user, read, write) in [+ ("read grant", f.reader, true, open),+ ("write grant", f.writer, true, true),+ ("no grant", f.outsider, open, open),+ ] {+ let reads = admits(&f.store, f.ws, f.project, user, ProjectAccess::Read).await;+ let writes = admits(&f.store, f.ws, f.project, user, ProjectAccess::Write).await;+ assert_eq!(reads, read, "{who} reading a {mode:?} project");+ assert_eq!(writes, write, "{who} writing a {mode:?} project");+ }+ // Root: no viewer, no check, whatever the mode.+ lookup_existing_scope_guarded(+ &f.store.reader,+ "default",+ "client-work",+ None,+ ProjectAccess::Write,+ )+ .await+ .unwrap_or_else(|e| panic!("root refused on a {mode:?} project: {e}"));+ }+}++/// The multi-session shape from the design: in a restricted project a granted+/// teammate reads what the creator wrote while an outsider is refused by name.+/// Grants gate entry to the project, never rows within it — the teammate sees+/// the same shared page, not a filtered copy (invariant #16).+#[tokio::test]+async fn a_restricted_project_admits_the_team_and_refuses_the_outsider() {+ let f = fixture().await;+ f.store+ .writer+ .set_access_mode(f.project, AccessMode::Restricted)+ .await+ .unwrap();+ f.store+ .writer+ .upsert_page(page(+ f.ws,+ f.project,+ "decisions/shared.md",+ "zebracrossing decision",+ Some(f.writer),+ ))+ .await+ .unwrap();++ lookup_existing_scope_guarded(+ &f.store.reader,+ "default",+ "client-work",+ Some(f.reader),+ ProjectAccess::Read,+ )+ .await+ .expect("a granted teammate is admitted");+ let hits = f+ .store+ .reader+ .search_pages("zebracrossing".into(), 10, Some(f.reader))+ .await+ .unwrap();+ assert_eq!(+ hits.len(),+ 1,+ "the teammate finds the page the creator wrote"+ );++ let refused = lookup_existing_scope_guarded(+ &f.store.reader,+ "default",+ "client-work",+ Some(f.outsider),+ ProjectAccess::Read,+ )+ .await+ .unwrap_err();+ assert!(refused.is_forbidden(), "{refused:?}");+ let hits = f+ .store+ .reader+ .search_pages("zebracrossing".into(), 10, Some(f.outsider))+ .await+ .unwrap();+ assert!(hits.is_empty(), "search must not leak a restricted project");++ // Open it again and the outsider reads it, grant or not.+ f.store+ .writer+ .set_access_mode(f.project, AccessMode::Open)+ .await+ .unwrap();+ let hits = f+ .store+ .reader+ .search_pages("zebracrossing".into(), 10, Some(f.outsider))+ .await+ .unwrap();+ assert_eq!(hits.len(), 1, "an open project is visible to every user");+}++/// `[auth] new_projects_restricted`: once set, a project created from then on+/// starts restricted and admits the creator recorded on it. The reserved+/// projects stay open whatever it says.+#[tokio::test]+async fn new_projects_follow_the_server_default_and_admit_their_creator() {+ let f = fixture().await;+ let w = &f.store.writer;+ let (open_one, _) = w+ .get_or_create_project_as(f.ws, "before-the-flag", None, Some(f.outsider))+ .await+ .unwrap();+ assert!(admits(&f.store, f.ws, open_one, f.reader, ProjectAccess::Write).await);++ w.set_new_project_mode(AccessMode::Restricted)+ .await+ .unwrap();+ let (locked, created) = w+ .get_or_create_project_as(f.ws, "after-the-flag", None, Some(f.outsider))+ .await+ .unwrap();+ assert!(created);+ let conn = rusqlite::Connection::open(f.store.db_path()).unwrap();+ let creator: Option<Vec<u8>> = conn+ .query_row(+ "SELECT created_by FROM projects WHERE id = ?1",+ [locked.as_bytes().to_vec()],+ |row| row.get(0),+ )+ .unwrap();+ assert_eq!(creator, Some(f.outsider.as_bytes().to_vec()));+ assert!(+ admits(&f.store, f.ws, locked, f.outsider, ProjectAccess::Write).await,+ "the creator is admitted"+ );+ assert!(+ !admits(&f.store, f.ws, locked, f.reader, ProjectAccess::Read).await,+ "everyone else is refused"+ );+ // A create with no creator — root, server start-up, admin — follows the+ // default too; the writer applies it to every insert.+ let plain = w+ .get_or_create_project(f.ws, "created-by-root", None)+ .await+ .unwrap();+ assert!(+ !admits(&f.store, f.ws, plain, f.reader, ProjectAccess::Read).await,+ "every new project starts restricted, whoever creates it"+ );+ for reserved in [+ ai_memory_core::DEFAULT_PROJECT_NAME,+ ai_memory_core::GLOBAL_SCOPE_PROJECT,+ ] {+ let (id, _) = w+ .get_or_create_project_as(f.ws, reserved, None, Some(f.outsider))+ .await+ .unwrap();+ assert!(+ admits(&f.store, f.ws, id, f.reader, ProjectAccess::Write).await,+ "{reserved} must stay open"+ );+ }+ // An existing project is not touched by the flag.+ assert!(admits(&f.store, f.ws, open_one, f.reader, ProjectAccess::Write).await);+}++/// Restricting names the people who were working in the project and are about+/// to be refused — authors with no grant who did not create it — and never the+/// ones who keep access.+#[tokio::test]+async fn restricting_reports_the_authors_it_locks_out() {+ let f = fixture().await;+ for (path, author) in [+ ("notes/a.md", f.outsider),+ ("notes/b.md", f.writer),+ ("notes/c.md", f.outsider),+ ] {+ f.store+ .writer+ .upsert_page(page(f.ws, f.project, path, "body", Some(author)))+ .await+ .unwrap();+ }+ assert_eq!(+ f.store+ .reader+ .authors_without_grant(f.project)+ .await+ .unwrap(),+ vec!["otto".to_owned()]+ );+}++/// Upgrading changes nobody's access: every project that existed before the+/// migration is open.+#[tokio::test]+async fn existing_projects_are_open_after_upgrade() {+ let tmp = tempfile::TempDir::new().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let ws = store+ .writer+ .get_or_create_workspace("default".to_string())+ .await+ .unwrap();+ let project = store+ .writer+ .get_or_create_project(ws, "legacy", None)+ .await+ .unwrap();+ let conn = rusqlite::Connection::open(store.db_path()).unwrap();+ let mode: String = conn+ .query_row(+ "SELECT access_mode FROM projects WHERE id = ?1",+ [project.as_bytes().to_vec()],+ |row| row.get(0),+ )+ .unwrap();+ assert_eq!(mode, "open");+ // And the database refuses a mode this version cannot read.+ let bad = conn.execute(+ "UPDATE projects SET access_mode = 'members_only' WHERE id = ?1",+ [project.as_bytes().to_vec()],+ );+ assert!(bad.is_err(), "an unknown mode must not be storable");+}diff --git a/crates/ai-memory-store/tests/suite/handoff_ownership.rs b/crates/ai-memory-store/tests/suite/handoff_ownership.rsindex 9aa9a6bc..dd1802ba 100644--- a/crates/ai-memory-store/tests/suite/handoff_ownership.rs+++ b/crates/ai-memory-store/tests/suite/handoff_ownership.rs@@ -428,7 +428,7 @@ async fn unattributed_readers_do_not_see_owned_handoffs() {assert!(store.reader- .latest_open_handoff_for_workspace(ws, OwnerFilter::Unattributed)+ .latest_open_handoff_for_workspace(ws, OwnerFilter::Unattributed, None).await.unwrap().is_none()@@ -437,7 +437,7 @@ async fn unattributed_readers_do_not_see_owned_handoffs() {assert!(store.reader- .latest_open_handoff_for_workspace(ws, OwnerFilter::Any)+ .latest_open_handoff_for_workspace(ws, OwnerFilter::Any, None).await.unwrap().is_some()@@ -721,7 +721,7 @@ async fn an_owner_name_with_a_quote_filters_like_any_other() {.pending_handoff_count,store.reader- .briefing_for_workspace(ws, 5, filter())+ .briefing_for_workspace(ws, 5, filter(), None).await.unwrap().pending_handoff_count,diff --git a/crates/ai-memory-store/tests/suite/mod.rs b/crates/ai-memory-store/tests/suite/mod.rsindex e4a1745b..52b6b25b 100644--- a/crates/ai-memory-store/tests/suite/mod.rs+++ b/crates/ai-memory-store/tests/suite/mod.rs@@ -3,6 +3,7 @@//! no extra binary; a new file must be declared below.mod access_breadth;+mod access_mode;mod agent_messages;mod audit_contamination;mod audit_log;diff --git a/crates/ai-memory-store/tests/suite/multi_session.rs b/crates/ai-memory-store/tests/suite/multi_session.rsindex 3e4f798b..86cdfdac 100644--- a/crates/ai-memory-store/tests/suite/multi_session.rs+++ b/crates/ai-memory-store/tests/suite/multi_session.rs@@ -110,7 +110,7 @@ async fn one_operators_page_is_readable_by_another_in_the_same_project() {// Carol's read of the same project: no owner coordinate involved.let hits = store.reader- .search_pages("SQLite".to_string(), 10)+ .search_pages("SQLite".to_string(), 10, None).await.unwrap();diff --git a/crates/ai-memory-store/tests/suite/slot_visibility.rs b/crates/ai-memory-store/tests/suite/slot_visibility.rsindex 2eabbe04..6485f5fd 100644--- a/crates/ai-memory-store/tests/suite/slot_visibility.rs+++ b/crates/ai-memory-store/tests/suite/slot_visibility.rs@@ -349,6 +349,7 @@ async fn briefing_slots_follow_the_same_visibility_rule() {10,ai_memory_core::OwnerFilter::Any,&mine,+ None,).await.unwrap(),@@ -412,6 +413,7 @@ async fn recent_pages_hide_other_operators_personal_slots() {100,ai_memory_core::OwnerFilter::Any,&mine,+ None,).await.unwrap()