Skip to content

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

Rust

feat(store): enforce (workspace_id, project_id) pairing on insert

Djalma Júniorbf1fd4320316
diff --git a/crates/ai-memory-store/migrations/V18__enforce_project_workspace_pairing.sql b/crates/ai-memory-store/migrations/V18__enforce_project_workspace_pairing.sql
new file mode 100644
index 00000000..95ce3eef
--- /dev/null
+++ b/crates/ai-memory-store/migrations/V18__enforce_project_workspace_pairing.sql
@@ -0,0 +1,49 @@
+-- Enforce the (workspace_id, project_id) identity invariant on write.
+--
+-- The schema denormalises workspace_id onto every domain row but only ever
+-- enforced `project_id → projects(id)` and `workspace_id → workspaces(id)`
+-- INDEPENDENTLY — never that the pair is consistent (that the project actually
+-- lives in that workspace). That gap lets a stale writer (e.g. a hook router
+-- whose per-cwd cache still holds the OLD workspace_id for a project that was
+-- just moved to another workspace) silently insert a split-brain row instead
+-- of failing cleanly.
+--
+-- These BEFORE INSERT triggers close the gap: an INSERT whose workspace_id
+-- disagrees with the project's actual workspace ABORTs. The hook router already
+-- evicts its cache and re-resolves on a write error, so a clean abort turns the
+-- worst case (silent corruption) into self-healing.
+--
+-- INSERT only — never UPDATE — so the move-project re-stamp (which UPDATEs
+-- workspace_id across these tables in one transaction) is unaffected.
+
+CREATE TRIGGER pages_ws_proj_pairing_ai
+BEFORE INSERT ON pages
+FOR EACH ROW
+WHEN NEW.workspace_id IS NOT (SELECT workspace_id FROM projects WHERE id = NEW.project_id)
+BEGIN
+ SELECT RAISE(ABORT, 'pages.workspace_id does not match the project''s workspace');
+END;
+
+CREATE TRIGGER sessions_ws_proj_pairing_ai
+BEFORE INSERT ON sessions
+FOR EACH ROW
+WHEN NEW.workspace_id IS NOT (SELECT workspace_id FROM projects WHERE id = NEW.project_id)
+BEGIN
+ SELECT RAISE(ABORT, 'sessions.workspace_id does not match the project''s workspace');
+END;
+
+CREATE TRIGGER observations_ws_proj_pairing_ai
+BEFORE INSERT ON observations
+FOR EACH ROW
+WHEN NEW.workspace_id IS NOT (SELECT workspace_id FROM projects WHERE id = NEW.project_id)
+BEGIN
+ SELECT RAISE(ABORT, 'observations.workspace_id does not match the project''s workspace');
+END;
+
+CREATE TRIGGER handoffs_ws_proj_pairing_ai
+BEFORE INSERT ON handoffs
+FOR EACH ROW
+WHEN NEW.workspace_id IS NOT (SELECT workspace_id FROM projects WHERE id = NEW.project_id)
+BEGIN
+ SELECT RAISE(ABORT, 'handoffs.workspace_id does not match the project''s workspace');
+END;
diff --git a/crates/ai-memory-store/src/ops.rs b/crates/ai-memory-store/src/ops.rs
index ad939ec9..7d23d9e6 100644
--- a/crates/ai-memory-store/src/ops.rs
+++ b/crates/ai-memory-store/src/ops.rs
@@ -2011,4 +2011,81 @@ mod tests {
.unwrap();
assert_eq!(src_pages, 1, "rollback must preserve source pages");
}
+
+ /// V18 integrity triggers: an INSERT whose `workspace_id` disagrees with
+ /// the project's actual workspace ABORTs (the split-brain a stale hook
+ /// cache would otherwise create), while the consistent pair inserts fine.
+ #[test]
+ fn insert_with_mismatched_workspace_is_rejected() {
+ use ai_memory_core::ObservationKind;
+
+ let (_tmp, mut conn, ws, proj) = fresh_db();
+ let other_ws = get_or_create_workspace(&mut conn, "other").unwrap();
+
+ // A page under the WRONG workspace (project lives in `ws`) is refused.
+ let mut bad_page = page(ws, proj, "notes/a.md", "body");
+ bad_page.workspace_id = other_ws;
+ assert!(
+ upsert_page(&mut conn, &bad_page).is_err(),
+ "page insert with mismatched workspace must abort"
+ );
+
+ // The consistent pair inserts fine.
+ upsert_page(&mut conn, &page(ws, proj, "notes/a.md", "body")).unwrap();
+
+ // The session insert is guarded too: a mismatched pair aborts.
+ let bad_sid = SessionId::new();
+ assert!(
+ begin_session(
+ &mut conn,
+ &NewSession {
+ id: bad_sid,
+ workspace_id: other_ws,
+ project_id: proj,
+ agent_kind: AgentKind::ClaudeCode,
+ cwd: None,
+ },
+ )
+ .is_err(),
+ "session insert with mismatched workspace must abort"
+ );
+
+ let sid = SessionId::new();
+ begin_session(
+ &mut conn,
+ &NewSession {
+ id: sid,
+ workspace_id: ws,
+ project_id: proj,
+ agent_kind: AgentKind::ClaudeCode,
+ cwd: None,
+ },
+ )
+ .unwrap();
+
+ // The split-brain case the maintainer flagged: a hook writes an
+ // observation with a stale workspace id for a moved project.
+ let mismatched_obs = NewObservation {
+ session_id: sid,
+ workspace_id: other_ws,
+ project_id: proj,
+ kind: ObservationKind::UserPrompt,
+ extension: None,
+ source_event: None,
+ title: "t".into(),
+ body: "b".into(),
+ importance: 5,
+ };
+ assert!(
+ insert_observation(&mut conn, &mismatched_obs).is_err(),
+ "observation insert with mismatched workspace must abort"
+ );
+
+ // Same observation under the correct workspace is accepted.
+ let good_obs = NewObservation {
+ workspace_id: ws,
+ ..mismatched_obs
+ };
+ insert_observation(&mut conn, &good_obs).unwrap();
+ }
}