Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(query): opt-in dialectic answer (synthesized, cited) on memory_query
AkitaOnRails378503492a99
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1054f6e8..184ba229 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,21 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]### Added+- Dialectic answer on `memory_query`: an opt-in, off-by-default `answer`+ argument (borrowed from Honcho's dialectic endpoint; targets the 2.4 line).+ When `answer: true` AND the server has an LLM provider configured, the query+ synthesizes a concise, cited natural-language answer over the top retrieved+ hits and attaches it as `answer: { text, citations }`, where `citations` are+ the page paths the answer drew from (JSON-schema structured output, grounded+ strictly in the retrieved snippets). When `answer: true` but no provider is+ configured, the normal hits are returned plus a short `answer_unavailable`+ note rather than an error. With `answer` omitted/`false` (the default), no LLM+ provider is accessed and the response is byte-identical to before, so the+ zero-LLM default path is untouched. Applies to the normal single-project /+ `scopes` search; `global` and `as_of` queries ignore it. Honest caveat: the+ feature is new and its answer quality is not yet eval-validated — treat the+ synthesized answer as a convenience over the same hits and still open the+ cited pages before acting (#NNN).- "Pin before search": `memory_query` gained an opt-in `pin_first` argument and`memory_briefing` now carries a bounded `pinned` list (default off/absent;targets the 2.4 line). Pinned pages previously earned only a small post-RRFdiff --git a/Cargo.lock b/Cargo.lockindex 6d78842a..6fcf9946 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -216,6 +216,7 @@ dependencies = ["jiff","rmcp","schemars",+ "secrecy","serde","serde_json","subtle",diff --git a/crates/ai-memory-core/src/routing_skills/ai-memory-retrieval/SKILL.md b/crates/ai-memory-core/src/routing_skills/ai-memory-retrieval/SKILL.mdindex a6a0e90e..1ee6ac1e 100644--- a/crates/ai-memory-core/src/routing_skills/ai-memory-retrieval/SKILL.md+++ b/crates/ai-memory-core/src/routing_skills/ai-memory-retrieval/SKILL.md@@ -71,6 +71,18 @@ score provenance to compiled-page hits, including matched entity names.Cross-project `global: true` search has a distinct FTS-only ranker, so it reportsthe active stream without per-hit RRF details.+Pass `answer: true` (opt-in, off by default) to also get a synthesized,+natural-language answer over the top hits, attached as `answer: { text,+citations }` where `citations` are the page paths the answer drew from. This+requires the server to have an LLM provider configured: with no provider the+call returns the normal hits plus a short `answer_unavailable` note and never+errors, and the default path (`answer` omitted/`false`) makes no LLM call at+all. The answer is grounded strictly in the retrieved snippets, so treat it as a+convenience over the same hits, not a new source — still open the cited pages+before acting. It applies to the normal single-project / `scopes` search;+`global` and `as_of` queries ignore it. This is a new 2.4 feature and its answer+quality is not yet eval-validated.+## Snippets are not full pagesSearch returns snippets, not complete bodies. An empty-looking or short snippet does not prove the page is empty because the match can be outside the snippet window. Fetch the full page when the path or title looks relevant, especially for rules, procedures, decisions, and gotchas.diff --git a/crates/ai-memory-mcp/Cargo.toml b/crates/ai-memory-mcp/Cargo.tomlindex 515dcddb..4b713b5c 100644--- a/crates/ai-memory-mcp/Cargo.toml+++ b/crates/ai-memory-mcp/Cargo.toml@@ -48,6 +48,7 @@ ai-memory-store.workspace = trueai-memory-wiki.workspace = trueasync-trait.workspace = trueflate2.workspace = true+secrecy.workspace = truetar.workspace = truetempfile.workspace = truetower.workspace = truediff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rsindex 6d9f5d96..6ac9b73e 100644--- a/crates/ai-memory-mcp/src/server.rs+++ b/crates/ai-memory-mcp/src/server.rs@@ -209,7 +209,12 @@ developer, user, and canonical project instructions.\n\`superseded: true`. Pass `pin_first=true` to prepend the project's \bounded pinned latest pages ahead of the search hits (deduped, each \marked `pinned: true`) when standing operator-curated context should be \- seen before the ranked matches. Use `explain=true` only when diagnosing \+ seen before the ranked matches. Pass `answer=true` (opt-in, off by \+ default, and only when the server has an LLM provider) to also synthesize \+ a cited natural-language answer over the top hits, attached as \+ `answer: { text, citations }`; with no provider it returns the hits plus \+ an `answer_unavailable` note (never an error), and the default path makes \+ no LLM call. Use `explain=true` only when diagnosing \project/scopes ranking; it adds score provenance, while global search \reports only its distinct FTS stream.\n\- `memory_recent` — at session start, or when the user asks 'what's \@@ -595,6 +600,17 @@ struct QueryArgs {/// combined with `global` or `scopes`. Omit for a normal search.#[serde(default)]as_of: Option<String>,+ /// Opt-in, off by default. When `true` AND the server has an LLM provider+ /// configured, synthesize a natural-language, cited answer over the top+ /// retrieved hits and attach it as `answer: { text, citations }` (the+ /// citations are the page paths the answer drew from). When `true` but no+ /// provider is configured, the normal hits are returned plus an+ /// `answer_unavailable` note — never an error. When `false`/omitted (the+ /// default) the response is unchanged and NO LLM call is made. Applies to+ /// the normal single-project / `scopes` search; ignored on `global` and+ /// `as_of` queries.+ #[serde(default)]+ answer: Option<bool>,}#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]@@ -656,9 +672,44 @@ struct ProjectSearchOptions<'a> {include_superseded: bool,}+/// Synthesized "dialectic" answer attached to a `memory_query` response when+/// the caller opts in with `answer=true` and a provider is configured. The+/// `text` is a natural-language answer drawn strictly from the retrieved hit+/// snippets; `citations` are the page paths the model reported drawing from.+#[derive(Debug, Serialize)]+struct QueryAnswer {+ text: String,+ citations: Vec<String>,+}++/// LLM structured-output schema for `memory_query(answer=true)`. JSON-schema+/// structured output only (invariant #7): derived via `schemars` and passed to+/// [`ai_memory_llm::complete_structured`].+#[derive(Debug, Deserialize, schemars::JsonSchema)]+struct AnswerSynthesis {+ /// A concise natural-language answer to the user's query, drawn strictly+ /// from the provided page snippets. If the snippets do not contain the+ /// answer, say so plainly instead of guessing.+ answer: String,+ /// The page paths (exactly as given in the context) that the answer drew+ /// from. Empty when the context did not contain the answer.+ citations: Vec<String>,+}+#[derive(Debug, Serialize)]struct MemoryQueryResponse {hits: Vec<QueryHit>,+ /// Present only when the caller set `answer=true` and a provider produced a+ /// synthesized answer. Omitted otherwise so the default response is+ /// unchanged.+ #[serde(skip_serializing_if = "Option::is_none")]+ answer: Option<QueryAnswer>,+ /// Present only when the caller set `answer=true` but synthesis could not+ /// run (no provider configured, or the provider call failed). A short+ /// human-readable reason; the hits are still returned normally and this is+ /// never an error.+ #[serde(skip_serializing_if = "Option::is_none")]+ answer_unavailable: Option<String>,#[serde(skip_serializing_if = "Vec::is_empty")]raw_hits: Vec<ai_memory_store::ObservationHit>,/// Populated only by a `global=true` query: cross-project hits, each@@ -1979,6 +2030,25 @@ impl AiMemoryServer {self}+ /// Attach a bare LLM provider so `memory_query(answer=true)` can synthesize+ /// a cited answer over the retrieved hits, without the full consolidation+ /// pipeline that [`with_consolidator_arc`](Self::with_consolidator_arc)+ /// wires.+ ///+ /// Production startup always populates `self.llm` through+ /// `with_consolidator_arc` (a provider without a consolidator has no+ /// production use), so this thin builder exists only for the query-answer+ /// tests, which need a provider but not the rest of that machinery — hence+ /// `#[cfg(test)]`. It is behavior-preserving: it only sets the same+ /// `self.llm` field the production builder does, and `answer` defaults off+ /// so an attached provider is never called unless the caller opts in.+ #[cfg(test)]+ #[must_use]+ pub(crate) fn with_llm(mut self, llm: Arc<dyn LlmProvider>) -> Self {+ self.llm = Some(llm);+ self+ }+/// Override the retention-sweep parameters (typically populated/// from the user's config.toml `[decay]` table).#[must_use]@@ -2105,6 +2175,11 @@ impl AiMemoryServer {.map_err(|e| McpError::internal_error(e.to_string(), None))?;return ok_json(&MemoryQueryResponse {hits: Vec::new(),+ answer: None,+ answer_unavailable: args.answer.unwrap_or(false).then(|| {+ "answer synthesis is not supported for global (cross-project) queries"+ .to_string()+ }),raw_hits: Vec::new(),global_hits,global_scope_hits: Vec::new(),@@ -2169,6 +2244,10 @@ impl AiMemoryServer {score_details: details,}).collect(),+ answer: None,+ answer_unavailable: args.answer.unwrap_or(false).then(|| {+ "answer synthesis is not supported for as_of (time-travel) queries".to_string()+ }),raw_hits: Vec::new(),global_hits: Vec::new(),global_scope_hits: Vec::new(),@@ -2398,8 +2477,54 @@ impl AiMemoryServer {} else {hits};+ // Opt-in dialectic answer (off by default). Only when the caller set+ // `answer=true` do we touch the LLM at all — this is the invariant-#13+ // guard: with `answer` unset/false the provider (if any) is never+ // accessed and the response is byte-identical to today. When requested+ // but no provider is configured, we return the hits plus a short+ // `answer_unavailable` note rather than erroring.+ let (answer, answer_unavailable) = if args.answer.unwrap_or(false) {+ match self.llm.as_ref() {+ Some(llm) => {+ let request = build_answer_request(&args.query, &hits, &global_scope_hits);+ match ai_memory_llm::complete_structured::<AnswerSynthesis>(+ llm.as_ref(),+ request,+ )+ .await+ {+ Ok(synth) => (+ Some(QueryAnswer {+ text: synth.answer,+ citations: synth.citations,+ }),+ None,+ ),+ Err(e) => {+ tracing::warn!(+ error = %e,+ "memory_query answer synthesis failed; returning hits without an answer"+ );+ (None, Some(format!("answer synthesis failed: {e}")))+ }+ }+ }+ None => (+ None,+ Some(+ "no LLM provider configured on the server; returning hits without a \+ synthesized answer"+ .to_string(),+ ),+ ),+ }+ } else {+ (None, None)+ };let response = MemoryQueryResponse {hits,+ answer,+ answer_unavailable,raw_hits,global_hits: Vec::new(),global_scope_hits,@@ -5088,6 +5213,60 @@ fn build_explore_request(/// `prompts/explore_system.md`.const EXPLORE_SYSTEM_PROMPT: &str = include_str!("../prompts/explore_system.md");+/// System prompt for the opt-in `memory_query(answer=true)` synthesis. Keeps+/// the model strictly grounded in the supplied snippets and forces the cited+/// paths to come from the provided context (invariant against fabricated+/// citations).+const ANSWER_SYSTEM_PROMPT: &str = "You answer a user's question using ONLY the \+ numbered memory-page snippets provided. Do not use any outside knowledge. \+ Write a concise, direct answer grounded strictly in those snippets. In \+ `citations`, list the exact `path` values (as given) of the pages you drew \+ from — never invent a path, and cite only pages you actually used. If the \+ snippets do not contain enough information to answer, say so plainly in \+ `answer` and return an empty `citations` list.";++/// Build the structured-output request for `memory_query(answer=true)`. Inlines+/// the retrieved hit snippets (project hits first, then any `_global` scope+/// hits) as numbered, path-labelled context so the model can ground its answer+/// and cite exact paths. Snippets are stripped of the FTS `<mark>` HTML so the+/// model sees clean text.+fn build_answer_request(+ query: &str,+ hits: &[QueryHit],+ global_scope_hits: &[QueryHit],+) -> ai_memory_llm::ChatRequest {+ fn clean(snippet: &str) -> String {+ snippet.replace("<mark>", "").replace("</mark>", "")+ }+ let mut user = String::new();+ user.push_str("## Question\n\n");+ user.push_str(query);+ user.push_str("\n\n## Memory page snippets\n\n");+ let mut n = 0usize;+ for hit in hits.iter().chain(global_scope_hits.iter()) {+ n += 1;+ user.push_str(&format!(+ "{}. path: `{}`\n title: {}\n snippet: {}\n\n",+ n,+ hit.hit.path.as_str(),+ hit.hit.title,+ clean(&hit.hit.snippet),+ ));+ }+ if n == 0 {+ user.push_str("(no snippets matched the query)\n\n");+ }+ ai_memory_llm::ChatRequest {+ system: Some(ANSWER_SYSTEM_PROMPT.into()),+ messages: vec![ai_memory_llm::ChatMessage {+ role: ai_memory_llm::Role::User,+ content: user,+ }],+ max_tokens: 2_000,+ temperature: Some(0.1),+ }+}+/// Synthetic anonymous request `Parts` for callers arriving without request/// parts (for example stdio): no actor headers, so downstream resolves an/// anonymous `ActorKey` — the correct identity for a local, unauthenticated@@ -5588,6 +5767,7 @@ mod tests {pin_first: None,explain: Some(true),as_of: None,+ answer: None,}),test_optional_parts(),)@@ -5621,6 +5801,7 @@ mod tests {pin_first: None,explain: None,as_of: None,+ answer: None,}),test_optional_parts(),)@@ -7350,6 +7531,7 @@ mod tests {pin_first: None,explain: Some(true),as_of,+ answer: None,};// Historical instant → the superseded version answers.@@ -7390,6 +7572,7 @@ mod tests {pin_first: None,explain: Some(true),as_of: Some(jiff::Timestamp::now().to_string()),+ answer: None,}),OptionalParts(test_parts_default()),)@@ -7461,6 +7644,7 @@ mod tests {pin_first: None,explain: None,as_of: None,+ answer: None,}),OptionalParts(test_parts_default()),)@@ -7488,6 +7672,7 @@ mod tests {pin_first: None,explain: Some(true),as_of: None,+ answer: None,}),OptionalParts(test_parts_default()),)@@ -7583,6 +7768,7 @@ mod tests {pin_first: None,explain: Some(true),as_of: None,+ answer: None,}),OptionalParts(test_parts_default()),)@@ -7672,6 +7858,7 @@ mod tests {pin_first: None,explain: None,as_of: None,+ answer: None,};let result = server@@ -7751,6 +7938,7 @@ mod tests {pin_first: None,explain: None,as_of: None,+ answer: None,}),OptionalParts(test_parts_default()),)@@ -7881,6 +8069,7 @@ mod tests {pin_first: None,explain: None,as_of: None,+ answer: None,}),OptionalParts(test_parts_default()),)@@ -7962,6 +8151,7 @@ mod tests {pin_first: None,explain: None,as_of: None,+ answer: None,}),test_optional_parts(),)@@ -8059,6 +8249,7 @@ mod tests {pin_first: None,explain: None,as_of: None,+ answer: None,}),test_optional_parts(),)@@ -8127,6 +8318,7 @@ mod tests {pin_first: None,explain: None,as_of: None,+ answer: None,}),test_optional_parts(),)@@ -8171,6 +8363,7 @@ mod tests {pin_first: None,explain: None,as_of: None,+ answer: None,}),test_optional_parts(),)@@ -8248,6 +8441,7 @@ mod tests {pin_first: None,explain: None,as_of: None,+ answer: None,}),test_optional_parts(),)@@ -8316,6 +8510,7 @@ mod tests {pin_first: None,explain: None,as_of: None,+ answer: None,}),OptionalParts(test_parts_default()),)@@ -9371,6 +9566,7 @@ mod tests {pin_first: None,explain: Some(true),as_of: None,+ answer: None,}),OptionalParts(test_parts_default()),)@@ -9482,6 +9678,7 @@ mod tests {pin_first: None,explain: Some(true),as_of: None,+ answer: None,}),OptionalParts(test_parts_default()),)@@ -9531,6 +9728,7 @@ mod tests {pin_first: None,explain: None,as_of: None,+ answer: None,}),OptionalParts(test_parts_default()),)@@ -9613,6 +9811,7 @@ mod tests {pin_first: None,explain: None,as_of: None,+ answer: None,}),OptionalParts(test_parts_default()),)@@ -9647,6 +9846,7 @@ mod tests {pin_first: None,explain: None,as_of: None,+ answer: None,}),OptionalParts(test_parts_default()),)@@ -9685,6 +9885,7 @@ mod tests {pin_first: None,explain: None,as_of: None,+ answer: None,}),OptionalParts(test_parts_default()),)@@ -12564,6 +12765,7 @@ mod tests {pin_first: None,explain: None,as_of: None,+ answer: None,}),OptionalParts(test_parts_default()),)@@ -12600,6 +12802,7 @@ mod tests {pin_first: None,explain: None,as_of: None,+ answer: None,}),OptionalParts(test_parts_default()),)diff --git a/crates/ai-memory-mcp/tests/suite/mod.rs b/crates/ai-memory-mcp/tests/suite/mod.rsindex 07683cb4..1577ec41 100644--- a/crates/ai-memory-mcp/tests/suite/mod.rs+++ b/crates/ai-memory-mcp/tests/suite/mod.rs@@ -22,6 +22,7 @@ mod autoscope_multiuser;mod handoff_admission;mod handoff_identity;mod mcp_stateless_http;+mod query_answer;mod query_pin_first;mod query_superseded;mod read_page_related;diff --git a/crates/ai-memory-mcp/tests/suite/query_answer.rs b/crates/ai-memory-mcp/tests/suite/query_answer.rsnew file mode 100644index 00000000..c7241334--- /dev/null+++ b/crates/ai-memory-mcp/tests/suite/query_answer.rs@@ -0,0 +1,420 @@+//! 2.4 opt-in "dialectic answer" on `memory_query` (borrowed from Honcho's+//! dialectic endpoint): when the caller sets `answer=true` AND an LLM provider+//! is configured, the server synthesizes a natural-language, cited answer over+//! the top retrieved hits and attaches it as `answer: { text, citations }`.+//!+//! The invariants this proves through the real MCP tool over the JSON-RPC HTTP+//! transport:+//!+//! 1. `answer=true` + provider → the response carries the synthesized answer+//! text + citations, and the provider WAS called.+//! 2. `answer=false` (the default) + provider wired → the provider is NEVER+//! called (ZERO LLM calls) and the response has no `answer` field. This is+//! the invariant-#13 guard: the zero-LLM default path is byte-identical.+//! 3. `answer=true` + NO provider → a graceful `answer_unavailable` note, the+//! normal hits still present, and NO error / panic.+//! 4. (`#[ignore]`) a live smoke test that wires a real provider when a key is+//! in the environment, and skips cleanly when it is not.++use std::sync::Arc;+use std::sync::atomic::{AtomicUsize, Ordering};++use ai_memory_core::{NewPage, PagePath, ProjectId, Tier, WorkspaceId};+use ai_memory_llm::{ChatRequest, ChatResponse, LlmProvider, LlmResult};+use ai_memory_mcp::AiMemoryServer;+use ai_memory_store::Store;+use ai_memory_wiki::Wiki;+use axum::Router;+use axum::body::Body;+use axum::http::Request;+use rmcp::transport::streamable_http_server::session::local::LocalSessionManager;+use rmcp::transport::streamable_http_server::{StreamableHttpServerConfig, StreamableHttpService};+use serde_json::{Value, json};+use tempfile::TempDir;+use tower::ServiceExt;++const WS: &str = "default";+const PROJ: &str = "scratch";++/// A fake `LlmProvider` that returns a canned structured answer and records how+/// many times ANY completion method was invoked, so a test can assert both the+/// synthesized shape AND that the default path never touches the LLM.+struct FakeAnswerLlm {+ calls: Arc<AtomicUsize>,+}++#[async_trait::async_trait]+impl LlmProvider for FakeAnswerLlm {+ fn name(&self) -> &'static str {+ "fake"+ }++ fn model(&self) -> &str {+ "fake-answer-1"+ }++ async fn complete(&self, _request: ChatRequest) -> LlmResult<ChatResponse> {+ self.calls.fetch_add(1, Ordering::SeqCst);+ Ok(ChatResponse {+ text: "unused".into(),+ usage: None,+ model: "fake-answer-1".into(),+ })+ }++ async fn complete_structured_raw(+ &self,+ _request: ChatRequest,+ _schema: serde_json::Value,+ ) -> LlmResult<serde_json::Value> {+ self.calls.fetch_add(1, Ordering::SeqCst);+ // Shape must deserialize into the server's answer-synthesis struct.+ Ok(json!({+ "answer": "The widget subsystem stores its needle in notes/topic.md.",+ "citations": ["notes/topic.md"],+ }))+ }+}++struct Harness {+ router: Router,+ store: Store,+ ws: WorkspaceId,+ proj: ProjectId,+ /// Call counter shared with the wired fake provider; `None` when no provider+ /// was attached.+ calls: Option<Arc<AtomicUsize>>,+ _tmp: TempDir,+}++fn mount(server: AiMemoryServer) -> Router {+ let service = StreamableHttpService::new(+ move || Ok(server.clone()),+ LocalSessionManager::default().into(),+ StreamableHttpServerConfig::default()+ .with_stateful_mode(false)+ .with_json_response(true),+ );+ Router::new().nest_service("/mcp", service)+}++/// Build a harness; `with_provider` decides whether a fake LLM is attached.+async fn harness(with_provider: bool) -> Harness {+ let tmp = TempDir::new().expect("tempdir");+ let store = Store::open(tmp.path()).expect("store");+ let ws = store.writer.get_or_create_workspace(WS).await.expect("ws");+ let proj = store+ .writer+ .get_or_create_project(ws, PROJ, None)+ .await+ .expect("proj");+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).expect("wiki");+ let mut server =+ AiMemoryServer::new(store.reader.clone(), store.writer.clone(), ws, proj).with_wiki(wiki);+ let calls = if with_provider {+ let calls = Arc::new(AtomicUsize::new(0));+ let provider: Arc<dyn LlmProvider> = Arc::new(FakeAnswerLlm {+ calls: calls.clone(),+ });+ server = server.with_llm(provider);+ Some(calls)+ } else {+ None+ };++ Harness {+ router: mount(server),+ store,+ ws,+ proj,+ calls,+ _tmp: tmp,+ }+}++async fn call(router: &Router, name: &str, arguments: Value) -> Value {+ let body = json!({+ "jsonrpc": "2.0",+ "id": 1,+ "method": "tools/call",+ "params": { "name": name, "arguments": arguments },+ });+ let req = Request::builder()+ .method("POST")+ .uri("/mcp")+ .header("host", "localhost")+ .header("content-type", "application/json")+ .header("accept", "application/json, text/event-stream")+ .body(Body::from(body.to_string()))+ .expect("mcp req");+ let resp = router.clone().oneshot(req).await.expect("oneshot");+ let bytes = axum::body::to_bytes(resp.into_body(), 4_000_000)+ .await+ .expect("body");+ let text = String::from_utf8(bytes.to_vec()).expect("utf8");+ let v: Value = serde_json::from_str(&text).unwrap_or_else(|e| panic!("non-JSON: {text}: {e}"));+ if let Some(err) = v.get("error") {+ panic!("JSON-RPC error: {err}\nfull: {text}");+ }+ let joined = v+ .pointer("/result/content")+ .and_then(|c| c.as_array())+ .unwrap_or_else(|| panic!("missing result.content: {text}"))+ .iter()+ .filter_map(|i| i.get("text").and_then(|t| t.as_str()))+ .collect::<Vec<_>>()+ .join("\n");+ serde_json::from_str(&joined).unwrap_or_else(|e| panic!("tool text not JSON: {joined}: {e}"))+}++fn page(ws: WorkspaceId, proj: ProjectId, path: &str, body: &str) -> NewPage {+ NewPage {+ workspace_id: ws,+ project_id: proj,+ path: PagePath::new(path).unwrap(),+ title: path.to_string(),+ body: body.into(),+ tier: Tier::Semantic,+ frontmatter_json: serde_json::json!({}),+ pinned: false,+ links: Vec::new(),+ author_id: None,+ expires_at: None,+ entities: Vec::new(),+ evidence: Vec::new(),+ }+}++fn hit_paths(resp: &Value) -> Vec<String> {+ resp.get("hits")+ .and_then(|h| h.as_array())+ .unwrap_or_else(|| panic!("no hits array: {resp}"))+ .iter()+ .filter_map(|h| h.get("path").and_then(|p| p.as_str()).map(str::to_owned))+ .collect()+}++fn query_args(query: &str, extra: Value) -> Value {+ let mut base = json!({+ "query": query,+ "workspace": WS,+ "project": PROJ,+ "limit": 10,+ });+ let obj = base.as_object_mut().unwrap();+ for (k, v) in extra.as_object().unwrap() {+ obj.insert(k.clone(), v.clone());+ }+ base+}++async fn seed_needle(h: &Harness) {+ h.store+ .writer+ .upsert_page(page(+ h.ws,+ h.proj,+ "notes/topic.md",+ "the widget subsystem needle lives here",+ ))+ .await+ .unwrap();+}++/// 1. `answer=true` + provider → synthesized answer text + citations, and the+/// provider WAS invoked.+#[tokio::test]+async fn answer_true_with_provider_synthesizes_cited_answer() {+ let h = harness(true).await;+ seed_needle(&h).await;++ let resp = call(+ &h.router,+ "memory_query",+ query_args("needle", json!({ "answer": true })),+ )+ .await;++ // Hits still present.+ assert!(+ hit_paths(&resp).contains(&"notes/topic.md".to_string()),+ "matching hit must still be present: {resp}"+ );++ // The synthesized answer is attached.+ let answer = resp+ .get("answer")+ .unwrap_or_else(|| panic!("answer=true must attach an answer: {resp}"));+ let text = answer+ .get("text")+ .and_then(|t| t.as_str())+ .unwrap_or_else(|| panic!("answer must carry text: {answer}"));+ assert!(!text.trim().is_empty(), "answer text must be non-empty");+ let citations: Vec<&str> = answer+ .get("citations")+ .and_then(|c| c.as_array())+ .unwrap_or_else(|| panic!("answer must carry citations: {answer}"))+ .iter()+ .filter_map(|c| c.as_str())+ .collect();+ assert!(+ citations.contains(&"notes/topic.md"),+ "answer must cite the page it drew from: {citations:?}"+ );++ // The provider WAS called.+ assert_eq!(+ h.calls.as_ref().unwrap().load(Ordering::SeqCst),+ 1,+ "answer=true must call the provider exactly once"+ );++ // No unavailable note when synthesis succeeded.+ assert!(+ resp.get("answer_unavailable").is_none(),+ "successful synthesis must not carry answer_unavailable: {resp}"+ );+}++/// 2. `answer=false` (the default) with a provider WIRED → ZERO LLM calls and no+/// `answer` field. This is the invariant-#13 guard.+#[tokio::test]+async fn answer_false_default_makes_zero_llm_calls() {+ let h = harness(true).await;+ seed_needle(&h).await;++ // Explicit answer=false.+ let explicit = call(+ &h.router,+ "memory_query",+ query_args("needle", json!({ "answer": false })),+ )+ .await;+ assert!(+ explicit.get("answer").is_none(),+ "answer=false must not attach an answer: {explicit}"+ );+ assert!(+ explicit.get("answer_unavailable").is_none(),+ "answer=false must not attach an unavailable note: {explicit}"+ );++ // Default (answer omitted entirely).+ let default = call(&h.router, "memory_query", query_args("needle", json!({}))).await;+ assert!(+ default.get("answer").is_none(),+ "default query must not attach an answer: {default}"+ );++ // The critical guarantee: the provider was never touched.+ assert_eq!(+ h.calls.as_ref().unwrap().load(Ordering::SeqCst),+ 0,+ "default / answer=false must make ZERO LLM calls (invariant #13)"+ );+}++/// 3. `answer=true` + NO provider → graceful `answer_unavailable`, hits present,+/// no error.+#[tokio::test]+async fn answer_true_without_provider_degrades_gracefully() {+ let h = harness(false).await;+ seed_needle(&h).await;++ let resp = call(+ &h.router,+ "memory_query",+ query_args("needle", json!({ "answer": true })),+ )+ .await;++ // Hits are returned normally.+ assert!(+ hit_paths(&resp).contains(&"notes/topic.md".to_string()),+ "hits must be returned even without a provider: {resp}"+ );+ // No synthesized answer.+ assert!(+ resp.get("answer").is_none(),+ "no provider must not fabricate an answer: {resp}"+ );+ // An explicit, non-empty unavailable note (never an error).+ let note = resp+ .get("answer_unavailable")+ .and_then(|n| n.as_str())+ .unwrap_or_else(|| {+ panic!("answer=true without a provider must note answer_unavailable: {resp}")+ });+ assert!(+ !note.trim().is_empty(),+ "answer_unavailable note must explain why"+ );+}++/// 4. Live smoke test: wire a real provider only when a key is in the+/// environment, and assert a non-empty answer. Skips cleanly (and is+/// `#[ignore]`d) so it never runs in CI or reads a key that isn't set. Run+/// manually with `cargo test -p ai-memory-mcp -- --ignored query_answer`.+#[tokio::test]+#[ignore = "requires a live provider key (GEMINI_API_KEY or ANTHROPIC_API_KEY); run manually"]+async fn answer_live_provider_smoke() {+ use secrecy::SecretString;++ let provider: Arc<dyn LlmProvider> = if let Ok(key) = std::env::var("GEMINI_API_KEY") {+ Arc::new(+ ai_memory_llm::GeminiProvider::new(SecretString::from(key), "gemini-2.5-flash")+ .expect("gemini provider"),+ )+ } else if let Ok(key) = std::env::var("ANTHROPIC_API_KEY") {+ Arc::new(+ ai_memory_llm::AnthropicProvider::new(+ SecretString::from(key),+ "claude-3-5-haiku-latest",+ )+ .expect("anthropic provider"),+ )+ } else {+ eprintln!("no live provider key set; skipping answer_live_provider_smoke");+ return;+ };++ let tmp = TempDir::new().expect("tempdir");+ let store = Store::open(tmp.path()).expect("store");+ let ws = store.writer.get_or_create_workspace(WS).await.expect("ws");+ let proj = store+ .writer+ .get_or_create_project(ws, PROJ, None)+ .await+ .expect("proj");+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).expect("wiki");+ let server = AiMemoryServer::new(store.reader.clone(), store.writer.clone(), ws, proj)+ .with_wiki(wiki)+ .with_llm(provider);+ store+ .writer+ .upsert_page(page(+ ws,+ proj,+ "notes/deploy.md",+ "Deploys always use `compose pull`, never bin/deploy, which is single-arch.",+ ))+ .await+ .unwrap();+ let router = mount(server);++ let resp = call(+ &router,+ "memory_query",+ query_args("how do we deploy?", json!({ "answer": true })),+ )+ .await;+ let text = resp+ .get("answer")+ .and_then(|a| a.get("text"))+ .and_then(|t| t.as_str())+ .unwrap_or_else(|| panic!("live provider must synthesize an answer: {resp}"));+ assert!(+ !text.trim().is_empty(),+ "live provider answer must be non-empty: {resp}"+ );+}diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex 12d20768..c48286dd 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -369,7 +369,7 @@ invariants below.| Tool | Hint | Purpose ||---|---|---|-| `memory_query` | read-only | FTS5 + entity-match + graph RRF + optional vector RRF search, followed by bounded kind/tier/pinned/tag authority adjustment and raw fallback. Bumps access counters for page hits. Defaults to the current project; default-scoped calls also union the reserved `_global` preferences scope as `global_scope_hits`; `scopes` searches named sibling projects; `global=true` searches every project at once (each hit annotated with its workspace + project). With `AI_MEMORY_RERANKER=llm`, project/scopes candidate pools are fused before at most one final LLM relevance pass; query/title/snippet data is bounded and JSON-encoded, and any timeout, provider error, invalid/incomplete score set, or four-call concurrency saturation preserves the adjusted order. The distinct `global=true` FTS-only ranker and supplemental global-preference hits are not reranked. `explain=true` attaches per-hit `score_details` (per-stream ranks, matched entities, raw FTS/cosine/entity inverse-frequency scores, RRF contributions, graph provenance including the typed edge kind (`causes`/`fixes`/`contradicts`) a neighbour was reached by, the page's evidence count, authority multiplier, and optional rerank score) to project/scopes hits plus a top-level `streams_active` list. The global FTS-only ranker reports its active stream without per-hit details. `include_expired=true` also returns TTL-expired pages. `include_superseded=true` also returns superseded (non-latest) page versions across the FTS/entity/vector/graph streams, each hit labelled `superseded: true` (the current version is never marked); default-off is byte-identical to the latest-only behaviour, and `global=true` / `as_of` are unaffected. `pin_first=true` prepends the project's bounded pinned latest pages (`ReaderPool::list_pinned_pages`, cap 10) ahead of the fused hits, deduped by page id (a pinned page that also matches appears once, marked `pinned: true`) and re-truncated to the requested limit; it applies to single-project searches (default or `workspace`+`project`), is ignored on `scopes`/`global`/`as_of`, and default-off is byte-identical. |+| `memory_query` | read-only | FTS5 + entity-match + graph RRF + optional vector RRF search, followed by bounded kind/tier/pinned/tag authority adjustment and raw fallback. Bumps access counters for page hits. Defaults to the current project; default-scoped calls also union the reserved `_global` preferences scope as `global_scope_hits`; `scopes` searches named sibling projects; `global=true` searches every project at once (each hit annotated with its workspace + project). With `AI_MEMORY_RERANKER=llm`, project/scopes candidate pools are fused before at most one final LLM relevance pass; query/title/snippet data is bounded and JSON-encoded, and any timeout, provider error, invalid/incomplete score set, or four-call concurrency saturation preserves the adjusted order. The distinct `global=true` FTS-only ranker and supplemental global-preference hits are not reranked. `explain=true` attaches per-hit `score_details` (per-stream ranks, matched entities, raw FTS/cosine/entity inverse-frequency scores, RRF contributions, graph provenance including the typed edge kind (`causes`/`fixes`/`contradicts`) a neighbour was reached by, the page's evidence count, authority multiplier, and optional rerank score) to project/scopes hits plus a top-level `streams_active` list. The global FTS-only ranker reports its active stream without per-hit details. `include_expired=true` also returns TTL-expired pages. `include_superseded=true` also returns superseded (non-latest) page versions across the FTS/entity/vector/graph streams, each hit labelled `superseded: true` (the current version is never marked); default-off is byte-identical to the latest-only behaviour, and `global=true` / `as_of` are unaffected. `pin_first=true` prepends the project's bounded pinned latest pages (`ReaderPool::list_pinned_pages`, cap 10) ahead of the fused hits, deduped by page id (a pinned page that also matches appears once, marked `pinned: true`) and re-truncated to the requested limit; it applies to single-project searches (default or `workspace`+`project`), is ignored on `scopes`/`global`/`as_of`, and default-off is byte-identical. `answer=true` (opt-in, off by default) additionally synthesizes a cited natural-language answer over the top hits via the configured LLM provider (`complete_structured`, JSON-schema `{ answer, citations }`), attached as `answer: { text, citations }`; with no provider configured it returns the hits plus an `answer_unavailable` note instead of erroring, and with `answer` unset/`false` no provider is accessed and the response is byte-identical (invariant #13). It applies to the normal single-project/`scopes` path; `global`/`as_of` ignore it. Answer quality is not yet eval-validated. || `memory_recent` | read-only | Most-recently-updated `is_latest=1` pages. || `memory_read_page` | read-only | Fetch the FULL body of a single wiki page by `path` or by top FTS5 hit for a `query`; optional `workspace` + `project` targets a named sibling workspace/project. Use when an agent needs more than the 24-word snippets from `memory_query`. `include_related=true` also walks the link graph outward from the page (bounded BFS reusing the `page_links` primitive per node: default 1 hop, hard cap 3, global visited set for dedup/cycle-safety, total-node cap 50, cross-project aware) and returns a `related` array of reachable pages, each labelled with its `depth` (hop distance) and `direction` (`link`/`backlink`); default-off is byte-identical (no `related` field). || `memory_read_session_observations` | read-only | Page through ONE session's raw hook observations (`ObservationRecord` with full sanitized body, capped per row by `body_max_chars`), restricted to the rows that landed in the resolved scope and to sessions the caller may see; `total` and `elided_other_scope` report the in-scope count and the rows the session left in another project. `session_id` omitted reads the latest completed visible session. |