Skip to content

Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors

Rust

feat(store): audit-log attribution for delete-page + handoff lifecycle

Djalma Júniora6c78379971c
diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rs
index 88b22e8b..43eadaae 100644
--- a/crates/ai-memory-mcp/src/admin.rs
+++ b/crates/ai-memory-mcp/src/admin.rs
@@ -4411,6 +4411,7 @@ async fn handle_delete_page(
State(state): State<Arc<AdminState>>,
actor_ext: Option<axum::Extension<ai_memory_core::ActorContext>>,
level_ext: Option<axum::Extension<ai_memory_core::AuthLevel>>,
+ author_ext: Option<axum::Extension<ai_memory_core::UserId>>,
headers: HeaderMap,
Json(req): Json<DeletePageAdminRequest>,
) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {
@@ -4451,9 +4452,10 @@ async fn handle_delete_page(
None
};
+ let author_id = author_ext.map(|axum::Extension(u)| u);
state
.wiki
- .delete_page(ws, proj, &path, admission_ctx)
+ .delete_page(ws, proj, &path, admission_ctx, author_id)
.await
.map_err(|e| internal_err(e.to_string()))?;
let checkpoint = checkpoint_or_warn(
diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rs
index 06d27598..935a3c5b 100644
--- a/crates/ai-memory-mcp/src/server.rs
+++ b/crates/ai-memory-mcp/src/server.rs
@@ -2043,7 +2043,8 @@ impl AiMemoryServer {
let pre_checkpoint =
checkpoint_or_mcp(wiki, format!("pre-memory_delete_page: {}", path.as_str()))?;
- wiki.delete_page(ws, proj, &path, admission_ctx)
+ let author_id = crate::actor::author_id_from_parts(&parts);
+ wiki.delete_page(ws, proj, &path, admission_ctx, author_id)
.await
.map_err(|e| McpError::internal_error(e.to_string(), None))?;
let checkpoint = checkpoint_or_warn(wiki, format!("memory_delete_page: {}", path.as_str()));
diff --git a/crates/ai-memory-store/src/ops.rs b/crates/ai-memory-store/src/ops.rs
index 0b1e0c8a..c0ec265b 100644
--- a/crates/ai-memory-store/src/ops.rs
+++ b/crates/ai-memory-store/src/ops.rs
@@ -986,12 +986,29 @@ pub fn soft_delete_for_decay(conn: &mut Connection, page_ids: &[PageId]) -> Stor
/// drop outgoing links + embeddings; the `pages_fts_ad` trigger keeps FTS in
/// sync; incoming links are set to NULL (unresolved). Idempotent.
pub fn delete_page(
- conn: &Connection,
+ conn: &mut Connection,
workspace_id: WorkspaceId,
project_id: ProjectId,
path: &PagePath,
+ author_id: Option<ai_memory_core::UserId>,
) -> StoreResult<()> {
- conn.execute(
+ let tx = conn.transaction()?;
+ // Capture the latest page id BEFORE the delete so the audit row can point
+ // at it. None when the page is absent (delete is an idempotent no-op).
+ let page_id: Option<[u8; 16]> = tx
+ .query_row(
+ "SELECT id FROM pages WHERE workspace_id = ?1 AND project_id = ?2 \
+ AND path = ?3 AND is_latest = 1 LIMIT 1",
+ params![
+ workspace_id.as_bytes(),
+ project_id.as_bytes(),
+ path.as_str()
+ ],
+ |row| row.get::<_, Vec<u8>>(0),
+ )
+ .optional()?
+ .and_then(|v| <[u8; 16]>::try_from(v.as_slice()).ok());
+ let rows = tx.execute(
"DELETE FROM pages WHERE workspace_id = ?1 AND project_id = ?2 AND path = ?3",
params![
workspace_id.as_bytes(),
@@ -999,6 +1016,20 @@ pub fn delete_page(
path.as_str()
],
)?;
+ // Only audit a real deletion — a no-op delete (0 rows) writes nothing, so
+ // the trail isn't polluted with idempotent misses.
+ if rows > 0 {
+ audit(
+ &tx,
+ "delete_page",
+ Some(workspace_id.as_bytes()),
+ Some(project_id.as_bytes()),
+ page_id.as_ref(),
+ author_id.as_ref().map(ai_memory_core::UserId::as_bytes),
+ Timestamp::now().as_microsecond(),
+ )?;
+ }
+ tx.commit()?;
Ok(())
}
@@ -1047,7 +1078,11 @@ pub fn insert_handoff(conn: &mut Connection, h: &NewHandoff) -> StoreResult<Hand
});
let from_agent = h.from_agent.as_str();
let to_agent = h.to_agent.map(AgentKind::as_str);
- conn.execute(
+ // Insert + audit atomically. Handoffs are keyed by agent/session, not a DB
+ // user, so the audit author is NULL — the row records the lifecycle event
+ // (op + workspace/project + time), not an operator identity.
+ let tx = conn.transaction()?;
+ tx.execute(
"INSERT INTO handoffs \
(id, workspace_id, project_id, from_session_id, from_agent, to_agent, cwd, summary, \
open_questions, next_steps, files_touched, state, created_at) \
@@ -1067,9 +1102,45 @@ pub fn insert_handoff(conn: &mut Connection, h: &NewHandoff) -> StoreResult<Hand
now,
],
)?;
+ audit(
+ &tx,
+ "insert_handoff",
+ Some(h.workspace_id.as_bytes()),
+ Some(h.project_id.as_bytes()),
+ None,
+ None,
+ now,
+ )?;
+ tx.commit()?;
Ok(id)
}
+/// A handoff's `(workspace_id, project_id)` as raw 16-byte ids, for tagging
+/// its audit rows. Either component is `None` when the handoff row is absent.
+type HandoffScope = (Option<[u8; 16]>, Option<[u8; 16]>);
+
+/// The `(workspace_id, project_id)` a handoff belongs to, for tagging its
+/// audit rows. `(None, None)` when the handoff row is absent.
+fn handoff_scope(
+ tx: &rusqlite::Transaction<'_>,
+ handoff_id: &HandoffId,
+) -> StoreResult<HandoffScope> {
+ let row = tx
+ .query_row(
+ "SELECT workspace_id, project_id FROM handoffs WHERE id = ?1",
+ params![handoff_id.as_bytes()],
+ |r| Ok((r.get::<_, Vec<u8>>(0)?, r.get::<_, Vec<u8>>(1)?)),
+ )
+ .optional()?;
+ Ok(match row {
+ Some((ws, proj)) => (
+ <[u8; 16]>::try_from(ws.as_slice()).ok(),
+ <[u8; 16]>::try_from(proj.as_slice()).ok(),
+ ),
+ None => (None, None),
+ })
+}
+
/// Mark a handoff accepted by `accepting_agent` / `accepting_session`.
pub fn accept_handoff(
conn: &mut Connection,
@@ -1080,21 +1151,51 @@ pub fn accept_handoff(
let now = Timestamp::now().as_microsecond();
let agent = accepting_agent.as_str();
let session: Option<&[u8]> = accepting_session.map(|s| &s.as_bytes()[..]);
- conn.execute(
+ let tx = conn.transaction()?;
+ let (ws, proj) = handoff_scope(&tx, handoff_id)?;
+ let changed = tx.execute(
"UPDATE handoffs SET state = 'accepted', accepted_by = ?1, accepted_at = ?2, \
accepted_by_session = ?3 \
WHERE id = ?4 AND state = 'open'",
params![agent, now, session, handoff_id.as_bytes()],
)?;
+ // Only a real state transition ('open' -> 'accepted') is audited.
+ if changed > 0 {
+ audit(
+ &tx,
+ "accept_handoff",
+ ws.as_ref(),
+ proj.as_ref(),
+ None,
+ None,
+ now,
+ )?;
+ }
+ tx.commit()?;
Ok(())
}
/// Mark an open handoff expired so it will no longer be consumed.
pub fn cancel_handoff(conn: &mut Connection, handoff_id: &HandoffId) -> StoreResult<bool> {
- let changed = conn.execute(
+ let now = Timestamp::now().as_microsecond();
+ let tx = conn.transaction()?;
+ let (ws, proj) = handoff_scope(&tx, handoff_id)?;
+ let changed = tx.execute(
"UPDATE handoffs SET state = 'expired' WHERE id = ?1 AND state = 'open'",
params![handoff_id.as_bytes()],
)?;
+ if changed > 0 {
+ audit(
+ &tx,
+ "cancel_handoff",
+ ws.as_ref(),
+ proj.as_ref(),
+ None,
+ None,
+ now,
+ )?;
+ }
+ tx.commit()?;
Ok(changed > 0)
}
@@ -2307,6 +2408,53 @@ mod tests {
assert!(second.is_ok(), "double-accept must not error");
}
+ /// The handoff lifecycle (insert / accept / cancel) writes audit rows,
+ /// scoped to the handoff's workspace/project, with a NULL author (handoffs
+ /// are agent/session-keyed, not owned by a DB user).
+ #[test]
+ fn audit_log_records_handoff_lifecycle_with_null_author() {
+ let (_tmp, mut conn, ws, proj) = fresh_db();
+ let new = || NewHandoff {
+ workspace_id: ws,
+ project_id: proj,
+ from_session_id: None,
+ from_agent: AgentKind::ClaudeCode,
+ to_agent: None,
+ cwd: None,
+ summary: "s".into(),
+ open_questions: vec![],
+ next_steps: vec![],
+ files_touched: vec![],
+ };
+ let id = insert_handoff(&mut conn, &new()).unwrap();
+ accept_handoff(&mut conn, &id, AgentKind::Codex, None).unwrap();
+ let id2 = insert_handoff(&mut conn, &new()).unwrap();
+ assert!(cancel_handoff(&mut conn, &id2).unwrap());
+
+ for op in ["insert_handoff", "accept_handoff", "cancel_handoff"] {
+ let (count, author) = audit_row_for(&conn, op);
+ assert!(count >= 1, "{op} must be audited");
+ assert!(author.is_none(), "{op} audit author must be NULL");
+ }
+ assert_eq!(
+ audit_row_for(&conn, "insert_handoff").0,
+ 2,
+ "two inserts → two rows"
+ );
+ let ws_bytes: Option<Vec<u8>> = conn
+ .query_row(
+ "SELECT workspace_id FROM audit_log WHERE op = 'accept_handoff'",
+ [],
+ |r| r.get(0),
+ )
+ .unwrap();
+ assert_eq!(
+ ws_bytes.as_deref(),
+ Some(&ws.as_bytes()[..]),
+ "handoff audit is scoped to its workspace"
+ );
+ }
+
/// The stored cwd is normalized (trailing path separator stripped) at insert time
/// so trailing-slash drift between agent payloads cannot break the next
/// session's path-boundary match. Covers both manual and auto handoffs,
@@ -3736,6 +3884,57 @@ mod tests {
assert_eq!(count, 0, "a rolled-back rename must leave no audit row");
}
+ /// Deleting an existing page writes ONE attributed `delete_page` audit row
+ /// pointing at the deleted page id — the "who deleted the gotcha page?"
+ /// case V16 names.
+ #[test]
+ fn audit_log_records_delete_page_with_author_and_page_id() {
+ let (_tmp, mut conn, ws, proj) = fresh_db();
+ let author = seed_user(&conn, "dave");
+ let pid = upsert_page(&mut conn, &page(ws, proj, "notes/doomed.md", "body")).unwrap();
+
+ delete_page(
+ &mut conn,
+ ws,
+ proj,
+ &PagePath::new("notes/doomed.md").unwrap(),
+ Some(author),
+ )
+ .unwrap();
+
+ let (count, op_author) = audit_row_for(&conn, "delete_page");
+ assert_eq!(count, 1, "exactly one delete_page audit row");
+ assert_eq!(op_author.as_deref(), Some(&author.as_bytes()[..]));
+ let page_id: Option<Vec<u8>> = conn
+ .query_row(
+ "SELECT page_id FROM audit_log WHERE op = 'delete_page'",
+ [],
+ |r| r.get(0),
+ )
+ .unwrap();
+ assert_eq!(
+ page_id.as_deref(),
+ Some(&pid.as_bytes()[..]),
+ "audit row must point at the deleted page id"
+ );
+ }
+
+ /// A delete that matches no row (idempotent no-op) writes NO audit row.
+ #[test]
+ fn audit_log_omits_delete_page_noop() {
+ let (_tmp, mut conn, ws, proj) = fresh_db();
+ delete_page(
+ &mut conn,
+ ws,
+ proj,
+ &PagePath::new("notes/ghost.md").unwrap(),
+ None,
+ )
+ .unwrap();
+ let (count, _) = audit_row_for(&conn, "delete_page");
+ assert_eq!(count, 0, "a no-op delete 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 as
diff --git a/crates/ai-memory-store/src/writer.rs b/crates/ai-memory-store/src/writer.rs
index 2df07135..336918b8 100644
--- a/crates/ai-memory-store/src/writer.rs
+++ b/crates/ai-memory-store/src/writer.rs
@@ -68,6 +68,9 @@ pub(crate) enum WriteCmd {
workspace_id: WorkspaceId,
project_id: ProjectId,
path: PagePath,
+ /// Authenticated operator recorded in the `audit_log` row (NULL when
+ /// single-user / unauthenticated).
+ author_id: Option<ai_memory_core::UserId>,
reply: oneshot::Sender<StoreResult<()>>,
},
BeginSession {
@@ -825,12 +828,14 @@ impl WriterHandle {
workspace_id: WorkspaceId,
project_id: ProjectId,
path: PagePath,
+ author_id: Option<ai_memory_core::UserId>,
) -> StoreResult<()> {
let (tx, rx) = oneshot::channel();
self.send(WriteCmd::DeletePage {
workspace_id,
project_id,
path,
+ author_id,
reply: tx,
})
.await?;
@@ -1099,9 +1104,11 @@ fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {
workspace_id,
project_id,
path,
+ author_id,
reply,
} => {
- let result = ops::delete_page(&conn, workspace_id, project_id, &path);
+ let result =
+ ops::delete_page(&mut conn, workspace_id, project_id, &path, author_id);
send_or_warn(reply, result, "delete_page");
}
WriteCmd::UpsertPageBatch { pages, reply } => {
diff --git a/crates/ai-memory-wiki/src/wiki.rs b/crates/ai-memory-wiki/src/wiki.rs
index 4a16458b..1a819f14 100644
--- a/crates/ai-memory-wiki/src/wiki.rs
+++ b/crates/ai-memory-wiki/src/wiki.rs
@@ -459,6 +459,7 @@ impl Wiki {
project_id: ProjectId,
path: &PagePath,
admission_ctx: Option<AdmissionContext>,
+ author_id: Option<ai_memory_core::UserId>,
) -> WikiResult<()> {
let _guard = self.mutation_lock.read().await;
self.ensure_project_workspace(workspace_id, project_id)
@@ -482,7 +483,7 @@ impl Wiki {
let delete_result = self
.writer
- .delete_page(workspace_id, project_id, path.clone())
+ .delete_page(workspace_id, project_id, path.clone(), author_id)
.await;
if let Err(e) = delete_result {
if let Some(quarantine) = &quarantined