Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(store): harden agent sessions and FTS queries
AkitaOnRailsef50d2709661
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6375168f..f9bd5616 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -57,6 +57,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- Docker images now bundle both POSIX and PowerShell hook scripts.### Fixed+- Session capture now persists every documented agent kind (`cursor`,+ `gemini-cli`, `claude-desktop`, `openclaw`, `omp` / `pi`) instead of+ failing the `sessions.agent_kind` database CHECK for agents added after+ the initial schema.+- `memory_handoff_begin` and `memory_handoff_accept` now resolve the active+ project the same way the briefing/search tools do, so MCP handoffs land in+ the project currently reported by hooks instead of the server's baked+ default project.+- Natural-language `memory_query` text containing bare colons, such as+ `pick: handoff`, no longer trips FTS5 column syntax errors while explicit+ FTS operators like `quick OR slow` remain supported.- Marker-file routing now reaches the generated OpenCode and OMPTypeScript hook integrations, not only the POSIX/PowerShell scripthooks. POSIX helpers also preserve the outer hook `cwd` when nesteddiff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rsindex 4a28be64..d4e38936 100644--- a/crates/ai-memory-mcp/src/server.rs+++ b/crates/ai-memory-mcp/src/server.rs@@ -1260,7 +1260,7 @@ mod tests {/// `memory_briefing` when hooks publish `ActiveProject` (issue #2).#[tokio::test]async fn handoff_begin_pending_count_matches_briefing_active_project() {- let (_tmp, store, mut server, ws, baked) = setup_server().await;+ let (_tmp, store, server, ws, baked) = setup_server().await;let active = store.writer.get_or_create_project(ws, "ai-memory", Some(r"C:\GIT\ai-memory".into()))diff --git a/crates/ai-memory-store/migrations/V07__agent_kind_omp.sql b/crates/ai-memory-store/migrations/V09__sessions_supported_agent_kinds.sqlsimilarity index 62%rename from crates/ai-memory-store/migrations/V07__agent_kind_omp.sqlrename to crates/ai-memory-store/migrations/V09__sessions_supported_agent_kinds.sqlindex b5b4e197..097a5785 100644--- a/crates/ai-memory-store/migrations/V07__agent_kind_omp.sql+++ b/crates/ai-memory-store/migrations/V09__sessions_supported_agent_kinds.sql@@ -1,9 +1,8 @@--- Expand sessions.agent_kind CHECK to include `omp` (Oh My Pi / pi hooks).+-- Expand sessions.agent_kind CHECK to include every currently supported agent.----- Hook payloads send `agent=pi` (or `omp`), parsed to AgentKind::Omp and--- persisted as the wire string `omp`. V01 only allowed claude-code/codex/--- open-code/other, so every pi hook tripped:--- CHECK constraint failed: agent_kind IN (...)+-- V01 only allowed claude-code/codex/open-code/other. Hook payloads now parse+-- Cursor, Gemini CLI, Claude Desktop, OpenClaw, and OMP/Pi into concrete+-- AgentKind values, so persisting those sessions must not trip the CHECK.PRAGMA foreign_keys = OFF;@@ -11,7 +10,7 @@ CREATE TABLE sessions_new (id BLOB PRIMARY KEY NOT NULL,workspace_id BLOB NOT NULL REFERENCES workspaces(id) ON DELETE CASCADE,project_id BLOB NOT NULL REFERENCES projects(id) ON DELETE CASCADE,- agent_kind TEXT NOT NULL CHECK (agent_kind IN ('claude-code','codex','open-code','omp','other')),+ agent_kind TEXT NOT NULL CHECK (agent_kind IN ('claude-code','codex','open-code','cursor','gemini-cli','claude-desktop','openclaw','omp','other')),cwd TEXT,started_at INTEGER NOT NULL,ended_at INTEGER,@@ -26,5 +25,6 @@ ALTER TABLE sessions_new RENAME TO sessions;CREATE INDEX idx_sessions_recent ON sessions(workspace_id, project_id, started_at DESC);CREATE INDEX idx_sessions_project ON sessions(project_id);+CREATE INDEX idx_sessions_started_at ON sessions(started_at DESC);PRAGMA foreign_keys = ON;diff --git a/crates/ai-memory-store/src/fts_query.rs b/crates/ai-memory-store/src/fts_query.rsindex 1d108dd2..4d968b2a 100644--- a/crates/ai-memory-store/src/fts_query.rs+++ b/crates/ai-memory-store/src/fts_query.rs@@ -1,9 +1,10 @@//! FTS5 `MATCH` query preparation for user/agent-supplied search text.//!//! FTS5 treats `column:term` as a column-qualified search. Natural-language-//! queries that contain colons (`pick: handoff`, `memory: bootstrap`) make+//! queries that contain bare colons (`pick: handoff`, `memory: bootstrap`) make//! SQLite error with `no such column: pick` because only `title` and `body`-//! exist on `pages_fts`. Colons are neutralised before each token is quoted.+//! exist on the FTS tables. Unknown bare column syntax is neutralised without+//! discarding deliberate FTS operators such as `OR`./// Sanitize free-text for use in `WHERE pages_fts MATCH ?`.///@@ -11,20 +12,40 @@/// should skip the SQL query in that case.#[must_use]pub fn prepare_fts5_query(raw: &str) -> String {- // Turn `pick:` / `memory:` into separate tokens so we never emit FTS5- // column syntax, while still matching indexed words (`pick`, `memory`).- let normalized: String = raw- .chars()- .map(|c| if c == ':' { ' ' } else { c })- .collect();- let tokens: Vec<String> = normalized+ let tokens: Vec<String> = raw.split_whitespace()- .filter(|t| !t.is_empty())- .map(quote_fts5_token)+ .flat_map(prepare_fts5_token).collect();tokens.join(" ")}+fn prepare_fts5_token(token: &str) -> Vec<String> {+ if has_unknown_bare_column(token) {+ return token+ .replace(':', " ")+ .split_whitespace()+ .map(quote_fts5_token)+ .collect();+ }++ if should_quote_fts5_token(token) {+ vec![quote_fts5_token(token)]+ } else {+ vec![token.to_string()]+ }+}++fn has_unknown_bare_column(token: &str) -> bool {+ token.contains(':')+ && !token.contains('"')+ && !token.starts_with("title:")+ && !token.starts_with("body:")+}++fn should_quote_fts5_token(token: &str) -> bool {+ token.contains('-') && !(token.starts_with('"') && token.ends_with('"'))+}+fn quote_fts5_token(token: &str) -> String {// FTS5 escapes `"` inside a quoted token by doubling it.let escaped = token.replace('"', "\"\"");@@ -38,7 +59,7 @@ mod tests {#[test]fn colon_is_not_column_syntax() {let q = prepare_fts5_query("pick: handoff ai-memory");- assert_eq!(q, "\"pick\" \"handoff\" \"ai-memory\"");+ assert_eq!(q, "\"pick\" handoff \"ai-memory\"");}#[test]@@ -48,7 +69,17 @@ mod tests {#[test]fn quotes_are_escaped() {- let q = prepare_fts5_query(r#"say "hello""#);- assert_eq!(q, r#""say" """hello""""#);+ let q = quote_fts5_token(r#"say "hello""#);+ assert_eq!(q, r#""say ""hello""""#);+ }++ #[test]+ fn boolean_operators_are_preserved() {+ assert_eq!(prepare_fts5_query("quick OR slow"), "quick OR slow");+ }++ #[test]+ fn known_columns_are_preserved() {+ assert_eq!(prepare_fts5_query("title:handoff"), "title:handoff");}}diff --git a/crates/ai-memory-store/src/lib.rs b/crates/ai-memory-store/src/lib.rsindex 6ed33f56..13fe68a3 100644--- a/crates/ai-memory-store/src/lib.rs+++ b/crates/ai-memory-store/src/lib.rs@@ -351,6 +351,34 @@ mod tests {);}+ #[tokio::test]+ async fn search_boolean_or_still_works() {+ let tmp = TempDir::new().unwrap();+ let store = Store::open(tmp.path()).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();+ store+ .writer+ .upsert_page(sample_page(ws, proj, "quick.md", "quick answer"))+ .await+ .unwrap();++ let hits = store+ .reader+ .search_pages("quick OR slow".into(), 10)+ .await+ .unwrap();+ assert!(!hits.is_empty(), "OR must remain an FTS5 operator");+ }+#[tokio::test]async fn search_quotes_hyphenated_tokens_for_fts5() {let tmp = TempDir::new().unwrap();diff --git a/crates/ai-memory-store/src/ops.rs b/crates/ai-memory-store/src/ops.rsindex c1b0f810..3c24e59f 100644--- a/crates/ai-memory-store/src/ops.rs+++ b/crates/ai-memory-store/src/ops.rs@@ -1031,32 +1031,44 @@ mod tests {assert!(second.is_ok(), "double-accept must not error");}- /// Pi / OMP hooks persist `agent_kind = 'omp'`. V01's CHECK omitted- /// that value; regression for the hook-router WARN on every event.+ /// Supported hook agents persist concrete agent_kind values. V01's CHECK+ /// omitted agents added after launch; regression for hook-router WARNs.#[test]- fn begin_session_accepts_omp_agent_kind() {+ fn begin_session_accepts_all_supported_agent_kinds() {let (_tmp, mut conn, ws, proj) = fresh_db();- let sid = SessionId::new();- begin_session(- &mut conn,- &NewSession {- id: sid,- workspace_id: ws,- project_id: proj,- agent_kind: AgentKind::Omp,- cwd: Some(std::path::PathBuf::from(r"C:\GIT\ai-memory")),- },- )- .unwrap();-- let stored: String = conn- .query_row(- "SELECT agent_kind FROM sessions WHERE id = ?1",- params![&sid.as_bytes()[..]],- |r| r.get(0),+ for agent_kind in [+ AgentKind::ClaudeCode,+ AgentKind::Codex,+ AgentKind::OpenCode,+ AgentKind::Cursor,+ AgentKind::GeminiCli,+ AgentKind::ClaudeDesktop,+ AgentKind::OpenClaw,+ AgentKind::Omp,+ AgentKind::Other,+ ] {+ let sid = SessionId::new();+ begin_session(+ &mut conn,+ &NewSession {+ id: sid,+ workspace_id: ws,+ project_id: proj,+ agent_kind,+ cwd: Some(std::path::PathBuf::from(r"C:\GIT\ai-memory")),+ },).unwrap();- assert_eq!(stored, "omp");++ let stored: String = conn+ .query_row(+ "SELECT agent_kind FROM sessions WHERE id = ?1",+ params![&sid.as_bytes()[..]],+ |r| r.get(0),+ )+ .unwrap();+ assert_eq!(stored, agent_kind.as_str());+ }}/// end_session links the synthesised summary page so callers candiff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rsindex 7a0c4908..afa55bae 100644--- a/crates/ai-memory-store/src/reader.rs+++ b/crates/ai-memory-store/src/reader.rs@@ -361,7 +361,10 @@ impl ReaderPool {query: String,limit: usize,) -> StoreResult<Vec<PageHitWithMeta>> {- let query = normalize_fts_query(&query);+ let fts_query = normalize_fts_query(&query);+ if fts_query.is_empty() {+ return Ok(Vec::new());+ }self.with_conn(move |conn| {let mut stmt = conn.prepare_cached("SELECT workspaces.name, projects.name, pages.path, pages.title, \@@ -376,7 +379,7 @@ impl ReaderPool {LIMIT ?2",)?;#[allow(clippy::cast_possible_wrap)]- let rows = stmt.query_map(params![query, limit as i64], |row| {+ let rows = stmt.query_map(params![fts_query, limit as i64], |row| {let workspace_name: String = row.get(0)?;let project_name: String = row.get(1)?;let path: String = row.get(2)?;@@ -477,7 +480,10 @@ impl ReaderPool {query: String,limit: usize,) -> StoreResult<Vec<ObservationHit>> {- let query = normalize_fts_query(&query);+ let fts_query = normalize_fts_query(&query);+ if fts_query.is_empty() {+ return Ok(Vec::new());+ }self.with_conn(move |conn| {let mut stmt = conn.prepare("SELECT observations.id, observations.session_id, observations.kind, \@@ -495,7 +501,7 @@ impl ReaderPool {#[allow(clippy::cast_possible_wrap)]let rows = stmt.query_map(params![- query,+ fts_query,workspace_id.as_bytes(),project_id.as_bytes(),limit as i64,