Skip to content

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

Rust

feat(attribution): post-P1.8 follow-ups — web UI chip + audit_log.author_id

AkitaOnRailsa851a5cd3d22
diff --git a/crates/ai-memory-store/migrations/V16__audit_log_author_id.sql b/crates/ai-memory-store/migrations/V16__audit_log_author_id.sql
new file mode 100644
index 00000000..101e021f
--- /dev/null
+++ b/crates/ai-memory-store/migrations/V16__audit_log_author_id.sql
@@ -0,0 +1,34 @@
+-- Operator-level attribution on the audit log.
+--
+-- V15 added `pages.author_id` so the latest version of every page
+-- can be JOINed to its author for read paths (`/api/v1`, `/web`).
+-- The audit log is a separate, append-only trail: every mutating op
+-- (page upserts including supersession, retention soft-delete, etc.)
+-- writes one row tagged with workspace/project/page + op + timestamp.
+--
+-- Without an author column on `audit_log`, queries like "who
+-- expired alice's token last week?" or "which user soft-deleted the
+-- gotcha page about X?" have to cross-reference the page row's
+-- current author — but that's the LATEST author, not the one at the
+-- time of the op (a page that was anonymous when soft-deleted but
+-- since attributed to alice would falsely surface alice). Putting
+-- the author on the audit row itself preserves point-in-time truth.
+--
+-- ON DELETE SET NULL matches V15: if an operator ever hard-deletes
+-- a `users` row (which `ai-memory user expire` does NOT do — see
+-- docs/users.md — but a future `purge` op could), the audit trail's
+-- timestamp + op + page reference all survive; only the
+-- "who did it" anchor becomes NULL, which the API surfaces by
+-- omitting the `author` field rather than emitting `null`.
+
+ALTER TABLE audit_log
+ ADD COLUMN author_id BLOB
+ REFERENCES users(id) ON DELETE SET NULL;
+
+-- Lookup pattern used by future "events by author" queries:
+-- `WHERE author_id = ? ORDER BY at DESC LIMIT N`. Partial index
+-- keeps the cost off the (overwhelming majority of) NULL-author
+-- rows, matching the V15 idx_pages_author shape.
+CREATE INDEX idx_audit_log_author
+ ON audit_log(author_id, at DESC)
+ WHERE author_id IS NOT NULL;
diff --git a/crates/ai-memory-store/src/ops.rs b/crates/ai-memory-store/src/ops.rs
index 843aaa3e..70258c1e 100644
--- a/crates/ai-memory-store/src/ops.rs
+++ b/crates/ai-memory-store/src/ops.rs
@@ -248,6 +248,9 @@ fn upsert_page_in_tx(
Some(page.workspace_id.as_bytes()),
Some(page.project_id.as_bytes()),
Some(new_id.as_bytes()),
+ page.author_id
+ .as_ref()
+ .map(ai_memory_core::UserId::as_bytes),
now,
)?;
return Ok(new_id);
@@ -281,6 +284,9 @@ fn upsert_page_in_tx(
Some(page.workspace_id.as_bytes()),
Some(page.project_id.as_bytes()),
Some(new_id.as_bytes()),
+ page.author_id
+ .as_ref()
+ .map(ai_memory_core::UserId::as_bytes),
now,
)?;
Ok(new_id)
@@ -640,6 +646,9 @@ pub fn soft_delete_for_decay(conn: &mut Connection, page_ids: &[PageId]) -> Stor
None,
None,
None,
+ // Decay sweep is a system op (scheduled / admin-triggered) — no
+ // user-attributable actor at the row level.
+ None,
Timestamp::now().as_microsecond(),
)?;
tx.commit()?;
@@ -730,17 +739,19 @@ fn audit(
workspace_id: Option<&[u8; 16]>,
project_id: Option<&[u8; 16]>,
page_id: Option<&[u8; 16]>,
+ author_id: Option<&[u8; 16]>,
at: i64,
) -> StoreResult<()> {
tx.execute(
- "INSERT INTO audit_log (at, op, workspace_id, project_id, page_id, detail) \
- VALUES (?1, ?2, ?3, ?4, ?5, '{}')",
+ "INSERT INTO audit_log (at, op, workspace_id, project_id, page_id, author_id, detail) \
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, '{}')",
params![
at,
op,
workspace_id.map(|b| &b[..]),
project_id.map(|b| &b[..]),
- page_id.map(|b| &b[..])
+ page_id.map(|b| &b[..]),
+ author_id.map(|b| &b[..]),
],
)?;
Ok(())
@@ -1060,6 +1071,114 @@ mod tests {
/// produce a NEW row and mark the previous row `is_latest = 0`.
/// This is the M7 supersession chain — the entire wiki versioning
/// guarantee rides on it.
+ /// V16: every page write lands an `audit_log` row whose
+ /// `author_id` mirrors the NewPage's. Anonymous writes leave it
+ /// NULL (the entire audit-log-by-author query pattern relies on
+ /// the partial index covering only the non-NULL minority).
+ #[test]
+ fn audit_log_records_author_for_attributed_create_page() {
+ use ai_memory_core::UserId;
+
+ let (_tmp, mut conn, ws, proj) = fresh_db();
+
+ // Seed a synthetic user row so the FK on author_id resolves.
+ let user_id = UserId::new();
+ let now = jiff::Timestamp::now().as_microsecond();
+ conn.execute(
+ "INSERT INTO users \
+ (id, username, name, email, token_hash, created_at) \
+ VALUES (?1, 'alice', NULL, NULL, X'00', ?2)",
+ params![user_id.as_bytes(), now],
+ )
+ .unwrap();
+
+ let mut np = page(ws, proj, "notes/by-alice.md", "alice body");
+ np.author_id = Some(user_id);
+ let page_id = upsert_page(&mut conn, &np).unwrap();
+
+ let author_bytes: Vec<u8> = conn
+ .query_row(
+ "SELECT author_id FROM audit_log \
+ WHERE op = 'create_page' AND page_id = ?1",
+ params![page_id.as_bytes()],
+ |r| r.get(0),
+ )
+ .unwrap();
+ let recorded = UserId::from_slice(&author_bytes).unwrap();
+ assert_eq!(
+ recorded, user_id,
+ "create_page audit row must carry the writer's user_id"
+ );
+ }
+
+ /// Backward-compat gate (and the headline of the "no behaviour
+ /// change for legacy installs" promise): anonymous writes leave
+ /// audit_log.author_id NULL — the partial index stays empty for
+ /// pre-multi-user history.
+ #[test]
+ fn audit_log_records_null_author_for_anonymous_create_page() {
+ let (_tmp, mut conn, ws, proj) = fresh_db();
+ let np = page(ws, proj, "notes/anon.md", "anon body");
+ assert!(np.author_id.is_none());
+ let page_id = upsert_page(&mut conn, &np).unwrap();
+
+ let author: Option<Vec<u8>> = conn
+ .query_row(
+ "SELECT author_id FROM audit_log \
+ WHERE op = 'create_page' AND page_id = ?1",
+ params![page_id.as_bytes()],
+ |r| r.get(0),
+ )
+ .unwrap();
+ assert!(
+ author.is_none(),
+ "anonymous writes must record audit_log.author_id = NULL"
+ );
+ }
+
+ /// Supersession rows carry the SUPERSEDING author, not the
+ /// original. Two consecutive attributed writes (alice then bob)
+ /// yield a create_page row tagged alice and a supersede_page row
+ /// tagged bob — point-in-time truth, not "latest author".
+ #[test]
+ fn audit_log_supersede_records_new_authors_identity() {
+ use ai_memory_core::UserId;
+
+ let (_tmp, mut conn, ws, proj) = fresh_db();
+ let now = jiff::Timestamp::now().as_microsecond();
+ let alice = UserId::new();
+ let bob = UserId::new();
+ conn.execute(
+ "INSERT INTO users (id, username, name, email, token_hash, created_at) \
+ VALUES (?1, 'alice', NULL, NULL, X'01', ?2), \
+ (?3, 'bob', NULL, NULL, X'02', ?2)",
+ params![alice.as_bytes(), now, bob.as_bytes()],
+ )
+ .unwrap();
+
+ let mut np1 = page(ws, proj, "notes/shared.md", "v1");
+ np1.author_id = Some(alice);
+ upsert_page(&mut conn, &np1).unwrap();
+
+ let mut np2 = page(ws, proj, "notes/shared.md", "v2 — different body");
+ np2.author_id = Some(bob);
+ let v2_id = upsert_page(&mut conn, &np2).unwrap();
+
+ let bob_bytes: Vec<u8> = conn
+ .query_row(
+ "SELECT author_id FROM audit_log \
+ WHERE op = 'supersede_page' AND page_id = ?1",
+ params![v2_id.as_bytes()],
+ |r| r.get(0),
+ )
+ .unwrap();
+ assert_eq!(
+ UserId::from_slice(&bob_bytes).unwrap(),
+ bob,
+ "supersede_page audit row must carry the SUPERSEDING author"
+ );
+ }
+
#[test]
fn upsert_page_supersedes_on_body_change() {
let (_tmp, mut conn, ws, proj) = fresh_db();
diff --git a/crates/ai-memory-web/src/routes/page.rs b/crates/ai-memory-web/src/routes/page.rs
index b25cf2ac..112f575d 100644
--- a/crates/ai-memory-web/src/routes/page.rs
+++ b/crates/ai-memory-web/src/routes/page.rs
@@ -48,6 +48,17 @@ pub(crate) async fn handler(
page_href(&workspace, &project, &supersedes_path)
};
+ let (author_username, author_name, author_email) = meta.author.map_or_else(
+ || (String::new(), String::new(), String::new()),
+ |a| {
+ (
+ a.username,
+ a.name.unwrap_or_default(),
+ a.email.unwrap_or_default(),
+ )
+ },
+ );
+
match (PageView {
workspace,
project,
@@ -62,6 +73,9 @@ pub(crate) async fn handler(
supersedes_path,
supersedes_href,
body_html,
+ author_username,
+ author_name,
+ author_email,
}
.render())
{
diff --git a/crates/ai-memory-web/src/templates.rs b/crates/ai-memory-web/src/templates.rs
index 4db4e846..a39af327 100644
--- a/crates/ai-memory-web/src/templates.rs
+++ b/crates/ai-memory-web/src/templates.rs
@@ -188,6 +188,18 @@ pub(crate) struct PageView {
pub supersedes_href: String,
/// Rendered markdown body (HTML, trusted).
pub body_html: String,
+ /// Username of the page's last author. Empty string when the page
+ /// was authored anonymously / by root / pre-multi-user — the
+ /// template uses the empty check to omit the "Last edited by"
+ /// chip entirely, so legacy pages render with the exact same
+ /// chrome they had before v0.8.
+ pub author_username: String,
+ /// Optional display name shown in parens after the username
+ /// (e.g. `alice (Alice Smith)`). Empty when not set on the user row.
+ pub author_name: String,
+ /// Optional email rendered as a `mailto:` link after the username.
+ /// Empty when not set on the user row.
+ pub author_email: String,
}
// ---------------------------------------------------------------------------
diff --git a/crates/ai-memory-web/templates/page.html b/crates/ai-memory-web/templates/page.html
index ee1bbdcf..9d4691d9 100644
--- a/crates/ai-memory-web/templates/page.html
+++ b/crates/ai-memory-web/templates/page.html
@@ -34,6 +34,15 @@
<span>·</span>
<span>Supersedes <a href="{{ supersedes_href }}" class="text-blue-600 dark:text-blue-400 underline">{{ supersedes_path }}</a></span>
{% endif %}
+ {% if author_username != "" %}
+ <span>·</span>
+ <span>
+ Last edited by
+ <span class="font-medium text-slate-700 dark:text-slate-300">{{ author_username }}</span>
+ {% if author_name != "" %}<span class="text-slate-500 dark:text-slate-500">({{ author_name }})</span>{% endif %}
+ {% if author_email != "" %}<a href="mailto:{{ author_email }}" class="text-blue-600 dark:text-blue-400 underline">{{ author_email }}</a>{% endif %}
+ </span>
+ {% endif %}
</div>
<!-- Rendered markdown body -->
diff --git a/crates/ai-memory-web/tests/routes.rs b/crates/ai-memory-web/tests/routes.rs
index bd734284..0484316c 100644
--- a/crates/ai-memory-web/tests/routes.rs
+++ b/crates/ai-memory-web/tests/routes.rs
@@ -173,6 +173,121 @@ async fn smoke_page_view_returns_200() {
assert!(text.contains("Hello world"), "expected rendered body");
}
+// ── /web HTML chrome for multi-user attribution ──────────────────────
+
+#[tokio::test]
+async fn web_page_view_omits_author_chrome_for_anonymous_pages() {
+ // Backward-compat gate: a page written without an actor (every
+ // pre-v0.8 caller built this shape, and every internal caller
+ // that isn't an HTTP request still does) must render with the
+ // exact "Updated · Created" metadata chip layout it had before
+ // multi-user landed — no "Last edited by …" chip, no email
+ // link, nothing.
+ 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", "anon body"))
+ .await
+ .unwrap();
+
+ let app = router(store.reader.clone(), wiki.clone());
+ let resp = app
+ .oneshot(
+ Request::builder()
+ .uri("/w/default/scratch/p/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 text = std::str::from_utf8(&body).unwrap();
+ assert!(
+ !text.contains("Last edited by"),
+ "anonymous page must NOT render the author chip — backward compat"
+ );
+}
+
+#[tokio::test]
+async fn web_page_view_renders_author_chip_for_attributed_pages() {
+ 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: 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 body");
+ 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 = router(store.reader.clone(), wiki.clone());
+ let resp = app
+ .oneshot(
+ Request::builder()
+ .uri("/w/default/scratch/p/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 text = std::str::from_utf8(&body).unwrap();
+ assert!(
+ text.contains("Last edited by"),
+ "attributed page must render the author chip"
+ );
+ assert!(text.contains("alice"), "username must appear in the chip");
+ assert!(
+ text.contains("Alice Smith"),
+ "display name must appear when set"
+ );
+ assert!(
+ text.contains("mailto:alice@home"),
+ "email must be a mailto: link"
+ );
+}
+
#[tokio::test]
async fn smoke_search_returns_200() {
let (_tmp, store, wiki) = setup().await;