Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(api): P1.7 surface attribution on /api/v1 + ETag invalidation
AkitaOnRails34d238065656
diff --git a/crates/ai-memory-store/src/lib.rs b/crates/ai-memory-store/src/lib.rsindex dc60829d..a2905ae4 100644--- a/crates/ai-memory-store/src/lib.rs+++ b/crates/ai-memory-store/src/lib.rs@@ -28,9 +28,9 @@ pub use error::{StoreError, StoreResult};pub use ops::{EmbeddingWrite, PurgeSummary, ReorgSummary};pub use reader::{ActivityWindow, BriefingPage, BriefingSnapshot, DecayCandidate, DerivedIndexStatus,- EmbeddingTripleCount, HealthDetail, HealthPage, ObservationHit, PageHit, PageHitWithMeta,- PageLinks, PageMeta, PageSummary, ProjectSummary, ReaderPool, RelatedPage, StatusCounts,- StoredEmbedding, WorkspaceSummary, f32_vec_to_bytes,+ EmbeddingTripleCount, HealthDetail, HealthPage, ObservationHit, PageAuthor, PageHit,+ PageHitWithMeta, PageLinks, PageMeta, PageSummary, ProjectSummary, ReaderPool, RelatedPage,+ StatusCounts, StoredEmbedding, WorkspaceSummary, f32_vec_to_bytes,};pub use users::{TOKEN_HASH_LEN, TOKEN_RAW_LEN, TokenPepper, generate_token, hash_token};pub use writer::WriterHandle;diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rsindex fd1b1c97..3025d756 100644--- a/crates/ai-memory-store/src/reader.rs+++ b/crates/ai-memory-store/src/reader.rs@@ -243,6 +243,27 @@ pub struct PageSummary {pub updated_at: String,}+/// Page author surfaced alongside read responses (P1.7).+/// JOINed from the `users` table when `pages.author_id IS NOT NULL`;+/// `None` for anonymous + root writes (where attribution lives only in+/// the on-disk frontmatter `last_modified_by` block from P1.6).+///+/// Repeated here rather than reused from `ai_memory_core::User` because+/// the response shape intentionally omits internal fields (id,+/// created_at, last_seen_at, token_expired_at) — only the human-facing+/// identity is part of the API contract.+#[derive(Debug, Clone, Serialize)]+pub struct PageAuthor {+ /// Stable username (the attribution key recorded on writes).+ pub username: String,+ /// Optional display name (`Alice Smith`).+ #[serde(skip_serializing_if = "Option::is_none")]+ pub name: Option<String>,+ /// Optional email surfaced alongside the username in UIs.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub email: Option<String>,+}+/// Full page metadata for the page-view template./// Returned by [`ReaderPool::page_meta`].#[derive(Debug, Clone, Serialize)]@@ -271,6 +292,11 @@ pub struct PageMeta {pub updated_at: String,/// Path of the page this one supersedes, if any.pub supersedes: Option<String>,+ /// Multi-user attribution (P1.7). `None` for pre-multi-user pages+ /// and for root / anonymous writes (where `pages.author_id IS+ /// NULL`); `Some` when JOIN resolves a `users` row.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub author: Option<PageAuthor>,}/// One resolved cross-project edge (a link whose endpoints live in@@ -2070,11 +2096,13 @@ impl ReaderPool {END \), \pg.tier, pg.pinned, pg.created_at, pg.updated_at, \- sp.path AS supersedes_path \+ sp.path AS supersedes_path, \+ au.username, au.name, au.email \FROM pages pg \JOIN projects p ON p.id = pg.project_id \JOIN workspaces w ON w.id = pg.workspace_id \LEFT JOIN pages sp ON sp.id = pg.supersedes \+ LEFT JOIN users au ON au.id = pg.author_id \WHERE pg.id = ?1 AND pg.is_latest = 1",params![page_id.as_bytes()],page_meta_from_row,@@ -2109,13 +2137,15 @@ impl ReaderPool {END \), \pg.tier, pg.pinned, pg.created_at, pg.updated_at, \- sp.path AS supersedes_path \+ sp.path AS supersedes_path, \+ au.username, au.name, au.email \FROM pages pg \JOIN projects p ON p.id = pg.project_id \JOIN workspaces w ON w.id = pg.workspace_id \LEFT JOIN pages sp ON sp.id = pg.supersedes \- WHERE pg.path = ?1 AND pg.is_latest = 1 \- LIMIT 1",+ LEFT JOIN users au ON au.id = pg.author_id \+ WHERE pg.path = ?1 AND pg.is_latest = 1 \+ LIMIT 1",params![path],page_meta_from_row,)@@ -2525,12 +2555,14 @@ impl ReaderPool {END \), \pg.tier, pg.pinned, pg.created_at, pg.updated_at, \- sp.path AS supersedes_path \+ sp.path AS supersedes_path, \+ au.username, au.name, au.email \FROM pages pg \JOIN projects p ON p.id = pg.project_id \JOIN workspaces w ON w.id = pg.workspace_id \- LEFT JOIN pages sp ON sp.id = pg.supersedes \- WHERE w.name = ?1 AND p.name = ?2 AND pg.path = ?3 AND pg.is_latest = 1",+ LEFT JOIN pages sp ON sp.id = pg.supersedes \+ LEFT JOIN users au ON au.id = pg.author_id \+ WHERE w.name = ?1 AND p.name = ?2 AND pg.path = ?3 AND pg.is_latest = 1",params![workspace, project, page_path],page_meta_from_row,)@@ -2824,6 +2856,17 @@ fn page_meta_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<StoreResult<Plet created_us: i64 = row.get(9)?;let updated_us: i64 = row.get(10)?;let supersedes: Option<String> = row.get(11)?;+ // P1.7: author columns LEFT JOIN'd from `users`. NULL when the+ // page was written anonymously / by root, or when the user row+ // has been hard-deleted (FK `ON DELETE SET NULL`).+ let author_username: Option<String> = row.get(12)?;+ let author_name: Option<String> = row.get(13)?;+ let author_email: Option<String> = row.get(14)?;+ let author = author_username.map(|username| PageAuthor {+ username,+ name: author_name,+ email: author_email,+ });let workspace_id = WorkspaceId::from_slice(&ws_id_bytes).map_err(|_| rusqlite::Error::IntegralValueOutOfRange(2, 0))?;@@ -2850,6 +2893,7 @@ fn page_meta_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<StoreResult<Pcreated_at,updated_at,supersedes,+ author,}))}diff --git a/crates/ai-memory-web/src/routes/api.rs b/crates/ai-memory-web/src/routes/api.rsindex 47eb3da4..63543812 100644--- a/crates/ai-memory-web/src/routes/api.rs+++ b/crates/ai-memory-web/src/routes/api.rs@@ -70,16 +70,6 @@ fn with_cache(resp: Response, max_age: u32) -> Response {resp}-/// Lowercase hex encoding of a SHA-256 digest.-fn sha256_hex(data: &[u8]) -> String {- let digest = Sha256::digest(data);- digest.iter().fold(String::with_capacity(64), |mut s, b| {- use std::fmt::Write as _;- let _ = write!(s, "{b:02x}");- s- })-}-async fn workspaces_handler(State(state): State<Arc<WebState>>) -> Result<Response, Response> {let workspaces = state.reader@@ -168,9 +158,31 @@ async fn page_handler(.read_page(meta.workspace_id, meta.project_id, &page_path).map_err(|_| not_found("page file not found"))?;- // ETag is computed over the markdown body bytes so a client can skip- // the JSON serialisation round-trip when content hasn't changed.- let etag_value = format!("\"{}\"", sha256_hex(markdown.body.as_bytes()));+ // ETag is computed over the markdown body PLUS the resolved author+ // identity (P1.7). Author change without body change (e.g. operator+ // rotates a token then user A re-writes a previously-anonymous page)+ // must invalidate the cached response. SHA-256 over a stable+ // concatenation: body || "\n--\n" || username || "\n" || email.+ // The "\n--\n" separator prevents `body=foo, user=bar` from hashing+ // the same as `body=foobar, user=` if either ever happened to slide+ // empty.+ let mut hasher = Sha256::new();+ hasher.update(markdown.body.as_bytes());+ if let Some(author) = meta.author.as_ref() {+ hasher.update(b"\n--\n");+ hasher.update(author.username.as_bytes());+ hasher.update(b"\n");+ if let Some(email) = author.email.as_deref() {+ hasher.update(email.as_bytes());+ }+ }+ let digest = hasher.finalize();+ let etag_hex = digest.iter().fold(String::with_capacity(64), |mut s, b| {+ use std::fmt::Write as _;+ let _ = write!(s, "{b:02x}");+ s+ });+ let etag_value = format!("\"{etag_hex}\"");let etag_header = HeaderValue::from_str(&etag_value).expect("sha256 hex is always valid ASCII");// If-None-Match: if the client sends back the exact ETag we issued,@@ -213,6 +225,7 @@ async fn page_handler(title: meta.title,updated_at: meta.updated_at,workspace: meta.workspace_name,+ author: meta.author,}).into_response(),PAGE_CACHE_MAX_AGE,@@ -731,6 +744,13 @@ struct ApiPage {links: Vec<RelatedPage>,/// Latest pages that reference this page (incoming back-links).backlinks: Vec<RelatedPage>,+ /// Multi-user attribution (P1.7). `None` for pre-multi-user pages+ /// and root / anonymous writes; `Some` when JOIN against the+ /// `users` table resolved a row at read time. Omitted from the+ /// serialised payload when `None` so the response shape stays+ /// backward-compatible with consumers that pre-date v0.8.+ #[serde(skip_serializing_if = "Option::is_none")]+ author: Option<ai_memory_store::PageAuthor>,}#[derive(Debug, Serialize)]diff --git a/crates/ai-memory-web/tests/routes.rs b/crates/ai-memory-web/tests/routes.rsindex 4f5c0aba..bd734284 100644--- a/crates/ai-memory-web/tests/routes.rs+++ b/crates/ai-memory-web/tests/routes.rs@@ -1695,3 +1695,199 @@ async fn api_error_responses_do_not_set_cache_control() {"error responses must not carry a Cache-Control header");}++// ── P1.7: /api/v1 page response surfaces author + ETag invalidation ──++#[tokio::test]+async fn api_v1_page_omits_author_for_anonymous_writes() {+ // Backward-compat gate: writes built with the default anonymous+ // ActorContext (every pre-multi-user caller) MUST leave the+ // serialised ApiPage shape identical to v0.7.x — `author` is+ // omitted, not serialised as `null`. Catches a regression where+ // someone forgets the `skip_serializing_if` annotation.+ let (_tmp, store, wiki) = setup().await;+ let ws = store+ .writer+ .get_or_create_workspace("default")+ .await+ .unwrap();+ let proj = store+ .writer+ .get_or_create_project(ws, "scratch", None)+ .await+ .unwrap();+ wiki.write_page(wiki_req(ws, proj, "notes/anon.md", "anonymous body"))+ .await+ .unwrap();++ let app = api_router(store.reader.clone(), wiki.clone());+ let resp = app+ .oneshot(+ Request::builder()+ .uri("/workspaces/default/projects/scratch/pages/notes/anon.md")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(resp.status(), StatusCode::OK);++ let body = axum::body::to_bytes(resp.into_body(), usize::MAX)+ .await+ .unwrap();+ let json: serde_json::Value = serde_json::from_slice(&body).unwrap();+ assert!(+ json.get("author").is_none(),+ "anonymous page response must omit `author` (not null) — backward-compat regression: {json}"+ );+}++#[tokio::test]+async fn api_v1_page_surfaces_author_for_db_user_writes() {+ let (_tmp, store, wiki) = setup().await;+ let ws = store+ .writer+ .get_or_create_workspace("default")+ .await+ .unwrap();+ let proj = store+ .writer+ .get_or_create_project(ws, "scratch", None)+ .await+ .unwrap();++ // Seed a `users` row and write a page attributed to that id.+ let pepper = ai_memory_store::TokenPepper::new("test-pepper");+ let token_hash = ai_memory_store::hash_token("any-token", &pepper);+ let mut new_user = ai_memory_core::NewUser {+ username: "alice".into(),+ name: Some("Alice Smith".into()),+ email: Some("alice@home".into()),+ };+ new_user.validate().unwrap();+ let user_id = store+ .writer+ .create_user(new_user, token_hash)+ .await+ .unwrap();++ let mut req = wiki_req(ws, proj, "notes/by-alice.md", "alice wrote this");+ req.author_id = Some(user_id);+ req.actor = ai_memory_core::ActorContext {+ user: Some("alice".into()),+ name: Some("Alice Smith".into()),+ email: Some("alice@home".into()),+ ..ai_memory_core::ActorContext::default()+ };+ wiki.write_page(req).await.unwrap();++ let app = api_router(store.reader.clone(), wiki.clone());+ let resp = app+ .oneshot(+ Request::builder()+ .uri("/workspaces/default/projects/scratch/pages/notes/by-alice.md")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(resp.status(), StatusCode::OK);++ let body = axum::body::to_bytes(resp.into_body(), usize::MAX)+ .await+ .unwrap();+ let json: serde_json::Value = serde_json::from_slice(&body).unwrap();+ let author = json+ .get("author")+ .expect("identified write must surface `author`");+ assert_eq!(author["username"], "alice");+ assert_eq!(author["name"], "Alice Smith");+ assert_eq!(author["email"], "alice@home");+}++#[tokio::test]+async fn api_v1_etag_differs_between_anonymous_and_attributed_writes() {+ // Regression guard: the ETag must invalidate when author changes+ // even if the body stays the same. Otherwise a client cached the+ // "anonymous" view of a page wouldn't see the attribution flip+ // after the operator runs `rotate-token` + re-writes the page.+ let (_tmp, store, wiki) = setup().await;+ let ws = store+ .writer+ .get_or_create_workspace("default")+ .await+ .unwrap();+ let proj = store+ .writer+ .get_or_create_project(ws, "scratch", None)+ .await+ .unwrap();+ let pepper = ai_memory_store::TokenPepper::new("test-pepper");+ let token_hash = ai_memory_store::hash_token("t", &pepper);+ let mut new_user = ai_memory_core::NewUser {+ username: "alice".into(),+ name: None,+ email: None,+ };+ new_user.validate().unwrap();+ let user_id = store+ .writer+ .create_user(new_user, token_hash)+ .await+ .unwrap();++ // First write: anonymous.+ wiki.write_page(wiki_req(ws, proj, "notes/etag.md", "shared body"))+ .await+ .unwrap();+ let app = api_router(store.reader.clone(), wiki.clone());+ let resp = app+ .clone()+ .oneshot(+ Request::builder()+ .uri("/workspaces/default/projects/scratch/pages/notes/etag.md")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ let etag_anon = resp+ .headers()+ .get(header::ETAG)+ .unwrap()+ .to_str()+ .unwrap()+ .to_string();++ // Second write: same body, but attributed to alice. Same wiki path+ // → supersession; the new latest version carries author_id.+ let mut req = wiki_req(ws, proj, "notes/etag.md", "shared body");+ req.author_id = Some(user_id);+ req.actor = ai_memory_core::ActorContext {+ user: Some("alice".into()),+ ..ai_memory_core::ActorContext::default()+ };+ wiki.write_page(req).await.unwrap();++ let resp = app+ .oneshot(+ Request::builder()+ .uri("/workspaces/default/projects/scratch/pages/notes/etag.md")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ let etag_with_author = resp+ .headers()+ .get(header::ETAG)+ .unwrap()+ .to_str()+ .unwrap()+ .to_string();+ assert_ne!(+ etag_anon, etag_with_author,+ "ETag must invalidate when author changes — even when body is identical \+ (would otherwise let stale caches hide attribution flips)"+ );+}