Skip to content

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

Rust

feat(query,explore): opt-in reasoning tier for the answer/explore LLM path

AkitaOnRails9d98676eb031
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4f59fec8..117be38e 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
+- Reasoning tier on the LLM synthesis paths: an opt-in `reasoning` argument on
+ `memory_query` (its `answer` path) and `memory_explore` (borrowed from
+ Honcho's reasoning-effort ladder; targets the 2.4 line). The knob is a schema
+ enum `minimal` (default) / `low` / `medium` / `high` / `max`; an unknown value
+ is rejected. Because the provider-neutral `ChatRequest` carries no per-request
+ reasoning/effort field (the provider-level `reasoning_effort` is fixed at
+ construction from config), the tier maps honestly to a per-tier max-token
+ budget scaled off each path's base budget (answer 2 000, explore 16 000):
+ `minimal` = 1x, `low` = 1.5x, `medium` = 2x, `high` = 3x, `max` = 4x — a
+ higher tier gives the model more room to reason before its output is
+ truncated. It only tunes the answer path: `reasoning` is inert unless the LLM
+ path actually runs (`answer: true` with a provider, or `memory_explore` with a
+ provider), so the zero-LLM default path is untouched. Omitting `reasoning`, or
+ passing `minimal`, is byte-identical to before. No new MCP tool (still 23)
+ (#784).
- 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
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.md
index 1ee6ac1e..e3fc1ede 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
@@ -83,6 +83,15 @@ 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.
+Pair `answer: true` with a `reasoning` tier — `minimal` (default), `low`,
+`medium`, `high`, or `max` — to tune how hard the model works on the synthesis.
+Higher tiers hand the model a larger token budget so it can reason longer before
+its answer is truncated; `minimal` (and omitting `reasoning`) is byte-identical
+to today. `memory_explore` takes the same `reasoning` tier for its prose digest.
+The tier only matters when the LLM path actually runs: with `answer: false` (or
+no provider configured) it is inert and no LLM call is made. An unknown value is
+rejected by the schema.
+
## Snippets are not full pages
Search 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/src/server.rs b/crates/ai-memory-mcp/src/server.rs
index 6ac9b73e..cd6b0891 100644
--- a/crates/ai-memory-mcp/src/server.rs
+++ b/crates/ai-memory-mcp/src/server.rs
@@ -214,7 +214,10 @@ developer, user, and canonical project instructions.\n\
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 \
+ no LLM call. Pair `answer=true` with `reasoning` \
+ (`minimal` (default) / `low` / `medium` / `high` / `max`) to give the \
+ synthesis a larger token budget for a harder question; `minimal` and \
+ omitting it are unchanged. 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 \
@@ -229,8 +232,11 @@ developer, user, and canonical project instructions.\n\
- `memory_explore` — when the user wants a PROSE digest. \
Calibrates verbosity to time since last activity: 'fresh' → one \
line, 'stale' (>30d) → full catchup. Accepts an optional `focus` \
- arg. Use over memory_briefing when the user asks open-ended \
- questions like 'catch me up' or 'what's important right now'.\n\
+ arg, and a `reasoning` tier (`minimal` (default) / `low` / `medium` / \
+ `high` / `max`) that widens the digest's token budget when a provider \
+ is configured (inert on the briefing-only path). Use over \
+ memory_briefing when the user asks open-ended questions like 'catch me \
+ up' or 'what's important right now'.\n\
- `memory_handoff_list` — READ-ONLY list of OPEN handoffs in the \
resolved project. It does not claim or expire anything. Use it when \
no SessionStart handoff block is in context (Grok, Zero, and other \
@@ -611,6 +617,58 @@ struct QueryArgs {
/// `as_of` queries.
#[serde(default)]
answer: Option<bool>,
+ /// Reasoning effort for the `answer` synthesis path: one of `minimal`
+ /// (default), `low`, `medium`, `high`, `max`. Higher tiers give the model a
+ /// larger token budget to reason within. Only meaningful together with
+ /// `answer=true`; inert on the default (no-LLM) path. Omitting it, or
+ /// `minimal`, is byte-identical to today. An unknown value is rejected.
+ #[serde(default)]
+ reasoning: Option<ReasoningTier>,
+}
+
+/// Operator-facing reasoning-effort tier for the opt-in LLM synthesis paths
+/// (`memory_query(answer=true)` and `memory_explore`). Borrowed from Honcho's
+/// reasoning-effort ladder.
+///
+/// `ChatRequest` carries no per-request reasoning/effort field today (the
+/// provider-level `reasoning_effort` is fixed at construction from config), so
+/// the honest per-request mapping is a per-tier **max-token budget**: a higher
+/// tier gives the model more room to reason before its answer is truncated.
+/// [`Self::Minimal`] (the default) leaves each path's base budget unchanged, so
+/// omitting `reasoning` is byte-identical to the pre-tier behavior. Serde
+/// rejects an unknown value (invariant #7: typed, schema-checked inputs).
+#[derive(
+ Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, schemars::JsonSchema,
+)]
+#[serde(rename_all = "lowercase")]
+enum ReasoningTier {
+ /// Current behavior: the path's base token budget, unchanged.
+ #[default]
+ Minimal,
+ /// A modestly wider budget.
+ Low,
+ /// Twice the base budget.
+ Medium,
+ /// Three times the base budget.
+ High,
+ /// Four times the base budget.
+ Max,
+}
+
+impl ReasoningTier {
+ /// Scale a path's base max-token budget for this tier. `Minimal` returns the
+ /// base unchanged (byte-identical to pre-tier behavior); higher tiers widen
+ /// it so synthesis can reason longer before truncation. Saturating so a
+ /// large base never overflows.
+ const fn scale_max_tokens(self, base: u32) -> u32 {
+ match self {
+ Self::Minimal => base,
+ Self::Low => base.saturating_add(base / 2),
+ Self::Medium => base.saturating_mul(2),
+ Self::High => base.saturating_mul(3),
+ Self::Max => base.saturating_mul(4),
+ }
+ }
}
#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]
@@ -1321,6 +1379,13 @@ struct ExploreArgs {
/// omit both for the current project; static MCP clients must pass both.
#[serde(default)]
workspace: Option<String>,
+ /// Reasoning effort for the LLM digest: one of `minimal` (default), `low`,
+ /// `medium`, `high`, `max`. Higher tiers give the model a larger token
+ /// budget. Inert when no provider is configured (the briefing-only path).
+ /// Omitting it, or `minimal`, is byte-identical to today. Unknown value
+ /// rejected.
+ #[serde(default)]
+ reasoning: Option<ReasoningTier>,
}
#[derive(Debug, Default, Serialize, Deserialize, schemars::JsonSchema)]
struct InstallSelfRoutingArgs {
@@ -2486,7 +2551,12 @@ impl AiMemoryServer {
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);
+ let request = build_answer_request(
+ &args.query,
+ &hits,
+ &global_scope_hits,
+ args.reasoning.unwrap_or_default(),
+ );
match ai_memory_llm::complete_structured::<AnswerSynthesis>(
llm.as_ref(),
request,
@@ -4552,7 +4622,12 @@ impl AiMemoryServer {
};
let gap = explore_gap_from_snapshot(&snapshot);
- let request = build_explore_request(&snapshot, &gap, args.focus.as_deref());
+ let request = build_explore_request(
+ &snapshot,
+ &gap,
+ args.focus.as_deref(),
+ args.reasoning.unwrap_or_default(),
+ );
let provider = llm.llm();
let text = match provider.complete(request).await {
Ok(resp) => resp.text,
@@ -5179,6 +5254,7 @@ fn build_explore_request(
snapshot: &ai_memory_store::BriefingSnapshot,
gap: &ExploreGap,
focus: Option<&str>,
+ reasoning: ReasoningTier,
) -> ai_memory_llm::ChatRequest {
let snapshot_json = serde_json::to_string_pretty(snapshot).unwrap_or_else(|_| "{}".into());
let mut user = String::new();
@@ -5204,7 +5280,8 @@ fn build_explore_request(
// memory_explore returns prose, not JSON, so a truncated
// response is degraded but not unparseable. Still generous
// so the long `dormant`/`stale` digests don't get cut off.
- max_tokens: 16_000,
+ // Base budget scaled by the reasoning tier; `Minimal` keeps 16_000.
+ max_tokens: reasoning.scale_max_tokens(16_000),
temperature: Some(0.2),
}
}
@@ -5234,6 +5311,7 @@ fn build_answer_request(
query: &str,
hits: &[QueryHit],
global_scope_hits: &[QueryHit],
+ reasoning: ReasoningTier,
) -> ai_memory_llm::ChatRequest {
fn clean(snippet: &str) -> String {
snippet.replace("<mark>", "").replace("</mark>", "")
@@ -5262,7 +5340,9 @@ fn build_answer_request(
role: ai_memory_llm::Role::User,
content: user,
}],
- max_tokens: 2_000,
+ // Base budget scaled by the reasoning tier; `Minimal` keeps 2_000
+ // (byte-identical to the pre-tier answer path).
+ max_tokens: reasoning.scale_max_tokens(2_000),
temperature: Some(0.1),
}
}
@@ -5768,6 +5848,7 @@ mod tests {
explain: Some(true),
as_of: None,
answer: None,
+ reasoning: None,
}),
test_optional_parts(),
)
@@ -5802,6 +5883,7 @@ mod tests {
explain: None,
as_of: None,
answer: None,
+ reasoning: None,
}),
test_optional_parts(),
)
@@ -7532,6 +7614,7 @@ mod tests {
explain: Some(true),
as_of,
answer: None,
+ reasoning: None,
};
// Historical instant → the superseded version answers.
@@ -7573,6 +7656,7 @@ mod tests {
explain: Some(true),
as_of: Some(jiff::Timestamp::now().to_string()),
answer: None,
+ reasoning: None,
}),
OptionalParts(test_parts_default()),
)
@@ -7645,6 +7729,7 @@ mod tests {
explain: None,
as_of: None,
answer: None,
+ reasoning: None,
}),
OptionalParts(test_parts_default()),
)
@@ -7673,6 +7758,7 @@ mod tests {
explain: Some(true),
as_of: None,
answer: None,
+ reasoning: None,
}),
OptionalParts(test_parts_default()),
)
@@ -7769,6 +7855,7 @@ mod tests {
explain: Some(true),
as_of: None,
answer: None,
+ reasoning: None,
}),
OptionalParts(test_parts_default()),
)
@@ -7859,6 +7946,7 @@ mod tests {
explain: None,
as_of: None,
answer: None,
+ reasoning: None,
};
let result = server
@@ -7939,6 +8027,7 @@ mod tests {
explain: None,
as_of: None,
answer: None,
+ reasoning: None,
}),
OptionalParts(test_parts_default()),
)
@@ -8070,6 +8159,7 @@ mod tests {
explain: None,
as_of: None,
answer: None,
+ reasoning: None,
}),
OptionalParts(test_parts_default()),
)
@@ -8152,6 +8242,7 @@ mod tests {
explain: None,
as_of: None,
answer: None,
+ reasoning: None,
}),
test_optional_parts(),
)
@@ -8250,6 +8341,7 @@ mod tests {
explain: None,
as_of: None,
answer: None,
+ reasoning: None,
}),
test_optional_parts(),
)
@@ -8319,6 +8411,7 @@ mod tests {
explain: None,
as_of: None,
answer: None,
+ reasoning: None,
}),
test_optional_parts(),
)
@@ -8364,6 +8457,7 @@ mod tests {
explain: None,
as_of: None,
answer: None,
+ reasoning: None,
}),
test_optional_parts(),
)
@@ -8442,6 +8536,7 @@ mod tests {
explain: None,
as_of: None,
answer: None,
+ reasoning: None,
}),
test_optional_parts(),
)
@@ -8511,6 +8606,7 @@ mod tests {
explain: None,
as_of: None,
answer: None,
+ reasoning: None,
}),
OptionalParts(test_parts_default()),
)
@@ -9567,6 +9663,7 @@ mod tests {
explain: Some(true),
as_of: None,
answer: None,
+ reasoning: None,
}),
OptionalParts(test_parts_default()),
)
@@ -9679,6 +9776,7 @@ mod tests {
explain: Some(true),
as_of: None,
answer: None,
+ reasoning: None,
}),
OptionalParts(test_parts_default()),
)
@@ -9729,6 +9827,7 @@ mod tests {
explain: None,
as_of: None,
answer: None,
+ reasoning: None,
}),
OptionalParts(test_parts_default()),
)
@@ -9812,6 +9911,7 @@ mod tests {
explain: None,
as_of: None,
answer: None,
+ reasoning: None,
}),
OptionalParts(test_parts_default()),
)
@@ -9847,6 +9947,7 @@ mod tests {
explain: None,
as_of: None,
answer: None,
+ reasoning: None,
}),
OptionalParts(test_parts_default()),
)
@@ -9886,6 +9987,7 @@ mod tests {
explain: None,
as_of: None,
answer: None,
+ reasoning: None,
}),
OptionalParts(test_parts_default()),
)
@@ -10037,6 +10139,7 @@ mod tests {
recent_pages_limit: Some(5),
project: None,
workspace: None,
+ reasoning: None,
}),
OptionalParts(test_parts_default()),
)
@@ -12766,6 +12869,7 @@ mod tests {
explain: None,
as_of: None,
answer: None,
+ reasoning: None,
}),
OptionalParts(test_parts_default()),
)
@@ -12803,6 +12907,7 @@ mod tests {
explain: None,
as_of: None,
answer: None,
+ reasoning: None,
}),
OptionalParts(test_parts_default()),
)
diff --git a/crates/ai-memory-mcp/tests/suite/mod.rs b/crates/ai-memory-mcp/tests/suite/mod.rs
index 1577ec41..4bcff315 100644
--- a/crates/ai-memory-mcp/tests/suite/mod.rs
+++ b/crates/ai-memory-mcp/tests/suite/mod.rs
@@ -24,6 +24,7 @@ mod handoff_identity;
mod mcp_stateless_http;
mod query_answer;
mod query_pin_first;
+mod query_reasoning;
mod query_superseded;
mod read_page_related;
mod retrieval_via_tools;
diff --git a/crates/ai-memory-mcp/tests/suite/query_reasoning.rs b/crates/ai-memory-mcp/tests/suite/query_reasoning.rs
new file mode 100644
index 00000000..f5fe7ff6
--- /dev/null
+++ b/crates/ai-memory-mcp/tests/suite/query_reasoning.rs
@@ -0,0 +1,277 @@
+//! 2.4 opt-in `reasoning` tier on the `memory_query(answer=true)` synthesis
+//! path (borrowed from Honcho's reasoning-effort ladder). The knob is a serde
+//! enum `{minimal, low, medium, high, max}` (default `minimal`).
+//!
+//! `ChatRequest` carries no per-request reasoning/effort field today (the
+//! provider-level `reasoning_effort` is fixed at construction from config), so
+//! the honest per-request mapping is a per-tier max-token budget. These tests
+//! capture the outgoing `ChatRequest.max_tokens` and prove:
+//!
+//! 1. `reasoning:high` forwards a strictly larger token budget than
+//! `reasoning:minimal`.
+//! 2. Omitting `reasoning` is byte-identical to `reasoning:minimal`, and both
+//! equal the pre-B5 default budget (2000) — the default path is unchanged.
+//! 3. An invalid `reasoning` value is rejected by the schema enum (the tool
+//! call errors cleanly rather than silently degrading).
+
+use std::sync::Arc;
+use std::sync::Mutex;
+
+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";
+
+/// The pre-B5 answer-synthesis token budget. `reasoning:minimal` (and omitting
+/// `reasoning`) must forward exactly this so the default path is unchanged.
+const MINIMAL_ANSWER_BUDGET: u32 = 2_000;
+
+/// A fake `LlmProvider` that records the `max_tokens` of every structured
+/// request it receives, so a test can assert how the tier scaled the budget.
+struct CapturingLlm {
+ seen_max_tokens: Arc<Mutex<Vec<u32>>>,
+}
+
+#[async_trait::async_trait]
+impl LlmProvider for CapturingLlm {
+ fn name(&self) -> &'static str {
+ "capture"
+ }
+
+ fn model(&self) -> &str {
+ "capture-1"
+ }
+
+ async fn complete(&self, request: ChatRequest) -> LlmResult<ChatResponse> {
+ self.seen_max_tokens
+ .lock()
+ .unwrap()
+ .push(request.max_tokens);
+ Ok(ChatResponse {
+ text: "unused".into(),
+ usage: None,
+ model: "capture-1".into(),
+ })
+ }
+
+ async fn complete_structured_raw(
+ &self,
+ request: ChatRequest,
+ _schema: serde_json::Value,
+ ) -> LlmResult<serde_json::Value> {
+ self.seen_max_tokens
+ .lock()
+ .unwrap()
+ .push(request.max_tokens);
+ 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,
+ seen_max_tokens: Arc<Mutex<Vec<u32>>>,
+ _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)
+}
+
+async fn harness() -> 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 seen_max_tokens = Arc::new(Mutex::new(Vec::new()));
+ let provider: Arc<dyn LlmProvider> = Arc::new(CapturingLlm {
+ seen_max_tokens: seen_max_tokens.clone(),
+ });
+ let server = AiMemoryServer::new(store.reader.clone(), store.writer.clone(), ws, proj)
+ .with_wiki(wiki)
+ .with_llm(provider);
+
+ Harness {
+ router: mount(server),
+ store,
+ ws,
+ proj,
+ seen_max_tokens,
+ _tmp: tmp,
+ }
+}
+
+/// Full JSON-RPC envelope (so a test can inspect `error` on a rejected call).
+async fn call_raw(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");
+ serde_json::from_str(&text).unwrap_or_else(|e| panic!("non-JSON: {text}: {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 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();
+}
+
+async fn query(h: &Harness, extra: Value) {
+ let resp = call_raw(&h.router, "memory_query", query_args("needle", extra)).await;
+ assert!(
+ resp.get("error").is_none(),
+ "unexpected JSON-RPC error: {resp}"
+ );
+}
+
+/// 1. A higher tier forwards a strictly larger token budget than minimal.
+#[tokio::test]
+async fn higher_reasoning_tier_widens_token_budget() {
+ let h = harness().await;
+ seed_needle(&h).await;
+
+ query(&h, json!({ "answer": true, "reasoning": "minimal" })).await;
+ query(&h, json!({ "answer": true, "reasoning": "high" })).await;
+
+ let seen = h.seen_max_tokens.lock().unwrap().clone();
+ assert_eq!(
+ seen.len(),
+ 2,
+ "each answer=true call must reach the provider once: {seen:?}"
+ );
+ let (minimal, high) = (seen[0], seen[1]);
+ assert!(
+ high > minimal,
+ "reasoning:high must forward a larger token budget than minimal \
+ (high={high}, minimal={minimal})"
+ );
+}
+
+/// 2. Omitting `reasoning` == `reasoning:minimal`, and both equal the pre-B5
+/// default budget. The default path stays byte-identical.
+#[tokio::test]
+async fn default_reasoning_equals_minimal_and_is_unchanged() {
+ let h = harness().await;
+ seed_needle(&h).await;
+
+ query(&h, json!({ "answer": true })).await;
+ query(&h, json!({ "answer": true, "reasoning": "minimal" })).await;
+
+ let seen = h.seen_max_tokens.lock().unwrap().clone();
+ assert_eq!(seen.len(), 2, "two answer=true calls expected: {seen:?}");
+ assert_eq!(
+ seen[0], seen[1],
+ "omitting reasoning must equal reasoning:minimal: {seen:?}"
+ );
+ assert_eq!(
+ seen[0], MINIMAL_ANSWER_BUDGET,
+ "the default/minimal budget must match the pre-B5 value ({MINIMAL_ANSWER_BUDGET})"
+ );
+}
+
+/// 3. An invalid `reasoning` value is rejected by the schema enum — the call
+/// errors cleanly and never reaches the provider.
+#[tokio::test]
+async fn invalid_reasoning_value_is_rejected() {
+ let h = harness().await;
+ seed_needle(&h).await;
+
+ let resp = call_raw(
+ &h.router,
+ "memory_query",
+ query_args("needle", json!({ "answer": true, "reasoning": "supreme" })),
+ )
+ .await;
+
+ assert!(
+ resp.get("error").is_some() || resp.pointer("/result/isError") == Some(&json!(true)),
+ "an invalid reasoning value must be rejected: {resp}"
+ );
+ assert!(
+ h.seen_max_tokens.lock().unwrap().is_empty(),
+ "a rejected call must never reach the provider"
+ );
+}
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index c48286dd..787d3cc9 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -369,13 +369,13 @@ 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. `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_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. An optional `reasoning` tier (`minimal` (default) / `low` / `medium` / `high` / `max`) tunes the synthesis effort: `ChatRequest` carries no per-request reasoning field (the provider-level `reasoning_effort` is fixed at construction from config), so the tier maps to a per-tier max-token budget scaled off the path's base (answer base 2 000; `minimal` = 1x = byte-identical, `low` 1.5x, `medium` 2x, `high` 3x, `max` 4x). The tier is inert unless the `answer` LLM path runs (invariant #13); an unknown value is rejected by the schema (invariant #7). |
| `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. |
| `memory_status` | read-only | Counts, paths, version. |
| `memory_briefing` | read-only | Structured counts/activity/rules/slots/recent snapshot. Project-scoped snapshots also carry a bounded `pinned` list (up to 10) of the project's pinned latest pages (`pinned = 1`, newest first) as standing SessionStart hot-context — distinct from `slots`, which is keyed by the `_slots/` path prefix; empty and omitted from JSON when the project has no pins, so the default shape is unchanged. Opt-in `settled_first: true` leads with up to 8 of the project's highest-standing `rule`/`decision` pages, ordered by evidence count then recency; off by default. |
-| `memory_explore` | read-only | LLM prose digest over the briefing snapshot, degrading to JSON without a provider. |
+| `memory_explore` | read-only | LLM prose digest over the briefing snapshot, degrading to JSON without a provider. An optional `reasoning` tier (`minimal` (default) / `low` / `medium` / `high` / `max`) scales the digest's max-token budget off its base (16 000; same 1x/1.5x/2x/3x/4x mapping as `memory_query`); inert on the no-provider briefing-only path, and `minimal` is byte-identical. |
| `memory_handoff_begin` | destructive | Open an owner-scoped handoff for the next agent; `shared=true` deliberately publishes it to the project. Optional `workspace` + `project` targets a named sibling workspace/project. |
| `memory_handoff_list` | read-only | List open own/shared handoffs with inspectable body and identity fields; does not claim or expire. Root-only `any_owner=true` recovers across operators. Optional `workspace` + `project` targets a named sibling workspace/project. |
| `memory_handoff_accept` | destructive | Fetch + ack an open own/shared handoff. Pass `handoff_id` from `memory_handoff_list` to claim that exact row; omitting it still claims the latest eligible open handoff (automatic handoffs are cwd-matched). Root-only `any_owner=true` recovers across operators. Optional `workspace` + `project` targets a named sibling workspace/project. |