The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
fix(memory): preserve token-and search after merge
Steven Enamakele8c7f39f87a4
diff --cc src/openhuman/mcp/server/tools/specs.rsindex 044da417ef,2958356f09..b204aefc70--- a/src/openhuman/mcp/server/tools/specs.rs+++ b/src/openhuman/mcp/server/tools/specs.rs@@@ -115,7 -107,7 +115,9 @@@ pub fn base_tool_specs() -> Vec<McpTooltitle: "Browse Memory",description: "Paginated listing of memory-tree chunks in reverse-chronological order, \with optional filters by source kind, source id, entity id, time window, \-- and substring keyword. Use this when the user wants to enumerate (\"what's \++ and token-AND keyword. Every whitespace-separated token must appear in the \++ chunk (case-insensitive, any order; punctuation does not matter). Use this \++ when the user wants to enumerate (\"what's \recent in my Gmail\", \"show me everything from last week about Alice\") \rather than search by query. Returns chunks plus a total match count for \pagination.",@@@ -317,7 -309,7 +319,7 @@@ fn tree_browse_schema() -> Value"query": {"type": "string","minLength": 1,-- "description": "Substring keyword filter over the chunk preview text."++ "description": "Space-separated keywords; every token must appear in the chunk (case-insensitive, any order; punctuation does not matter)."},"k": {"type": "integer",diff --cc src/openhuman/memory/read_rpc/chunks.rsindex 999a308aa4,25454d675d..bac497cd90--- a/src/openhuman/memory/read_rpc/chunks.rs+++ b/src/openhuman/memory/read_rpc/chunks.rs@@@ -1,9 -1,13 +1,13 @@@- use anyhow::{Context, Result};+ use anyhow::Result;+ use std::collections::{HashMap, HashSet};use crate::openhuman::config::Config;- use crate::openhuman::memory::tree::retrieval::types::NodeKind;+ use crate::openhuman::memory::api::provider::retrieval::{+ RetrievalNodeKind, RetrievalResponse, SourceRetrievalQuery,+ };-use crate::openhuman::memory::api::provider::{ChunkListRow, ChunkQuery};++use crate::openhuman::memory::api::provider::{ChunkListRow, ChunkQuery, MemoryChunks};use crate::rpc::RpcOutcome;- use tinymemory_core::store::chunks::store::with_connection;+ use tinymemory_api::chunks::SourceKind;use super::types::{ChunkFilter, ChunkRow, ListChunksResponse, RecallResponse, Source, DEFAULT_LIST_LIMIT,@@@ -42,147 -57,174 +57,225 @@@ async fn list_chunks_page.clamp(1, MAX_LIST_LIMIT);let offset = filter.offset.unwrap_or(0);- with_connection(config, |conn| {- let mut sql = String::from(- "SELECT DISTINCT- c.id, c.source_kind, c.source_id, c.source_ref, c.owner,- c.timestamp_ms, c.token_count, c.lifecycle_status,- c.content_path, c.content, c.tags_json,- CASE WHEN c.embedding IS NULL THEN 0 ELSE 1 END AS has_embedding- FROM mem_tree_chunks c",+ let Some(query) = chunk_query_from_filter(filter, limit, offset) else {+ // Not an empty query — a query that cannot match. See+ // [`chunk_query_from_filter`]: sending it would ask for the whole+ // store.+ log::debug!("[memory_tree::read] list_chunks: filter matches nothing; query skipped");+ return Ok(ListChunksResponse {+ chunks: Vec::new(),+ total: 0,+ });+ };++ // No `spawn_blocking`: the driver owns whether its own reads block, and the+ // module's do not run on this thread at all.+ let binding = crate::openhuman::memory::binding::for_config(config)?;+ let Some(chunks) = binding.provider().as_chunks() else {+ // Read-only, so an empty page is the honest answer: a driver with no+ // chunk tier holds no rows to list, and no rows to count either.+ log::debug!(+ "[memory_tree::read] list_chunks: driver '{}' does not serve Chunks; reporting empty",+ binding.driver_id());- let mut where_clauses: Vec<String> = vec![];- let mut params_owned: Vec<Box<dyn rusqlite::ToSql>> = Vec::new();-- if let Some(eids) = &filter.entity_ids {- if !eids.is_empty() {- sql.push_str(" INNER JOIN mem_tree_entity_index ei ON ei.node_id = c.id");- let placeholders: Vec<String> = (0..eids.len()).map(|_| "?".to_string()).collect();- where_clauses.push(format!("ei.entity_id IN ({})", placeholders.join(", ")));- for eid in eids {- params_owned.push(Box::new(eid.clone()));- }- }- }- if let Some(kinds) = &filter.source_kinds {- if !kinds.is_empty() {- let placeholders: Vec<String> = (0..kinds.len()).map(|_| "?".to_string()).collect();- where_clauses.push(format!("c.source_kind IN ({})", placeholders.join(", ")));- for k in kinds {- params_owned.push(Box::new(k.clone()));- }- }- }- if let Some(sids) = &filter.source_ids {- if !sids.is_empty() {- let placeholders: Vec<String> = (0..sids.len()).map(|_| "?".to_string()).collect();- where_clauses.push(format!("c.source_id IN ({})", placeholders.join(", ")));- for s in sids {- params_owned.push(Box::new(s.clone()));- }- }- }- if let Some(since) = filter.since_ms {- where_clauses.push("c.timestamp_ms >= ?".into());- params_owned.push(Box::new(since));- }- if let Some(until) = filter.until_ms {- where_clauses.push("c.timestamp_ms <= ?".into());- params_owned.push(Box::new(until));- }- if let Some(query) = &filter.query {- let q = query.trim();- if !q.is_empty() {- // Tokenized AND-matching: every whitespace-separated token must- // appear somewhere in the chunk, in any order. A literal phrase- // still matches (all of its tokens appear), so this is a strict- // superset of the old whole-phrase LIKE — which punctuation- // could silently defeat: querying "Grade 4 Week 1" against a- // chunk containing "Grade 4: Week 1" returned nothing, and an- // agent concluded the email was never ingested.- for token in q.split_whitespace() {- where_clauses.push("c.content LIKE ?".into());- params_owned.push(Box::new(format!("%{}%", token)));- }+ return Ok(ListChunksResponse {+ chunks: Vec::new(),+ total: 0,+ });+ };++ // `scope` is `None` here because this listing has never been source-scoped:+ // the SQL it replaces had no allowlist clause at all. Passing the ambient+ // scope would be a new restriction on the Memory tab, not a translation of+ // one.- let rows = chunks- .list_chunk_details(&query, None)- .await- .map_err(|e| format!("list_chunk_details: {e}"))?;- let total = chunks- .count_chunks(&query, None)- .await- .map_err(|e| format!("count_chunks: {e}"))?;++ let tokens = query_tokens(filter.query.as_deref());++ let (rows, total) = if tokens.len() > 1 {++ let mut unpaged = query.clone();++ unpaged.content_contains = None;++ unpaged.limit = None;++ unpaged.offset = None;++ let rows = token_and_details(chunks, &unpaged, &tokens).await?;++ let total = rows.len() as u64;++ let page = rows++ .into_iter()++ .skip(offset as usize)++ .take(limit as usize)++ .collect();++ (page, total)++ } else {++ let rows = chunks++ .list_chunk_details(&query, None)++ .await++ .map_err(|e| format!("list_chunk_details: {e}"))?;++ let total = chunks++ .count_chunks(&query, None)++ .await++ .map_err(|e| format!("count_chunks: {e}"))?;++ (rows, total)++ };++ log::debug!(+ "[memory_tree::read] list_chunks: limit={limit} offset={offset} rows={} total={total}",+ rows.len()+ );++ Ok(ListChunksResponse {+ chunks: rows.into_iter().map(chunk_row_from_list_row).collect(),+ total,+ })+ }++ /// Translate the RPC's [`ChunkFilter`] into the contract's [`ChunkQuery`].+ ///+ /// `None` means **this filter can match nothing, so skip the query entirely**.+ /// That is not the same as an unconstrained query, and the difference is the+ /// one footgun `ChunkQuery` carries: every `Vec` predicate defaults to empty+ /// and an empty predicate is *unfiltered*, so handing over the empty result of+ /// a narrowing computation asks for the whole store rather than for nothing.+ ///+ /// Exactly one field here narrows: `source_kinds` arrives as free text and the+ /// contract carries a decoded enum, so kinds this build does not know drop out.+ /// Dropping them reproduces the old SQL, where an unrecognised value sat in+ /// `source_kind IN (…)` and simply matched no row — `["chat", "bogus"]` still+ /// returns the chat rows. When *every* value is unrecognised the old clause+ /// matched nothing, and `None` is how that answer is spelled here; leaving the+ /// vec empty instead would return the whole store.+ ///+ /// An empty `Some(vec![])` is *not* that case: the old SQL skipped the clause+ /// for an empty list, so it is unfiltered here too, which is what the empty vec+ /// already means.+ fn chunk_query_from_filter(filter: &ChunkFilter, limit: u32, offset: u32) -> Option<ChunkQuery> {+ let mut source_kinds: Vec<SourceKind> = Vec::new();+ if let Some(requested) = filter.source_kinds.as_ref() {+ for raw in requested {+ match SourceKind::parse(raw) {+ Ok(kind) => source_kinds.push(kind),+ Err(e) => log::debug!(+ "[memory_tree::read] list_chunks: dropping unknown source_kind {raw:?} ({e})"+ ),}}-- if !where_clauses.is_empty() {- sql.push_str(" WHERE ");- sql.push_str(&where_clauses.join(" AND "));+ if source_kinds.is_empty() && !requested.is_empty() {+ return None;}- let count_sql = format!(- "SELECT COUNT(*) FROM ({}) AS sub",- sql.replacen(- "SELECT DISTINCT\n c.id, c.source_kind, c.source_id, c.source_ref, c.owner,\n c.timestamp_ms, c.token_count, c.lifecycle_status,\n c.content_path, c.content, c.tags_json,\n CASE WHEN c.embedding IS NULL THEN 0 ELSE 1 END AS has_embedding",- "SELECT DISTINCT c.id",- 1- )- );+ }- sql.push_str(" ORDER BY c.timestamp_ms DESC, c.seq_in_source ASC LIMIT ? OFFSET ?");- params_owned.push(Box::new(limit as i64));- params_owned.push(Box::new(offset as i64));+ let content_contains = filter.query.as_deref().and_then(content_predicate);- let count_params: Vec<&dyn rusqlite::ToSql> = params_owned- .iter()- .take(params_owned.len() - 2)- .map(|b| b.as_ref() as &dyn rusqlite::ToSql)- .collect();- let total: i64 = conn- .query_row(&count_sql, count_params.as_slice(), |r| r.get(0))- .context("count chunks")?;-- let mut stmt = conn.prepare(&sql).context("prepare list_chunks")?;- let param_refs: Vec<&dyn rusqlite::ToSql> = params_owned- .iter()- .map(|b| b.as_ref() as &dyn rusqlite::ToSql)- .collect();- let rows = stmt- .query_map(param_refs.as_slice(), |row| {- let id: String = row.get(0)?;- let source_kind: String = row.get(1)?;- let source_id: String = row.get(2)?;- let source_ref: Option<String> = row.get(3)?;- let owner: String = row.get(4)?;- let timestamp_ms: i64 = row.get(5)?;- let token_count: i64 = row.get(6)?;- let lifecycle_status: String = row.get(7)?;- let content_path: Option<String> = row.get(8)?;- let content: String = row.get(9)?;- let tags_json: String = row.get(10)?;- let has_embedding: i64 = row.get(11)?;- let preview: String = content.chars().take(PREVIEW_MAX_CHARS).collect();- let tags: Vec<String> = serde_json::from_str(&tags_json).unwrap_or_default();- Ok(ChunkRow {- id,- source_kind,- source_id,- source_ref,- owner,- timestamp_ms,- token_count: token_count.max(0) as u32,- lifecycle_status,- content_path,- content_preview: if preview.is_empty() {- None- } else {- Some(preview)- },- has_embedding: has_embedding != 0,- tags,- })- })?- .collect::<rusqlite::Result<Vec<_>>>()- .context("collect list_chunks rows")?;-- Ok(ListChunksResponse {- chunks: rows,- total: total.max(0) as u64,- })+ Some(ChunkQuery {+ source_ids: filter.source_ids.clone().unwrap_or_default(),+ entity_ids: filter.entity_ids.clone().unwrap_or_default(),+ source_kinds,+ since_ms: filter.since_ms,+ until_ms: filter.until_ms,+ content_contains,+ limit: Some(limit as usize),+ offset: Some(offset as usize),+ // The predicates this filter does not carry. `exclude_dropped` stays+ // false because the SQL had no lifecycle clause: the Memory tab lists+ // dropped rows and renders their status.+ ..Default::default()})}+ /// The `content_contains` predicate for a caller-supplied query string, or+ /// `None` when the caller typed only whitespace.+ ///+ /// One function because two call sites need the same rule and a drifted pair+ /// would show as a search that filters differently from the listing behind it.+ ///+ /// Two things it deliberately does not do. It does not wrap the value in+ /// `%…%` — that is the driver's, and so is escaping any `%` or `_` the user+ /// typed, which the `format!("%{}%", q)` this replaces did not do at all: a+ /// query containing `_` silently matched any character in that position. And a+ /// blank query places no predicate rather than matching nothing, which is what+ /// the old `if !q.is_empty()` guard did and is why a cleared search box lists+ /// the newest rows instead of emptying the table.+ fn content_predicate(query: &str) -> Option<String> {+ let trimmed = query.trim();+ if trimmed.is_empty() {+ None+ } else {+ Some(trimmed.to_string())+ }+ }+++fn query_tokens(query: Option<&str>) -> Vec<String> {++ query++ .unwrap_or_default()++ .split(|c: char| !c.is_alphanumeric())++ .filter(|token| !token.is_empty())++ .map(str::to_string)++ .collect()++}++++async fn token_and_details(++ chunks: &dyn MemoryChunks,++ query: &ChunkQuery,++ tokens: &[String],++) -> Result<Vec<ChunkListRow>, String> {++ let mut matches: Option<Vec<ChunkListRow>> = None;++ for token in tokens {++ let mut token_query = query.clone();++ token_query.content_contains = Some(token.clone());++ let rows = chunks++ .list_chunk_details(&token_query, None)++ .await++ .map_err(|e| format!("list_chunk_details: {e}"))?;++ let current: HashSet<_> = rows.iter().map(|row| row.chunk.id.clone()).collect();++ matches = Some(match matches {++ None => rows,++ Some(previous) => previous++ .into_iter()++ .filter(|row| current.contains(&row.chunk.id))++ .collect(),++ });++ }++ Ok(matches.unwrap_or_default().into_values().collect())++}+++ /// Render one contract listing row as the wire [`ChunkRow`] the Memory tab+ /// reads.+ ///+ /// [`ChunkListRow`] carries no body, deliberately — `ChunkDetail::body`+ /// promises `None` means the vault read *failed*, which a page of rows can only+ /// honour by reading every file or by lying. Nothing is lost here: the preview+ /// has always come from the stored `content` column, which is a ≤500-char+ /// preview for a chunk whose body went to the content vault and the whole body+ /// for an inline one, and that column is `Chunk::content`. The truncation below+ /// is therefore a no-op on already-previewed rows and identical to the SQL's on+ /// inline ones.+ fn chunk_row_from_list_row(row: ChunkListRow) -> ChunkRow {+ let ChunkListRow {+ chunk,+ content_path,+ lifecycle_status,+ has_embedding,+ } = row;+ let preview: String = chunk.content.chars().take(PREVIEW_MAX_CHARS).collect();+ ChunkRow {+ id: chunk.id,+ source_kind: chunk.metadata.source_kind.as_str().to_string(),+ source_id: chunk.metadata.source_id,+ source_ref: chunk.metadata.source_ref.map(|r| r.value),+ owner: chunk.metadata.owner,+ timestamp_ms: chunk.metadata.timestamp.timestamp_millis(),+ token_count: chunk.token_count,+ // Matches `read_chunk_row` below. The column is `NOT NULL DEFAULT+ // 'admitted'`, so `None` is unreachable through the engine driver; a+ // driver with no lifecycle concept at all is what the `Option` is for.+ lifecycle_status: lifecycle_status.unwrap_or_else(|| "unknown".to_string()),+ content_path,+ content_preview: if preview.is_empty() {+ None+ } else {+ Some(preview)+ },+ has_embedding,+ tags: chunk.metadata.tags,+ }+ }+// ── list_sources ─────────────────────────────────────────────────────────pub async fn list_sources_rpc(@@@ -271,23 -347,44 +398,57 @@@ pub async fn search_rpck: u32,) -> Result<RpcOutcome<Vec<ChunkRow>>, String> {let limit = k.clamp(1, MAX_LIST_LIMIT);- let filter = ChunkFilter {- query: Some(query.clone()),- limit: Some(limit),- ..ChunkFilter::default()+ let content_contains = content_predicate(&query);+ // Captured before `query` is shadowed by the `ChunkQuery` below. The log+ // line reports the length of the search TEXT, never of the built query, and+ // it is deliberately the length rather than the text itself — a search term+ // is user-authored content and does not belong in a log.+ let query_len = query.len();++ let binding = crate::openhuman::memory::binding::for_config(config)?;+ let Some(chunks) = binding.provider().as_chunks() else {+ log::debug!(+ "[memory_tree::read] search: driver '{}' does not serve Chunks; reporting empty",+ binding.driver_id()+ );+ return Ok(RpcOutcome::single_log(+ Vec::new(),+ format!("memory_tree::read: search query_len={query_len} n=0"),+ ));};- let cfg = config.clone();- let chunks = tokio::task::spawn_blocking(move || -> Result<Vec<ChunkRow>> {- Ok(list_chunks_blocking(&cfg, &filter)?.chunks)- })- .await- .map_err(|e| format!("search join error: {e}"))?- .map_err(|e| format!("search: {e:#}"))?;- let n = chunks.len();+ // `content_contains` and a limit, and nothing else: no source predicate, no+ // time window, no offset. `scope` is `None` for the same reason the listing+ // passes `None` — the SQL this replaces carried no allowlist clause.- let query = ChunkQuery {- content_contains,- limit: Some(limit as usize),- ..Default::default()++ let tokens = query_tokens(Some(&query));++ let rows = if tokens.len() > 1 {++ let query = ChunkQuery {++ limit: None,++ ..Default::default()++ };++ token_and_details(chunks, &query, &tokens)++ .await?++ .into_iter()++ .take(limit as usize)++ .collect()++ } else {++ let query = ChunkQuery {++ content_contains,++ limit: Some(limit as usize),++ ..Default::default()++ };++ chunks++ .list_chunk_details(&query, None)++ .await++ .map_err(|e| format!("list_chunk_details: {e}"))?+ };- let rows = chunks- .list_chunk_details(&query, None)- .await- .map_err(|e| format!("list_chunk_details: {e}"))?;++ let hits: Vec<ChunkRow> = rows.into_iter().map(chunk_row_from_list_row).collect();+ let n = hits.len();+ log::debug!("[memory_tree::read] search: limit={limit} n={n}");Ok(RpcOutcome::single_log(- chunks,- format!("memory_tree::read: search query_len={} n={n}", query.len()),+ hits,+ format!("memory_tree::read: search query_len={query_len} n={n}"),))}diff --cc src/openhuman/memory/schema/schema_schema_part_01.rsindex 0000000000,e140fa0b33..8a03847e14mode 000000,100644..100644--- a/src/openhuman/memory/schema/schema_schema_part_01.rs+++ b/src/openhuman/memory/schema/schema_schema_part_01.rs@@@ -1,0 -1,669 +1,669 @@@+ use super::*;++ pub(super) fn lookup(function: &str) -> Option<ControllerSchema> {+ match function {+ "ingest" => Some( ControllerSchema {+ namespace: NAMESPACE,+ function: "ingest",+ description: "Ingest a source into canonical chunks. \+ Dispatches on `source_kind`; `payload` shape depends on the kind \+ (chat → ChatBatch, email → EmailThread, document → DocumentInput).",+ inputs: vec![+ FieldSchema {+ name: "source_kind",+ ty: TypeSchema::Enum {+ variants: vec!["chat", "email", "document"],+ },+ comment: "Which source kind the payload represents.",+ required: true,+ },+ FieldSchema {+ name: "source_id",+ ty: TypeSchema::String,+ comment: "Stable logical source id (channel, thread, document id).",+ required: true,+ },+ FieldSchema {+ name: "owner",+ ty: TypeSchema::String,+ comment: "Optional account / user this content belongs to.",+ required: false,+ },+ FieldSchema {+ name: "tags",+ ty: TypeSchema::Array(Box::new(TypeSchema::String)),+ comment: "Optional tags or labels carried through.",+ required: false,+ },+ FieldSchema {+ name: "payload",+ ty: TypeSchema::Json,+ comment: "Adapter-specific payload. \+ chat: {platform, channel_label, messages[]}. \+ email: {provider, thread_subject, messages[]}. \+ document: {provider, title, body, modified_at, source_ref}.",+ required: true,+ },+ ],+ outputs: vec![+ FieldSchema {+ name: "source_id",+ ty: TypeSchema::String,+ comment: "Logical source id the ingest was scoped to.",+ required: true,+ },+ FieldSchema {+ name: "chunks_written",+ ty: TypeSchema::U64,+ comment: "Number of chunks persisted after admission.",+ required: true,+ },+ FieldSchema {+ name: "chunks_dropped",+ ty: TypeSchema::U64,+ comment: "Number of chunks rejected by the admission gate.",+ required: true,+ },+ FieldSchema {+ name: "chunk_ids",+ ty: TypeSchema::Array(Box::new(TypeSchema::String)),+ comment: "IDs of all chunks persisted after admission.",+ required: true,+ },+ ],+ }),+ "list_chunks" => Some( ControllerSchema {+ namespace: NAMESPACE,+ function: "list_chunks",+ description: "Paginated list of chunks with optional filters by source kind / source id / \+ entity ids / time window / keyword. Returns chunks plus total match count for \+ pagination.",+ inputs: vec![+ FieldSchema {+ name: "source_kinds",+ ty: TypeSchema::Option(Box::new(TypeSchema::Array(Box::new(+ TypeSchema::String,+ )))),+ comment: "Restrict to one or more source kinds (chat / email / document).",+ required: false,+ },+ FieldSchema {+ name: "source_ids",+ ty: TypeSchema::Option(Box::new(TypeSchema::Array(Box::new(+ TypeSchema::String,+ )))),+ comment: "Restrict to one or more logical source ids.",+ required: false,+ },+ FieldSchema {+ name: "entity_ids",+ ty: TypeSchema::Option(Box::new(TypeSchema::Array(Box::new(+ TypeSchema::String,+ )))),+ comment: "Restrict to chunks indexed against any of these canonical entity ids.",+ required: false,+ },+ FieldSchema {+ name: "since_ms",+ ty: TypeSchema::Option(Box::new(TypeSchema::I64)),+ comment: "Inclusive lower bound on chunk timestamp (ms since epoch).",+ required: false,+ },+ FieldSchema {+ name: "until_ms",+ ty: TypeSchema::Option(Box::new(TypeSchema::I64)),+ comment: "Inclusive upper bound on chunk timestamp (ms since epoch).",+ required: false,+ },+ FieldSchema {+ name: "query",+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),- comment: "Substring keyword filter over chunk preview content.",++ comment: "Space-separated keywords; every token must appear in the chunk (case-insensitive, any order; punctuation does not matter).",+ required: false,+ },+ FieldSchema {+ name: "limit",+ ty: TypeSchema::Option(Box::new(TypeSchema::U64)),+ comment: "Maximum rows per page (defaults to 50, capped at 1000).",+ required: false,+ },+ FieldSchema {+ name: "offset",+ ty: TypeSchema::Option(Box::new(TypeSchema::U64)),+ comment: "Pagination offset (defaults to 0).",+ required: false,+ },+ ],+ outputs: vec![+ FieldSchema {+ name: "chunks",+ ty: TypeSchema::Array(Box::new(TypeSchema::Ref("Chunk"))),+ comment: "Page of matching chunks ordered by timestamp DESC.",+ required: true,+ },+ FieldSchema {+ name: "total",+ ty: TypeSchema::U64,+ comment: "Total number of chunks matching the filter (pre-pagination).",+ required: true,+ },+ ],+ }),+ "get_chunk" => Some( ControllerSchema {+ namespace: NAMESPACE,+ function: "get_chunk",+ description: "Fetch a single chunk by its deterministic id.",+ inputs: vec![FieldSchema {+ name: "id",+ ty: TypeSchema::String,+ comment: "Chunk id (32 hex chars).",+ required: true,+ }],+ outputs: vec![FieldSchema {+ name: "chunk",+ ty: TypeSchema::Option(Box::new(TypeSchema::Ref("Chunk"))),+ comment: "The chunk if found, otherwise null.",+ required: false,+ }],+ }),+ "list_sources" => Some( ControllerSchema {+ namespace: NAMESPACE,+ function: "list_sources",+ description: "Distinct (source_kind, source_id) pairs with chunk counts and most-recent timestamps. \+ `display_name` is computed from the source_id (un-slug + strip user email when known).",+ inputs: vec![FieldSchema {+ name: "user_email_hint",+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),+ comment: "When provided, source ids that contain this email get it stripped from \+ their display name so the UI shows the other party of an email thread.",+ required: false,+ }],+ outputs: vec![FieldSchema {+ name: "sources",+ ty: TypeSchema::Array(Box::new(TypeSchema::Ref("Source"))),+ comment: "All distinct ingest sources, newest activity first.",+ required: true,+ }],+ }),+ "search" => Some( ControllerSchema {+ namespace: NAMESPACE,+ function: "search",+ description: "Keyword LIKE-search over chunk bodies. Cheap, deterministic; useful as a \+ fallback when semantic recall is unavailable.",+ inputs: vec![+ FieldSchema {+ name: "query",+ ty: TypeSchema::String,- comment: "Substring to match against chunk content.",++ comment: "Space-separated keywords; every token must appear in the chunk (case-insensitive, any order; punctuation does not matter).",+ required: true,+ },+ FieldSchema {+ name: "k",+ ty: TypeSchema::U64,+ comment: "Maximum chunks to return.",+ required: true,+ },+ ],+ outputs: vec![FieldSchema {+ name: "chunks",+ ty: TypeSchema::Array(Box::new(TypeSchema::Ref("Chunk"))),+ comment: "Matching chunks ordered by recency.",+ required: true,+ }],+ }),+ "recall" => Some( ControllerSchema {+ namespace: NAMESPACE,+ function: "recall",+ description: "Semantic recall — runs the Phase 4 cosine rerank against the query embedding \+ and returns leaf chunks (not summaries) for UI display.",+ inputs: vec![+ FieldSchema {+ name: "query",+ ty: TypeSchema::String,+ comment: "Free-text query — embedded once and reranked against summary embeddings.",+ required: true,+ },+ FieldSchema {+ name: "k",+ ty: TypeSchema::U64,+ comment: "Maximum chunks to return.",+ required: true,+ },+ ],+ outputs: vec![+ FieldSchema {+ name: "chunks",+ ty: TypeSchema::Array(Box::new(TypeSchema::Ref("Chunk"))),+ comment: "Recalled chunks, sorted in the same order as the rerank.",+ required: true,+ },+ FieldSchema {+ name: "scores",+ ty: TypeSchema::Array(Box::new(TypeSchema::Json)),+ comment: "Parallel array of similarity scores (one per chunk).",+ required: true,+ },+ ],+ }),+ "entity_index_for" => Some( ControllerSchema {+ namespace: NAMESPACE,+ function: "entity_index_for",+ description: "Return all canonical entities indexed against a chunk (or summary node) id.",+ inputs: vec![FieldSchema {+ name: "chunk_id",+ ty: TypeSchema::String,+ comment: "Chunk id (32 hex chars).",+ required: true,+ }],+ outputs: vec![FieldSchema {+ name: "entities",+ ty: TypeSchema::Array(Box::new(TypeSchema::Ref("EntityRef"))),+ comment: "Entities attached to the node, ordered by mention count DESC.",+ required: true,+ }],+ }),+ "chunks_for_entity" => Some( ControllerSchema {+ namespace: NAMESPACE,+ function: "chunks_for_entity",+ description: "Return chunk IDs that reference an entity_id (inverse of entity_index_for). \+ Used by the Memory tab's People/Topics lenses to filter the chunk list.",+ inputs: vec![FieldSchema {+ name: "entity_id",+ ty: TypeSchema::String,+ comment: "Canonical entity id (e.g. `person:Steven Enamakel`, \+ `email:[email protected]`).",+ required: true,+ }],+ outputs: vec![FieldSchema {+ name: "chunk_ids",+ ty: TypeSchema::Array(Box::new(TypeSchema::String)),+ comment: "Chunk ids that mention the entity, ordered by recency DESC.",+ required: true,+ }],+ }),+ "top_entities" => Some( ControllerSchema {+ namespace: NAMESPACE,+ function: "top_entities",+ description: "Most-frequent canonical entities across the workspace, optionally narrowed by kind.",+ inputs: vec![+ FieldSchema {+ name: "kind",+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),+ comment: "Restrict to a single entity_kind (`person`, `email`, `topic`, …).",+ required: false,+ },+ FieldSchema {+ name: "limit",+ ty: TypeSchema::U64,+ comment: "Maximum rows to return.",+ required: true,+ },+ ],+ outputs: vec![FieldSchema {+ name: "entities",+ ty: TypeSchema::Array(Box::new(TypeSchema::Ref("EntityRef"))),+ comment: "Top entities, ordered by mention count DESC.",+ required: true,+ }],+ }),+ "chunk_score" => Some( ControllerSchema {+ namespace: NAMESPACE,+ function: "chunk_score",+ description: "Score breakdown stored in `mem_tree_score` for one chunk — used by the Memory \+ tab's 'why was this kept / dropped' panel.",+ inputs: vec![FieldSchema {+ name: "chunk_id",+ ty: TypeSchema::String,+ comment: "Chunk id (32 hex chars).",+ required: true,+ }],+ outputs: vec![FieldSchema {+ name: "breakdown",+ ty: TypeSchema::Option(Box::new(TypeSchema::Ref("ScoreBreakdown"))),+ comment: "Per-signal weight + value array, total, threshold, kept flag, llm_consulted flag.",+ required: false,+ }],+ }),+ "delete_chunk" => Some( ControllerSchema {+ namespace: NAMESPACE,+ function: "delete_chunk",+ description: "Purge one chunk plus its score row, entity-index rows, and on-disk .md file. \+ Idempotent — missing chunk returns deleted=false. Does NOT cascade through \+ sealed summaries; UIs warn the user.",+ inputs: vec![FieldSchema {+ name: "chunk_id",+ ty: TypeSchema::String,+ comment: "Chunk id to remove.",+ required: true,+ }],+ outputs: vec![+ FieldSchema {+ name: "deleted",+ ty: TypeSchema::Bool,+ comment: "True when the chunk row was found and removed.",+ required: true,+ },+ FieldSchema {+ name: "score_rows_removed",+ ty: TypeSchema::U64,+ comment: "Count of rows removed from `mem_tree_score`.",+ required: true,+ },+ FieldSchema {+ name: "entity_index_rows_removed",+ ty: TypeSchema::U64,+ comment: "Count of rows removed from `mem_tree_entity_index`.",+ required: true,+ },+ ],+ }),+ "delete_source" => Some( ControllerSchema {+ namespace: NAMESPACE,+ function: "delete_source",+ description: "Fully delete one document source by its EXACT source_id: every chunk \+ plus its score / entity-index / embedding / reembed-skip side rows and chunk \+ content files, the ingest dedup gates (bare source_id AND versioned \+ source_id@version), and (when the source becomes fully orphaned) its \+ source-scoped summary tree — summaries, summary embeddings + reembed-skip, \+ tree entity-index, buffers, the tree row, and summary content files. Unlike \+ delete_chunk this cascades, so stale summaries of the deleted source cannot \+ resurface in recall, and it also finishes legacy partial deletes (chunks already \+ gone, tree/gate left behind). Exact match only (never a prefix); shared \+ collection/path_scope trees that summarise multiple documents are left intact. \+ Idempotent — an unknown source_id returns deleted=false.",+ inputs: vec![FieldSchema {+ name: "source_id",+ ty: TypeSchema::String,+ comment: "Exact source id to remove (e.g. a Telegram note/event/meeting id).",+ required: true,+ }],+ outputs: vec![+ FieldSchema {+ name: "deleted",+ ty: TypeSchema::Bool,+ comment: "True when the call did real work: chunks were removed OR a stale \+ orphaned source tree was cleaned (legacy case, chunks_removed=0).",+ required: true,+ },+ FieldSchema {+ name: "chunks_removed",+ ty: TypeSchema::U64,+ comment: "Number of chunk rows removed for the source.",+ required: true,+ },+ ],+ }),+ "wipe_all" => Some( ControllerSchema {+ namespace: NAMESPACE,+ function: "wipe_all",+ description: "Destructive reset: truncate every mem_tree_* table, remove the \+ on-disk content folders (raw / wiki / email / chat / document / \+ legacy summaries) under the workspace memory_tree content root, \+ and clear every Composio sync-state KV row so the next sync \+ re-fetches all upstream items. Used by the Memory tab's 'Reset \+ memory' button.",+ inputs: vec![],+ outputs: vec![+ FieldSchema {+ name: "rows_deleted",+ ty: TypeSchema::U64,+ comment: "Total mem_tree_* rows removed across all tables.",+ required: true,+ },+ FieldSchema {+ name: "dirs_removed",+ ty: TypeSchema::Array(Box::new(TypeSchema::String)),+ comment: "Top-level directories under content_root that were deleted.",+ required: true,+ },+ FieldSchema {+ name: "sync_state_cleared",+ ty: TypeSchema::U64,+ comment: "Composio sync-state KV rows deleted (cursors + synced-id sets).",+ required: true,+ },+ ],+ }),+ "reset_tree" => Some( ControllerSchema {+ namespace: NAMESPACE,+ function: "reset_tree",+ description: "Wipe summary-tree state but keep chunks + raw archive + sync state, \+ then re-enqueue every chunk through the extraction pipeline so the \+ tree rebuilds from scratch. Useful after changing the summariser \+ backend (e.g. enabling a local LLM) without paying the upstream \+ re-sync cost.",+ inputs: vec![],+ outputs: vec![+ FieldSchema {+ name: "tree_rows_deleted",+ ty: TypeSchema::U64,+ comment: "Tree-state rows removed (summaries + trees + buffers + jobs).",+ required: true,+ },+ FieldSchema {+ name: "chunks_requeued",+ ty: TypeSchema::U64,+ comment: "Chunks reset to lifecycle_status = 'pending_extraction'.",+ required: true,+ },+ FieldSchema {+ name: "jobs_enqueued",+ ty: TypeSchema::U64,+ comment: "extract_chunk jobs enqueued (one per chunk).",+ required: true,+ },+ ],+ }),+ "flush_source" => Some( ControllerSchema {+ namespace: NAMESPACE,+ function: "flush_source",+ description: "Immediately seal one source tree's L0 buffer, bypassing the job \+ queue. Mutex per source scope so concurrent clicks are serialised. \+ Returns the number of seal cascades that fired.",+ inputs: vec![FieldSchema {+ name: "source_scope",+ ty: TypeSchema::String,+ comment: "Source tree scope (e.g. `github:org/repo`, `slack:#eng`).",+ required: true,+ }],+ outputs: vec![+ FieldSchema {+ name: "tree_scope",+ ty: TypeSchema::String,+ comment: "Echo of the source scope.",+ required: true,+ },+ FieldSchema {+ name: "seals_fired",+ ty: TypeSchema::U64,+ comment: "Number of seal cascades that fired.",+ required: true,+ },+ ],+ }),+ "backfill_connector_trees" => Some( ControllerSchema {+ namespace: NAMESPACE,+ function: "backfill_connector_trees",+ description: "Re-file connector documents stored before the memory-tree \+ routing fix (#6007) into the tree. Those records are already \+ embedded in the document store but invisible to tree recall, \+ the memory graph and the source row's ingest status, and a \+ re-sync will not recover them: the per-item sync gate treats \+ them as done. Idempotent — the ingest gate recognises what it \+ already treed, so a repeated pass writes nothing. EXPENSIVE: \+ one read and one set of chunk embeddings per document, so \+ `dry_run` defaults to true and a caller must ask for the write.",+ inputs: vec![+ FieldSchema {+ name: "dry_run",+ ty: TypeSchema::Bool,+ comment: "Report what a pass would examine and write nothing. \+ Defaults to TRUE — the write is the opt-in.",+ required: false,+ },+ FieldSchema {+ name: "limit",+ ty: TypeSchema::U64,+ comment: "Documents to examine at most. Omit to leave the bound to \+ the driver. Resume by calling again; the work is \+ idempotent, so there is no cursor to carry.",+ required: false,+ },+ ],+ outputs: vec![+ FieldSchema {+ name: "executed",+ ty: TypeSchema::Bool,+ comment: "Which mode ran: false is the dry-run preview, true a \+ real pass. The mode, not \"did anything change\" — \+ `ingested` answers that.",+ required: true,+ },+ FieldSchema {+ name: "scanned",+ ty: TypeSchema::U64,+ comment: "Documents examined.",+ required: true,+ },+ FieldSchema {+ name: "ingested",+ ty: TypeSchema::U64,+ comment: "Documents that produced new memory-tree rows.",+ required: true,+ },+ FieldSchema {+ name: "already_present",+ ty: TypeSchema::U64,+ comment: "Documents the tree already held — what makes a repeated \+ run readable as \"nothing left to do\".",+ required: true,+ },+ FieldSchema {+ name: "skipped",+ ty: TypeSchema::U64,+ comment: "Documents left alone rather than filed under a guess.",+ required: true,+ },+ FieldSchema {+ name: "more_pending",+ ty: TypeSchema::Bool,+ comment: "The pass stopped on its limit with documents unexamined.",+ required: true,+ },+ FieldSchema {+ name: "notes",+ ty: TypeSchema::Json,+ comment: "Bounded, human-readable reasons behind `skipped`.",+ required: true,+ },+ ],+ }),+ "flush_now" => Some( ControllerSchema {+ namespace: NAMESPACE,+ function: "flush_now",+ description: "Manually trigger the summary-tree build. Enqueues a flush_stale \+ job with max_age_secs=0 so every L0 buffer force-seals immediately; \+ the seal worker runs each through the configured (cloud or local) \+ summariser. Idempotent — same UTC-day dedupe key as the scheduled \+ flush so spamming the button is safe.",+ inputs: vec![],+ outputs: vec![+ FieldSchema {+ name: "enqueued",+ ty: TypeSchema::Bool,+ comment: "True when a fresh job row was inserted; false when an active \+ flush job already exists for today.",+ required: true,+ },+ FieldSchema {+ name: "stale_buffers",+ ty: TypeSchema::U64,+ comment: "Count of L0 buffers that currently qualify for force-seal.",+ required: true,+ },+ ],+ }),+ "graph_export" => Some( ControllerSchema {+ namespace: NAMESPACE,+ function: "graph_export",+ description: "Return either the summary tree (parent→child links between sealed \+ summary nodes) or the document↔contact graph (chunks linked to \+ person entities they mention). Includes the absolute path to the \+ on-disk content root so deep links can point Obsidian at the same \+ files.",+ inputs: vec![FieldSchema {+ name: "mode",+ ty: TypeSchema::Option(Box::new(TypeSchema::Enum {+ variants: vec!["tree", "contacts"],+ })),+ comment: "Which graph to return. Defaults to `tree`.",+ required: false,+ }],+ outputs: vec![+ FieldSchema {+ name: "nodes",+ ty: TypeSchema::Array(Box::new(TypeSchema::Ref("GraphNode"))),+ comment: "Summary, chunk, or contact nodes depending on mode.",+ required: true,+ },+ FieldSchema {+ name: "edges",+ ty: TypeSchema::Array(Box::new(TypeSchema::Ref("GraphEdge"))),+ comment: "Explicit edges. Empty in tree mode (parent_id encodes \+ edges); chunk→contact mention edges in contacts mode.",+ required: true,+ },+ FieldSchema {+ name: "content_root_abs",+ ty: TypeSchema::String,+ comment: "Absolute path to <workspace>/memory_tree/content/.",+ required: true,+ },+ ],+ }),+ "obsidian_vault_status" => Some( ControllerSchema {+ namespace: NAMESPACE,+ function: "obsidian_vault_status",+ description: "Best-effort check of whether the memory-tree content root is \+ already a registered Obsidian vault. `obsidian://open?path=` only \+ resolves vaults present in Obsidian's obsidian.json registry — it \+ cannot register a new one — so the Memory tab calls this before \+ firing the deep link and guides the user to 'Open folder as vault' \+ when it isn't registered. Never errors; a probe miss reports \+ registered=false.",+ inputs: vec![FieldSchema {+ name: "obsidian_config_dir",+ ty: TypeSchema::Option(Box::new(TypeSchema::String)),+ comment: "Optional override for Obsidian's config directory (where \+ obsidian.json lives), for non-standard installs \+ (Flatpak / Snap / portable). Omitted ⇒ probe the standard per-OS \+ location plus known sandbox paths.",+ required: false,+ }],+ outputs: vec![+ FieldSchema {+ name: "registered",+ ty: TypeSchema::Bool,+ comment: "True when the content root (or an ancestor) is a registered \+ Obsidian vault, so the deep link will resolve.",+ required: true,+ },+ FieldSchema {+ name: "config_found",+ ty: TypeSchema::Bool,+ comment: "True when an obsidian.json was found and parsed (Obsidian is \+ set up). Lets the UI offer add-as-vault vs. install.",+ required: true,+ },+ FieldSchema {+ name: "content_root_abs",+ ty: TypeSchema::String,+ comment: "Absolute path to <workspace>/memory_tree/content/ — the folder \+ to add to Obsidian and the deep-link target.",+ required: true,+ },+ ],+ }),+ _ => None,+ }+ }