Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
Merge remote-tracking branch 'upstream/main' into feature/admission-webhooks
Djalma Júnior480598639724
diff --cc crates/ai-memory-cli/src/commands/serve.rsindex ba1c1713,82d5211d..73e821e8--- a/crates/ai-memory-cli/src/commands/serve.rs+++ b/crates/ai-memory-cli/src/commands/serve.rs@@@ -932,7 -931,8 +948,9 @@@ mod teststier: Tier::Semantic,pinned: false,title: None,+ admission_ctx: None,+ author_id: None,+ actor: ai_memory_core::ActorContext::anonymous(),}).await.unwrap();diff --cc crates/ai-memory-consolidate/src/bootstrap.rsindex 12fc7a4c,9b2a3dd5..1902caa4--- a/crates/ai-memory-consolidate/src/bootstrap.rs+++ b/crates/ai-memory-consolidate/src/bootstrap.rs@@@ -409,7 -409,8 +409,9 @@@ impl Bootstraptier: Tier::Semantic,pinned: false,title: Some(page.title.clone()),+ admission_ctx: None,+ author_id: None,+ actor: ai_memory_core::ActorContext::anonymous(),});}// Plus the manifest itself.@@@ -437,7 -438,8 +439,9 @@@tier: Tier::Semantic,pinned: true,title: Some("Bootstrap manifest".into()),+ admission_ctx: None,+ author_id: None,+ actor: ai_memory_core::ActorContext::anonymous(),});let _ids = self.wiki.apply_batch(requests).await?;diff --cc crates/ai-memory-consolidate/src/consolidator.rsindex 6adff12c,9755a3b0..c2ccc891--- a/crates/ai-memory-consolidate/src/consolidator.rs+++ b/crates/ai-memory-consolidate/src/consolidator.rs@@@ -157,10 -157,8 +157,12 @@@ impl Consolidatortier: Tier::Episodic,pinned: false,title: None,+ admission_ctx: Some(AdmissionContext {+ op: AdmissionOp::Consolidate,+ ..Default::default()+ }),+ author_id: None,+ actor: ai_memory_core::ActorContext::anonymous(),}).await?;// Auto-commit the result so the supersession lands in git.@@@ -394,10 -392,8 +396,12 @@@ fn build_updatetier,pinned: false,title: Some(upd.title.clone()),+ admission_ctx: Some(AdmissionContext {+ op: AdmissionOp::Consolidate,+ ..Default::default()+ }),+ author_id: None,+ actor: ai_memory_core::ActorContext::anonymous(),};let outcome = ConsolidationOutcome {path,diff --cc crates/ai-memory-consolidate/src/lint.rsindex 682f68bc,439e72e7..60cd2fa5--- a/crates/ai-memory-consolidate/src/lint.rs+++ b/crates/ai-memory-consolidate/src/lint.rs@@@ -313,10 -313,8 +313,12 @@@ async fn write_report_pagetier: Tier::Semantic,pinned: false,title: Some(title),+ admission_ctx: Some(AdmissionContext {+ op: AdmissionOp::Consolidate,+ ..Default::default()+ }),+ author_id: None,+ actor: ai_memory_core::ActorContext::anonymous(),}).await?;Ok(())diff --cc crates/ai-memory-consolidate/tests/embeddings.rsindex e4cba15b,797e0f41..c580c1f8--- a/crates/ai-memory-consolidate/tests/embeddings.rs+++ b/crates/ai-memory-consolidate/tests/embeddings.rs@@@ -65,7 -65,8 +65,9 @@@ async fn m9_embeddings_roundtrip_via_sytier: Tier::Semantic,pinned: false,title: None,+ admission_ctx: None,+ author_id: None,+ actor: ai_memory_core::ActorContext::anonymous(),}).await.expect("write page");@@@ -183,7 -184,8 +185,9 @@@tier: Tier::Semantic,pinned: false,title: None,+ admission_ctx: None,+ author_id: None,+ actor: ai_memory_core::ActorContext::anonymous(),}).await.expect("rewrite page");diff --cc crates/ai-memory-consolidate/tests/lifecycle.rsindex 7a1c6126,56b350e3..5bc4fec8--- a/crates/ai-memory-consolidate/tests/lifecycle.rs+++ b/crates/ai-memory-consolidate/tests/lifecycle.rs@@@ -199,7 -199,8 +199,9 @@@ async fn m8_retention_lifecycle_end_to_tier: fx.tier,pinned: false,title: Some(title),+ admission_ctx: None,+ author_id: None,+ actor: ai_memory_core::ActorContext::anonymous(),}).await.expect("write page");diff --cc crates/ai-memory-consolidate/tests/recall_eval.rsindex 92488e77,24cfdca4..55e0b993--- a/crates/ai-memory-consolidate/tests/recall_eval.rs+++ b/crates/ai-memory-consolidate/tests/recall_eval.rs@@@ -133,7 -133,8 +133,9 @@@ async fn recall_at_5_baseline()tier: Tier::Semantic,pinned: false,title: None,+ admission_ctx: None,+ author_id: None,+ actor: ai_memory_core::ActorContext::anonymous(),}).await.expect("write page");@@@ -190,7 -191,8 +192,9 @@@ async fn graph_neighbor_expansion_recovtier: Tier::Semantic,pinned: false,title: None,+ admission_ctx: None,+ author_id: None,+ actor: ai_memory_core::ActorContext::anonymous(),}).await.expect("write target");@@@ -203,7 -205,8 +207,9 @@@tier: Tier::Semantic,pinned: false,title: None,+ admission_ctx: None,+ author_id: None,+ actor: ai_memory_core::ActorContext::anonymous(),}).await.expect("write source");diff --cc crates/ai-memory-hooks/src/router.rsindex 927212a2,18f701ce..f81e3bea--- a/crates/ai-memory-hooks/src/router.rs+++ b/crates/ai-memory-hooks/src/router.rs@@@ -506,7 -506,8 +506,9 @@@ async fn process(state: &HookState, envtier: new_page.tier,pinned: new_page.pinned,title: None,+ admission_ctx: None,+ author_id: None,+ actor: ai_memory_core::ActorContext::anonymous(),}).await?;state.writer.end_session(session_id, Some(page_id)).await?;@@@ -703,7 -704,8 +705,9 @@@ async fn consolidate_or_synthtier: new_page.tier,pinned: new_page.pinned,title: None,+ admission_ctx: None,+ author_id: None,+ actor: ai_memory_core::ActorContext::anonymous(),}).await?;let _ = state.wiki.commit_all(&format!(diff --cc crates/ai-memory-mcp/src/admin.rsindex 0fc7f2f6,a76de943..52af6286--- a/crates/ai-memory-mcp/src/admin.rs+++ b/crates/ai-memory-mcp/src/admin.rs@@@ -1647,7 -1630,8 +1647,9 @@@ async fn handle_write_pagetier,pinned: req.pinned,title: req.title,+ admission_ctx: None,+ author_id: None,+ actor: ai_memory_core::ActorContext::anonymous(),}).await.map_err(|e| internal_err(e.to_string()))?;diff --cc crates/ai-memory-mcp/src/server.rsindex 8d3086d5,d5057754..5aed971a--- a/crates/ai-memory-mcp/src/server.rs+++ b/crates/ai-memory-mcp/src/server.rs@@@ -1032,7 -993,8 +1032,9 @@@ impl AiMemoryServertier,pinned: args.pinned,title: args.title,+ admission_ctx,+ author_id: None,+ actor: ai_memory_core::ActorContext::anonymous(),}).await.map_err(|e| McpError::internal_error(e.to_string(), None))?;diff --cc crates/ai-memory-mcp/tests/admin_backup.rsindex 585cf18a,f57f78a9..aa3a15a9--- a/crates/ai-memory-mcp/tests/admin_backup.rs+++ b/crates/ai-memory-mcp/tests/admin_backup.rs@@@ -65,7 -65,8 +65,9 @@@ async fn seed_page(state: &AdminState,tier: Tier::Semantic,pinned: false,title: Some("Test".into()),+ admission_ctx: None,+ author_id: None,+ actor: ai_memory_core::ActorContext::anonymous(),}).await.unwrap();diff --cc crates/ai-memory-mcp/tests/admin_phase3.rsindex cd040661,c96e8377..004c9505--- a/crates/ai-memory-mcp/tests/admin_phase3.rs+++ b/crates/ai-memory-mcp/tests/admin_phase3.rs@@@ -361,7 -362,8 +362,9 @@@ async fn embed_all_projects_rebuilds_wotier: Tier::Semantic,pinned: false,title: Some("A".into()),+ admission_ctx: None,+ author_id: None,+ actor: ai_memory_core::ActorContext::anonymous(),}).await.unwrap();@@@ -376,7 -378,8 +379,9 @@@tier: Tier::Semantic,pinned: false,title: Some("B".into()),+ admission_ctx: None,+ author_id: None,+ actor: ai_memory_core::ActorContext::anonymous(),}).await.unwrap();@@@ -466,7 -469,8 +471,9 @@@ async fn commit_with_new_page_returns_ctier: Tier::Semantic,pinned: false,title: Some("Commit test".into()),+ admission_ctx: None,+ author_id: None,+ actor: ai_memory_core::ActorContext::anonymous(),}).await.unwrap();diff --cc crates/ai-memory-mcp/tests/admin_purge.rsindex 46d730b3,9bcdced5..b459277a--- a/crates/ai-memory-mcp/tests/admin_purge.rs+++ b/crates/ai-memory-mcp/tests/admin_purge.rs@@@ -90,7 -90,8 +90,9 @@@ async fn seed_two_projects(store: &Stortier: Tier::Semantic,pinned: false,title: Some("Keep page".into()),+ admission_ctx: None,+ author_id: None,+ actor: ai_memory_core::ActorContext::anonymous(),}).await.unwrap();@@@ -104,7 -105,8 +106,9 @@@tier: Tier::Semantic,pinned: false,title: Some("Doomed page".into()),+ admission_ctx: None,+ author_id: None,+ actor: ai_memory_core::ActorContext::anonymous(),}).await.unwrap();diff --cc crates/ai-memory-mcp/tests/admin_rename.rsindex 011e37d8,73054924..3303837a--- a/crates/ai-memory-mcp/tests/admin_rename.rs+++ b/crates/ai-memory-mcp/tests/admin_rename.rs@@@ -79,7 -79,8 +79,9 @@@ async fn seed_page(store: &Store, wikitier: Tier::Semantic,pinned: false,title: Some(project.into()),+ admission_ctx: None,+ author_id: None,+ actor: ai_memory_core::ActorContext::anonymous(),}).await.unwrap();diff --cc crates/ai-memory-web/tests/routes.rsindex 104b360c,0484316c..77f40604--- a/crates/ai-memory-web/tests/routes.rs+++ b/crates/ai-memory-web/tests/routes.rs@@@ -55,7 -56,8 +56,9 @@@ fn wiki_reqtier: Tier::Semantic,pinned: false,title: None,+ admission_ctx: None,+ author_id: None,+ actor: ai_memory_core::ActorContext::anonymous(),}}@@@ -1519,7 -1638,8 +1639,9 @@@ async fn api_page_handler_emits_etag_antier: Tier::Semantic,pinned: false,title: None,+ admission_ctx: None,+ author_id: None,+ actor: ai_memory_core::ActorContext::anonymous(),}).await.unwrap();@@@ -1598,7 -1718,8 +1720,9 @@@ async fn api_page_handler_etag_differs_tier: Tier::Semantic,pinned: false,title: None,+ admission_ctx: None,+ author_id: None,+ actor: ai_memory_core::ActorContext::anonymous(),}).await.unwrap();@@@ -1611,7 -1732,8 +1735,9 @@@tier: Tier::Semantic,pinned: false,title: None,+ admission_ctx: None,+ author_id: None,+ actor: ai_memory_core::ActorContext::anonymous(),}).await.unwrap();diff --cc crates/ai-memory-wiki/src/wiki.rsindex eb767e98,609f738e..2b894776--- a/crates/ai-memory-wiki/src/wiki.rs+++ b/crates/ai-memory-wiki/src/wiki.rs@@@ -419,7 -306,8 +422,9 @@@ impl Wikitier,pinned,title: explicit_title,+ admission_ctx,+ author_id,+ actor,} = req;// Defence-in-depth: scrub the body before we touch disk or the@@@ -429,41 -317,6 +434,46 @@@// tool slips through.let body = self.sanitizer.scrub(&body);+ let pinned = pinned || is_slot_path(&path);++ // Multi-user attribution (P1.6): stamp `last_modified_by` into the++ // frontmatter BEFORE building the markdown, so both the admission++ // chain and the on-disk file see the resolved author. Rung 0++ // (anonymous) → no block, no disk-shape change for single-user.++ let frontmatter = stamp_last_modified_by(frontmatter, &actor);+ let mut markdown = Markdown { frontmatter, body };++ // Admission webhook chain — runs AFTER the markdown is built and+ // sanitised, BEFORE emit + atomic write. Mutations to+ // frontmatter/body here propagate to both the on-disk markdown+ // (via emit below) and the store's `frontmatter_json` / `body`+ // (via the upsert below) atomically. See `crate::admission`.+ if let Some(chain) = &self.admission_chain {+ let mut ctx = admission_ctx.unwrap_or_default();+ // Resolve workspace + project names from the store reader (if+ // attached) so webhooks address pages by the human-readable+ // names the engine uses on disk and in the UI. Best-effort —+ // lookup failures fall through with empty names (webhooks+ // tolerate that and fall back to header introspection).+ if let Some(reader) = &self.store_reader {+ if ctx.workspace.is_empty()+ && let Ok(Some(name)) = reader.workspace_name_by_id(workspace_id).await+ {+ ctx.workspace = name;+ }+ if ctx.project.is_empty()+ && let Ok(Some(name)) =+ reader.project_name_by_id(workspace_id, project_id).await+ {+ ctx.project = name;+ }+ }+ chain.run(&path, &mut markdown, &ctx).await?;+ }++ // Re-derive title + links from the (possibly mutated) markdown.+ // We do this after the chain so explicit title overrides survive+ // mutations and webhooks that rename or restructure the body+ // still get the right title/links extracted.let title = explicit_title.clone().map(|t| self.sanitizer.scrub(&t))@@@ -488,11 -346,12 +498,12 @@@project_id,path,title,- body: body.clone(),+ body: final_body.clone(),tier,- frontmatter_json: frontmatter,+ frontmatter_json: final_frontmatter,pinned,links,+ author_id,}).await?;// Embed if configured. We do this on the caller's task so the@@@ -544,14 -403,23 +555,32 @@@ pub struct WritePageRequest/// title between the staged markdown file + the store row).#[doc(hidden)]pub title: Option<String>,- /// Optional admission webhook context (actor identity + JWT claims +- /// request headers + loop-prevention skip list). Populated by- /// authenticated callers (MCP tool, admin endpoint) from the JWT +- /// `X-Memory-Actor-*` / `X-Memory-Skip-Admission-Chain` headers; left- /// `None` by internal callers (CLI bootstrap, consolidator from hooks,- /// tests) — when the chain is configured, `None` is treated as a- /// default [`AdmissionContext`] with `actor = unknown`.++ /// Optional admission webhook context (op + loop-prevention skip++ /// list + resolved workspace/project names). Populated by++ /// authenticated callers (MCP tool, admin endpoint); left `None` by++ /// internal callers (CLI bootstrap, consolidator from hooks, tests)++ /// — when the chain is configured, `None` is treated as a default++ /// [`AdmissionContext`]. The actor that rides in the webhook payload++ /// comes from [`Self::actor`], not from here (single source of++ /// identity since the v0.8 multi-user merge).+ pub admission_ctx: Option<AdmissionContext>,+ /// Multi-user attribution: the registered user (rung-2) who made+ /// this write, when resolved by the auth middleware. Propagates to+ /// `pages.author_id` and the on-disk frontmatter `last_modified_by`+ /// block (the latter is built from the broader `ActorContext` —+ /// see [`Self::actor`] — so root + anonymous writes also get+ /// frontmatter even though they leave `author_id` NULL). Defaults+ /// to `None` for backward compat with internal callers+ /// (consolidator, lint rewriters) that build `WritePageRequest`+ /// without an HTTP request layer.+ pub author_id: Option<ai_memory_core::UserId>,- /// Identity carried in the on-disk frontmatter's- /// `last_modified_by` block (when `actor.user.is_some()`). The- /// auth middleware fills this from the four-rung resolution: rung- /// 1 supplies the configured root template, rung 2 supplies the- /// row's user/name/email. Defaults to anonymous for backward- /// compat.++ /// Identity carried in the on-disk frontmatter's `last_modified_by`++ /// block AND the admission webhook payload's `ctx.actor`. The auth++ /// middleware fills this from the four-rung resolution (injected as++ /// `Extension<ai_memory_core::ActorContext>`): rung 1 supplies the++ /// configured root template, rung 2 supplies the row's++ /// user/name/email. Defaults to anonymous for backward compat.+ pub actor: ai_memory_core::ActorContext,}fn ai_memory_wiki_error(msg: &str) -> crate::WikiError {@@@ -600,7 -514,8 +675,9 @@@ mod teststier: Tier::Semantic,pinned: false,title: None,+ admission_ctx: None,+ author_id: None,+ actor: ai_memory_core::ActorContext::anonymous(),}}@@@ -780,7 -695,8 +857,9 @@@tier: Tier::Semantic,pinned: false,title: None,+ admission_ctx: None,+ author_id: None,+ actor: ai_memory_core::ActorContext::anonymous(),}).collect();let ids = wiki.apply_batch(batch).await.unwrap();@@@ -829,7 -745,8 +908,9 @@@tier: Tier::Semantic,pinned: false,title: None,+ admission_ctx: None,+ author_id: None,+ actor: ai_memory_core::ActorContext::anonymous(),}).await.unwrap();@@@ -843,7 -760,8 +924,9 @@@tier: Tier::Semantic,pinned: false,title: None,+ admission_ctx: None,+ author_id: None,+ actor: ai_memory_core::ActorContext::anonymous(),}).await.unwrap();@@@ -887,96 -805,224 +970,300 @@@assert_ne!(b, c);}+ /// End-to-end gate for the workspace/project name resolution:+ /// when a wiki is built with both a store reader and an admission+ /// chain, `write_page` populates `AdmissionContext.workspace` and+ /// `AdmissionContext.project` from the resolved store rows before+ /// invoking the chain. Without [`Wiki::with_store_reader`] the+ /// fields stay empty (backward compat with external test setups).+ #[tokio::test]+ async fn write_page_resolves_workspace_and_project_names_for_chain() {+ use crate::admission::{+ AdmissionChain, AdmissionContext, AdmissionOp, FailurePolicy, WebhookConfig,+ };+ use axum::http::StatusCode;+ use axum::response::IntoResponse;+ use axum::routing::post;+ use axum::{Json, Router};+ use std::sync::Mutex;+ use tokio::net::TcpListener;++ let tmp = TempDir::new().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let ws = store+ .writer+ .get_or_create_workspace("staging")+ .await+ .unwrap();+ let proj = store+ .writer+ .get_or_create_project(ws, "ai-memory-ops", None)+ .await+ .unwrap();++ // Throwaway HTTP server that records the payload it receives.+ let recorder: Arc<Mutex<Option<serde_json::Value>>> = Arc::new(Mutex::new(None));+ let recorder_clone = recorder.clone();+ let app = Router::new().route(+ "/sync",+ post(move |Json(payload): Json<serde_json::Value>| {+ let recorder = recorder_clone.clone();+ async move {+ *recorder.lock().unwrap() = Some(payload);+ StatusCode::NO_CONTENT.into_response()+ }+ }),+ );+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();+ let addr = listener.local_addr().unwrap();+ tokio::spawn(async move {+ axum::serve(listener, app).await.unwrap();+ });++ let chain = AdmissionChain::new(vec![WebhookConfig {+ name: "recorder".into(),+ url: format!("http://{addr}/sync"),+ timeout_ms: 1_000,+ failure_policy: FailurePolicy::Ignore,+ events: vec![AdmissionOp::WritePage],+ }])+ .unwrap();++ let wiki = Wiki::new(tmp.path(), store.writer.clone())+ .unwrap()+ .with_admission_chain(chain)+ .with_store_reader(store.reader.clone());++ wiki.write_page(WritePageRequest {+ workspace_id: ws,+ project_id: proj,+ path: PagePath::new("notes/x.md").unwrap(),+ frontmatter: serde_json::json!({"title": "X"}),+ body: "hi".into(),+ tier: Tier::Semantic,+ pinned: false,+ title: None,+ admission_ctx: Some(AdmissionContext {+ op: AdmissionOp::WritePage,+ ..AdmissionContext::default()+ }),++ author_id: None,++ actor: ai_memory_core::ActorContext::anonymous(),+ })+ .await+ .unwrap();++ let payload = recorder+ .lock()+ .unwrap()+ .clone()+ .expect("webhook should have recorded the payload");+ assert_eq!(payload["ctx"]["workspace"], serde_json::json!("staging"));+ assert_eq!(+ payload["ctx"]["project"],+ serde_json::json!("ai-memory-ops")+ );+ }+++ // ── P1.6: write attribution ─────────────────────────────────────++ /// Anonymous actor must NOT add a `last_modified_by` block — this+ /// is the backward-compat gate for every existing single-user- /// install. The on-disk frontmatter shape stays exactly as it was- /// in pre-multi-user releases.++ /// install.+ #[test]+ fn stamp_last_modified_by_skips_anonymous_actor() {+ let fm = serde_json::json!({"title": "X", "kind": "fact"});+ let stamped =+ stamp_last_modified_by(fm.clone(), &ai_memory_core::ActorContext::anonymous());+ assert_eq!(+ stamped, fm,+ "anonymous actor must leave frontmatter untouched"+ );+ }++ /// Identified actor adds the full block (username + name + email+ /// when present). Existing keys in frontmatter are preserved.+ #[test]+ fn stamp_last_modified_by_adds_full_block() {+ let actor = ai_memory_core::ActorContext {+ user: Some("alice".into()),+ name: Some("Alice Smith".into()),+ email: Some("alice@home".into()),+ ..ai_memory_core::ActorContext::default()+ };+ let stamped =+ stamp_last_modified_by(serde_json::json!({"title": "X", "kind": "fact"}), &actor);+ let lmb = &stamped["last_modified_by"];+ assert_eq!(lmb["username"], "alice");+ assert_eq!(lmb["name"], "Alice Smith");+ assert_eq!(lmb["email"], "alice@home");- // Pre-existing keys survive.+ assert_eq!(stamped["title"], "X");+ assert_eq!(stamped["kind"], "fact");+ }+- /// Username-only (no name/email) writes a minimal block — the- /// rung-1 root-template case where the operator set- /// `[auth].root_username` but skipped the optional fields.++ /// Username-only (no name/email) writes a minimal block.+ #[test]+ fn stamp_last_modified_by_minimal_username_only() {+ let actor = ai_memory_core::ActorContext {+ user: Some("boss".into()),+ ..ai_memory_core::ActorContext::default()+ };+ let stamped = stamp_last_modified_by(serde_json::json!({}), &actor);+ let lmb = &stamped["last_modified_by"];+ assert_eq!(lmb["username"], "boss");+ assert!(lmb.get("name").is_none(), "name omitted when not set");+ assert!(lmb.get("email").is_none(), "email omitted when not set");+ }+- /// Repeated writes by different actors replace the block — we- /// don't accumulate authorship history in frontmatter. That lives- /// in `pages.author_id` + the supersession chain.++ /// Repeated writes by different actors replace the block.+ #[test]+ fn stamp_last_modified_by_replaces_previous_block() {+ let first = ai_memory_core::ActorContext {+ user: Some("alice".into()),+ ..ai_memory_core::ActorContext::default()+ };+ let after_alice = stamp_last_modified_by(serde_json::json!({}), &first);+ assert_eq!(after_alice["last_modified_by"]["username"], "alice");++ let second = ai_memory_core::ActorContext {+ user: Some("bob".into()),+ ..ai_memory_core::ActorContext::default()+ };+ let after_bob = stamp_last_modified_by(after_alice, &second);+ assert_eq!(+ after_bob["last_modified_by"]["username"], "bob",+ "second write replaces, doesn't accumulate"+ );+ }+- /// Null frontmatter (legacy pages without any block) is turned- /// into a fresh object on a non-anonymous write rather than- /// rejected — protects the upgrade path for installs that wrote- /// pages before frontmatter became canonical.++ /// Null frontmatter is turned into a fresh object on a++ /// non-anonymous write rather than rejected.+ #[test]+ fn stamp_last_modified_by_handles_null_input() {+ let actor = ai_memory_core::ActorContext {+ user: Some("alice".into()),+ ..ai_memory_core::ActorContext::default()+ };+ let stamped = stamp_last_modified_by(serde_json::Value::Null, &actor);+ assert_eq!(stamped["last_modified_by"]["username"], "alice");+ }++ /// End-to-end: a write with a non-anonymous actor lands a- /// `last_modified_by` block on disk, AND `pages.author_id` carries- /// the UserId. Critical proof that the plumbing is wired all the- /// way through.++ /// `last_modified_by` block on disk AND `pages.author_id` carries++ /// the UserId.+ #[tokio::test]+ async fn write_page_with_actor_stamps_frontmatter_and_author_id() {+ use ai_memory_core::{NewUser, UserId};+ let tmp = TempDir::new().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();++ let ws = store+ .writer+ .get_or_create_workspace("default")+ .await+ .unwrap();+ let proj = store+ .writer+ .get_or_create_project(ws, "scratch", None)+ .await+ .unwrap();++ // Pre-load an actual users row so author_id can FK-resolve.+ let pepper = ai_memory_store::TokenPepper::new("test-pepper-attribution");+ let token_hash = ai_memory_store::hash_token("test-token", &pepper);+ let mut new_user = NewUser {+ username: "alice".into(),+ name: Some("Alice Smith".into()),+ email: Some("[email protected]".into()),+ };+ new_user.validate().unwrap();+ let user_id: UserId = store+ .writer+ .create_user(new_user, token_hash)+ .await+ .unwrap();+- // Write a page as alice.+ wiki.write_page(WritePageRequest {+ workspace_id: ws,+ project_id: proj,+ path: PagePath::new("notes/note.md").unwrap(),+ frontmatter: serde_json::json!({"title": "Note"}),+ body: "body".into(),+ tier: Tier::Semantic,+ pinned: false,+ title: None,++ admission_ctx: None,+ author_id: Some(user_id),+ actor: ai_memory_core::ActorContext {+ user: Some("alice".into()),+ name: Some("Alice Smith".into()),+ email: Some("[email protected]".into()),+ ..ai_memory_core::ActorContext::default()+ },+ })+ .await+ .unwrap();+- // On-disk frontmatter carries last_modified_by.+ let md = wiki+ .read_page(ws, proj, &PagePath::new("notes/note.md").unwrap())+ .unwrap();+ assert_eq!(md.frontmatter["last_modified_by"]["username"], "alice");+ assert_eq!(+ md.frontmatter["last_modified_by"]["email"],+ );+- // pages.author_id matches the user row.+ let meta = store+ .reader+ .page_meta_by_path("notes/note.md")+ .await+ .unwrap()+ .expect("page exists");- // No direct exposure of author_id on PageMeta yet (P1.7), so- // probe the column directly via the reader's connection pool- // through the public path — for the moment, assert via the- // existing reader query is sufficient indirect proof; deeper- // verification (and P1.7's `author` block on responses) lands- // with the next milestone.- let _ = meta; // silence unused; the read succeeded which is the proof of plumbing.++ let _ = meta;+ }+- /// Backward-compat: anonymous writes (the only kind pre-P1.6- /// callers built) leave frontmatter and author_id untouched.- /// `pages.author_id` is NULL, the on-disk file has the exact- /// shape it would have had before this milestone.++ /// Backward-compat: anonymous writes leave frontmatter and++ /// author_id untouched.+ #[tokio::test]+ async fn write_page_with_anonymous_actor_leaves_frontmatter_unchanged() {+ let tmp = TempDir::new().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();+ 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(WritePageRequest {+ workspace_id: ws,+ project_id: proj,+ path: PagePath::new("notes/anon.md").unwrap(),+ frontmatter: serde_json::json!({"title": "Anon"}),+ body: "body".into(),+ tier: Tier::Semantic,+ pinned: false,+ title: None,++ admission_ctx: None,+ author_id: None,+ actor: ai_memory_core::ActorContext::anonymous(),+ })+ .await+ .unwrap();++ let md = wiki+ .read_page(ws, proj, &PagePath::new("notes/anon.md").unwrap())+ .unwrap();+ assert!(+ md.frontmatter.get("last_modified_by").is_none(),+ "anonymous writes must NOT add last_modified_by — backward compat"+ );- // Other keys preserved.+ assert_eq!(md.frontmatter["title"], "Anon");+ }}