Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
Refresh answer budget and characterize correction-loss boundaries
Mihael Zamin Sousa3ac9e2329508
diff --cc CHANGELOG.mdindex d1eb2cc4,81ab3a74..ba1b91c4--- a/CHANGELOG.md+++ b/CHANGELOG.md@@@ -13,11 -13,37 +13,30 @@@ version in [`docs/changelog/`](docs/cha### Added-<<<<<<< HEAD+- Added an optional `[query_answer] max_context_tokens` admission budget for+ answer synthesis. It preserves retrieval hits, reports omitted or clipped+ evidence, and skips the model when no meaningful evidence fits. The default+ remains disabled (#1684).++ - `[auto_improve.eval] builtin = "structure"` runs the eval gate's structural+ checks in process, so the gate needs no interpreter, no scorer script inside+ the container and no timeout to hit. It checks an H1, an upper-case+ `TODO`/`TBD` placeholder (a hard failure), a `##` section and a list of steps+ for `procedures/`, and text beyond the heading within 2,400 characters for+ `_rules/` — never a section name or a wording, so the wiki's language does+ not matter. `eval_results` records `checker_name = "builtin:structure"`.+ `builtin` and `command` are mutually exclusive; `command` is unchanged for+ project-specific scorers (#1638).+-- `ai-memory llm-test --server` probes the server's own configured provider- instead of building one from the caller's environment, through a new- root-only `POST /admin/llm-test`. The retry hint that `status` and the health- panel print now names it: with the server in a container or on another host- its keys exist only there, so the old client-side hint failed with "no API- key" or a provider `400` while the server was healthy. The probe runs one- fixed short prompt, reports provider, model, latency and the error class, and- scrubs the provider's message before printing it (#1639).-||||||| d39e1165-=======+ - `ai-memory llm-test --server` probes the server's own configured provider+ instead of building one from the caller's environment, through a new+ root-only `POST /admin/llm-test`. The retry hint that `status` and the health+ panel print now names it: with the server in a container or on another host+ its keys exist only there, so the old client-side hint failed with "no API+ key" or a provider `400` while the server was healthy. The probe runs one+ fixed short prompt, reports provider, model, latency and the error class, and+ scrubs the provider's message before printing it (#1639).+->>>>>>> origin/release/3.3- Added `[handoff] deliver_on_session_start = false` to `.ai-memory.toml`. Aproject that sets it no longer gets its handoff, or the continuity notice, atsession start; the handoff is still created when the session ends and staysdiff --cc crates/ai-memory-mcp/src/server.rsindex 3489939c,830a66ec..17b26c1a--- a/crates/ai-memory-mcp/src/server.rs+++ b/crates/ai-memory-mcp/src/server.rs@@@ -8394,351 -8179,6 +8399,496 @@@ mod tests.collect()}+ #[test]+ #[ignore = "local builder microbenchmark; no provider calls"]+ fn answer_budget_measurements() {+ fn sample(mut run: impl FnMut()) -> (u128, u128) {+ for _ in 0..20 {+ run();+ }+ let mut samples = Vec::new();+ for _ in 0..31 {+ let start = std::time::Instant::now();+ for _ in 0..20 {+ run();+ }+ samples.push(start.elapsed().as_nanos() / 20);+ }+ samples.sort_unstable();+ (samples[15], samples[29])+ }+ println!(+ "C2CSV,fixture,hits,mode,request_built,content_bytes,content_scalars,admitted,omitted,clipped,estimated_input_tokens,reserved_output_tokens,p50_ns,p95_ns"+ );+ for (name, text) in [+ (+ "ascii",+ "The deployment uses a worker queue with retry policy and bounded concurrency. ",+ ),+ (+ "pt-BR",+ "A implantação usa uma fila de tarefas com repetição e concorrência limitada. ",+ ),+ ("CJK", "部署使用任务队列、重试策略和受限并发。"),+ (+ "code",+ "fn retry(attempt: usize) -> bool { attempt < 3 && queue.len() < 64 }\n",+ ),+ ] {+ let snippet: String = text.repeat(20).chars().take(240).collect();+ for n in [1, 10, 50, 100] {+ let mut hits = answer_budget_hits(&vec![snippet.as_str(); n]);+ for hit in &mut hits {+ hit.hit.title = "Deployment decision".into();+ }+ for (suffix, query) in [+ ("short", "What is the deployment decision?".to_owned()),+ ("long", "Which decision? ".repeat(10_000)),+ ] {+ for (mode, budget) in [("disabled", None), ("16000", Some(16_000))] {+ let (p50, p95) = sample(|| {+ std::hint::black_box(prepare_answer_request(+ std::hint::black_box(&query),+ &hits,+ &[],+ ReasoningTier::Minimal,+ budget,+ ));+ });+ let plan = prepare_answer_request(+ &query,+ &hits,+ &[],+ ReasoningTier::Minimal,+ budget,+ );+ let (bytes, scalars) = plan+ .request+ .as_ref()+ .map(|request| {+ let system = request.system.as_deref().unwrap_or_default();+ (+ system.len() + request.messages[0].content.len(),+ system.chars().count()+ + request.messages[0].content.chars().count(),+ )+ })+ .unwrap_or_default();+ let (admitted, omitted, clipped, estimated) = plan+ .context+ .as_ref()+ .map(|context| {+ (+ context.admitted,+ context.omitted,+ context.clipped,+ context.estimated_input_tokens.to_string(),+ )+ })+ .unwrap_or((n, 0, 0, "NA".into()));+ println!(+ "C2CSV,{name}-{suffix},{n},{mode},{},{bytes},{scalars},{admitted},{omitted},{clipped},{estimated},2000,{p50},{p95}",+ plan.request.is_some()+ );+ }+ }+ }+ }+ }++ fn answer_budget_hits(snippets: &[&str]) -> Vec<QueryHit> {+ rerank_test_hits(snippets.len())+ .into_iter()+ .zip(snippets)+ .map(|((mut hit, _), snippet)| {+ hit.snippet = (*snippet).into();+ QueryHit::from(hit)+ })+ .collect()+ }++ #[test]+ fn answer_budget_disabled_preserves_request_and_sources() {+ let hits = answer_budget_hits(&["The current deployment uses the queue."]);+ let (original, sources) = build_answer_request("question", &hits, &[], ReasoningTier::Max);+ let plan = prepare_answer_request("question", &hits, &[], ReasoningTier::Max, None);+ let actual = plan.request.unwrap();+ assert_eq!(actual.system, original.system);+ assert_eq!(actual.messages[0].content, original.messages[0].content);+ assert_eq!(actual.max_tokens, original.max_tokens);+ assert_eq!(actual.temperature, original.temperature);+ assert_eq!(plan.sources, sources);+ assert!(plan.context.is_none());+ }++ #[test]+ fn answer_budget_exact_boundary_and_one_byte_over() {+ for snippet in [+ "The current architecture uses a bounded queue with retries.",+ "A implantação usa uma fila com repetição e concorrência limitada.",+ "当前部署使用任务队列、重试策略和受限并发。当前决定已替代之前的同步调用。",+ "fn retry(n: usize) -> bool { n < 3 && queue.len() < 64 }",+ ] {+ let hits = answer_budget_hits(&[snippet]);+ let full = prepare_answer_request(+ "question",+ &hits,+ &[],+ ReasoningTier::Minimal,+ Some(100_000),+ );+ let context = full.context.unwrap();+ let exact = context.estimated_input_tokens + context.reserved_output_tokens as usize;+ let plan =+ prepare_answer_request("question", &hits, &[], ReasoningTier::Minimal, Some(exact));+ assert_eq!(plan.context.as_ref().unwrap().clipped, 0);+ assert_eq!(plan.context.as_ref().unwrap().admitted, 1);+ let plan = prepare_answer_request(+ "question",+ &hits,+ &[],+ ReasoningTier::Minimal,+ Some(exact - 1),+ );+ let context = plan.context.unwrap();+ assert_eq!(context.clipped, 1, "{snippet}");+ assert!(+ context.estimated_input_tokens + (context.reserved_output_tokens as usize) < exact+ );+ assert!(plan.request.unwrap().messages[0].content.contains('…'));+ }+ }++ #[test]+ fn answer_budget_refuses_empty_or_meaningless_evidence() {+ let hits = answer_budget_hits(&["An actual supported architecture decision."]);+ for query in ["question".to_owned(), "long question ".repeat(10_000)] {+ let plan = prepare_answer_request(&query, &hits, &[], ReasoningTier::Max, Some(1_000));+ assert!(plan.request.is_none());+ assert!(plan.sources.is_empty());+ }+ // With the same sufficient budget and evidence, only the long question+ // prevents admission: fixed question content is charged before snippets.+ let short =+ prepare_answer_request("question", &hits, &[], ReasoningTier::Minimal, Some(10_000));+ assert!(short.request.is_some());+ let long = prepare_answer_request(+ &"long question ".repeat(10_000),+ &hits,+ &[],+ ReasoningTier::Minimal,+ Some(10_000),+ );+ assert!(long.request.is_none());+ assert!(long.sources.is_empty());+ for snippets in [&[][..], &[" "][..], &["---```---```---```---```---"][..]] {+ let empty = answer_budget_hits(snippets);+ assert!(+ prepare_answer_request(+ "question",+ &empty,+ &[],+ ReasoningTier::Minimal,+ Some(100_000)+ )+ .request+ .is_none()+ );+ }+ let full = prepare_answer_request(+ "question",+ &hits,+ &[],+ ReasoningTier::Minimal,+ Some(100_000),+ );+ let context = full.context.unwrap();+ let tiny = context.estimated_input_tokens + context.reserved_output_tokens as usize+ - hits[0].hit.snippet.len()+ + 10;+ assert!(+ prepare_answer_request("question", &hits, &[], ReasoningTier::Minimal, Some(tiny))+ .request+ .is_none()+ );+ }++ #[test]+ fn answer_budget_keeps_ranked_evidence_and_excludes_omitted_citations() {+ let hits = answer_budget_hits(&[+ "The current decision uses PostgreSQL for persistence.",+ "An unrelated procedure fills the remaining context.",+ ]);+ let first = prepare_answer_request(+ "question",+ &hits[..1],+ &[],+ ReasoningTier::Minimal,+ Some(100_000),+ );+ let context = first.context.unwrap();+ let limit = context.estimated_input_tokens + context.reserved_output_tokens as usize;+ let plan =+ prepare_answer_request("question", &hits, &[], ReasoningTier::Minimal, Some(limit));+ let context = plan.context.unwrap();+ assert_eq!(+ (context.admitted, context.omitted, context.clipped),+ (1, 1, 0)+ );+ assert_eq!(hits.len(), 2);+ assert!(+ validate_answer_citations(+ AnswerSynthesis {+ answer: "supported".into(),+ citations: vec![hits[0].hit.path.to_string()]+ },+ &plan.sources+ )+ .is_some()+ );+ assert!(+ validate_answer_citations(+ AnswerSynthesis {+ answer: "unsupported".into(),+ citations: vec![hits[1].hit.path.to_string()]+ },+ &plan.sources+ )+ .is_none()+ );+ assert!(+ plan.request.unwrap().messages[0]+ .content+ .contains("1 omitted")+ );+ }++ #[test]+ fn answer_budget_does_not_hide_same_path_ambiguity_by_omission() {+ let mut hits = answer_budget_hits(&[+ "Current evidence supplies a real supported answer.",+ "Other-scope evidence must not be confused with it.",+ ]);+ hits[1].hit.path = hits[0].hit.path.clone();+ let full = prepare_answer_request(+ "question",+ &hits[..1],+ &[],+ ReasoningTier::Minimal,+ Some(100_000),+ );+ let context = full.context.unwrap();+ let limit = context.estimated_input_tokens + context.reserved_output_tokens as usize;+ let plan =+ prepare_answer_request("question", &hits, &[], ReasoningTier::Minimal, Some(limit));+ assert_eq!(plan.context.unwrap().admitted, 1);+ assert!(+ validate_answer_citations(+ AnswerSynthesis {+ answer: "ambiguous".into(),+ citations: vec![hits[0].hit.path.to_string()]+ },+ &plan.sources+ )+ .is_none()+ );+ }++ #[test]+ fn answer_budget_labels_superseded_decisions_and_preserves_corrections() {+ let mut hits = answer_budget_hits(&[+ "Correction: current deployments use PostgreSQL, replacing SQLite.",+ "Historical decision: deployments use SQLite.",+ ]);+ hits[1].hit.superseded = true;+ let plan = prepare_answer_request(+ "current deployment?",+ &hits,+ &[],+ ReasoningTier::Minimal,+ Some(10_000),+ );+ let body = &plan.request.as_ref().unwrap().messages[0].content;+ assert!(body.contains("superseded: false"));+ assert!(body.contains("superseded: true"));+ assert!(body.contains("Correction: current deployments use PostgreSQL, replacing SQLite."));+ assert_eq!(plan.context.unwrap().admitted, 2);+ }+++ /// A literal-retention oracle, not an answer-quality evaluator. Expected++ /// losses make the ranked-prefix policy's limits executable and visible.++ #[test]++ fn answer_budget_labeled_evidence_retention_boundaries() {++ const QUERY: &str = "What is the current decision?";++ let fixtures = [++ (++ "en",++ "Historical deployment decision: use SQLite for durable storage.",++ "Correction: current deployment uses PostgreSQL.",++ "current deployment uses PostgreSQL",++ ),++ (++ "pt-BR",++ "Decisão histórica de implantação: usar SQLite para armazenamento durável.",++ "Correção: a implantação atual usa PostgreSQL.",++ "a implantação atual usa PostgreSQL",++ ),++ (++ "CJK",++ "历史部署决定使用旧数据库保存持久数据,此记录仅描述之前的方案。",++ "更正:当前部署使用新的数据库方案。",++ "当前部署使用新的数据库方案",++ ),++ (++ "code",++ "// Historical deployment configuration: const DATABASE = \"sqlite\";",++ "// Correction: const DATABASE = \"postgresql\";",++ "const DATABASE = \"postgresql\";",++ ),++ ];++ println!(++ "C2RETENTION,fixture,case,baseline_literal_retained,candidate_literal_retained,admitted,omitted,clipped"++ );++ for (language, historical, correction, required_literal) in fixtures {++ let combined = format!("{historical} {correction}");++ for (case, snippets, retained, expected_counts) in [++ ("exact-fit", vec![combined.as_str()], true, (1, 0, 0)),++ ("trimmed-tail", vec![combined.as_str()], false, (1, 0, 1)),++ (++ "historical-first-omitted-correction",++ vec![historical, correction],++ false,++ (1, 1, 0),++ ),++ (++ "current-first-omitted-history",++ vec![correction, historical],++ true,++ (1, 1, 0),++ ),++ ] {++ let mut hits = answer_budget_hits(&snippets);++ if case == "historical-first-omitted-correction" {++ hits[0].hit.superseded = true;++ } else if case == "current-first-omitted-history" {++ hits[1].hit.superseded = true;++ }++ let before = serde_json::to_value(&hits).unwrap();++ let baseline =++ prepare_answer_request(QUERY, &hits, &[], ReasoningTier::Minimal, None);++ let baseline_retained = baseline.request.as_ref().unwrap().messages[0]++ .content++ .contains(required_literal);++ assert!(baseline_retained, "disabled baseline: {language}/{case}");++ assert!(baseline.context.is_none());++ let full_first = prepare_answer_request(++ QUERY,++ &hits[..1],++ &[],++ ReasoningTier::Minimal,++ Some(100_000),++ );++ let context = full_first.context.unwrap();++ let exact =++ context.estimated_input_tokens + context.reserved_output_tokens as usize;++ // In the tail case the allowance ends before the correction;++ // the ellipsis consumes three bytes of the historical prefix.++ let limit = if case == "trimmed-tail" {++ exact - correction.len() - 1++ } else {++ exact++ };++ let plan =++ prepare_answer_request(QUERY, &hits, &[], ReasoningTier::Minimal, Some(limit));++ let context = plan.context.as_ref().unwrap();++ let request = plan.request.as_ref().unwrap();++ let body = &request.messages[0].content;++ assert_eq!(++ body.contains(required_literal),++ retained,++ "{language}/{case}"++ );++ assert_eq!(++ (context.admitted, context.omitted, context.clipped),++ expected_counts,++ "{language}/{case}"++ );++ // Reconstruct the accounting from the actual request/schema,++ // independently of the builder's remaining-capacity variable.++ let schema = serde_json::to_vec(&schemars::schema_for!(AnswerSynthesis)).unwrap();++ let input = request.system.as_ref().unwrap().len()++ + request++ .messages++ .iter()++ .map(|m| m.content.len())++ .sum::<usize>()++ + schema.len()++ + ANSWER_ENVELOPE_RESERVE;++ assert_eq!(context.estimated_input_tokens, input, "{language}/{case}");++ assert!(++ input + request.max_tokens as usize <= limit,++ "{language}/{case}"++ );++ assert_eq!(plan.sources.len(), 1, "{language}/{case}");++ assert_eq!(++ plan.sources.get(hits[0].hit.path.as_str()),++ Some(&Some(hits[0].hit.id)),++ "{language}/{case}"++ );++ if hits.len() > 1 {++ assert!(!plan.sources.contains_key(hits[1].hit.path.as_str()));++ assert!(++ validate_answer_citations(++ AnswerSynthesis {++ answer: "unsupported omitted-source claim".into(),++ citations: vec![hits[1].hit.path.to_string()],++ },++ &plan.sources,++ )++ .is_none()++ );++ }++ if case == "historical-first-omitted-correction" {++ assert!(body.contains("superseded: true"));++ }++ assert_eq!(serde_json::to_value(&hits).unwrap(), before);++ println!(++ "C2RETENTION,{language},{case},{baseline_retained},{retained},{},{},{}",++ context.admitted, context.omitted, context.clipped++ );++ }++ }++ }+++ #[test]+ fn answer_sources_distinguish_repeated_rows_from_ambiguous_paths() {+ let mut hits: Vec<QueryHit> = rerank_test_hits(3)+ .into_iter()+ .map(|(hit, _)| QueryHit::from(hit))+ .collect();+ hits[1].hit = hits[0].hit.clone();+ let path = hits[0].hit.path.as_str().to_owned();+ let (_, sources) = build_answer_request("query", &hits[..2], &[], ReasoningTier::Minimal);+ let answer = || AnswerSynthesis {+ answer: "A supported answer".into(),+ citations: vec![path.clone(), path.clone()],+ };+ assert_eq!(+ validate_answer_citations(answer(), &sources)+ .unwrap()+ .citations+ .as_slice(),+ std::slice::from_ref(&path)+ );++ // Different scoped rows (or versions) can have the same path. A later+ // repeat of the first row must not erase that ambiguity.+ hits[2].hit.path = hits[0].hit.path.clone();+ hits.swap(1, 2);+ let (_, sources) = build_answer_request("query", &hits, &[], ReasoningTier::Minimal);+ assert!(validate_answer_citations(answer(), &sources).is_none());+ }+#[tokio::test]async fn reranker_reorders_one_bounded_prefix_without_shrinking_large_limits() {let (_tmp, _store, server, _ws, _proj) = setup_server().await;diff --cc crates/ai-memory-mcp/tests/suite/query_answer.rsindex e62d4bfb,c7241334..6ae7fa72--- a/crates/ai-memory-mcp/tests/suite/query_answer.rs+++ b/crates/ai-memory-mcp/tests/suite/query_answer.rs@@@ -16,8 -16,8 +16,8 @@@//! 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 std::sync::{Arc, Mutex};use ai_memory_core::{NewPage, PagePath, ProjectId, Tier, WorkspaceId};use ai_memory_llm::{ChatRequest, ChatResponse, LlmProvider, LlmResult};@@@ -41,7 -41,6 +41,8 @@@ const PROJ: &str = "scratch"/// synthesized shape AND that the default path never touches the LLM.struct FakeAnswerLlm {calls: Arc<AtomicUsize>,+ response: Value,++ requests: Arc<Mutex<Vec<(ChatRequest, Value)>>>,}#[async_trait::async_trait]@@@ -65,12 -64,15 +66,13 @@@ impl LlmProvider for FakeAnswerLlmasync fn complete_structured_raw(&self,-- _request: ChatRequest,-- _schema: serde_json::Value,++ request: ChatRequest,++ schema: serde_json::Value,) -> LlmResult<serde_json::Value> {self.calls.fetch_add(1, Ordering::SeqCst);++ self.requests.lock().unwrap().push((request, schema));// 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"],- }))+ Ok(self.response.clone())}}@@@ -82,6 -84,6 +84,7 @@@ struct Harness/// Call counter shared with the wired fake provider; `None` when no provider/// was attached.calls: Option<Arc<AtomicUsize>>,++ requests: Arc<Mutex<Vec<(ChatRequest, Value)>>>,_tmp: TempDir,}@@@ -126,14 -109,12 +129,16 @@@ async fn harness_with_budget.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 mut server = AiMemoryServer::new(store.reader.clone(), store.writer.clone(), ws, proj)+ .with_wiki(wiki)+ .with_answer_context_budget(budget);++ let requests = Arc::new(Mutex::new(Vec::new()));let calls = if with_provider {let calls = Arc::new(AtomicUsize::new(0));let provider: Arc<dyn LlmProvider> = Arc::new(FakeAnswerLlm {calls: calls.clone(),+ response,++ requests: requests.clone(),});server = server.with_llm(provider);Some(calls)@@@ -147,6 -128,6 +152,7 @@@ws,proj,calls,++ requests,_tmp: tmp,}}@@@ -638,121 -418,3 +644,171 @@@ async fn answer_live_provider_smoke()"live provider answer must be non-empty: {resp}");}++#[tokio::test]+async fn answer_budget_never_calls_provider_without_evidence_and_keeps_hits() {+ let h = harness_with_budget(+ true,+ json!({"answer":"unreachable", "citations":[]}),+ Some(1),+ )+ .await;+ seed_needle(&h).await;+ let resp = call(+ &h.router,+ "memory_query",+ query_args("needle", json!({"answer":true})),+ )+ .await;+ assert_eq!(hit_paths(&resp), ["notes/topic.md"]);+ assert!(resp.get("answer").is_none());+ assert!(+ resp["answer_unavailable"]+ .as_str()+ .unwrap()+ .contains("no meaningful evidence")+ );+ assert_eq!(resp["answer_context"]["omitted"], 1);+ assert_eq!(h.calls.unwrap().load(Ordering::SeqCst), 0);+}++#[tokio::test]+async fn answer_budget_is_inert_on_default_and_no_provider_queries() {+ for with_provider in [true, false] {+ let h = harness_with_budget(+ with_provider,+ json!({"answer":"unused", "citations":[]}),+ Some(1),+ )+ .await;+ seed_needle(&h).await;+ let default = call(&h.router, "memory_query", query_args("needle", json!({}))).await;+ assert!(default.get("answer_context").is_none());+ assert!(default.get("answer_unavailable").is_none());+ if !with_provider {+ let answer = call(+ &h.router,+ "memory_query",+ query_args("needle", json!({"answer":true})),+ )+ .await;+ assert!(answer.get("answer_context").is_none());+ assert!(+ answer["answer_unavailable"]+ .as_str()+ .unwrap()+ .contains("no LLM")+ );+ }+ }+}++async fn seed_budget_pages(h: &Harness, second: bool) {+ let mut first = page(+ h.ws,+ h.proj,+ "notes/topic.md",+ "needle: current deployment uses PostgreSQL.",+ );+ first.pinned = true;+ h.store.writer.upsert_page(first).await.unwrap();+ if second {+ h.store+ .writer+ .upsert_page(page(+ h.ws,+ h.proj,+ "notes/omitted.md",+ "needle: unrelated procedure for the build system.",+ ))+ .await+ .unwrap();+ }+}++#[tokio::test]+async fn answer_budget_transport_accepts_admitted_and_rejects_omitted_sources() {+ let response = |path: &str| json!({"answer":"PostgreSQL", "citations":[path]});+ let full = harness_with_budget(true, response("notes/topic.md"), Some(100_000)).await;+ seed_budget_pages(&full, false).await;+ let arguments = || query_args("needle", json!({"answer":true, "pin_first":true}));+ let resp = call(&full.router, "memory_query", arguments()).await;+ assert_eq!(resp["answer"]["citations"], json!(["notes/topic.md"]));+ let limit = resp["answer_context"]["estimated_input_tokens"]+ .as_u64()+ .unwrap()+ + resp["answer_context"]["reserved_output_tokens"]+ .as_u64()+ .unwrap();+ for path in ["notes/topic.md", "notes/omitted.md"] {+ let h = harness_with_budget(true, response(path), Some(limit as usize)).await;+ seed_budget_pages(&h, true).await;+ let resp = call(&h.router, "memory_query", arguments()).await;+ assert_eq!(hit_paths(&resp), ["notes/topic.md", "notes/omitted.md"]);+ assert_eq!(resp["answer_context"]["admitted"], 1);+ assert_eq!(resp["answer_context"]["omitted"], 1);+ assert_eq!(h.calls.as_ref().unwrap().load(Ordering::SeqCst), 1);+ if path == "notes/topic.md" {+ assert_eq!(resp["answer"]["citations"], json!([path]));+ assert!(resp.get("answer_unavailable").is_none());+ } else {+ assert!(resp.get("answer").is_none());+ assert!(+ resp["answer_unavailable"]+ .as_str()+ .unwrap()+ .contains("citations")+ );+ }+ }+}++++#[tokio::test]++async fn answer_budget_receipt_matches_request_at_provider_boundary() {++ // Inspect the actual structured call, including its schema. A canned answer++ // alone cannot detect a handler that accounts one prompt and sends another.++ for (tier, output) in [++ ("minimal", 2_000_u64),++ ("low", 3_000),++ ("medium", 4_000),++ ("high", 6_000),++ ("max", 8_000),++ ] {++ let h = harness_with_budget(++ true,++ json!({"answer":"PostgreSQL", "citations":["notes/topic.md"]}),++ Some(16_000),++ )++ .await;++ seed_budget_pages(&h, true).await;++ let resp = call(++ &h.router,++ "memory_query",++ query_args("needle", json!({"answer":true, "reasoning":tier})),++ )++ .await;++ let requests = h.requests.lock().unwrap();++ assert_eq!(requests.len(), 1, "{tier}");++ let (request, schema) = &requests[0];++ let actual_input = request.system.as_ref().unwrap().len()++ + request++ .messages++ .iter()++ .map(|m| m.content.len())++ .sum::<usize>()++ + serde_json::to_vec(schema).unwrap().len()++ + 1_024;++ assert_eq!(request.max_tokens as u64, output, "{tier}");++ assert_eq!(resp["answer_context"]["reserved_output_tokens"], output);++ assert_eq!(++ resp["answer_context"]["estimated_input_tokens"],++ actual_input++ );++ assert!(actual_input + request.max_tokens as usize <= 16_000);++ assert_eq!(resp["answer_context"]["admitted"], 2);++ assert_eq!(resp["answer_context"]["omitted"], 0);++ assert_eq!(resp["answer_context"]["clipped"], 0);++ assert_eq!(hit_paths(&resp).len(), 2);++ assert_eq!(h.calls.as_ref().unwrap().load(Ordering::SeqCst), 1);++ }++}diff --cc docs/benchmarks/query-answer-context-draft.mdindex 254c8310,00000000..d5661a9cmode 100644,000000..100644--- a/docs/benchmarks/query-answer-context-draft.md+++ b/docs/benchmarks/query-answer-context-draft.md@@@ -1,71 -1,0 +1,111 @@@+# Query-answer context admission: draft local measurements++This receipt accompanies the default-disabled proposal in #1684. Its configuration,+response contract and pruning policy still need maintainer agreement. It measures+builder size and local execution time, not answer correctness or provider usage.++## Provenance++- Feature base: `e7e17555efb6a95596480249598ad517ff587310`.+- Citation-validation prerequisite: `91aa3d26df4df8064b270f8d5242cfca465d08d7`.+- Candidate code: `71f9cd36015ab4a578641630714615e5b37f4768`.+- Run: 2026-10-25 UTC, Linux 6.18.55 x86_64, AMD EPYC 9V74, 9 visible logical CPUs.+- Rust: `1.95.0 (59807616e 2026-04-14)`, debug test profile, `CARGO_INCREMENTAL=0`.+- Provider/model: none. No model requests or paid evaluations.+- Fixture: `server::tests::answer_budget_measurements`; SHA-256 of that function's+ source through the following helper boundary:+ `570d36eca47aaf411461991588642fbc432124ed6800bd99c1f1fe1d81bbd6e7`.+- CSV SHA-256: `83d1ead149d3fe2c0108135ca6440fd8b29db39b872453cab918b66da4c787ed`.+- Published candidate tree equals local tested commit `bd3179ef5d89ebdc5bd71167425d821d0c6e9f5e`+ (tree `ac2c5787080eab464d7958a09ccc0c1733c64f41`).+- Both modes ran in the candidate binary. Disabled admission delegates to the+ unchanged baseline builder; this is a mode comparison, not two separately+ compiled binaries. The disabled-request regression test compares their fields.++The fixture uses 1, 10, 50 and 100 hits, each with a 240-scalar snippet, across+ASCII, pt-BR, CJK and code. Questions are either 32 bytes or 160,000 bytes. Each+mode uses 20 warmup calls and 31 timed trials of 20 calls. The CSV records per-call+p50 and p95 nanoseconds from those trials. Other builds ran on the shared host,+so these debug timings are exploratory and do not establish production latency.++## Results++The table shows the 100-hit short-question cases. Content bytes count only system+and user messages. The enabled mode also counts serialized schema bytes and 1024+envelope units, then reserves 2000 output tokens, within its 16000-unit target.+The one-byte-per-estimated-input-token contract is not a tokenizer guarantee.++| Fixture | Disabled bytes | Enabled bytes | Byte reduction | Admitted / omitted / clipped | Disabled p50 / p95 µs | Enabled p50 / p95 µs |+|---|---:|---:|---:|---|---:|---:|+| ascii | 31422 | 12156 | 61.31% | 35 / 65 / 0 | 261.37 / 270.36 | 185.12 / 200.18 |+| pt-BR | 32922 | 12191 | 62.97% | 34 / 66 / 1 | 270.66 / 291.94 | 194.16 / 228.80 |+| CJK | 79422 | 12189 | 84.65% | 15 / 85 / 1 | 728.71 / 1087.62 | 179.16 / 195.91 |+| code | 31422 | 12156 | 61.31% | 35 / 65 / 0 | 250.47 / 491.15 | 179.76 / 276.06 |++All long-question cases produced no request in the enabled mode. Their receipt+can report estimated input above the limit: it explains the refused request,+not a prompt sent to a provider. CSV `NA` means disabled mode has no input-token+estimate; it does not mean zero tokens. `content_bytes=0` with `request_built=false`+means no request was built.++The one-hit ASCII case added local work: p50 rose from 5.317 µs to 49.540 µs,+including schema sizing. Larger cases did less rendering because they omitted+sources. No overhead acceptance threshold has been agreed.++The CJK case admits only 15 of 100 sources at this conservative budget. Clipping+can remove a correction or qualification. Deterministic tests check that supplied+corrections remain intact when they fit and that superseded status is labelled;+answer accuracy under pruning remains unmeasured and blocks a ready-for-review+claim. Retrieval hits and ranking remain unchanged.++Full measurements: [CSV](query-answer-context-draft.csv).+++## Offline evidence-retention regression++++`answer_budget_labeled_evidence_retention_boundaries` uses labeled English,++pt-BR, CJK and code fixtures with an exact required current-fact literal. It++checks the prompt produced by the actual builder, without a provider. Its++16 cases specify these outcomes for each language:++++| Budget/order boundary | Required current-fact literal | Admission |++|---|---|---|++| Exact fit, history followed by correction in one snippet | Retained | 1 admitted, 0 omitted, 0 clipped |++| Same snippet, allowance ends before its correction | Lost | 1 admitted, 0 omitted, 1 clipped |++| Historical source first; only that source fits | Lost | 1 admitted, 1 omitted, 0 clipped |++| Current correction first; only that source fits | Retained | 1 admitted, 1 omitted, 0 clipped |++++Measured on 2026-10-25 with local source commit++`94293327faa450b52d13bea584e89865c185ac56`, Rust 1.95.0, on the Linux host++described above: the disabled-mode baseline retained the required literal in++16 of 16 cases; the bounded candidate retained it in 8 of 16 cases. These are++deliberate boundary probes, not representative quality estimates or model-answer++accuracy scores. One deterministic run records baseline and candidate retention++separately for every case; it makes no provider calls.++++The assertions also reconstruct input accounting from the request and schema,++check the configured bound, verify admitted/omitted citation identities, and++compare full retrieval hits before and after admission. Historical-first++fixtures mark the admitted historical source `superseded: true`; that label++does not recover an omitted correction. Lines prefixed `C2RETENTION,` report++the asserted outcomes when run with `--nocapture`.++++This is a literal-retention regression, not model answer-quality evaluation.++The two loss cases deliberately pass only when they expose the known loss;++they do not establish acceptable pruning quality. Clipping and ranked-prefix++omission can remove the current fact while leaving historical evidence available++for synthesis. That unresolved policy risk and maintainer contract agreement++still block readiness. No prompt-only abstention guarantee is claimed.++++```sh++cargo test -p ai-memory-mcp --lib answer_budget_labeled_evidence_retention_boundaries -- --nocapture++```+++## Reproduce++```sh+cargo test -p ai-memory-mcp --lib answer_budget_measurements -- --ignored --nocapture+```++Lines beginning `C2CSV,` contain the receipt. Remove that prefix to recover the+CSV. No provider configuration is needed. The test is ignored in normal CI so+its timing loop does not become part of the everyday test run.