Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(store): audit-log attribution for purge-project and rename-project
Djalma Júnior803c95f72af3
diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rsindex 1b1993a8..2742dca7 100644--- a/crates/ai-memory-hooks/src/router.rs+++ b/crates/ai-memory-hooks/src/router.rs@@ -3548,7 +3548,7 @@ mod tests {// points at it (exactly the purge-on-live-server scenario).state.writer- .purge_project(ws, proj, "default/heal-project")+ .purge_project(ws, proj, "default/heal-project", None).await.unwrap();assert!(@@ -3731,7 +3731,7 @@ mod tests {state.writer- .purge_project(ws, proj, "default/repo-root-project")+ .purge_project(ws, proj, "default/repo-root-project", None).await.unwrap();diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rsindex b79d1fa4..29e8eeea 100644--- a/crates/ai-memory-mcp/src/admin.rs+++ b/crates/ai-memory-mcp/src/admin.rs@@ -2875,8 +2875,10 @@ pub struct PurgeProjectReport {async fn handle_purge_project(State(state): State<Arc<AdminState>>,actor_ext: Option<axum::Extension<ai_memory_core::ActorContext>>,+ author_ext: Option<axum::Extension<ai_memory_core::UserId>>,Json(req): Json<PurgeProjectRequest>,) -> impl IntoResponse {+ let author_id = author_ext.map(|axum::Extension(u)| u);if !req.confirm {return (StatusCode::BAD_REQUEST,@@ -2926,7 +2928,11 @@ async fn handle_purge_project(Err(e) => return e,};- let summary = match state.writer.purge_project(ws_id, proj_id, &label).await {+ let summary = match state+ .writer+ .purge_project(ws_id, proj_id, &label, author_id)+ .await+ {Ok(s) => s,Err(e) => return internal_err(e.to_string()),};@@ -3239,8 +3245,10 @@ pub struct RenameProjectSummary {async fn handle_rename_project(State(state): State<Arc<AdminState>>,+ author_ext: Option<axum::Extension<ai_memory_core::UserId>>,Json(req): Json<RenameProjectRequest>,) -> impl IntoResponse {+ let author_id = author_ext.map(|axum::Extension(u)| u);// Look up workspace + source project; 404 if either is absent.let (ws_id, proj_id) = match lookup_ws_proj_no_create(&state, &req.workspace, &req.from).await {Ok(ids) => ids,@@ -3255,7 +3263,7 @@ async fn handle_rename_project(// instead of the previous false-200.if let Err(e) = state.writer- .rename_project(ws_id, proj_id, req.to.clone())+ .rename_project(ws_id, proj_id, req.to.clone(), author_id).await{let status = match &e {@@ -4115,7 +4123,14 @@ async fn copy_purge_merge(Err(e) => return internal_err(e.to_string()),};- let summary = match state.writer.purge_project(src_ws, src_proj, &label).await {+ // The source purge is an internal step of move-project (a distinct op that+ // records its own move report); it is not attributed as a standalone+ // `purge_project` here, so the audit author is left NULL.+ let summary = match state+ .writer+ .purge_project(src_ws, src_proj, &label, None)+ .await+ {Ok(s) => s,Err(e) => return internal_err(e.to_string()),};diff --git a/crates/ai-memory-store/src/ops.rs b/crates/ai-memory-store/src/ops.rsindex 05ef4e72..0b1e0c8a 100644--- a/crates/ai-memory-store/src/ops.rs+++ b/crates/ai-memory-store/src/ops.rs@@ -1200,6 +1200,7 @@ pub fn rename_project(workspace_id: &WorkspaceId,project_id: &ProjectId,new_name: &str,+ author_id: Option<ai_memory_core::UserId>,) -> StoreResult<()> {let trimmed = new_name.trim();if trimmed.is_empty() {@@ -1213,7 +1214,11 @@ pub fn rename_project());}- let rows = conn.execute(+ // Wrap the UPDATE + audit row in one transaction so the trail can never+ // diverge from the rename it records (on any error the tx drops without+ // commit, rolling both back).+ let tx = conn.transaction()?;+ let rows = tx.execute("UPDATE projects SET name = ?1 WHERE id = ?2 AND workspace_id = ?3",params![trimmed, project_id.as_bytes(), workspace_id.as_bytes()],);@@ -1230,7 +1235,19 @@ pub fn rename_project("project id {project_id} no longer exists in workspace {workspace_id} \(race with concurrent purge or delete)",))),- Ok(_) => Ok(()),+ Ok(_) => {+ audit(+ &tx,+ "rename_project",+ Some(workspace_id.as_bytes()),+ Some(project_id.as_bytes()),+ None,+ author_id.as_ref().map(ai_memory_core::UserId::as_bytes),+ Timestamp::now().as_microsecond(),+ )?;+ tx.commit()?;+ Ok(())+ }Err(rusqlite::Error::SqliteFailure(err, _))if err.extended_code == rusqlite::ffi::SQLITE_CONSTRAINT_UNIQUE|| err.code == rusqlite::ErrorCode::ConstraintViolation =>@@ -1283,6 +1300,7 @@ pub fn purge_project(workspace_id: &WorkspaceId,project_id: &ProjectId,workspace_project_label: &str,+ author_id: Option<ai_memory_core::UserId>,) -> StoreResult<PurgeSummary> {let tx = conn.transaction()?;@@ -1333,6 +1351,19 @@ pub fn purge_project(rusqlite::params![&pid[..], workspace_id.as_bytes()],)?;+ // Attributed audit trail for the destructive purge. `page_id` is None+ // (the whole project is gone); the operator identity comes from the+ // authenticated request (NULL when single-user / unauthenticated).+ audit(+ &tx,+ "purge_project",+ Some(workspace_id.as_bytes()),+ Some(project_id.as_bytes()),+ None,+ author_id.as_ref().map(ai_memory_core::UserId::as_bytes),+ Timestamp::now().as_microsecond(),+ )?;+tx.commit()?;Ok(PurgeSummary {label: workspace_project_label.to_string(),@@ -3606,13 +3637,13 @@ mod tests {let (_tmp, mut conn, ws, proj) = fresh_db();// Simulate the post-purge state: project row gone.// `purge_project` drives the cascading deletes we want here.- let _ = purge_project(&mut conn, &ws, &proj, "default/scratch")+ let _ = purge_project(&mut conn, &ws, &proj, "default/scratch", None).expect("purge of fresh project should succeed");// Now try to rename the project that no longer exists. The// pre-fix code returned `Ok(())` because `UPDATE` affected// zero rows. The fix returns `NotFound` so admin handlers// can respond 404 honestly.- let err = rename_project(&mut conn, &ws, &proj, "renamed")+ let err = rename_project(&mut conn, &ws, &proj, "renamed", None).expect_err("rename of purged project must error");match err {StoreError::NotFound(_) => {}@@ -3626,10 +3657,85 @@ mod tests {#[test]fn rename_project_of_live_project_succeeds() {let (_tmp, mut conn, ws, proj) = fresh_db();- rename_project(&mut conn, &ws, &proj, "renamed-live")+ rename_project(&mut conn, &ws, &proj, "renamed-live", None).expect("rename of live project must succeed");}+ fn seed_user(conn: &Connection, username: &str) -> ai_memory_core::UserId {+ crate::users::insert_user(+ conn,+ &ai_memory_core::NewUser {+ username: username.to_string(),+ name: None,+ email: None,+ },+ &[7u8; crate::users::TOKEN_HASH_LEN],+ )+ .expect("seed user")+ }++ fn audit_row_for(conn: &Connection, op: &str) -> (i64, Option<Vec<u8>>) {+ conn.query_row(+ "SELECT COUNT(*), MAX(author_id) FROM audit_log WHERE op = ?1",+ [op],+ |r| Ok((r.get(0)?, r.get(1)?)),+ )+ .unwrap()+ }++ /// Attribution guard: a `purge_project` leaves exactly one `audit_log`+ /// row tagged with the op + the authenticated operator — the+ /// point-in-time answer to "who wiped this project?" (V16's motivating+ /// case). Without the audit call the count would be 0.+ #[test]+ fn audit_log_records_purge_project_with_author() {+ let (_tmp, mut conn, ws, proj) = fresh_db();+ let author = seed_user(&conn, "alice");++ purge_project(&mut conn, &ws, &proj, "default/scratch", Some(author))+ .expect("purge should succeed");++ let (count, op_author) = audit_row_for(&conn, "purge_project");+ assert_eq!(count, 1, "exactly one purge_project audit row");+ assert_eq!(+ op_author.as_deref(),+ Some(&author.as_bytes()[..]),+ "audit row must carry the purging operator"+ );+ }++ /// A `rename_project` writes an attributed audit row, committed+ /// atomically with the rename.+ #[test]+ fn audit_log_records_rename_project_with_author() {+ let (_tmp, mut conn, ws, proj) = fresh_db();+ let author = seed_user(&conn, "bob");++ rename_project(&mut conn, &ws, &proj, "renamed", Some(author))+ .expect("rename should succeed");++ let (count, op_author) = audit_row_for(&conn, "rename_project");+ assert_eq!(count, 1, "exactly one rename_project audit row");+ assert_eq!(op_author.as_deref(), Some(&author.as_bytes()[..]));+ }++ /// A failed rename (name collision) writes NO audit row — the tx that+ /// wraps the UPDATE + audit rolls back as a unit.+ #[test]+ fn audit_log_omits_rename_project_on_collision() {+ let (_tmp, mut conn, ws, _proj) = fresh_db();+ let author = seed_user(&conn, "carol");+ // Second project whose name we'll collide with.+ let other = get_or_create_project(&mut conn, &ws, "taken", None).unwrap();++ let err = rename_project(&mut conn, &ws, &other, "scratch", Some(author))+ .expect_err("rename onto an existing name must fail");+ assert!(matches!(err, StoreError::ProjectNameTaken(_)));++ let (count, _) = audit_row_for(&conn, "rename_project");+ assert_eq!(count, 0, "a rolled-back rename must leave no audit row");+ }+/// Run the reader's exact FTS5 `MATCH` against the real, populated/// `pages_fts` index — the path the web search / MCP query take./// Returns the matched paths (and surfaces any FTS5 syntax error asdiff --git a/crates/ai-memory-store/src/writer.rs b/crates/ai-memory-store/src/writer.rsindex 37eb0139..2df07135 100644--- a/crates/ai-memory-store/src/writer.rs+++ b/crates/ai-memory-store/src/writer.rs@@ -154,6 +154,9 @@ pub(crate) enum WriteCmd {project_id: ProjectId,/// Human-readable `workspace/project` label forwarded into the summary.label: String,+ /// Authenticated operator recorded in the `audit_log` row (NULL when+ /// single-user / unauthenticated).+ author_id: Option<ai_memory_core::UserId>,reply: oneshot::Sender<StoreResult<PurgeSummary>>,},/// Delete a workspace row (its `workspace_id` FKs cascade projects/pages/@@ -186,6 +189,9 @@ pub(crate) enum WriteCmd {workspace_id: WorkspaceId,project_id: ProjectId,new_name: String,+ /// Authenticated operator recorded in the `audit_log` row (NULL when+ /// single-user / unauthenticated).+ author_id: Option<ai_memory_core::UserId>,reply: oneshot::Sender<StoreResult<()>>,},/// Record a successfully-applied wiki-structure migration.@@ -627,12 +633,14 @@ impl WriterHandle {workspace_id: WorkspaceId,project_id: ProjectId,label: impl Into<String>,+ author_id: Option<ai_memory_core::UserId>,) -> StoreResult<PurgeSummary> {let (tx, rx) = oneshot::channel();self.send(WriteCmd::PurgeProject {workspace_id,project_id,label: label.into(),+ author_id,reply: tx,}).await?;@@ -723,12 +731,14 @@ impl WriterHandle {workspace_id: WorkspaceId,project_id: ProjectId,new_name: impl Into<String>,+ author_id: Option<ai_memory_core::UserId>,) -> StoreResult<()> {let (tx, rx) = oneshot::channel();self.send(WriteCmd::RenameProject {workspace_id,project_id,new_name: new_name.into(),+ author_id,reply: tx,}).await?;@@ -1214,9 +1224,11 @@ fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {workspace_id,project_id,label,+ author_id,reply,} => {- let result = ops::purge_project(&mut conn, &workspace_id, &project_id, &label);+ let result =+ ops::purge_project(&mut conn, &workspace_id, &project_id, &label, author_id);send_or_warn(reply, result, "purge_project");}WriteCmd::DeleteWorkspace {@@ -1253,9 +1265,16 @@ fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {workspace_id,project_id,new_name,+ author_id,reply,} => {- let result = ops::rename_project(&mut conn, &workspace_id, &project_id, &new_name);+ let result = ops::rename_project(+ &mut conn,+ &workspace_id,+ &project_id,+ &new_name,+ author_id,+ );send_or_warn(reply, result, "rename_project");}WriteCmd::InsertWikiMigration {