Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(llm): measure workload health
AkitaOnRails67ff1a48a38a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f0ec4241..bcaba705 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -13,6 +13,14 @@ version in [`docs/changelog/`](docs/changelog/):### Added+- Added passive per-workload LLM telemetry to `ai-memory status --json` and+ `GET /admin/status`. The closed workload set covers consolidation, reranking,+ auto-improvement, bootstrap, query answers, lint, profile maintenance, dream+ merges, and experience abstraction, with process-lifetime calls, outcomes,+ latency buckets, coarse token estimates, and provider-reported usage where available.+ It records no prompt or output text and does not change provider/model+ routing; public per-workload profiles remain deferred until measurements+ justify their configuration and authentication surface.- Added structured pre-rank filters to `memory_query`: case-insensitive`kind` and exact-array `tag`, typed `tier`, and literal `path_prefix`.Filters apply consistently to project/scopes hybrid streams, cross-projectdiff --git a/README.md b/README.mdindex 8acb4f17..9bef3009 100644--- a/README.md+++ b/README.md@@ -592,6 +592,9 @@ readable wiki pages; the next session starts with a handoff.- Narrow a large wiki before ranking with `memory_query` filters such as`path_prefix: "procedures/"`, `tag: "rust"`, `kind: "decision"`, or`tier: "procedural"`.+- Inspect content-free per-workload LLM call, outcome, latency, and usage+ telemetry with `ai-memory status --json`; it diagnoses the configured+ provider but does not route different workloads to different models.- Ask "catch me up" for a prose digest of recent project activity.- Run `ai-memory bootstrap` once when adopting an existing project withmonths of history.diff --git a/crates/ai-memory-consolidate/src/auto_improve.rs b/crates/ai-memory-consolidate/src/auto_improve.rsindex 2cb357bb..829e11b7 100644--- a/crates/ai-memory-consolidate/src/auto_improve.rs+++ b/crates/ai-memory-consolidate/src/auto_improve.rs@@ -725,7 +725,8 @@ pub async fn run_auto_improve_review(// One review call is one LLM operation: a fresh identity, never// the agent's session id — two reviews of the same session must// not look like one operation on the provider side.- let operation_id = LlmOperationId::new();+ let operation_id =+ LlmOperationId::for_workload(ai_memory_llm::LlmWorkload::AutoImprove);let raw: AutoImproveLlmResponse =complete_structured_with_operation_id(llm, request, operation_id).await?;let (mut proposals, mut rejected_candidates, mut warnings) =@@ -3184,6 +3185,11 @@ mod tests {"two reviews of one session get distinct operation ids");for id in &ids {+ assert_eq!(+ id.workload(),+ ai_memory_llm::LlmWorkload::AutoImprove,+ "auto-improve reviews keep their closed workload label"+ );let s = id.to_string();assert_eq!(s.len(), 36, "the hyphenated wire form is 36 chars: {s}");let parsed = uuid::Uuid::parse_str(&s).expect("parses as a UUID");diff --git a/crates/ai-memory-consolidate/src/bootstrap.rs b/crates/ai-memory-consolidate/src/bootstrap.rsindex ee4b592f..8308c430 100644--- a/crates/ai-memory-consolidate/src/bootstrap.rs+++ b/crates/ai-memory-consolidate/src/bootstrap.rs@@ -34,7 +34,10 @@ use std::sync::Arc;use std::time::Duration;use ai_memory_core::{PagePath, ProjectId, Tier, WorkspaceId};-use ai_memory_llm::{ChatMessage, ChatRequest, LlmError, LlmProvider, Role, complete_structured};+use ai_memory_llm::{+ ChatMessage, ChatRequest, LlmError, LlmOperationId, LlmProvider, LlmWorkload, Role,+ complete_structured_with_operation_id,+};use ai_memory_store::ReaderPool;use ai_memory_wiki::{Wiki, WritePageRequest};use jiff::Timestamp;@@ -343,8 +346,15 @@ async fn complete_chunk_with_retry(retry_delay: Duration,) -> Result<BootstrapBatch, LlmError> {let mut attempt = 1;+ let operation_id = LlmOperationId::for_workload(LlmWorkload::Bootstrap);loop {- match complete_structured::<BootstrapBatch>(llm, request.clone()).await {+ match complete_structured_with_operation_id::<BootstrapBatch>(+ llm,+ request.clone(),+ operation_id,+ )+ .await+ {Ok(batch) => return Ok(batch),Err(e) if attempt < BOOTSTRAP_CHUNK_MAX_ATTEMPTS && e.is_transient() => {warn!(@@ -1687,6 +1697,7 @@ mod tests {/// then returns an empty batch.struct FlakyLlm {calls: AtomicUsize,+ ids: std::sync::Mutex<Vec<LlmOperationId>>,transient_failures: usize,permanent: bool,}@@ -1722,6 +1733,16 @@ mod tests {}Ok(serde_json::json!({ "pages": [], "rationale": "ok" }))}++ async fn complete_structured_raw_with_operation_id(+ &self,+ request: ChatRequest,+ schema: serde_json::Value,+ operation_id: LlmOperationId,+ ) -> ai_memory_llm::LlmResult<serde_json::Value> {+ self.ids.lock().unwrap().push(operation_id);+ self.complete_structured_raw(request, schema).await+ }}fn chunk_request() -> ChatRequest {@@ -1737,6 +1758,7 @@ mod tests {async fn chunk_retry_recovers_from_transient_failures() {let llm = FlakyLlm {calls: AtomicUsize::new(0),+ ids: std::sync::Mutex::new(Vec::new()),transient_failures: 2, // fails twice, succeeds on the 3rd (= MAX)permanent: false,};@@ -1749,12 +1771,17 @@ mod tests {3,"should have retried twice");+ let ids = llm.ids.lock().unwrap();+ assert_eq!(ids.len(), 3);+ assert!(ids.iter().all(|id| *id == ids[0]));+ assert_eq!(ids[0].workload(), LlmWorkload::Bootstrap);}#[tokio::test]async fn chunk_retry_gives_up_after_the_attempt_budget() {let llm = FlakyLlm {calls: AtomicUsize::new(0),+ ids: std::sync::Mutex::new(Vec::new()),transient_failures: usize::MAX, // never clearspermanent: false,};@@ -1773,6 +1800,7 @@ mod tests {async fn chunk_retry_does_not_retry_a_deterministic_error() {let llm = FlakyLlm {calls: AtomicUsize::new(0),+ ids: std::sync::Mutex::new(Vec::new()),transient_failures: 0,permanent: true, // returns Auth — not transient};diff --git a/crates/ai-memory-consolidate/src/consolidator.rs b/crates/ai-memory-consolidate/src/consolidator.rsindex 6b6d7a0a..abed2a44 100644--- a/crates/ai-memory-consolidate/src/consolidator.rs+++ b/crates/ai-memory-consolidate/src/consolidator.rs@@ -347,7 +347,7 @@ impl Consolidator {// session id) is shared by every attempt of this invocation; a// re-entry after a crash or a new queue claim is a NEW operation// with a new id.- let operation_id = LlmOperationId::new();+ let operation_id = LlmOperationId::for_workload(ai_memory_llm::LlmWorkload::Consolidation);let request = assemble_single_request(&plan, &projected, self.budgets);debug!(session = %session_id,@@ -801,7 +801,7 @@ impl Consolidator {// fresh id is shared by every attempt of this invocation; a// re-entry after a crash or a new queue claim is a new operation// with a new id.- let operation_id = LlmOperationId::new();+ let operation_id = LlmOperationId::for_workload(ai_memory_llm::LlmWorkload::Consolidation);let request = assemble_batch_request(&plan, &projected, self.budgets);debug!(session = %session_id,@@ -4916,6 +4916,14 @@ mod tests {);assert_fresh_gateway_form(single1[0]);assert_fresh_gateway_form(single2[0]);+ assert_eq!(+ single1[0].workload(),+ ai_memory_llm::LlmWorkload::Consolidation+ );+ assert_eq!(+ single2[0].workload(),+ ai_memory_llm::LlmWorkload::Consolidation+ );assert_ne!(single1[0].to_string(),session.to_string(),@@ -4978,6 +4986,14 @@ mod tests {);assert_fresh_gateway_form(multi1[0]);assert_fresh_gateway_form(multi2[0]);+ assert_eq!(+ multi1[0].workload(),+ ai_memory_llm::LlmWorkload::Consolidation+ );+ assert_eq!(+ multi2[0].workload(),+ ai_memory_llm::LlmWorkload::Consolidation+ );assert_ne!(multi1[0].to_string(),session.to_string(),diff --git a/crates/ai-memory-consolidate/src/dream.rs b/crates/ai-memory-consolidate/src/dream.rsindex 62f23643..bb668386 100644--- a/crates/ai-memory-consolidate/src/dream.rs+++ b/crates/ai-memory-consolidate/src/dream.rs@@ -44,7 +44,10 @@ use std::sync::atomic::{AtomicBool, AtomicI64, Ordering};use ai_memory_core::{ActorContext, PageEvidence, PageEvidenceKind, PageId, ProjectId, Tier, WorkspaceId,};-use ai_memory_llm::{ChatMessage, ChatRequest, LlmProvider, Role, complete_structured};+use ai_memory_llm::{+ ChatMessage, ChatRequest, LlmOperationId, LlmProvider, LlmWorkload, Role,+ complete_structured_with_operation_id,+};use ai_memory_store::{DecayParams, ReaderPool};use ai_memory_wiki::{AdmissionContext, AdmissionOp, Wiki, WritePageRequest};use schemars::JsonSchema;@@ -619,7 +622,13 @@ async fn merge_one_cluster(// JSON-schema structured merge (invariant #7). A failed completion skips.let request = build_merge_request(&member_bodies);- let merged: DreamMergedPage = match complete_structured(llm, request).await {+ let merged: DreamMergedPage = match complete_structured_with_operation_id(+ llm,+ request,+ LlmOperationId::for_workload(LlmWorkload::Dream),+ )+ .await+ {Ok(page) => page,Err(error) => {tracing::warn!(path = %survivor.path.as_str(), %error, "dream pass: LLM merge failed; skipping cluster (retried next run)");diff --git a/crates/ai-memory-consolidate/src/experience.rs b/crates/ai-memory-consolidate/src/experience.rsindex 1b999347..c827cd8a 100644--- a/crates/ai-memory-consolidate/src/experience.rs+++ b/crates/ai-memory-consolidate/src/experience.rs@@ -15,7 +15,10 @@//! zero-LLM default path never runs it.use ai_memory_core::{ProjectId, WorkspaceId};-use ai_memory_llm::{ChatMessage, ChatRequest, LlmProvider, Role, complete_structured};+use ai_memory_llm::{+ ChatMessage, ChatRequest, LlmOperationId, LlmProvider, LlmWorkload, Role,+ complete_structured_with_operation_id,+};use ai_memory_store::{ReaderPool, StoredPageBody};use crate::auto_improve::{@@ -221,9 +224,13 @@ pub async fn run_experience_review(max_tokens: REVIEW_MAX_TOKENS,temperature: Some(0.1),};- let raw: AutoImproveLlmResponse = complete_structured(llm, request)- .await- .map_err(AutoImproveError::from)?;+ let raw: AutoImproveLlmResponse = complete_structured_with_operation_id(+ llm,+ request,+ LlmOperationId::for_workload(LlmWorkload::Experience),+ )+ .await+ .map_err(AutoImproveError::from)?;let (mut proposals, mut rejected_candidates, mut response_warnings) =crate::auto_improve::validate_response(raw, &cfg, &existing_index);warnings.append(&mut response_warnings);diff --git a/crates/ai-memory-consolidate/src/lint.rs b/crates/ai-memory-consolidate/src/lint.rsindex a9e71b26..1aa4c85b 100644--- a/crates/ai-memory-consolidate/src/lint.rs+++ b/crates/ai-memory-consolidate/src/lint.rs@@ -20,7 +20,10 @@ const LINT_SYSTEM_PROMPT: &str = include_str!("../prompts/lint_system.md");use crate::EmbeddingCoord;use crate::cold_cluster::cosine_distance;use ai_memory_core::{PageId, PagePath, ProjectId, Tier, WorkspaceId};-use ai_memory_llm::{ChatMessage, ChatRequest, LlmProvider, Role, complete_structured};+use ai_memory_llm::{+ ChatMessage, ChatRequest, LlmOperationId, LlmProvider, LlmWorkload, Role,+ complete_structured_with_operation_id,+};use ai_memory_store::{DecayCandidate, ReaderPool};use ai_memory_wiki::{AdmissionContext, AdmissionOp, Wiki, WritePageRequest};use jiff::Timestamp;@@ -706,7 +709,12 @@ async fn contradiction_pass(max_tokens: 32_000,temperature: Some(0.1),};- let report: LintReport = complete_structured(&*provider, request).await?;+ let report: LintReport = complete_structured_with_operation_id(+ &*provider,+ request,+ LlmOperationId::for_workload(LlmWorkload::Lint),+ )+ .await?;Ok(report.findings)}diff --git a/crates/ai-memory-consolidate/src/profile.rs b/crates/ai-memory-consolidate/src/profile.rsindex 72232007..20e70beb 100644--- a/crates/ai-memory-consolidate/src/profile.rs+++ b/crates/ai-memory-consolidate/src/profile.rs@@ -34,7 +34,10 @@ use ai_memory_core::{ActorContext, AutoImproveProposalId, IdentityKey, PagePath, Tier, UserId, WorkspaceId,find_marker_line,};-use ai_memory_llm::{ChatMessage, ChatRequest, LlmProvider, complete_structured};+use ai_memory_llm::{+ ChatMessage, ChatRequest, LlmOperationId, LlmProvider, LlmWorkload,+ complete_structured_with_operation_id,+};use ai_memory_store::{NewProfileCandidate, PROFILE_CANDIDATES_LIMIT, PROFILE_HARVEST_BATCH, ProfileCandidateRow,ProfileHarvestProject, ProfileLedgerEntry, ProfilePageRow, ProfileScopePage, ProjectAccess,@@ -1716,7 +1719,12 @@ async fn classify_batch(max_tokens: PROFILE_LLM_MAX_TOKENS,temperature: Some(0.0),};- let response: ClassifyResponse = complete_structured(llm, request).await?;+ let response: ClassifyResponse = complete_structured_with_operation_id(+ llm,+ request,+ LlmOperationId::for_workload(LlmWorkload::Profile),+ )+ .await?;let mut out: Vec<Option<DetectedPreference>> = vec![None; batch.len()];for item in response.items {let Ok(index) = usize::try_from(item.index) else {@@ -1781,7 +1789,12 @@ async fn merge_entry(max_tokens: PROFILE_LLM_MAX_TOKENS,temperature: Some(0.0),};- complete_structured(llm, request).await+ complete_structured_with_operation_id(+ llm,+ request,+ LlmOperationId::for_workload(LlmWorkload::Profile),+ )+ .await}// ---------------------------------------------------------------------------diff --git a/crates/ai-memory-core/src/lib.rs b/crates/ai-memory-core/src/lib.rsindex d9589936..c9f60e53 100644--- a/crates/ai-memory-core/src/lib.rs+++ b/crates/ai-memory-core/src/lib.rs@@ -17,7 +17,7 @@ pub mod ingest_metrics;pub use ingest_metrics::{IngestMetrics, IngestMetricsSnapshot};pub mod ids;pub mod latency;-pub use latency::{LatencyHistogram, LatencySnapshot, LatencyTimer};+pub use latency::{LATENCY_BUCKET_BOUNDS_US, LatencyHistogram, LatencySnapshot, LatencyTimer};pub mod log_ledger;pub mod message;pub mod observation;diff --git a/crates/ai-memory-llm/src/health.rs b/crates/ai-memory-llm/src/health.rsindex aa010044..17b9527c 100644--- a/crates/ai-memory-llm/src/health.rs+++ b/crates/ai-memory-llm/src/health.rs@@ -4,6 +4,7 @@//! the result of calls the server was already going to make.use std::sync::{Arc, Mutex};+use std::time::{Duration, Instant};use async_trait::async_trait;use jiff::Timestamp;@@ -12,7 +13,7 @@ use serde::{Deserialize, Serialize};use crate::embedding::Embedder;use crate::error::{LlmError, LlmResult};use crate::provider::LlmProvider;-use crate::types::{ChatRequest, ChatResponse, LlmOperationId};+use crate::types::{ChatRequest, ChatResponse, LlmOperationId, LlmWorkload, Usage};const MAX_ERROR_MESSAGE_CHARS: usize = 1024;@@ -20,6 +21,7 @@ const MAX_ERROR_MESSAGE_CHARS: usize = 1024;#[derive(Clone, Default)]pub struct ProviderHealth {llm: ProviderRoleHealth,+ llm_workloads: LlmWorkloadHealth,embedding: ProviderRoleHealth,/// The configured LLM provider, held only so `snapshot()` can read its/// [`LlmProvider::candidate_health`] — a plain provider always returns@@ -40,9 +42,16 @@ impl ProviderHealth {.as_ref().map(|provider| provider.candidate_health()).unwrap_or_default();+ let llm = self.llm.snapshot();+ let llm_workloads = if llm.status == ProviderHealthStatus::Disabled {+ Vec::new()+ } else {+ self.llm_workloads.snapshot()+ };ProviderHealthSnapshot {- llm: self.llm.snapshot(),+ llm,llm_candidates,+ llm_workloads,embedding: self.embedding.snapshot(),}}@@ -58,8 +67,13 @@ impl ProviderHealth {) -> Arc<dyn LlmProvider> {let health = self.llm.clone();health.configure(provider.into(), model.into(), None, retry_hint);+ self.llm_workloads.reset();*self.llm_provider.lock().unwrap_or_else(|e| e.into_inner()) = Some(inner.clone());- Arc::new(HealthRecordingLlmProvider { inner, health })+ Arc::new(HealthRecordingLlmProvider {+ inner,+ health,+ workloads: self.llm_workloads.clone(),+ })}/// Mark the embedding role as configured and wrap it with passive recording.@@ -117,10 +131,63 @@ pub struct ProviderHealthSnapshot {/// field existed still deserializes for a newer CLI.#[serde(default)]pub llm_candidates: Vec<CandidateHealth>,+ /// Passive per-workload LLM counts, latency, token estimates, reported+ /// usage and last outcome. Empty when no LLM provider is configured.+ #[serde(default)]+ pub llm_workloads: Vec<LlmWorkloadHealthSnapshot>,/// Embedding provider role.pub embedding: ProviderRoleHealthSnapshot,}+/// Passive process-lifetime telemetry for one closed LLM workload label.+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+pub struct LlmWorkloadHealthSnapshot {+ /// Why ai-memory made these calls.+ pub workload: LlmWorkload,+ /// Provider-interface invocations, including errors. Candidate attempts+ /// inside one fallback-chain invocation remain one call; an outer caller+ /// that deliberately retries makes another invocation.+ pub calls: u64,+ /// Successful provider-interface invocations.+ pub successes: u64,+ /// Failed provider-interface invocations.+ pub errors: u64,+ /// Total wall time across calls, in microseconds.+ pub latency_total_us: u64,+ /// Slowest observed call, in microseconds.+ pub latency_max_us: u64,+ /// Upper bound of the bucket containing p50. `None` means no calls or a+ /// value above the largest fixed bucket (10 seconds).+ pub latency_p50_upper_us: Option<u64>,+ /// Upper bound of the bucket containing p95, with the same `None`+ /// semantics as p50.+ pub latency_p95_upper_us: Option<u64>,+ /// Coarse four-characters-per-token input estimate for every call.+ pub estimated_input_tokens: u64,+ /// Coarse four-characters-per-token output estimate for successful calls.+ pub estimated_output_tokens: u64,+ /// Provider-reported input tokens when the provider returned usage.+ pub reported_input_tokens: u64,+ /// Provider-reported output tokens when the provider returned usage.+ pub reported_output_tokens: u64,+ /// Calls for which the provider returned token usage. Structured-output+ /// providers currently return JSON without usage, so estimates remain the+ /// comparable measurement for those workloads.+ pub usage_reported_calls: u64,+ /// Outcome of the most recent call, or `unknown` before the first call.+ pub status: ProviderHealthStatus,+ /// Time of the most recent call.+ pub last_call_at: Option<Timestamp>,+ /// Time of the most recent success.+ pub last_success_at: Option<Timestamp>,+ /// Time of the most recent error.+ pub last_error_at: Option<Timestamp>,+ /// Redacted error class for the most recent error.+ pub last_error_class: Option<String>,+ /// HTTP status for the most recent error, when one existed.+ pub last_error_status: Option<u16>,+}+/// One candidate's passive health state in an ordered LLM fallback chain./// See `docs/llm-provider-fallback.md`. Every entry here is by construction/// a configured chain member; redaction is total — only labels, timestamps,@@ -324,9 +391,211 @@ impl ProviderRoleState {}}+const LLM_WORKLOAD_BUCKETS: usize = ai_memory_core::LATENCY_BUCKET_BOUNDS_US.len() + 1;++#[derive(Clone)]+struct LlmWorkloadHealth {+ state: Arc<Mutex<[LlmWorkloadState; LlmWorkload::ALL.len()]>>,+}++impl Default for LlmWorkloadHealth {+ fn default() -> Self {+ Self {+ state: Arc::new(Mutex::new(std::array::from_fn(|_| {+ LlmWorkloadState::default()+ }))),+ }+ }+}++impl LlmWorkloadHealth {+ fn reset(&self) {+ *self.state.lock().unwrap_or_else(|e| e.into_inner()) =+ std::array::from_fn(|_| LlmWorkloadState::default());+ }++ fn record<T>(+ &self,+ workload: LlmWorkload,+ elapsed: Duration,+ estimated_input_tokens: u64,+ result: &LlmResult<T>,+ estimated_output_tokens: impl FnOnce(&T) -> u64,+ reported_usage: impl FnOnce(&T) -> Option<Usage>,+ ) {+ let now = Timestamp::now();+ let elapsed_us = u64::try_from(elapsed.as_micros()).unwrap_or(u64::MAX);+ let mut states = self.state.lock().unwrap_or_else(|e| e.into_inner());+ let state = &mut states[workload.index()];+ state.calls = state.calls.saturating_add(1);+ state.latency_total_us = state.latency_total_us.saturating_add(elapsed_us);+ state.latency_max_us = state.latency_max_us.max(elapsed_us);+ let bucket = ai_memory_core::LATENCY_BUCKET_BOUNDS_US+ .iter()+ .position(|bound| elapsed_us <= *bound)+ .unwrap_or(LLM_WORKLOAD_BUCKETS - 1);+ state.latency_buckets[bucket] = state.latency_buckets[bucket].saturating_add(1);+ state.estimated_input_tokens = state+ .estimated_input_tokens+ .saturating_add(estimated_input_tokens);+ state.last_call_at = Some(now);+ match result {+ Ok(output) => {+ state.successes = state.successes.saturating_add(1);+ state.estimated_output_tokens = state+ .estimated_output_tokens+ .saturating_add(estimated_output_tokens(output));+ if let Some(usage) = reported_usage(output) {+ state.usage_reported_calls = state.usage_reported_calls.saturating_add(1);+ state.reported_input_tokens = state+ .reported_input_tokens+ .saturating_add(u64::from(usage.input_tokens));+ state.reported_output_tokens = state+ .reported_output_tokens+ .saturating_add(u64::from(usage.output_tokens));+ }+ state.status = ProviderHealthStatus::Ok;+ state.last_success_at = Some(now);+ }+ Err(error) => {+ state.errors = state.errors.saturating_add(1);+ state.status = ProviderHealthStatus::Error;+ state.last_error_at = Some(now);+ state.last_error_class = Some(error.class().to_owned());+ state.last_error_status = error.http_status();+ }+ }+ }++ fn snapshot(&self) -> Vec<LlmWorkloadHealthSnapshot> {+ let states = self.state.lock().unwrap_or_else(|e| e.into_inner());+ LlmWorkload::ALL+ .iter()+ .copied()+ .map(|workload| states[workload.index()].snapshot(workload))+ .collect()+ }+}++#[derive(Clone)]+struct LlmWorkloadState {+ calls: u64,+ successes: u64,+ errors: u64,+ latency_buckets: [u64; LLM_WORKLOAD_BUCKETS],+ latency_total_us: u64,+ latency_max_us: u64,+ estimated_input_tokens: u64,+ estimated_output_tokens: u64,+ reported_input_tokens: u64,+ reported_output_tokens: u64,+ usage_reported_calls: u64,+ status: ProviderHealthStatus,+ last_call_at: Option<Timestamp>,+ last_success_at: Option<Timestamp>,+ last_error_at: Option<Timestamp>,+ last_error_class: Option<String>,+ last_error_status: Option<u16>,+}++impl Default for LlmWorkloadState {+ fn default() -> Self {+ Self {+ calls: 0,+ successes: 0,+ errors: 0,+ latency_buckets: [0; LLM_WORKLOAD_BUCKETS],+ latency_total_us: 0,+ latency_max_us: 0,+ estimated_input_tokens: 0,+ estimated_output_tokens: 0,+ reported_input_tokens: 0,+ reported_output_tokens: 0,+ usage_reported_calls: 0,+ status: ProviderHealthStatus::Unknown,+ last_call_at: None,+ last_success_at: None,+ last_error_at: None,+ last_error_class: None,+ last_error_status: None,+ }+ }+}++impl LlmWorkloadState {+ fn snapshot(&self, workload: LlmWorkload) -> LlmWorkloadHealthSnapshot {+ LlmWorkloadHealthSnapshot {+ workload,+ calls: self.calls,+ successes: self.successes,+ errors: self.errors,+ latency_total_us: self.latency_total_us,+ latency_max_us: self.latency_max_us,+ latency_p50_upper_us: percentile_upper_bound(&self.latency_buckets, self.calls, 50),+ latency_p95_upper_us: percentile_upper_bound(&self.latency_buckets, self.calls, 95),+ estimated_input_tokens: self.estimated_input_tokens,+ estimated_output_tokens: self.estimated_output_tokens,+ reported_input_tokens: self.reported_input_tokens,+ reported_output_tokens: self.reported_output_tokens,+ usage_reported_calls: self.usage_reported_calls,+ status: self.status,+ last_call_at: self.last_call_at,+ last_success_at: self.last_success_at,+ last_error_at: self.last_error_at,+ last_error_class: self.last_error_class.clone(),+ last_error_status: self.last_error_status,+ }+ }+}++fn percentile_upper_bound(+ buckets: &[u64; LLM_WORKLOAD_BUCKETS],+ count: u64,+ percentile: u64,+) -> Option<u64> {+ if count == 0 {+ return None;+ }+ let target = count.saturating_mul(percentile).div_ceil(100).max(1);+ let mut cumulative = 0_u64;+ for (bound, bucket) in ai_memory_core::LATENCY_BUCKET_BOUNDS_US.iter().zip(buckets) {+ cumulative = cumulative.saturating_add(*bucket);+ if cumulative >= target {+ return Some(*bound);+ }+ }+ None+}++fn estimate_request_tokens(request: &ChatRequest) -> u64 {+ let chars = request+ .system+ .as_deref()+ .map_or(0, |value| value.chars().count())+ + request+ .messages+ .iter()+ .map(|message| message.content.chars().count())+ .sum::<usize>();+ u64::try_from(chars.div_ceil(4)).unwrap_or(u64::MAX)+}++fn estimate_text_tokens(text: &str) -> u64 {+ u64::try_from(text.chars().count().div_ceil(4)).unwrap_or(u64::MAX)+}++fn estimate_json_tokens(value: &serde_json::Value) -> u64 {+ estimate_text_tokens(&value.to_string())+}++fn estimate_structured_input_tokens(request: &ChatRequest, schema: &serde_json::Value) -> u64 {+ estimate_request_tokens(request).saturating_add(estimate_json_tokens(schema))+}+struct HealthRecordingLlmProvider {inner: Arc<dyn LlmProvider>,health: ProviderRoleHealth,+ workloads: LlmWorkloadHealth,}#[async_trait]@@ -340,8 +609,18 @@ impl LlmProvider for HealthRecordingLlmProvider {}async fn complete(&self, request: ChatRequest) -> LlmResult<ChatResponse> {+ let estimated_input = estimate_request_tokens(&request);+ let started = Instant::now();let result = self.inner.complete(request).await;self.health.record_result(&result);+ self.workloads.record(+ LlmWorkload::Unspecified,+ started.elapsed(),+ estimated_input,+ &result,+ |response| estimate_text_tokens(&response.text),+ |response| response.usage,+ );result}@@ -354,11 +633,21 @@ impl LlmProvider for HealthRecordingLlmProvider {request: ChatRequest,operation_id: LlmOperationId,) -> LlmResult<ChatResponse> {+ let estimated_input = estimate_request_tokens(&request);+ let started = Instant::now();let result = self.inner.complete_with_operation_id(request, operation_id).await;self.health.record_result(&result);+ self.workloads.record(+ operation_id.workload(),+ started.elapsed(),+ estimated_input,+ &result,+ |response| estimate_text_tokens(&response.text),+ |response| response.usage,+ );result}@@ -367,8 +656,18 @@ impl LlmProvider for HealthRecordingLlmProvider {request: ChatRequest,schema: serde_json::Value,) -> LlmResult<serde_json::Value> {+ let estimated_input = estimate_structured_input_tokens(&request, &schema);+ let started = Instant::now();let result = self.inner.complete_structured_raw(request, schema).await;self.health.record_result(&result);+ self.workloads.record(+ LlmWorkload::Unspecified,+ started.elapsed(),+ estimated_input,+ &result,+ estimate_json_tokens,+ |_| None,+ );result}@@ -378,11 +677,21 @@ impl LlmProvider for HealthRecordingLlmProvider {schema: serde_json::Value,operation_id: LlmOperationId,) -> LlmResult<serde_json::Value> {+ let estimated_input = estimate_structured_input_tokens(&request, &schema);+ let started = Instant::now();let result = self.inner.complete_structured_raw_with_operation_id(request, schema, operation_id).await;self.health.record_result(&result);+ self.workloads.record(+ operation_id.workload(),+ started.elapsed(),+ estimated_input,+ &result,+ estimate_json_tokens,+ |_| None,+ );result}@@ -488,7 +797,10 @@ mod tests {}Ok(ChatResponse {text: "pong".to_string(),- usage: None,+ usage: Some(Usage {+ input_tokens: 2,+ output_tokens: 1,+ }),model: "fake-model".to_string(),})}@@ -552,7 +864,10 @@ mod tests {async fn complete(&self, _request: ChatRequest) -> LlmResult<ChatResponse> {Ok(ChatResponse {text: "pong".to_string(),- usage: None,+ usage: Some(Usage {+ input_tokens: 2,+ output_tokens: 1,+ }),model: "fake-model".to_string(),})}@@ -590,7 +905,7 @@ mod tests {let health = ProviderHealth::default();let inner = Arc::new(OperationIdLlm::default());let llm = health.wrap_llm_provider(inner.clone(), "openai", "gpt-test", None);- let id = LlmOperationId::new();+ let id = LlmOperationId::for_workload(LlmWorkload::Consolidation);llm.complete_with_operation_id(ChatRequest::user_prompt("ping"), id).await@@ -604,7 +919,31 @@ mod tests {.unwrap();assert_eq!(*inner.seen.lock().unwrap(), vec![id, id]);- assert_eq!(health.snapshot().llm.status, ProviderHealthStatus::Ok);+ let snapshot = health.snapshot();+ assert_eq!(snapshot.llm.status, ProviderHealthStatus::Ok);+ let consolidation = snapshot+ .llm_workloads+ .iter()+ .find(|row| row.workload == LlmWorkload::Consolidation)+ .unwrap();+ assert_eq!(+ (+ consolidation.calls,+ consolidation.successes,+ consolidation.errors,+ consolidation.usage_reported_calls,+ consolidation.reported_input_tokens,+ consolidation.reported_output_tokens,+ ),+ (2, 2, 0, 1, 2, 1)+ );+ assert!(consolidation.estimated_input_tokens > 0);+ assert!(consolidation.estimated_output_tokens > 0);+ assert!(consolidation.latency_p50_upper_us.is_some());+ assert!(+ !id.to_string().contains(LlmWorkload::Consolidation.as_str()),+ "the workload label must not change the provider wire id"+ );}#[tokio::test]@@ -629,11 +968,21 @@ mod tests {llm.complete(ChatRequest::user_prompt("ping")).await.unwrap();- let after_success = health.snapshot().llm;+ let snapshot = health.snapshot();+ let after_success = snapshot.llm;assert_eq!(after_success.status, ProviderHealthStatus::Ok);assert!(after_success.last_call_at.is_some());assert!(after_success.last_success_at.is_some());assert!(after_success.last_error_message.is_none());+ let unspecified = snapshot+ .llm_workloads+ .iter()+ .find(|row| row.workload == LlmWorkload::Unspecified)+ .unwrap();+ assert_eq!(unspecified.calls, 1);+ assert_eq!(unspecified.usage_reported_calls, 1);+ assert_eq!(unspecified.reported_input_tokens, 2);+ assert_eq!(unspecified.reported_output_tokens, 1);let llm = health.wrap_llm_provider(Arc::new(FakeLlm { fail: true }),@@ -650,6 +999,87 @@ mod tests {assert_eq!(after_error.retry_hint.as_deref(), Some(retry_hint.as_str()));}+ #[test]+ fn workload_snapshot_is_bounded_redacted_and_percentiled() {+ let workloads = LlmWorkloadHealth::default();+ let request = ChatRequest::user_prompt("do not expose this private prompt");+ let response = Ok(ChatResponse {+ text: "private provider output".into(),+ usage: Some(Usage {+ input_tokens: 11,+ output_tokens: 3,+ }),+ model: "fake".into(),+ });+ workloads.record(+ LlmWorkload::Rerank,+ Duration::from_millis(40),+ estimate_request_tokens(&request),+ &response,+ |output| estimate_text_tokens(&output.text),+ |output| output.usage,+ );+ let failure: LlmResult<ChatResponse> = Err(LlmError::Provider {+ status: 429,+ body: "secret upstream body".into(),+ });+ workloads.record(+ LlmWorkload::Rerank,+ Duration::from_secs(12),+ estimate_request_tokens(&request),+ &failure,+ |output| estimate_text_tokens(&output.text),+ |output| output.usage,+ );+ workloads.record(+ LlmWorkload::Rerank,+ Duration::from_millis(20),+ estimate_request_tokens(&request),+ &response,+ |output| estimate_text_tokens(&output.text),+ |output| output.usage,+ );++ let row = workloads+ .snapshot()+ .into_iter()+ .find(|row| row.workload == LlmWorkload::Rerank)+ .unwrap();+ assert_eq!((row.calls, row.successes, row.errors), (3, 2, 1));+ assert_eq!(+ (row.reported_input_tokens, row.reported_output_tokens),+ (22, 6)+ );+ assert_eq!(row.usage_reported_calls, 2);+ assert_eq!(row.status, ProviderHealthStatus::Ok);+ assert!(row.last_success_at.is_some());+ assert_eq!(row.latency_p50_upper_us, Some(50_000));+ assert_eq!(row.latency_p95_upper_us, None, "p95 is above 10 seconds");+ assert!(+ row.last_error_at.is_some(),+ "a later success must not erase the last error evidence"+ );+ assert_eq!(row.last_error_class.as_deref(), Some("provider"));+ assert_eq!(row.last_error_status, Some(429));+ let json = serde_json::to_string(&row).unwrap();+ for secret in ["private prompt", "provider output", "upstream body"] {+ assert!(!json.contains(secret), "telemetry leaked {secret}: {json}");+ }+ }++ #[test]+ fn structured_input_estimate_includes_the_schema() {+ let request = ChatRequest::user_prompt("x");+ let schema = serde_json::json!({+ "type": "object",+ "description": "s".repeat(400),+ });+ assert!(+ estimate_structured_input_tokens(&request, &schema)+ > estimate_request_tokens(&request) + 90+ );+ }+#[tokio::test]async fn embedder_wrapper_records_and_preserves_task_specific_methods() {let health = ProviderHealth::default();diff --git a/crates/ai-memory-llm/src/lib.rs b/crates/ai-memory-llm/src/lib.rsindex 6b47ec5c..5a48365a 100644--- a/crates/ai-memory-llm/src/lib.rs+++ b/crates/ai-memory-llm/src/lib.rs@@ -132,8 +132,8 @@ pub use fallback::{CIRCUIT_COOLDOWN, Candidate, FallbackLlmProvider};pub use gemini::GeminiProvider;pub use google::{DEFAULT_MODEL as GOOGLE_DEFAULT_EMBED_MODEL, GoogleEmbedder};pub use health::{- CandidateHealth, ProviderHealth, ProviderHealthSnapshot, ProviderHealthStatus,- ProviderRoleHealthSnapshot,+ CandidateHealth, LlmWorkloadHealthSnapshot, ProviderHealth, ProviderHealthSnapshot,+ ProviderHealthStatus, ProviderRoleHealthSnapshot,};#[cfg(feature = "local-embeddings")]pub use local::{LOCAL_DIM, LOCAL_MODEL, LocalEmbedder, fetch_model, model_present};@@ -157,8 +157,8 @@ pub use reranker::{LlmReranker, RerankCandidate, RerankScore, RerankStage, Reranpub use response::provider_error_body;pub use stored_token::StoredOAuthToken;pub use types::{- ChatMessage, ChatRequest, ChatResponse, ExtraHeaders, LlmOperationId, ReasoningEffort, Role,- Usage,+ ChatMessage, ChatRequest, ChatResponse, ExtraHeaders, LlmOperationId, LlmWorkload,+ ReasoningEffort, Role, Usage,};// Integration tests compile into this crate's test harness instead of adiff --git a/crates/ai-memory-llm/src/reranker.rs b/crates/ai-memory-llm/src/reranker.rsindex b6ff2885..9b88e0b7 100644--- a/crates/ai-memory-llm/src/reranker.rs+++ b/crates/ai-memory-llm/src/reranker.rs@@ -23,9 +23,9 @@ use tokio::sync::Semaphore;use tracing::{debug, warn};use crate::error::LlmResult;-use crate::provider::{LlmProvider, complete_structured};+use crate::provider::{LlmProvider, complete_structured_with_operation_id};use crate::text::truncate_with_ellipsis;-use crate::types::{ChatMessage, ChatRequest, Role};+use crate::types::{ChatMessage, ChatRequest, LlmOperationId, LlmWorkload, Role};/// One candidate handed to a reranker.#[derive(Debug, Clone)]@@ -203,7 +203,12 @@ impl Reranker for LlmReranker {max_tokens: 4_000,temperature: Some(0.0),};- let response: LlmRerankResponse = complete_structured(&*self.provider, request).await?;+ let response: LlmRerankResponse = complete_structured_with_operation_id(+ &*self.provider,+ request,+ LlmOperationId::for_workload(LlmWorkload::Rerank),+ )+ .await?;Ok(map_judgements(&response.scores, candidates))}}@@ -599,6 +604,7 @@ mod tests {#[derive(Default)]struct CapturingProvider {request: std::sync::Mutex<Option<ChatRequest>>,+ operation_id: std::sync::Mutex<Option<LlmOperationId>>,}#[async_trait]@@ -634,6 +640,16 @@ mod tests {.collect::<Vec<_>>()}))}++ async fn complete_structured_raw_with_operation_id(+ &self,+ request: ChatRequest,+ schema: serde_json::Value,+ operation_id: LlmOperationId,+ ) -> LlmResult<serde_json::Value> {+ *self.operation_id.lock().unwrap() = Some(operation_id);+ self.complete_structured_raw(request, schema).await+ }}#[tokio::test]@@ -663,6 +679,10 @@ mod tests {assert_eq!(input["candidates"][0]["candidate"], 1);assert_eq!(input["candidates"][0]["title"], candidates[0].title);assert_eq!(input["candidates"][0]["text"], candidates[0].snippet);+ assert_eq!(+ provider.operation_id.lock().unwrap().unwrap().workload(),+ LlmWorkload::Rerank+ );}#[tokio::test]diff --git a/crates/ai-memory-llm/src/types.rs b/crates/ai-memory-llm/src/types.rsindex 49ba7ac2..cadcd35a 100644--- a/crates/ai-memory-llm/src/types.rs+++ b/crates/ai-memory-llm/src/types.rs@@ -12,13 +12,100 @@ use uuid::Uuid;/// operations of the same session (or a crash-resumed or re-claimed run)/// must not look like one operation on the provider side.#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]-pub struct LlmOperationId(Uuid);+pub struct LlmOperationId {+ id: Uuid,+ workload: LlmWorkload,+}++/// Closed workload labels for passive LLM telemetry.+///+/// These labels describe why ai-memory made a call. They are not provider+/// routes and do not select a model. Keeping the set closed prevents prompts,+/// project names, or other caller-controlled text from becoming metric keys.+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]+#[serde(rename_all = "kebab-case")]+#[repr(u8)]+pub enum LlmWorkload {+ /// A caller used the provider API without assigning a workload.+ #[default]+ Unspecified,+ /// Session-to-page consolidation.+ Consolidation,+ /// Post-retrieval relevance reranking.+ Rerank,+ /// Reviewed auto-improvement proposal generation.+ AutoImprove,+ /// Existing-project bootstrap extraction.+ Bootstrap,+ /// Opt-in query answer or project briefing synthesis.+ QueryAnswer,+ /// LLM-assisted wiki lint.+ Lint,+ /// Profile classification or extraction.+ Profile,+ /// Cross-session dream merge.+ Dream,+ /// Cross-trajectory experience abstraction.+ Experience,+}++impl LlmWorkload {+ /// Every workload in stable wire order.+ pub const ALL: [Self; 10] = [+ Self::Unspecified,+ Self::Consolidation,+ Self::Rerank,+ Self::AutoImprove,+ Self::Bootstrap,+ Self::QueryAnswer,+ Self::Lint,+ Self::Profile,+ Self::Dream,+ Self::Experience,+ ];++ /// Stable kebab-case label.+ #[must_use]+ pub const fn as_str(self) -> &'static str {+ match self {+ Self::Unspecified => "unspecified",+ Self::Consolidation => "consolidation",+ Self::Rerank => "rerank",+ Self::AutoImprove => "auto-improve",+ Self::Bootstrap => "bootstrap",+ Self::QueryAnswer => "query-answer",+ Self::Lint => "lint",+ Self::Profile => "profile",+ Self::Dream => "dream",+ Self::Experience => "experience",+ }+ }++ pub(crate) const fn index(self) -> usize {+ self as usize+ }+}impl LlmOperationId {/// Generate a fresh time-ordered operation identifier.#[must_use]pub fn new() -> Self {- Self(Uuid::now_v7())+ Self::for_workload(LlmWorkload::Unspecified)+ }++ /// Generate an operation identifier carrying a passive workload label.+ #[must_use]+ pub fn for_workload(workload: LlmWorkload) -> Self {+ Self {+ id: Uuid::now_v7(),+ workload,+ }+ }++ /// Workload assigned by the call site.+ #[must_use]+ pub const fn workload(self) -> LlmWorkload {+ self.workload}}@@ -30,7 +117,7 @@ impl Default for LlmOperationId {impl std::fmt::Display for LlmOperationId {fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {- self.0.fmt(f)+ self.id.fmt(f)}}@@ -405,7 +492,7 @@ fn split_entry(entry: &str, position: usize) -> crate::error::LlmResult<(&str, &#[cfg(test)]mod tests {- use super::{ExtraHeaders, ReasoningEffort};+ use super::{ExtraHeaders, LlmOperationId, LlmWorkload, ReasoningEffort};use rstest::rstest;const ALL_EFFORTS: [ReasoningEffort; 9] = [@@ -420,6 +507,25 @@ mod tests {ReasoningEffort::Persistent,];+ #[test]+ fn workload_labels_are_stable_and_do_not_change_the_wire_operation_id() {+ for workload in LlmWorkload::ALL {+ let value = serde_json::to_value(workload).unwrap();+ assert_eq!(value, serde_json::json!(workload.as_str()));+ assert_eq!(+ serde_json::from_value::<LlmWorkload>(value).unwrap(),+ workload+ );+ let wire_id = LlmOperationId::for_workload(workload).to_string();+ assert_eq!(wire_id.len(), 36);+ assert_eq!(+ uuid::Uuid::parse_str(&wire_id).unwrap().get_version_num(),+ 7+ );+ assert!(!wire_id.contains(workload.as_str()));+ }+ }+#[test]fn reasoning_effort_roundtrips() {assert_eq!(diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rsindex 14d5307f..bd1489c2 100644--- a/crates/ai-memory-mcp/src/admin.rs+++ b/crates/ai-memory-mcp/src/admin.rs@@ -9357,7 +9357,7 @@ mod tests {ActorContext, AgentKind, IdentityKey, NewObservation, NewSession, ObservationKind,};use ai_memory_core::{Sanitized, Sanitizer};- use ai_memory_llm::{ChatRequest, ChatResponse, LlmResult};+ use ai_memory_llm::{ChatRequest, ChatResponse, LlmOperationId, LlmResult, LlmWorkload};use ai_memory_store::Store;use axum::body::to_bytes;use axum::http::Request;@@ -9649,6 +9649,7 @@ mod tests {let body = to_bytes(resp.into_body(), usize::MAX).await.unwrap();let json: serde_json::Value = serde_json::from_slice(&body).unwrap();assert_eq!(json["providers"]["llm"]["status"], "disabled");+ assert_eq!(json["providers"]["llm_workloads"], serde_json::json!([]));assert_eq!(json["providers"]["embedding"]["status"], "disabled");// 2.0 item 7: the report carries the wedged-writer gauge and the// wiki-format state — a fresh store is natively conformant (no@@ -9658,6 +9659,79 @@ mod tests {assert!(json["wiki_format"]["backup_archive"].is_null());}+ #[tokio::test]+ async fn status_reports_bounded_content_free_llm_workload_telemetry() {+ let tmp = TempDir::new().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let wiki = Wiki::new(tmp.path(), store.writer.clone())+ .unwrap()+ .with_store_reader(store.reader.clone());+ let provider_health = ProviderHealth::default();+ let llm = provider_health.wrap_llm_provider(+ Arc::new(FakeAutoImproveLlm),+ "fake-auto-improve",+ "fake-model",+ None,+ );+ llm.complete_with_operation_id(+ ChatRequest::user_prompt("private prompt").with_max_tokens(16),+ LlmOperationId::for_workload(LlmWorkload::QueryAnswer),+ )+ .await+ .unwrap();+ let router = admin_router(AdminState {+ ingest_metrics: std::sync::Arc::new(ai_memory_core::IngestMetrics::default()),+ mcp_metrics: std::sync::Arc::new(crate::McpMetrics::default()),+ writer: store.writer.clone(),+ reader: store.reader.clone(),+ wiki,+ llm: Some(llm),+ auto_improve_require_approval: false,+ auto_improve_review_config: Default::default(),+ embedder: None,+ provider_health,+ decay_params: DecayParams::default(),+ contradiction_band_min: ai_memory_consolidate::DEFAULT_CONTRADICTION_SIM_LOW,+ contradiction_band_max: ai_memory_consolidate::DEFAULT_CONTRADICTION_SIM_HIGH,+ data_dir: tmp.path().to_path_buf(),+ db_path: store.db_path().to_path_buf(),+ bind: "127.0.0.1:49374".to_string(),+ home_dir: None,+ bootstrap_lock: Arc::new(tokio::sync::Mutex::new(())),+ token_pepper: None,+ active_project: ai_memory_core::ActiveProject::new(),+ scope_invalidator: None,+ trusted_proxy_identity: false,+ });++ let resp = router+ .oneshot(+ Request::builder()+ .uri("/admin/status")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();++ assert_eq!(resp.status(), StatusCode::OK);+ let body = to_bytes(resp.into_body(), usize::MAX).await.unwrap();+ let json: serde_json::Value = serde_json::from_slice(&body).unwrap();+ let workloads = json["providers"]["llm_workloads"].as_array().unwrap();+ assert_eq!(workloads.len(), LlmWorkload::ALL.len());+ let query_answer = workloads+ .iter()+ .find(|entry| entry["workload"] == "query-answer")+ .unwrap();+ assert_eq!(query_answer["calls"], 1);+ assert_eq!(query_answer["successes"], 1);+ assert_eq!(query_answer["errors"], 0);+ assert_eq!(query_answer["status"], "ok");+ assert_eq!(query_answer["usage_reported_calls"], 0);+ let encoded = serde_json::to_string(workloads).unwrap();+ assert!(!encoded.contains("private prompt"));+ }+/// The MCP-only complement: per-client tool-call counters served/// back with the same window semantics as by-agent.#[tokio::test]diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rsindex c4def354..f2844a22 100644--- a/crates/ai-memory-mcp/src/server.rs+++ b/crates/ai-memory-mcp/src/server.rs@@ -3232,9 +3232,12 @@ impl AiMemoryServer {&global_scope_hits,args.reasoning.unwrap_or_default(),);- match ai_memory_llm::complete_structured::<AnswerSynthesis>(+ match ai_memory_llm::complete_structured_with_operation_id::<AnswerSynthesis>(llm.as_ref(),request,+ ai_memory_llm::LlmOperationId::for_workload(+ ai_memory_llm::LlmWorkload::QueryAnswer,+ ),).await{@@ -6475,7 +6478,15 @@ impl AiMemoryServer {args.reasoning.unwrap_or_default(),);let provider = llm.llm();- let text = match provider.complete(request).await {+ let text = match provider+ .complete_with_operation_id(+ request,+ ai_memory_llm::LlmOperationId::for_workload(+ ai_memory_llm::LlmWorkload::QueryAnswer,+ ),+ )+ .await+ {Ok(resp) => resp.text,Err(e) => {// Redacted fields only: the `Display` of a provider failurediff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex 077b52e2..dede73d4 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -804,6 +804,27 @@ series, and scope is never a label. The route sits behind the same`require_root_for_multiuser_admin` gate as every `/admin/*` route: root-only oncethe deployment distinguishes operators. Counters reset on restart.+### LLM workload telemetry++The root-protected `GET /admin/status` snapshot includes a bounded+`providers.llm_workloads` array when an LLM is configured. Call sites attach+one member of the closed `LlmWorkload` enum to the existing UUIDv7 logical+operation id; its displayed/wire value remains only the UUID, so the label+cannot affect a provider request or fallback correlation. The provider-health+wrapper records one provider-interface invocation around the whole fallback+chain (outer caller retries are separate invocations): outcome,+wall time, fixed-bucket p50/p95 bounds, coarse four-characters-per-token+estimates, provider-reported usage when available, and redacted error+class/status. It stores no prompt, output, scope, project, model selected by a+caller, or unbounded label. State is in memory, resets on restart, and does not+choose a provider or model. The server constructs the wrapper once at startup;+there is no runtime provider hot-reload.++This instrumentation is the evidence gate for any future per-operation+provider profiles. The current configuration remains one global provider plus+its ordered fallback chain; no routing surface exists until measured latency,+usage, and quality justify the added auth and configuration boundary.+### Web search and the recall traceA project search in the web UI (`/web/search` with `workspace` and `project`)@@ -1473,6 +1494,11 @@ status (never a response body or credential), and its circuit-open-untiltimestamp. It is empty for a plain single-provider setup; the top-level`llm` role fields are unchanged.+The same response reports `llm_workloads`, a fixed-order, fixed-cardinality+diagnostic described under [LLM workload telemetry](#llm-workload-telemetry).+Use `ai-memory status --json` to inspect the rows; the ordinary human status+output stays concise.+Every chat request carries `User-Agent: ai-memory/<version>`(`ai_memory_llm::DEFAULT_USER_AGENT`, layered in `build_provider`). `reqwest`sends no user agent unless configured, so without this header providerdiff --git a/docs/comparison.md b/docs/comparison.mdindex a321d521..62fc43e0 100644--- a/docs/comparison.md+++ b/docs/comparison.md@@ -407,6 +407,11 @@ ships something ai-memory does not, it is named.limited to one slot and a second slot remains available for query embedding.Hosted providers retain their existing concurrency policy; the LLM rerankerremains separately bounded and fail-open.+- **Per-workload LLM behavior is measured before it is routed.** Root-only+ status JSON reports bounded calls, outcomes, latency, estimated tokens, and+ provider-reported usage for each closed internal workload. It records no+ prompt or output text. Provider/model selection remains global until real+ measurements and quality evaluation justify a larger configuration surface.- **Marketplace reach is narrower than harness support.** ai-memory now shipsits own Claude Code and Codex marketplace plugins and `ai-memory setup`detects and wires installed agents across Linux, macOS, and Windows. It isdiff --git a/docs/competitive-parity.md b/docs/competitive-parity.mdindex e324d14e..64b3b9a6 100644--- a/docs/competitive-parity.md+++ b/docs/competitive-parity.md@@ -280,10 +280,10 @@ invariants), **ALREADY** (we have it and should say so).| Capability seen in the field | Verdict | Why ||---|---|---|-| Human workstream operations view (claude-mem v14 “My Work”) | ADOPT | The managed-workstream ledger already has runs, leases, events, and handoff evidence, but humans cannot scan active/attention/review-ready work in `/web`. Build a read-only derived view; add only a minimal review marker, not a second task system |+| Human workstream operations view (claude-mem v14 “My Work”) | SHIPPED (3.2) | `/web/workstreams` shows bounded active, interrupted, completed, and empty lifecycle state to the root/operator without exposing checkout paths, native session ids, or transcript content. It does not invent attention/review states from prose or become a second task system || Foreground query capacity isolated from embedding backfill (EverOS v1.4.2) | SHIPPED (3.2) for local inference | A real-model probe measured eight-worker query p50/p95 rising from 36/41 ms idle to 74/76 ms. Limiting local document inference to one slot while reserving one query slot reduced loaded latency to 39/51 ms. Hosted providers keep their existing concurrency; provider failures still degrade to lexical/entity/graph retrieval || Structured pre-rank filters (Mem0; basic-memory v0.24 unreleased) | SHIPPED (3.2), except author | `memory_query` applies bounded kind, tier, literal path-prefix and exact-array tag predicates before every page-ranking stream, including global, historical, profile and pinned results. `as_of` is the valid-time control. Author stays deferred until null root/anonymous attribution has explicit semantics |-| Per-operation LLM provider/model profiles (Graphiti v0.31; Hindsight `main`) | MEASURE-FIRST | Potentially lowers cost and latency for consolidation, rerank, and auto-improvement, but expands config and auth surface. Prototype against the evals before adding public settings |+| Per-operation LLM provider/model profiles (Graphiti v0.31; Hindsight `main`) | TELEMETRY SHIPPED (3.2); ROUTING MEASURE-FIRST | Root-only status now measures calls, outcomes, latency, estimated tokens, reported usage and health for a fixed workload set without storing content. Labels remain routing-inert. Add public profiles only after real measurements plus quality evaluation show a benefit worth the config/auth surface || Retrieval recall through capture (several tools rank whole raw sessions) | SHIPPED (3.0) | The 2026-10-12 decomposition showed our zero-LLM session page indexed only 80-character turn titles; the observation stream recovered it (FTS hit@5 0.662 → 0.951, local 0.800 → 0.945, all 470). Chasing another tool's headline number is declined: those numbers measure different things || Local zero-LLM cross-encoder reranker | MEASURE-FIRST | Fits the zero-LLM invariant (a local model, not an LLM). Bar before building: hit@5 at least +0.03 on both FTS and local paths over the shipped ranking, p95 at most +100 ms on the reference host and measured on a low-end ARM host; default-on only if the keyless path gains. Measured headroom is small after the stream (component-mode FTS 0.972 vs pipeline 0.951) || Editable browser viewer (edit / forget / bulk forget) | DECLINE | The web UI is read-only by design (`frontend-api.md` §10); wiki mutations go only through `Wiki::write_page`/`apply_batch`; agents already edit and forget via MCP (`memory_write_page` with `expected_page_id`, `memory_delete_page`) and the CLI |@@ -317,22 +317,17 @@ which should be checked before any work is scoped.**Step up** (gaps a coding-agent user notices):-1. **A human workstream operations view** over existing managed runs, with- attention/review states and bounded evidence (claude-mem v14). This should- expose work already tracked, not create a kanban subsystem.-2. **Structured filters before ranking** for path prefix, kind, tier, tag,- author, and valid time (Mem0; basic-memory v0.24, currently unreleased).-3. **Foreground embedding isolation backed by a contention benchmark**+1. **Foreground embedding isolation backed by a contention benchmark**(EverOS v1.4.2) is now shipped for the in-process local model. The manualprobe remains in-tree so the capacity can be rechecked on other CPU classes.-4. **One reproducible end-to-end QA number** beside hit@5, with reader,+2. **One reproducible end-to-end QA number** beside hit@5, with reader,judge, context tokens and latency stated, and more benchmarks thanLongMemEval (Mem0, Zep, Hindsight and EverOS publish QA numbers; Hindsight'sAMB harness is open, so an adapter is worth considering). Most numberspublished in the field are QA numbers.-5. **Git-history ingestion on first run**, zero-LLM and sanitized+3. **Git-history ingestion on first run**, zero-LLM and sanitized(Hindsight), so a new repository starts with its commit history as context.-6. **Answer harness-native memory reads from our store** (claude-mem's bridge+4. **Answer harness-native memory reads from our store** (claude-mem's bridgefor Claude Code and Codex memory folders). Careful: this touches trustand routing, and the gap decisions above decline a bidirectional bridge.@@ -354,7 +349,9 @@ undelivered event for a later drain.- A statusline indicator (Cognee): shows capture is alive.- An opt-in local cross-encoder reranker (Hindsight, basic-memory,agentmemory), gated on the recall-eval bar in the table above.-- Per-step model routing (Graphiti's `LLMRuntime`): cheaper consolidation.+- Per-step model routing (Graphiti's `LLMRuntime`) only if the shipped workload+ telemetry plus quality evaluation demonstrate cheaper or faster operation+ without a meaningful quality loss.- A dry-run-first unified audit/repair command (MemPalace v3.11): consolidatethe checks already spread across `doctor`, lint, reindex, health, and backuponly if one operator workflow is demonstrably simpler.diff --git a/docs/llm-providers.md b/docs/llm-providers.mdindex fb014d78..2f5f0e91 100644--- a/docs/llm-providers.md+++ b/docs/llm-providers.md@@ -438,6 +438,33 @@ preserves the normal order. `global=true` and supplemental global-preferencehits keep their existing non-RRF ranking. Concurrent provider calls are cappedat four; saturated queries keep their local ranking without waiting.+## Workload telemetry++`ai-memory status --json` (the root-protected `GET /admin/status` response)+includes `providers.llm_workloads` whenever an LLM provider is configured. Its+closed labels are `unspecified`, `consolidation`, `rerank`, `auto-improve`,+`bootstrap`, `query-answer`, `lint`, `profile`, `dream`, and `experience`.+Each row reports process-lifetime calls, successes and errors, total/max+latency, fixed-bucket p50/p95 upper bounds, last outcome, and token counts. The+counters are process-local and reset on restart; the server constructs the+configured provider wrapper once at startup and has no runtime provider reload.++`estimated_input_tokens` and `estimated_output_tokens` use a deliberately+coarse four-characters-per-token estimate so structured and plain calls remain+comparable. `reported_input_tokens` and `reported_output_tokens` count only+responses for which the provider supplied usage; `usage_reported_calls` shows+that coverage. Structured-output provider adapters currently return decoded+JSON without usage, so their reported counters can remain zero even when the+estimate is nonzero.++The telemetry stores no prompt, completion, scope, project, or caller-supplied+label. A fallback chain is measured as one provider-interface invocation, not+as one call per internal candidate attempt; an outer caller retry is another+invocation. Workload labels do not select a+provider or model: all operations still use the configured global provider and+fallback chain. Per-workload routing remains measure-first and has no public+configuration surface.+Embeddings are optional and separate from the LLM provider. Set`AI_MEMORY_EMBEDDING_PROVIDER=openai`, `voyage`, `google`/`gemini`,`openai-compat`, or `copilot` when you want vector retrieval in addition todiff --git a/docs/research-2026-landscape.md b/docs/research-2026-landscape.mdindex c8573083..de52d51d 100644--- a/docs/research-2026-landscape.md+++ b/docs/research-2026-landscape.md@@ -849,28 +849,26 @@ budget on pinned and slot content. It runs without an LLM or migration. Theremaining retrieval gap was a path-prefix filter, now shipped with the otherstructured MCP filters described below.-**R8: Queryable metadata/tag filters + a published eval triple - partly-open.** The retrieval harness and accuracy/latency/context reporting exist.-The store and web search already filter kind and tier before every ranking-stream; `memory_query` does not expose them, and path prefix, author, and tag-remain absent. Extending that bounded filter surface is the remaining work.-Connectors and document+**R8: Queryable metadata/tag filters shipped; full eval run still open.** The+retrieval harness and accuracy/latency/context reporting exist. `memory_query`+now exposes kind, tier, literal path-prefix, and exact-array tag predicates+before every page-ranking stream, including global, historical, profile, and+pinned results. Author remains deferred until null root/anonymous attribution+has explicit semantics. Connectors and documentextraction, if adopted, stay in the importer companion so untrusted input stillcrosses the sanitizer boundary and the server remains text-first.### Current plan after the 2026-10-18 pass-This is the short list that remains after removing work already shipped.-Each item needs its own design and approval before implementation.--1. **P1 - Workstream operations view.** Add a read-only, root/operator `/web`- view over the managed-workstream ledger. Derive only states the trusted- lifecycle columns support: active, interrupted, completed, and empty;- show the latest run and bounded operational evidence. Do not infer "waiting- for input" from untrusted transcript prose or pretend handoffs are linked to- workstreams when the schema has no such relationship. This borrows- claude-mem's useful human visibility without turning ai-memory into a kanban- system or cloud collaboration product.+This is the implementation ledger for the short list selected by that pass.+Items not marked complete still need their own design and approval.++1. **P1 - Workstream operations view. Completed.** `/web/workstreams` is a+ read-only root/operator view over bounded managed-run aggregates. It derives+ only active, interrupted, completed, and empty from trusted lifecycle+ columns and exposes no checkout path, native session id, or transcript+ content. It does not infer task states from untrusted prose or create a+ second task system.2. **P1 - Protect interactive recall from background embedding. Completed.**The opt-in real-model probe found material local CPU contention, so localinference now admits one document embedding and reserves a second slot for@@ -884,10 +882,13 @@ Each item needs its own design and approval before implementation.omit metadata-less raw observations. `as_of` remains the valid-time control,and author remains deferred until null root/anonymous attribution hasexplicit semantics.-4. **P2 - Per-operation LLM profiles, measure first.** Prototype separate- provider/model choices for consolidation, reranking, and auto-improvement,- plus a cheap structured decision tier. Measure cost, latency, call count,- and quality before adding public configuration or changing defaults.+4. **P2 - Per-operation LLM profiles, telemetry completed; routing deferred.**+ Root-protected status now reports bounded process-lifetime call count,+ outcome, latency, coarse token estimates, reported usage, and health for a+ closed set of workloads. It captures no prompts or outputs, and labels do+ not affect the provider wire request. Real measurements still need to show+ a quality/cost benefit before public per-workload provider/model settings or+ a cheap decision tier are added.5. **P3 - Optional document importer.** If demand is real, extend theimporter companion to extract PDF/Office/media transcripts into attributed,sanitized markdown. Keep opaque files and native multimodal embeddings outdiff --git a/docs/security-boundaries.md b/docs/security-boundaries.mdindex 6bb1c6aa..a9483a75 100644--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@ -140,6 +140,7 @@ means the boundary is not built yet.| 26 | Cross-harness native-history continuation stays checkout-scoped and client-local | `ai-memory-store/src/workstream.rs` `prepare_run` selects the newest current native session only when its harness differs from the destination and pins that typed identity on the run before destination linking can change recency; `ai-memory-cli/src/commands/run.rs` validates the returned `NativeSessionIdentity`, resolves only known adapter flavors, requires `native_session_in_checkout`, exports through the bounded read-only adapter, and writes an untrusted-history dossier to a private temporary directory exposed only to the child as `AI_MEMORY_PREVIOUS_SESSION_HISTORY`; the server wire type deliberately has no path/content field and same-harness launches select no source; `ai-memory-hooks/src/router.rs` keeps the server-authored resume directive outside the untrusted-history fence while fencing the transcript evidence itself, and `ai-memory-core/src/routing_snippet.rs` gives installed project instructions the same wrapper-variable-gated fallback | Core `prepare_response_carries_only_previous_native_identity`, `older_prepare_response_defaults_to_no_adoption`, and `snippets_route_managed_continue_to_the_previous_native_history`; store `managed_adoption_stops_after_any_harness_links_the_workstream` (switch control, destination-link recency cannot replace the pinned source, same-harness refusal); hooks `managed_context_points_at_local_history_on_a_harness_switch` (no session id rendered, directive precedes the untrusted fence); CLI `previous_session_history_is_private_local_and_checkout_scoped` (legitimate control, foreign checkout refused, private local file removed with its owner) | STRONG for checkout isolation, prompt-boundary placement, and server path/content privacy. The dossier is a bounded visible-history projection, not raw hidden reasoning; if the source store is absent, remote, unreadable, or over bounds, the child receives only the portable ledger and handoff || 27 | Plain-HTTP human authentication stays fail-closed beyond loopback unless the operator supplies the dedicated dangerous override (#1383) | `ai-memory-cli/src/cli.rs` exposes `serve --allow-insecure-human-auth` separately from `--allow-insecure-no-auth`; `serve.rs` `validate_http_exposure` accepts it only when authentication and human mode are both active and the listener is non-loopback with a Non-Secure cookie, while the ordinary unauthenticated guard still runs otherwise. `HttpExposure::InsecureHumanAuthByOverride` gives that path its own unconditional stderr banner and structured warning, naming passwords, API credentials, session cookies, and memory data as plaintext. The default remains refusal, and `secure_cookie=true` or loopback remains the safe path | `serve.rs` `human_auth_non_loopback_requires_secure_cookie_posture` (default refusal, the no-auth override cannot substitute, the dedicated override succeeds, and that override cannot expose a server with no authentication even under inconsistent human-mode input; secure-cookie and loopback controls), `every_unsafe_exposure_produces_an_operator_banner` (the dedicated banner names the flag and session-cookie risk), and `cli.rs` `serve_parses_insecure_transport_overrides` (both dangerous flags remain distinct) | STRONG for the startup boundary. This is an explicit operator acceptance of transport risk, not encryption; authorization, CSRF, rate limits, Host validation, and the unauthenticated exposure refusal are unchanged || 27a | Provider credentials stay on the configured origin | `ai-memory-llm/src/redirect.rs` `same_origin_redirects`, set on every provider and embedder client (`anthropic.rs`, `codex.rs`, `copilot.rs`, `embedding.rs`, `gemini.rs`, `google.rs`, `openai.rs`, `openai_oauth.rs`, `opencode.rs`): a redirect is followed only when scheme, host and port match the previous request, with reqwest's ten-hop limit; any other redirect fails the request. reqwest's own guard strips only `Authorization`, cookies and the proxy headers, so `x-api-key`, `x-goog-api-key` and `llm_headers` values depend on this one. The local model download (`local.rs`) carries no credential and keeps the default policy for its CDN redirects; OIDC and CLI login requests refuse every redirect on clients of their own (`oidc.rs`, `auth.rs` `auth_http_client`) | `ai-memory-llm` `tests/suite/redirect_credentials.rs` `gemini_api_key_does_not_follow_a_cross_origin_redirect`, `anthropic_api_key_does_not_follow_a_cross_origin_redirect`, `operator_headers_do_not_follow_a_cross_origin_redirect` (with `Authorization` stripped as the control), `google_embedder_key_does_not_follow_a_cross_origin_redirect`, `a_refused_redirect_says_where_it_pointed`; legitimate control `a_same_origin_redirect_still_reaches_the_provider` (the key follows a path redirect on one origin); each cross-origin test fails with the policy removed | STRONG for the provider and embedder clients in `ai-memory-llm` |+| 27b | LLM workload telemetry cannot turn prompts, outputs, scopes, projects, or caller text into status data or unbounded metric labels | `ai-memory-llm/src/types.rs` `LlmWorkload` is a closed enum carried beside, but absent from the display/wire form of, `LlmOperationId`; `health.rs` `LlmWorkloadHealth` uses one fixed array and fixed latency buckets and records only counts/times/coarse estimates/reported usage/redacted error class and status; `ProviderHealth::snapshot` omits the rows when LLM support is disabled; `/admin/status` remains behind the common admin gate | `ai-memory-llm` `workload_snapshot_is_bounded_redacted_and_percentiled` (private prompt, output and upstream body absent; fixed row count, recovery-preserved last error, and percentile controls), `llm_wrapper_forwards_the_callers_operation_id` (label recorded while the same UUID-only id reaches the provider), `types::tests::workload_labels_are_stable_and_do_not_change_the_wire_operation_id`; `ai-memory-mcp` `status_reports_bounded_content_free_llm_workload_telemetry` (private prompt absent from serialized status, one fixed row per label), `status_reports_provider_health_block` (disabled LLM emits no rows) | STRONG for content/cardinality and the existing root-only admin surface || 28 | An Antigravity hook reads, and uploads as prompts, only the named conversation's own transcript, within bounds | `ai-memory-hooks/src/antigravity.rs` `antigravity_transcript_path` accepts the payload's `transcriptPath` only when it is absolute, has no `..`, names `transcript.jsonl` or `transcript_full.jsonl`, and its canonical directory equals `canonical(<home>/.gemini/<app>/brain)/<conversationId>/.system_generated/logs` for `<app>` `antigravity`, `antigravity-cli` or `antigravity-ide`, with `conversationId` a plain id (`antigravity_conversation_id`); `read_transcript_prompts` opens only a regular, non-symlink file that is still the same file once open (`open_regular_file`, opened with `O_NOFOLLOW | O_NONBLOCK` so a symlink or FIFO swapped in after the check is refused without blocking, and on Linux only when the opened descriptor's `/proc/self/fd` path is the checked one, so a directory swapped for a symlink after the containment check is refused too), reads at most `MAX_TRANSCRIPT_SCAN_BYTES` per hook and parses lines up to `MAX_TRANSCRIPT_LINE_BYTES`, and returns only `USER_INPUT` steps whose `source` is absent or `USER_EXPLICIT`; `ai-memory-cli/src/commands/hook.rs` `antigravity_transcript_prompt_events` runs inside the spool block, so after the capture allowlist, routing, server-profile and external-capture gates, with the home `run_with_payload` resolved once; its path checks, bounded cursor load and transcript read run behind `ANTIGRAVITY_TRANSCRIPT_READ_BUDGET`, and a timeout advances no cursor so a later hook retries; cursor replacement uses the canonical atomic writer; each prompt is capped and scrubbed client-side, keyed by conversation and step, and sanitized again by the server (row 7) | `antigravity.rs` `transcript_path_refuses_anything_outside_the_conversations_own_logs` (another conversation's transcript, the same layout outside the home, another file in the logs directory, an unknown app directory, `..`, a traversal or empty id, a relative path, a missing or non-string path; the conversation's own transcript is the control), `transcript_path_refuses_symlinked_directories_that_leave_the_conversation` (a symlinked `.system_generated` and `brain/<id>` refused; a symlinked `~/.gemini` accepted as the control), `transcript_reader_refuses_symlinks_and_special_files` (a symlinked transcript and a directory refused; the same bytes as a regular file are read), `skips_injected_malformed_empty_and_non_prompt_steps`, `a_line_longer_than_the_scan_budget_is_skipped_across_reads`, `one_read_returns_a_bounded_number_of_prompts`; `hook.rs` `antigravity_transcript_reads_are_confined_to_the_conversations_own_logs` (end to end through the native hook: a forged path outside the home, another conversation's transcript and an arbitrary JSONL file under the home spool no prompt; the conversation's own transcript spools one), `antigravity_transcript_prompts_follow_the_capture_allowlist` (a repository the allowlist leaves out is not read), `antigravity_transcript_read_deadline_does_not_wait_for_blocked_work`, and `antigravity_transcript_cursor_store_is_atomic_and_bounded` (oversized cursor refused) | STRONG on Linux, including the opened descriptor path. Stable symlink escapes and special files are refused on every platform; without Linux `/proc/self/fd`, a same-user process able to replace an ancestor in the narrow interval between canonicalization and open could redirect the read, which still remains size- and time-bounded. The directory-swap bite test is Linux-only; the other symlink cases are `cfg(unix)` |### IBM Bob evidence