Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(auth): inert project-grant schema and authorize_project choke point (#708)
AkitaOnRails8b89bf299ed9
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3a7a5193..06342913 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]### Added+- Inert per-project-authorization schema and the `authorize_project` choke+ point (first slice of #708). A new `project_grants` table+ (`(workspace, project, user) -> read|write`) and a `projects.access_mode`+ column (`open` | `restricted`, default `open`) are added additively — every+ existing project stays `open`, so there is no behaviour change. The typed+ `authorize_project` gate (consulted by `ScopeResolver` read/write resolution+ and, as defense in depth, by the writer actor) short-circuits `open`+ projects and single-user/loopback deployments to ALLOW, and degrades to open+ when grants cannot be read (never a lockout). A `restricted` project with+ zero grants still admits root and the creator. Because nothing sets+ `restricted` yet, this is a pure pass-through; enforcing `restricted` across+ the unscoped-read and raw-id bypass classes plus the root-only management+ surface (setting `restricted`, issuing grants) follow in a later slice. (#708)- Native `ai-memory upgrade` for GitHub-release installs (Linux/macOStarballs and Windows x86_64 zip): downloads the matching release archive,verifies the `.sha256` sidecar, replaces the on-disk binary (and a siblingdiff --git a/crates/ai-memory-store/migrations/V67__project_grants.sql b/crates/ai-memory-store/migrations/V67__project_grants.sqlnew file mode 100644index 00000000..efb421e3--- /dev/null+++ b/crates/ai-memory-store/migrations/V67__project_grants.sql@@ -0,0 +1,40 @@+-- Per-project authorization: inert schema (#708, slice 2).+--+-- On a multi-user server a DB-user token *attributes* writes but does not+-- *scope* which projects the user may read or write: any authenticated caller+-- can resolve any `(workspace, project)`. This migration lays the storage for+-- closing that gap without changing any behaviour yet.+--+-- Two additive pieces:+--+-- 1. `project_grants` — an explicit `(user, workspace, project) -> level`+-- grant. `read` allows reads in the project; `write` allows reads and+-- writes. Project-level `admin` stays out of scope for v1 (admin remains+-- global/root).+--+-- 2. `projects.access_mode` — per-project enforcement switch. `open`+-- (the default, and every existing project on upgrade) means today's+-- behaviour: any authenticated user is admitted. `restricted` means only+-- root, the project creator, and users with a matching grant are admitted.+--+-- Ship inert: nothing sets `restricted` in this slice, the grants table starts+-- empty, and the choke point short-circuits `open` projects to ALLOW, so this+-- is a pure pass-through. A missing/unreadable grants table degrades to `open`+-- (never a lockout — the #678 degrade-don't-fail-closed lesson). Enforcement of+-- `restricted` across the two bypass classes (unscoped/global reads, raw-id+-- entry points) and the root-only management surface land in the follow-up.++CREATE TABLE project_grants (+ workspace_id BLOB NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,+ project_id BLOB NOT NULL REFERENCES projects(id) ON DELETE CASCADE,+ user_id BLOB NOT NULL REFERENCES users(id) ON DELETE CASCADE,+ level TEXT NOT NULL CHECK (level IN ('read', 'write')),+ granted_by BLOB REFERENCES users(id) ON DELETE SET NULL,+ granted_at INTEGER NOT NULL,+ PRIMARY KEY (workspace_id, project_id, user_id)+) WITHOUT ROWID;++-- Every existing project defaults to `open`, so nothing changes on upgrade.+ALTER TABLE projects+ ADD COLUMN access_mode TEXT NOT NULL DEFAULT 'open'+ CHECK (access_mode IN ('open', 'restricted'));diff --git a/crates/ai-memory-store/src/api_credentials.rs b/crates/ai-memory-store/src/api_credentials.rsindex cc271eeb..37f6e010 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, 66, "update the pin when adding a migration");+ assert_eq!(version, 67, "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/lib.rs b/crates/ai-memory-store/src/lib.rsindex fd2608ac..7e8e4394 100644--- a/crates/ai-memory-store/src/lib.rs+++ b/crates/ai-memory-store/src/lib.rs@@ -24,6 +24,7 @@ mod maintenance;mod migrations;mod ops;pub mod password;+mod project_authz;mod reader;mod retrieval_tuning;mod scope;@@ -62,6 +63,10 @@ pub use ops::{PurgeSummary, ReorgSummary, backfill_entity_index, backfill_page_windows,backfill_page_windows_in_batches, purge_session, record_embed_failure,};+pub use project_authz::{+ AccessMode, GrantLevel, ProjectAccess, ProjectAuthz, ProjectPrincipal,+ RESTRICTED_PROJECT_FORBIDDEN, authorize_project, resolve_project_authz,+};pub use reader::{ActivityWindow, AgentSessionCount, AuditEvent, AuditLogFilter, AutoImproveCandidateSession,AutoImproveParkedClaim, BriefPageBody, BriefingPage, BriefingSnapshot, ClientActivity,diff --git a/crates/ai-memory-store/src/project_authz.rs b/crates/ai-memory-store/src/project_authz.rsnew file mode 100644index 00000000..2a09a2bf--- /dev/null+++ b/crates/ai-memory-store/src/project_authz.rs@@ -0,0 +1,395 @@+//! Per-project authorization choke point (#708).+//!+//! On a multi-user server, attribution ([`ai_memory_core::ActorContext`]) records+//! *who* made a write but does not gate *whether* they were allowed to touch a+//! given project. This module is the single typed decision point that closes+//! that gap. It is consulted by [`crate::ScopeResolver`] read/write resolution+//! (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)+//!+//! The V67 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:+//! - 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.+//!+//! ## Never fail closed on a resolution gap (#678)+//!+//! A `restricted` project with **zero** grants still admits root and the+//! project creator — an operator is never locked out of their own data. If the+//! grants table cannot be read (an older schema mid-migration), the decision+//! degrades to `open` with a loud warning rather than denying every read.+//!+//! ## Invariant #16+//!+//! This is an *authorization* check that returns allow/deny for **entry** to a+//! project. It is never an [`ai_memory_core::OwnerFilter`] on page rows and it+//! never scopes page reads by user: a team with grants sees the same shared+//! pages. `pages.author_id` must never become a read filter.++use ai_memory_core::{AuthzError, ProjectId, UserId, WorkspaceId};+use rusqlite::{Connection, OptionalExtension, params};++use crate::error::StoreResult;++/// Denial message surfaced when a `restricted` project refuses a caller.+pub const RESTRICTED_PROJECT_FORBIDDEN: &str =+ "project access is restricted; root, the project creator, or a matching grant is required";++/// A project's enforcement mode, stored in `projects.access_mode` (V67).+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum AccessMode {+ /// Today's behaviour: any authenticated user is admitted.+ Open,+ /// Only root, the project creator, and matching grants are admitted.+ Restricted,+}++impl AccessMode {+ /// Stable snake_case token stored in SQL.+ #[must_use]+ pub fn as_str(self) -> &'static str {+ match self {+ AccessMode::Open => "open",+ AccessMode::Restricted => "restricted",+ }+ }++ /// Parse the stored value, degrading anything unexpected to [`Self::Open`].+ ///+ /// A `NULL`/absent column, an unknown token, or a value written by a newer+ /// build all read as `open`. Never fail closed on a value we cannot make+ /// sense of (the #678 degrade-don't-lock-out rule).+ #[must_use]+ pub fn from_db(value: Option<&str>) -> Self {+ match value {+ Some("restricted") => AccessMode::Restricted,+ _ => AccessMode::Open,+ }+ }+}++/// A user's grant level on a project (`project_grants.level`, V67).+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum GrantLevel {+ /// Read the project's pages/observations/status.+ Read,+ /// Read plus write/consolidate/handoff/message/delete.+ Write,+}++impl GrantLevel {+ /// Stable snake_case token stored in SQL.+ #[must_use]+ pub fn as_str(self) -> &'static str {+ match self {+ GrantLevel::Read => "read",+ GrantLevel::Write => "write",+ }+ }++ /// Parse the stored value; an unknown token is no grant.+ #[must_use]+ pub fn from_db(value: &str) -> Option<Self> {+ match value {+ "read" => Some(GrantLevel::Read),+ "write" => Some(GrantLevel::Write),+ _ => None,+ }+ }+}++/// What a caller is attempting to do in a project.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum ProjectAccess {+ /// A read (query, read page/observations, status, briefing).+ Read,+ /// A write (write page, consolidate, handoff, message, delete).+ Write,+}++/// 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.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct ProjectPrincipal {+ /// Authenticated as the configured root operator.+ pub is_root: bool,+ /// The creator of this project.+ pub is_creator: bool,+ /// The caller's `users.id`, used to look up a grant. `None` for anonymous+ /// callers and for identities not mapped to a DB user.+ pub user_id: Option<UserId>,+}++impl ProjectPrincipal {+ /// An anonymous, ungranted, non-privileged caller.+ #[must_use]+ pub fn anonymous() -> Self {+ Self {+ is_root: false,+ is_creator: false,+ user_id: None,+ }+ }++ /// A root caller.+ #[must_use]+ pub fn root() -> Self {+ Self {+ is_root: true,+ is_creator: false,+ user_id: None,+ }+ }+}++/// A project's authorization state, fully resolved from SQL, ready to decide.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct ProjectAuthz {+ /// Whether the deployment distinguishes operators (DB users / trusted proxy).+ pub distinguishes_operators: bool,+ /// The project's enforcement mode.+ pub access_mode: AccessMode,+ /// Whether the caller is root.+ pub is_root: bool,+ /// Whether the caller created the project.+ pub is_creator: bool,+ /// The caller's grant on the project, if any.+ pub grant: Option<GrantLevel>,+}++impl ProjectAuthz {+ /// Decide whether the caller may perform `need` in this project.+ ///+ /// - A deployment that does not distinguish operators skips the gate.+ /// - An `open` project admits everyone (today's behaviour).+ /// - A `restricted` project admits root and the creator unconditionally;+ /// otherwise a read needs any grant and a write needs a `write` grant.+ /// Anyone else — including an anonymous caller — is [`AuthzError::Forbidden`].+ ///+ /// # Errors+ /// [`AuthzError::Forbidden`] when a restricted project refuses the caller.+ pub fn authorize(&self, need: ProjectAccess) -> Result<(), AuthzError> {+ if !self.distinguishes_operators {+ return Ok(());+ }+ match self.access_mode {+ AccessMode::Open => Ok(()),+ AccessMode::Restricted => {+ if self.is_root || self.is_creator {+ return Ok(());+ }+ let admitted = match need {+ // A read or write grant both admit a read.+ ProjectAccess::Read => self.grant.is_some(),+ ProjectAccess::Write => self.grant == Some(GrantLevel::Write),+ };+ if admitted {+ Ok(())+ } else {+ Err(AuthzError::Forbidden(RESTRICTED_PROJECT_FORBIDDEN))+ }+ }+ }+ }+}++/// The choke point: decide `need` for `ctx`. Free-function form of+/// [`ProjectAuthz::authorize`] so call sites read as `authorize_project(...)`.+///+/// # Errors+/// [`AuthzError::Forbidden`] when a restricted project refuses the caller.+pub fn authorize_project(ctx: &ProjectAuthz, need: ProjectAccess) -> Result<(), AuthzError> {+ 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 {+ match conn.query_row(+ "SELECT access_mode FROM projects WHERE id = ?1",+ params![project_id.as_bytes()],+ |row| row.get::<_, Option<String>>(0),+ ) {+ Ok(value) => AccessMode::from_db(value.as_deref()),+ Err(rusqlite::Error::QueryReturnedNoRows) => AccessMode::Open,+ Err(err) => {+ tracing::warn!(+ error = %err,+ "could not read projects.access_mode; degrading project authz to open",+ );+ AccessMode::Open+ }+ }+}++/// Look up a caller's grant on a project. Returns the failure so the caller can+/// decide how to degrade (a restricted project degrades to open when its grants+/// cannot be read).+fn read_grant(+ conn: &Connection,+ workspace_id: WorkspaceId,+ project_id: ProjectId,+ user_id: UserId,+) -> rusqlite::Result<Option<GrantLevel>> {+ let level: Option<String> = conn+ .query_row(+ "SELECT level FROM project_grants \+ WHERE workspace_id = ?1 AND project_id = ?2 AND user_id = ?3",+ params![+ workspace_id.as_bytes(),+ project_id.as_bytes(),+ user_id.as_bytes()+ ],+ |row| row.get(0),+ )+ .optional()?;+ Ok(level.as_deref().and_then(GrantLevel::from_db))+}++/// Resolve the full [`ProjectAuthz`] for a project from a live connection.+///+/// `open` short-circuits without touching `project_grants`. A `restricted`+/// project whose grants cannot be read degrades to `open` with a warning rather+/// than denying every caller (#678).+///+/// # Errors+/// Propagates only failures that are not the grant-read degrade path; the+/// access-mode read itself never errors (it degrades to open).+pub fn resolve_project_authz(+ conn: &Connection,+ workspace_id: WorkspaceId,+ project_id: ProjectId,+ principal: &ProjectPrincipal,+ distinguishes_operators: bool,+) -> StoreResult<ProjectAuthz> {+ let mut access_mode = read_access_mode(conn, project_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) {+ Ok(grant) => grant,+ Err(err) => {+ // The grants table cannot be read: degrade to open rather+ // than lock everyone out of a restricted project (#678).+ tracing::warn!(+ error = %err,+ "could not read project_grants; degrading project authz to open",+ );+ access_mode = AccessMode::Open;+ None+ }+ },+ None => None,+ }+ } else {+ None+ };+ Ok(ProjectAuthz {+ distinguishes_operators,+ access_mode,+ is_root: principal.is_root,+ is_creator: principal.is_creator,+ grant,+ })+}++#[cfg(test)]+mod tests {+ use super::*;++ fn ctx(+ distinguishes_operators: bool,+ access_mode: AccessMode,+ is_root: bool,+ is_creator: bool,+ grant: Option<GrantLevel>,+ ) -> ProjectAuthz {+ ProjectAuthz {+ distinguishes_operators,+ access_mode,+ is_root,+ is_creator,+ grant,+ }+ }++ #[test]+ fn access_mode_round_trips_and_degrades_open() {+ assert_eq!(AccessMode::from_db(Some("open")), AccessMode::Open);+ assert_eq!(+ AccessMode::from_db(Some("restricted")),+ AccessMode::Restricted+ );+ // Anything unexpected degrades to open, never fail closed.+ for weird in [None, Some(""), Some("RESTRICTED"), Some("locked")] {+ assert_eq!(AccessMode::from_db(weird), AccessMode::Open, "{weird:?}");+ }+ assert_eq!(AccessMode::Open.as_str(), "open");+ assert_eq!(AccessMode::Restricted.as_str(), "restricted");+ }++ #[test]+ fn grant_level_parse() {+ assert_eq!(GrantLevel::from_db("read"), Some(GrantLevel::Read));+ assert_eq!(GrantLevel::from_db("write"), Some(GrantLevel::Write));+ assert_eq!(GrantLevel::from_db("admin"), None);+ }++ /// The pure decision table. Every row must flip if the gate were removed or+ /// inverted, so this is the adversarial core the SQL wrapper reuses.+ #[test]+ fn authorize_decision_matrix() {+ use AccessMode::{Open, Restricted};+ use GrantLevel::{Read, Write};+ use ProjectAccess as A;++ // (distinguishes, mode, is_root, is_creator, grant, need, expect_ok)+ let rows = [+ // Single-user / loopback: the gate does not exist.+ (false, Restricted, false, false, None, A::Read, true),+ (false, Restricted, false, false, None, A::Write, true),+ // Open: everyone is admitted, even anonymous.+ (true, Open, false, false, None, A::Read, true),+ (true, Open, false, false, None, A::Write, true),+ // Restricted + root: always admitted.+ (true, Restricted, true, false, None, A::Read, true),+ (true, Restricted, true, false, None, A::Write, true),+ // Restricted + creator, zero grants: still admitted.+ (true, Restricted, false, true, None, A::Read, true),+ (true, Restricted, false, true, None, A::Write, true),+ // Restricted + no grant, non-root, non-creator: denied both ways.+ (true, Restricted, false, false, None, A::Read, false),+ (true, Restricted, false, false, None, A::Write, false),+ // Restricted + read grant: read OK, write denied.+ (true, Restricted, false, false, Some(Read), A::Read, true),+ (true, Restricted, false, false, Some(Read), A::Write, false),+ // Restricted + write grant: both OK.+ (true, Restricted, false, false, Some(Write), A::Read, true),+ (true, Restricted, false, false, Some(Write), A::Write, true),+ ];++ for (distinguishes, mode, root, creator, grant, need, expect_ok) in rows {+ let decision = authorize_project(&ctx(distinguishes, mode, root, creator, grant), need);+ assert_eq!(+ decision.is_ok(),+ expect_ok,+ "row d={distinguishes} mode={mode:?} root={root} creator={creator} \+ grant={grant:?} need={need:?}",+ );+ if !expect_ok {+ assert_eq!(+ decision.unwrap_err(),+ AuthzError::Forbidden(RESTRICTED_PROJECT_FORBIDDEN),+ );+ }+ }+ }+}diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rsindex acb08772..ae21788c 100644--- a/crates/ai-memory-store/src/reader.rs+++ b/crates/ai-memory-store/src/reader.rs@@ -9017,6 +9017,50 @@ impl ReaderPool {self.with_conn(move |conn| crate::maintenance::last_success(conn, job)).await}++ /// Resolve the per-project authorization state (#708) from the read pool.+ ///+ /// An `open` project short-circuits without a grant lookup; a `restricted`+ /// project whose grants cannot be read degrades to `open` (never fail+ /// closed). See [`crate::project_authz`].+ pub async fn resolve_project_authz(+ &self,+ workspace_id: WorkspaceId,+ project_id: ProjectId,+ principal: crate::ProjectPrincipal,+ distinguishes_operators: bool,+ ) -> StoreResult<crate::ProjectAuthz> {+ self.with_conn(move |conn| {+ crate::project_authz::resolve_project_authz(+ conn,+ workspace_id,+ project_id,+ &principal,+ distinguishes_operators,+ )+ })+ .await+ }++ /// The per-project authorization choke point (#708), evaluated on the read+ /// pool: resolve the project's access state and decide `need`.+ ///+ /// Returns `Ok(Ok(()))` when the caller is admitted, `Ok(Err(Forbidden))`+ /// when a restricted project refuses them, and `Err(_)` only on an+ /// infrastructure failure.+ pub async fn authorize_project(+ &self,+ workspace_id: WorkspaceId,+ project_id: ProjectId,+ principal: crate::ProjectPrincipal,+ distinguishes_operators: bool,+ need: crate::ProjectAccess,+ ) -> StoreResult<Result<(), ai_memory_core::AuthzError>> {+ let ctx = self+ .resolve_project_authz(workspace_id, project_id, principal, distinguishes_operators)+ .await?;+ Ok(ctx.authorize(need))+ }}/// Build the bounded history query and its optional owner binding.diff --git a/crates/ai-memory-store/src/scope.rs b/crates/ai-memory-store/src/scope.rsindex 255687de..2e88d2aa 100644--- a/crates/ai-memory-store/src/scope.rs+++ b/crates/ai-memory-store/src/scope.rs@@ -14,6 +14,7 @@ use ai_memory_core::{};use crate::error::StoreError;+use crate::project_authz::{ProjectAccess, ProjectPrincipal};use crate::{ReaderPool, WriterHandle};/// Canonical error for partial explicit scope arguments.@@ -177,6 +178,9 @@ pub enum ScopeResolutionError {AmbiguousUnscopedWrite,/// A write-create policy was requested without a writer handle.WriterRequired,+ /// The per-project authorization choke point (#708) refused the caller a+ /// `restricted` project. Carries the policy message.+ Forbidden(String),/// Underlying store failure.Store(String),}@@ -206,6 +210,13 @@ impl ScopeResolutionError {| ScopeResolutionError::ProjectNotFoundInActiveOrDefault { .. })}++ /// True when the per-project authorization choke point (#708) refused the+ /// caller. Surfaces map this to a 403/permission error.+ #[must_use]+ pub fn is_forbidden(&self) -> bool {+ matches!(self, ScopeResolutionError::Forbidden(_))+ }}impl fmt::Display for ScopeResolutionError {@@ -240,6 +251,7 @@ impl fmt::Display for ScopeResolutionError {ScopeResolutionError::WriterRequired => {f.write_str("scope resolver requires a writer for create-on-write resolution")}+ ScopeResolutionError::Forbidden(msg) => f.write_str(msg),ScopeResolutionError::Store(msg) => f.write_str(msg),}}@@ -261,6 +273,14 @@ pub struct ScopeResolver<'a> {active_project: Option<&'a ActiveProject>,default_workspace_id: WorkspaceId,default_project_id: ProjectId,+ /// Per-project authorization principal (#708). `None` skips the gate+ /// entirely, preserving legacy behaviour for callers that have not opted+ /// in. When set, every resolved read/write scope is run through the+ /// `authorize_project` choke point before it is returned.+ authz: Option<ProjectPrincipal>,+ /// Whether the deployment distinguishes operators; only meaningful when+ /// [`Self::authz`] is set.+ distinguishes_operators: bool,}/// Look up an explicit workspace/project pair without creating anything.@@ -413,6 +433,8 @@ impl<'a> ScopeResolver<'a> {active_project: None,default_workspace_id,default_project_id,+ authz: None,+ distinguishes_operators: false,}}@@ -423,6 +445,64 @@ impl<'a> ScopeResolver<'a> {self}+ /// Opt into the per-project authorization choke point (#708).+ ///+ /// Once attached, every scope this resolver returns is run through+ /// `authorize_project`: reads through the read pool, writes through the+ /// writer actor (defense in depth) when a writer is attached. In slice 2+ /// every project is `open`, so this is a behaviour-preserving pass-through.+ #[must_use]+ pub fn with_project_authz(+ mut self,+ principal: ProjectPrincipal,+ distinguishes_operators: bool,+ ) -> Self {+ self.authz = Some(principal);+ self.distinguishes_operators = distinguishes_operators;+ self+ }++ /// Run the resolved scope through the authorization choke point (#708).+ ///+ /// A no-op when no principal is attached. A read is decided on the read+ /// pool; a write is decided on the writer actor's own connection when a+ /// writer is attached, so the check cannot race a concurrent grant change+ /// against the write it guards.+ async fn authorize_scope(+ &self,+ scope: ResolvedScope,+ need: ProjectAccess,+ ) -> Result<(), ScopeResolutionError> {+ 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()))+ }+/// Attach the active-project map used for current-project defaults.#[must_use]pub fn with_active_project(mut self, active_project: &'a ActiveProject) -> Self {@@ -465,10 +545,11 @@ impl<'a> ScopeResolver<'a> {trimmed_opt(explicit_workspace),trimmed_opt(explicit_project),) {- (Some(workspace), Some(project)) => self- .lookup_existing(workspace, project)- .await- .map(|scope| (scope, ScopeSource::Explicit)),+ (Some(workspace), Some(project)) => {+ let scope = self.lookup_existing(workspace, project).await?;+ self.authorize_scope(scope, ProjectAccess::Read).await?;+ Ok((scope, ScopeSource::Explicit))+ }(Some(_), None) => Err(ScopeResolutionError::WorkspaceProjectPairRequired),(None, project) => self.resolve_current_or_project_traced(project, actor).await,}@@ -519,6 +600,7 @@ impl<'a> ScopeResolver<'a> {workspace_id: active_ws,project_id,};+ self.authorize_scope(scope, ProjectAccess::Read).await?;return Ok((scope, ScopeSource::Explicit));}if active.map(|(ws, _)| ws) != Some(self.default_workspace_id)@@ -531,6 +613,7 @@ impl<'a> ScopeResolver<'a> {workspace_id: self.default_workspace_id,project_id,};+ self.authorize_scope(scope, ProjectAccess::Read).await?;return Ok((scope, ScopeSource::Explicit));}return Err(ScopeResolutionError::ProjectNotFoundInActiveOrDefault {@@ -543,6 +626,7 @@ impl<'a> ScopeResolver<'a> {workspace_id,project_id,};+ self.authorize_scope(scope, ProjectAccess::Read).await?;Ok((scope, source))}@@ -575,10 +659,12 @@ impl<'a> ScopeResolver<'a> {(self.default_workspace_id, self.default_project_id)}};- return Ok(ResolvedScope {+ let scope = ResolvedScope {workspace_id,project_id,- });+ };+ self.authorize_scope(scope, ProjectAccess::Write).await?;+ return Ok(scope);};let Some(writer) = self.writer else {return Err(ScopeResolutionError::WriterRequired);@@ -593,10 +679,12 @@ impl<'a> ScopeResolver<'a> {let project_id = writer.get_or_create_project(workspace_id, project.to_owned(), None).await?;- Ok(ResolvedScope {+ let scope = ResolvedScope {workspace_id,project_id,- })+ };+ self.authorize_scope(scope, ProjectAccess::Write).await?;+ Ok(scope)}/// Resolve and de-duplicate an explicit multi-scope list.diff --git a/crates/ai-memory-store/src/writer.rs b/crates/ai-memory-store/src/writer.rsindex 4289f3bf..b0d30191 100644--- a/crates/ai-memory-store/src/writer.rs+++ b/crates/ai-memory-store/src/writer.rs@@ -654,6 +654,14 @@ pub(crate) enum WriteCmd {input: RenameWorkstream,reply: oneshot::Sender<StoreResult<RenamedWorkstream>>,},+ AuthorizeProject {+ workspace_id: WorkspaceId,+ project_id: ProjectId,+ principal: crate::ProjectPrincipal,+ distinguishes_operators: bool,+ need: crate::ProjectAccess,+ reply: oneshot::Sender<StoreResult<Result<(), ai_memory_core::AuthzError>>>,+ },Shutdown,}@@ -703,6 +711,41 @@ impl WriterHandle {rx.await.map_err(|_| StoreError::WriterClosed)?}+ /// The per-project authorization choke point (#708), evaluated on the+ /// **writer** connection as defense in depth for writes: a write decision+ /// is made against the same connection that will perform the write, so it+ /// cannot race a concurrent grant/access-mode change between a read-pool+ /// check and the write.+ ///+ /// Returns `Ok(Ok(()))` when admitted, `Ok(Err(Forbidden))` when a+ /// restricted project refuses the caller, and `Err(_)` only on an+ /// infrastructure failure. In slice 2 every project is `open`, so this is a+ /// pass-through.+ ///+ /// # Errors+ /// Returns [`StoreError::WriterClosed`] if the actor has shut down, or+ /// propagates the SQL error from the authz resolver.+ pub async fn authorize_project(+ &self,+ workspace_id: WorkspaceId,+ project_id: ProjectId,+ principal: crate::ProjectPrincipal,+ distinguishes_operators: bool,+ need: crate::ProjectAccess,+ ) -> StoreResult<Result<(), ai_memory_core::AuthzError>> {+ let (tx, rx) = oneshot::channel();+ self.send(WriteCmd::AuthorizeProject {+ workspace_id,+ project_id,+ principal,+ distinguishes_operators,+ need,+ reply: tx,+ })+ .await?;+ rx.await.map_err(|_| StoreError::WriterClosed)?+ }+/// Resolve a project by `(workspace_id, name)`, creating it atomically/// if missing.///@@ -2705,6 +2748,24 @@ fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {while let Some(cmd) = rx.blocking_recv() {match cmd {WriteCmd::Shutdown => break,+ WriteCmd::AuthorizeProject {+ workspace_id,+ project_id,+ principal,+ distinguishes_operators,+ need,+ reply,+ } => {+ let result = crate::project_authz::resolve_project_authz(+ &conn,+ workspace_id,+ project_id,+ &principal,+ distinguishes_operators,+ )+ .map(|ctx| ctx.authorize(need));+ send_or_warn(reply, result, "authorize_project");+ }WriteCmd::GetOrCreateWorkspace { name, reply } => {let result = ops::get_or_create_workspace(&mut conn, &name);send_or_warn(reply, result, "get_or_create_workspace");diff --git a/crates/ai-memory-store/tests/suite/mod.rs b/crates/ai-memory-store/tests/suite/mod.rsindex f2529030..e4a1745b 100644--- a/crates/ai-memory-store/tests/suite/mod.rs+++ b/crates/ai-memory-store/tests/suite/mod.rs@@ -14,6 +14,7 @@ mod handoff_ownership;mod most_recently_active_scope;mod multi_session;mod pinned_pages;+mod project_authz;mod related_walk;mod retrieval_superseded;mod retrieval_tuning_streams;diff --git a/crates/ai-memory-store/tests/suite/project_authz.rs b/crates/ai-memory-store/tests/suite/project_authz.rsnew file mode 100644index 00000000..b0bc1ec6--- /dev/null+++ b/crates/ai-memory-store/tests/suite/project_authz.rs@@ -0,0 +1,509 @@+//! Adversarial integration tests for the per-project authorization choke+//! point (#708, slice 2).+//!+//! These prove the gate BITES: with the guard removed or inverted every+//! restricted-project row here would flip. They deliberately live at+//! integration level (invariant #16) — a single-tenant happy path cannot see+//! an authorization defect. The gate is an allow/deny check for ENTRY to a+//! project; it is never an `OwnerFilter` on page rows, so nothing here filters+//! page reads by user.+//!+//! Slice 2 ships inert: every project defaults to `open`, so the gate is a+//! pass-through until an operator opts a project into `restricted`. The tests+//! set `access_mode='restricted'` and insert `project_grants` rows directly via+//! SQL to exercise the enforcing branch the management surface (slice 3) will+//! drive.++use ai_memory_core::{ActorKey, AuthzError, NewUser, ProjectId, UserId, UserRole, WorkspaceId};+use ai_memory_store::{+ AccessMode, GrantLevel, ProjectAccess, ProjectAuthz, ProjectPrincipal, ScopeResolver, Store,+ authorize_project,+};+use rusqlite::{Connection, params};++const GRANTED_AT: i64 = 1_700_000_000_000_000;++async fn make_user(store: &Store, username: &str) -> UserId {+ store+ .writer+ .create_human_user(+ NewUser {+ username: username.to_string(),+ name: None,+ email: None,+ },+ UserRole::User,+ None,+ false,+ )+ .await+ .unwrap()+}++/// Flip a project's access mode via raw SQL — stands in for the slice-3+/// management surface.+fn set_access_mode(store: &Store, project_id: ProjectId, mode: &str) {+ let conn = Connection::open(store.db_path()).unwrap();+ let updated = conn+ .execute(+ "UPDATE projects SET access_mode = ?1 WHERE id = ?2",+ params![mode, project_id.as_bytes()],+ )+ .unwrap();+ assert_eq!(updated, 1, "expected to update exactly one project row");+}++/// Insert a grant row via raw SQL.+fn insert_grant(+ store: &Store,+ workspace_id: WorkspaceId,+ project_id: ProjectId,+ user_id: UserId,+ level: &str,+) {+ let conn = Connection::open(store.db_path()).unwrap();+ conn.execute(+ "INSERT INTO project_grants \+ (workspace_id, project_id, user_id, level, granted_by, granted_at) \+ VALUES (?1, ?2, ?3, ?4, NULL, ?5)",+ params![+ workspace_id.as_bytes(),+ project_id.as_bytes(),+ user_id.as_bytes(),+ level,+ GRANTED_AT+ ],+ )+ .unwrap();+}++async fn scope(store: &Store, ws_name: &str, proj_name: &str) -> (WorkspaceId, ProjectId) {+ let ws = store+ .writer+ .get_or_create_workspace(ws_name.to_string())+ .await+ .unwrap();+ let proj = store+ .writer+ .get_or_create_project(ws, proj_name.to_string(), None)+ .await+ .unwrap();+ (ws, proj)+}++/// (a) AUTHZ MATRIX — root / granted-read / granted-write / no-grant /+/// anonymous × {open, restricted}, resolved from real SQL through both the+/// reader-pool and writer-actor entry points. Every restricted row flips if the+/// gate is removed; the legitimate controls (root, creator, matching grant) are+/// admitted.+#[tokio::test]+async fn authz_matrix_reader_and_writer_paths() {+ let tmp = tempfile::tempdir().unwrap();+ let store = Store::open(tmp.path()).unwrap();++ let (ws, restricted) = scope(&store, "acme", "restricted").await;+ let (_, open) = scope(&store, "acme", "open").await;++ let reader = make_user(&store, "reader-user").await;+ let writer = make_user(&store, "writer-user").await;+ let nogrant = make_user(&store, "no-grant-user").await;++ set_access_mode(&store, restricted, "restricted");+ insert_grant(&store, ws, restricted, reader, "read");+ insert_grant(&store, ws, restricted, writer, "write");++ let root = ProjectPrincipal::root();+ let creator = ProjectPrincipal {+ is_root: false,+ is_creator: true,+ user_id: None,+ };+ let read_grantee = ProjectPrincipal {+ is_root: false,+ is_creator: false,+ user_id: Some(reader),+ };+ let write_grantee = ProjectPrincipal {+ is_root: false,+ is_creator: false,+ user_id: Some(writer),+ };+ let no_grant = ProjectPrincipal {+ is_root: false,+ is_creator: false,+ user_id: Some(nogrant),+ };+ let anon = ProjectPrincipal::anonymous();++ // (principal, need, target_project, expect_ok)+ use ProjectAccess::{Read, Write};+ let cases: Vec<(&str, ProjectPrincipal, ProjectAccess, ProjectId, bool)> = vec![+ // Restricted project.+ (+ "root reads restricted",+ root.clone(),+ Read,+ restricted,+ true,+ ),+ (+ "root writes restricted",+ root.clone(),+ Write,+ restricted,+ true,+ ),+ (+ "creator reads restricted",+ creator.clone(),+ Read,+ restricted,+ true,+ ),+ (+ "creator writes restricted",+ creator.clone(),+ Write,+ restricted,+ true,+ ),+ (+ "read-grant reads restricted",+ read_grantee.clone(),+ Read,+ restricted,+ true,+ ),+ (+ "read-grant CANNOT write restricted",+ read_grantee.clone(),+ Write,+ restricted,+ false,+ ),+ (+ "write-grant reads restricted",+ write_grantee.clone(),+ Read,+ restricted,+ true,+ ),+ (+ "write-grant writes restricted",+ write_grantee.clone(),+ Write,+ restricted,+ true,+ ),+ (+ "no-grant CANNOT read restricted",+ no_grant.clone(),+ Read,+ restricted,+ false,+ ),+ (+ "no-grant CANNOT write restricted",+ no_grant.clone(),+ Write,+ restricted,+ false,+ ),+ (+ "anonymous CANNOT read restricted",+ anon.clone(),+ Read,+ restricted,+ false,+ ),+ (+ "anonymous CANNOT write restricted",+ anon.clone(),+ Write,+ restricted,+ false,+ ),+ // Open project — everyone, including anonymous, is admitted.+ ("anonymous reads open", anon.clone(), Read, open, true),+ ("anonymous writes open", anon.clone(), Write, open, true),+ ("no-grant reads open", no_grant.clone(), Read, open, true),+ ("no-grant writes open", no_grant.clone(), Write, open, true),+ ];++ for (name, principal, need, project, expect_ok) in cases {+ // Reader-pool entry point.+ let via_reader = store+ .reader+ .authorize_project(ws, project, principal.clone(), true, need)+ .await+ .unwrap();+ assert_eq!(via_reader.is_ok(), expect_ok, "reader: {name}");++ // Writer-actor entry point (defense in depth) — same decision.+ let via_writer = store+ .writer+ .authorize_project(ws, project, principal.clone(), true, need)+ .await+ .unwrap();+ assert_eq!(via_writer.is_ok(), expect_ok, "writer: {name}");++ if !expect_ok {+ assert!(+ matches!(via_reader, Err(AuthzError::Forbidden(_))),+ "{name} must be Forbidden, not some other outcome",+ );+ }+ }+}++/// (b) SHIP-INERT — an empty grants table with the default `open` mode admits+/// everyone; a `restricted` project with ZERO grants still admits root and the+/// creator (never locked out of your own data).+#[tokio::test]+async fn ship_inert_open_admits_all_and_restricted_admits_root_and_creator() {+ let tmp = tempfile::tempdir().unwrap();+ let store = Store::open(tmp.path()).unwrap();++ let (ws, open) = scope(&store, "team", "open").await;+ let (_, restricted) = scope(&store, "team", "locked").await;+ set_access_mode(&store, restricted, "restricted");++ // Empty grants + default open: anonymous is admitted for read and write.+ for need in [ProjectAccess::Read, ProjectAccess::Write] {+ let decision = store+ .reader+ .authorize_project(ws, open, ProjectPrincipal::anonymous(), true, need)+ .await+ .unwrap();+ assert!(decision.is_ok(), "open project admits everyone: {need:?}");+ }++ // Restricted + zero grants: root and creator still admitted.+ let creator = ProjectPrincipal {+ is_root: false,+ is_creator: true,+ user_id: None,+ };+ for principal in [ProjectPrincipal::root(), creator] {+ for need in [ProjectAccess::Read, ProjectAccess::Write] {+ let decision = store+ .reader+ .authorize_project(ws, restricted, principal.clone(), true, need)+ .await+ .unwrap();+ assert!(+ decision.is_ok(),+ "restricted-with-zero-grants must admit root/creator: {principal:?} {need:?}",+ );+ }+ }++ // The control that proves the restriction is real: a bare authenticated+ // user with no grant is refused the same restricted project.+ let stranger = make_user(&store, "stranger").await;+ let decision = store+ .reader+ .authorize_project(+ ws,+ restricted,+ ProjectPrincipal {+ is_root: false,+ is_creator: false,+ user_id: Some(stranger),+ },+ true,+ ProjectAccess::Read,+ )+ .await+ .unwrap();+ assert!(+ decision.is_err(),+ "a restricted project with zero grants must still refuse an ungranted stranger",+ );+}++/// (d) distinguishes_operators() == false skips the gate entirely: even a+/// restricted project with no grant admits an anonymous caller, because a+/// single-user / loopback deployment has no notion of "another operator".+#[tokio::test]+async fn gate_is_skipped_when_operators_are_not_distinguished() {+ let tmp = tempfile::tempdir().unwrap();+ let store = Store::open(tmp.path()).unwrap();++ let (ws, restricted) = scope(&store, "solo", "locked").await;+ set_access_mode(&store, restricted, "restricted");++ for need in [ProjectAccess::Read, ProjectAccess::Write] {+ // distinguishes_operators = false -> allow.+ let skipped = store+ .reader+ .authorize_project(ws, restricted, ProjectPrincipal::anonymous(), false, need)+ .await+ .unwrap();+ assert!(skipped.is_ok(), "single-user mode skips the gate: {need:?}");++ // The control: with distinguishing ON, the same call is refused, so the+ // pass above is the skip, not an always-allow bug.+ let enforced = store+ .reader+ .authorize_project(ws, restricted, ProjectPrincipal::anonymous(), true, need)+ .await+ .unwrap();+ assert!(+ enforced.is_err(),+ "multi-user mode enforces the gate: {need:?}"+ );+ }+}++/// (c) MIGRATION IDEMPOTENCY — V67 applies cleanly (the table exists, the column+/// defaults to 'open'), the CHECK constraints bite, and re-opening the store+/// (which re-runs the migration set) is a no-op that preserves the data.+#[tokio::test]+async fn migration_applies_defaults_open_and_reopen_is_a_noop() {+ let tmp = tempfile::tempdir().unwrap();+ let project_id;+ {+ let store = Store::open(tmp.path()).unwrap();+ let (_, proj) = scope(&store, "acme", "app").await;+ project_id = proj;++ let conn = Connection::open(store.db_path()).unwrap();++ // Additive: an existing project defaults to 'open'.+ let mode: String = conn+ .query_row(+ "SELECT access_mode FROM projects WHERE id = ?1",+ params![proj.as_bytes()],+ |row| row.get(0),+ )+ .unwrap();+ assert_eq!(mode, "open");++ // The grants table exists and starts empty.+ let grant_count: i64 = conn+ .query_row("SELECT COUNT(*) FROM project_grants", [], |row| row.get(0))+ .unwrap();+ assert_eq!(grant_count, 0);++ // CHECK constraints bite.+ assert!(+ conn.execute(+ "UPDATE projects SET access_mode = 'bogus' WHERE id = ?1",+ params![proj.as_bytes()],+ )+ .is_err(),+ "access_mode CHECK must reject an unknown mode",+ );+ assert!(+ conn.execute(+ "INSERT INTO project_grants \+ (workspace_id, project_id, user_id, level, granted_by, granted_at) \+ VALUES (randomblob(16), ?1, randomblob(16), 'admin', NULL, ?2)",+ params![proj.as_bytes(), GRANTED_AT],+ )+ .is_err(),+ "level CHECK must reject a level other than read/write",+ );+ }++ // Re-open the same data dir: migrations re-run and must be a no-op.+ let store = Store::open(tmp.path()).unwrap();+ let conn = Connection::open(store.db_path()).unwrap();+ let mode: String = conn+ .query_row(+ "SELECT access_mode FROM projects WHERE id = ?1",+ params![project_id.as_bytes()],+ |row| row.get(0),+ )+ .unwrap();+ assert_eq!(+ mode, "open",+ "re-open must preserve the applied schema + data"+ );+}++/// The choke point is genuinely wired into `ScopeResolver` read + write+/// resolution: a restricted project is refused there, an ungated resolver still+/// admits it (proving the gate — not something else — is what bites), and root+/// is admitted through the same wiring.+#[tokio::test]+async fn scope_resolver_gates_restricted_projects() {+ let tmp = tempfile::tempdir().unwrap();+ let store = Store::open(tmp.path()).unwrap();++ let (ws, restricted) = scope(&store, "acme", "restricted").await;+ let (default_ws, default_proj) = scope(&store, "acme", "fallback").await;+ set_access_mode(&store, restricted, "restricted");++ let actor = ActorKey::default();++ // With the authz principal attached, an anonymous caller is Forbidden the+ // restricted project on both the read and write paths.+ let gated_read = ScopeResolver::new(&store.reader, default_ws, default_proj)+ .with_project_authz(ProjectPrincipal::anonymous(), true)+ .resolve_read_args(Some("acme"), Some("restricted"), &actor)+ .await+ .unwrap_err();+ assert!(gated_read.is_forbidden(), "read: {gated_read:?}");++ let gated_write = ScopeResolver::new(&store.reader, default_ws, default_proj)+ .with_writer(&store.writer)+ .with_project_authz(ProjectPrincipal::anonymous(), true)+ .resolve_write_args(Some("acme"), Some("restricted"), &actor)+ .await+ .unwrap_err();+ assert!(gated_write.is_forbidden(), "write: {gated_write:?}");++ // Proof it bites: the SAME resolution WITHOUT the authz principal admits the+ // restricted project (today's behaviour — the gate is opt-in and inert).+ let ungated = ScopeResolver::new(&store.reader, default_ws, default_proj)+ .resolve_read_args(Some("acme"), Some("restricted"), &actor)+ .await+ .unwrap();+ assert_eq!(ungated.as_tuple(), (ws, restricted));++ // The legitimate control: root is admitted through the same wiring.+ let root_ok = ScopeResolver::new(&store.reader, default_ws, default_proj)+ .with_project_authz(ProjectPrincipal::root(), true)+ .resolve_read_args(Some("acme"), Some("restricted"), &actor)+ .await+ .unwrap();+ assert_eq!(root_ok.as_tuple(), (ws, restricted));++ // And an open project is unaffected: the gate admits everyone.+ let open_ok = ScopeResolver::new(&store.reader, default_ws, default_proj)+ .with_project_authz(ProjectPrincipal::anonymous(), true)+ .resolve_read_args(Some("acme"), Some("fallback"), &actor)+ .await+ .unwrap();+ assert_eq!(open_ok.as_tuple(), (default_ws, default_proj));+}++/// The pure decision function reused as documentation of intent: a resolved+/// restricted context with no grant denies, a write grant admits both.+#[tokio::test]+async fn pure_authorize_project_reference() {+ let deny = ProjectAuthz {+ distinguishes_operators: true,+ access_mode: AccessMode::Restricted,+ is_root: false,+ is_creator: false,+ grant: None,+ };+ assert!(authorize_project(&deny, ProjectAccess::Read).is_err());++ let write_grant = ProjectAuthz {+ grant: Some(GrantLevel::Write),+ ..deny+ };+ assert!(authorize_project(&write_grant, ProjectAccess::Read).is_ok());+ assert!(authorize_project(&write_grant, ProjectAccess::Write).is_ok());++ let read_grant = ProjectAuthz {+ grant: Some(GrantLevel::Read),+ ..deny+ };+ assert!(authorize_project(&read_grant, ProjectAccess::Read).is_ok());+ assert!(authorize_project(&read_grant, ProjectAccess::Write).is_err());+}diff --git a/docs/design-per-project-authz.md b/docs/design-per-project-authz.mdindex d5acc6b9..cabd371f 100644--- a/docs/design-per-project-authz.md+++ b/docs/design-per-project-authz.md@@ -1,8 +1,20 @@# Design proposal: per-project authorization for multi-user servers (#708)-**Status: proposal for review — not implemented.** This is the design pass promised-on #708 before any code lands. It changes a security boundary, so it is deliberately-separated from implementation.+**Implementation status.** Slice 2 has landed: the inert V67 schema+(`project_grants` + `projects.access_mode`, default `open`) and the+`authorize_project` choke point (`ai-memory-store/src/project_authz.rs`),+wired into `ScopeResolver` read/write resolution and the writer actor. It is+always-allow (no project is `restricted` yet), so there is no behaviour change.+**Slice 3 is pending** and is what makes `restricted` safe end-to-end: closing+the two bypass classes below (unscoped/global reads filtered before `LIMIT`;+raw-id entry points resolving through `authorize_project`), the root-only+management surface (setting `restricted`, issuing grants), and a+`projects.created_by` source for the creator check. Sections below are the+original design pass, retained as the spec.++**Original status: proposal for review — not implemented.** This was the design+pass promised on #708 before any code lands. It changes a security boundary, so+it is deliberately separated from implementation.## Problemdiff --git a/docs/security-boundaries.md b/docs/security-boundaries.mdindex b838ec4e..3fbca745 100644--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@ -45,7 +45,7 @@ boundary not yet built.| 11b | Capture exclusions drop before storage | `ai-memory-hooks` `capture_policy.rs` `inspect`→`Drop` (before semaphore/spawn) | `capture_policy.rs` per-agent `…honors_exclusions` tests | STRONG || 11c | Capture hook ≤200ms budget (invariant #5) | `hooks/_lib.sh` capture path `curl --max-time 0.2` (context-fetch 1.0s and background drain 2.0s are separate, larger-budget paths) | none (shell-script timeout; hard to unit-test) — watch on any capture-path change | WATCH || 12 | Network/auth posture | `config.rs` loopback `DEFAULT_BIND`; `serve.rs` `validate_http_exposure`, `require_allowed_host`; `auth.rs` `require_bearer` | `serve.rs` host-guard (missing→400 / forged→403), non-loopback-requires-token; `auth.rs` wrong-token 401 | STRONG |-| — | Per-project authorization (#708) | proposal only — `docs/design-per-project-authz.md` (`authorize_project` choke point + unscoped-read/raw-id bypass classes) | none yet — the design's "Verification plan" tests (authz matrix, unscoped-read-leak, raw-id-authz, ship-inert) land WITH the code | FUTURE |+| 13 | Per-project authorization (#708) | `ai-memory-store/src/project_authz.rs` `authorize_project` / `ProjectAuthz::authorize` choke point (inert V67 schema: `project_grants` + `projects.access_mode`, default `open`); consulted by `scope.rs` `ScopeResolver` read+write resolution (opt-in `with_project_authz`, reader-pool for reads, writer-actor for writes) and by `WriterHandle::authorize_project` as defense in depth | `tests/suite/project_authz.rs` — `authz_matrix_reader_and_writer_paths`, `ship_inert_open_admits_all_and_restricted_admits_root_and_creator`, `gate_is_skipped_when_operators_are_not_distinguished`, `scope_resolver_gates_restricted_projects`, `migration_applies_defaults_open_and_reopen_is_a_noop`, `authorize_decision_matrix` (each proven to fail with the gate neutralized) | PARTIAL — slice 2: choke point + inert schema exist and are always-allow (no project is `restricted` yet). `restricted` is **not safe end-to-end** until slice 3 closes the two bypass classes (unscoped/global reads must filter by readable projects **before** `LIMIT`; raw-id entry points — session/run/page id, `page_evidence_counts` — must resolve→`authorize_project`) and adds the root-only management surface that sets `restricted` and issues grants (creator resolution + a `projects.created_by` source land there too) |## Keeping this current (the standing protocol)