Skip to content

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

Rust

fix(mcp): harden client activity accounting

AkitaOnRails9873b0c12c5a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 937a00fc..d88d6179 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -14,18 +14,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
transport runs stateful (`--http-stateful`) or over stdio, else the
`X-Memory-Actor-Agent` overlay an ingress proxy asserts, else
`unknown` — split into reads and writes and bucketed per UTC day in a
- new `client_activity` table (V46). A new root-gated
+ new `client_activity` table (V46). A new multi-user root-gated
`GET /admin/activity/by-client?since_days=N` reports the aggregate,
volume-descending with a name tiebreak (`0`/absent = whole history).
- Counts buffer in memory and fold into the store at most once per
- minute, so a query burst costs the writer one tiny batch rather than
- one write per call — the M8 access-bump trade; up to a minute of
- telemetry is lost on shutdown by design. Unknown future tools count
- as writes, so an unclassified tool surfaces as suspicious growth
- instead of hiding among reads. This complements
+ Counts buffer in memory and flush from one background task on a one-minute
+ interval, even when the server becomes quiet; failed batches remain bounded
+ in memory and retry once per interval. Process exit can still lose the
+ current interval. Each UTC day retains at most 128 distinct names and folds
+ additional names into `other`, preventing untrusted client names from
+ causing traffic-proportional row growth. Unknown future tools count as
+ writes, so an unclassified tool surfaces as suspicious growth instead of
+ hiding among reads. This complements
`/admin/sessions/by-agent`: hook-driven agents open sessions,
MCP-only clients (VS Code Copilot, Claude Desktop, scripts) never do,
- and until now left no trace at all.
+ and until now left no trace at all. (#366)
- Added explicit Kiro CLI v2 managed-workstream launches through `ai-memory run
kiro` / `kiro-cli`, including native `--resume-id` reuse, `$KIRO_HOME`
discovery, v2 `--yolo` translation, read-only visible-event import, and
diff --git a/README.md b/README.md
index 9a703e8e..23deffe6 100644
--- a/README.md
+++ b/README.md
@@ -147,6 +147,12 @@ priors are at the [bottom](#influences-and-prior-art).
- **Built-in `/web` browser.** Read-only HTML UI for the wiki -
project list, folder tree, FTS5 search, markdown rendering, dark
mode. Mounted on the same axum server as MCP.
+- **Server-wide MCP client activity.**
+ `GET /admin/activity/by-client?since_days=7` shows which MCP clients are
+ calling memory tools, split into reads and writes. Counts use bounded UTC-day
+ buckets, so arbitrary client names cannot grow the database with request
+ volume; shared deployments keep the endpoint root-only. See
+ [MCP client activity](docs/users.md#mcp-client-activity).
- **Multi-agent + multi-machine ready.** Supported clients: Claude
Code, Codex, Devin CLI, OpenCode, Cursor, Claude Desktop (via `mcp-remote`),
Gemini CLI, Antigravity CLI, Grok Build CLI, Kimi Code, OpenClaw, Oh My Pi
diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rs
index 398946c0..07c9b890 100644
--- a/crates/ai-memory-mcp/src/admin.rs
+++ b/crates/ai-memory-mcp/src/admin.rs
@@ -511,6 +511,7 @@ fn hex_to_sha256(hex: &str) -> Result<[u8; 32], String> {
/// - `GET /admin/projects`
/// - `GET /admin/open-sessions`
/// - `GET /admin/sessions/by-agent`
+/// - `GET /admin/activity/by-client`
/// - `GET /admin/audit-contamination`
/// - `GET /admin/search`
/// - `GET /admin/read-page`
@@ -8384,6 +8385,11 @@ mod tests {
"/admin/sessions/by-agent?workspace=default&project=scratch",
serde_json::Value::Null,
),
+ (
+ "GET",
+ "/admin/activity/by-client?since_days=7",
+ serde_json::Value::Null,
+ ),
("GET", "/admin/audit-contamination", serde_json::Value::Null),
("GET", "/admin/search?q=test", serde_json::Value::Null),
(
@@ -8598,6 +8604,19 @@ mod tests {
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
+ let resp = router
+ .clone()
+ .oneshot(
+ Request::builder()
+ .uri("/admin/activity/by-client?since_days=7")
+ .header("authorization", "Bearer root-token")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(resp.status(), StatusCode::OK);
+
// The scope does not exist in this fixture, so reaching the handler
// produces 404. A rejected root request would instead be 401/403.
let resp = router
diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rs
index 906f5acb..fbe798f8 100644
--- a/crates/ai-memory-mcp/src/server.rs
+++ b/crates/ai-memory-mcp/src/server.rs
@@ -14,7 +14,11 @@ use ai_memory_core::{
ProjectId, Sanitizer, SessionId, Tier, WorkspaceId,
};
use ai_memory_llm::{Embedder, LlmProvider};
-use ai_memory_store::{AutoImproveProposalOperation, NewAutoImproveProposal, StageAutoImproveRun};
+use ai_memory_store::{
+ AutoImproveProposalOperation, CLIENT_ACTIVITY_MAX_CLIENTS_PER_DAY,
+ CLIENT_ACTIVITY_MAX_NAME_CHARS, CLIENT_ACTIVITY_OVERFLOW_CLIENT, NewAutoImproveProposal,
+ StageAutoImproveRun,
+};
use ai_memory_store::{DecayParams, PageHit, ReaderPool, ScopeName, ScopeResolver, WriterHandle};
use ai_memory_wiki::{Wiki, WikiError, WritePageRequest};
use rmcp::handler::server::router::tool::ToolRouter;
@@ -598,28 +602,117 @@ const RERANK_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(20);
/// Microseconds in one UTC day, for `client_activity` bucketing.
const US_PER_DAY: i64 = 86_400_000_000;
-/// How long buffered client-activity counts may age before the next
-/// tool call flushes them to the store. Counts inside the window are
-/// lost on process exit — acceptable for telemetry, and the price of
-/// not putting a write on every read's hot path.
+/// How long buffered client-activity counts may age before a background
+/// task flushes them to the store. Counts inside the window are lost on
+/// process exit; failed writes stay bounded in memory and retry.
const CLIENT_ACTIVITY_FLUSH: std::time::Duration = std::time::Duration::from_secs(60);
-/// Cap on a sanitized client name. MCP `clientInfo.name` is untrusted
-/// free text; anything longer is truncated on a char boundary.
-const MAX_CLIENT_NAME_CHARS: usize = 64;
+
+type ClientActivityEntry = (String, i64, u32, u32);
/// In-memory accumulation of per-client tool-call counts between
/// flushes. Keyed by `(client, utc_day)` so a flush that straddles
/// midnight books each call to the day it actually happened.
struct ClientActivityBuffer {
- last_flush: std::time::Instant,
pending: HashMap<(String, i64), (u32, u32)>,
+ flush_scheduled: bool,
}
impl ClientActivityBuffer {
fn new() -> Self {
Self {
- last_flush: std::time::Instant::now(),
pending: HashMap::new(),
+ flush_scheduled: false,
+ }
+ }
+
+ /// Record a delta and return whether the caller must start the sole
+ /// background flusher for this shared buffer.
+ fn record(&mut self, client: String, day: i64, is_write: bool) -> bool {
+ self.record_delta(client, day, u32::from(!is_write), u32::from(is_write));
+ if self.flush_scheduled {
+ false
+ } else {
+ self.flush_scheduled = true;
+ true
+ }
+ }
+
+ fn record_delta(&mut self, client: String, day: i64, reads: u32, writes: u32) {
+ let client = if client == CLIENT_ACTIVITY_OVERFLOW_CLIENT
+ || self.pending.contains_key(&(client.clone(), day))
+ {
+ client
+ } else {
+ let named_clients = self
+ .pending
+ .keys()
+ .filter(|(name, bucket_day)| {
+ *bucket_day == day && name.as_str() != CLIENT_ACTIVITY_OVERFLOW_CLIENT
+ })
+ .count();
+ if named_clients < CLIENT_ACTIVITY_MAX_CLIENTS_PER_DAY {
+ client
+ } else {
+ CLIENT_ACTIVITY_OVERFLOW_CLIENT.to_string()
+ }
+ };
+ let slot = self.pending.entry((client, day)).or_insert((0, 0));
+ slot.0 = slot.0.saturating_add(reads);
+ slot.1 = slot.1.saturating_add(writes);
+ }
+
+ fn take_entries(&mut self) -> Vec<ClientActivityEntry> {
+ std::mem::take(&mut self.pending)
+ .into_iter()
+ .map(|((client, day), (reads, writes))| (client, day, reads, writes))
+ .collect()
+ }
+
+ fn restore_entries(&mut self, entries: Vec<ClientActivityEntry>) {
+ for (client, day, reads, writes) in entries {
+ self.record_delta(client, day, reads, writes);
+ }
+ }
+}
+
+async fn flush_client_activity_loop(
+ buffer: Arc<Mutex<ClientActivityBuffer>>,
+ writer: WriterHandle,
+ interval: Duration,
+) {
+ loop {
+ tokio::time::sleep(interval).await;
+ let entries = {
+ let mut buffer = buffer
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner());
+ if buffer.pending.is_empty() {
+ buffer.flush_scheduled = false;
+ None
+ } else {
+ Some(buffer.take_entries())
+ }
+ };
+ let Some(entries) = entries else {
+ return;
+ };
+
+ if let Err(error) = writer.bump_client_activity(entries.clone()).await {
+ let mut buffer = buffer
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner());
+ buffer.restore_entries(entries);
+ drop(buffer);
+ tracing::warn!(%error, "client activity flush failed; retrying");
+ continue;
+ }
+
+ let mut buffer = buffer
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner());
+ if buffer.pending.is_empty() {
+ buffer.flush_scheduled = false;
+ return;
}
}
}
@@ -638,22 +731,39 @@ fn tool_call_is_write(tool: &str) -> bool {
| "memory_briefing"
| "memory_explore"
| "memory_status"
+ | "memory_install_self_routing"
)
}
/// Trim, drop control characters, and cap an untrusted client name.
/// `None` when nothing printable remains.
fn sanitize_client_name(raw: &str) -> Option<String> {
- let cleaned: String = raw
+ let printable: String = raw
.trim()
.chars()
- .filter(|c| !c.is_control())
- .take(MAX_CLIENT_NAME_CHARS)
+ .filter(|c| !c.is_control() && !is_bidi_control(*c))
+ .collect();
+ let cleaned: String = printable
+ .split_whitespace()
+ .collect::<Vec<_>>()
+ .join(" ")
+ .chars()
+ .take(CLIENT_ACTIVITY_MAX_NAME_CHARS)
.collect();
- let cleaned = cleaned.trim().to_string();
(!cleaned.is_empty()).then_some(cleaned)
}
+fn is_bidi_control(c: char) -> bool {
+ matches!(
+ c,
+ '\u{061c}'
+ | '\u{200e}'
+ | '\u{200f}'
+ | '\u{202a}'..='\u{202e}'
+ | '\u{2066}'..='\u{2069}'
+ )
+}
+
/// Cap on the free-text `reason` stored with a feedback signal.
const MAX_FEEDBACK_REASON_CHARS: usize = 500;
@@ -3612,16 +3722,8 @@ impl AiMemoryServer {
.and_then(ai_memory_core::ActorContext::identity_key)
}
- /// Fire-and-forget access-counter bump for the M8 reinforcement term,
- /// throttled to at most one bump per page PER OPERATOR per
- /// [`ACCESS_BUMP_COOLDOWN`] (see [`select_bumpable`]). Keyed per operator
- /// on purpose: a throttle keyed on the page alone would let whoever read
- /// it first swallow everybody else's reinforcement inside the window, so
- /// breadth — the signal `[decay] breadth_weight` exists to read — would
- /// under-count exactly on the busy pages it matters for. Failures are
- /// logged at warn but never surfaced to the caller.
- /// Record one MCP tool call against its client and flush the buffer
- /// when it is older than [`CLIENT_ACTIVITY_FLUSH`]. Client identity
+ /// Record one MCP tool call against its client and start the shared
+ /// background flusher when needed. Client identity
/// prefers the MCP `clientInfo.name` from the initialize handshake
/// (present in stateful HTTP / stdio); a stateless transport carries
/// no handshake, so the `X-Memory-Actor-Agent` overlay is the
@@ -3648,38 +3750,30 @@ impl AiMemoryServer {
.as_microsecond()
.div_euclid(US_PER_DAY);
let is_write = tool_call_is_write(tool);
- let due = {
+ let schedule_flush = {
let mut buffer = self
.client_activity
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
- let slot = buffer.pending.entry((client, day)).or_insert((0, 0));
- if is_write {
- slot.1 = slot.1.saturating_add(1);
- } else {
- slot.0 = slot.0.saturating_add(1);
- }
- if buffer.last_flush.elapsed() >= CLIENT_ACTIVITY_FLUSH {
- buffer.last_flush = std::time::Instant::now();
- Some(std::mem::take(&mut buffer.pending))
- } else {
- None
- }
+ buffer.record(client, day, is_write)
};
- if let Some(pending) = due {
- let entries: Vec<(String, i64, u32, u32)> = pending
- .into_iter()
- .map(|((client, day), (reads, writes))| (client, day, reads, writes))
- .collect();
- let writer = self.writer.clone();
- tokio::spawn(async move {
- if let Err(e) = writer.bump_client_activity(entries).await {
- tracing::warn!(error = %e, "client activity flush failed");
- }
- });
+ if schedule_flush {
+ tokio::spawn(flush_client_activity_loop(
+ self.client_activity.clone(),
+ self.writer.clone(),
+ CLIENT_ACTIVITY_FLUSH,
+ ));
}
}
+ /// Fire-and-forget access-counter bump for the M8 reinforcement term,
+ /// throttled to at most one bump per page PER OPERATOR per
+ /// [`ACCESS_BUMP_COOLDOWN`] (see [`select_bumpable`]). Keyed per operator
+ /// on purpose: a throttle keyed on the page alone would let whoever read
+ /// it first swallow everybody else's reinforcement inside the window, so
+ /// breadth — the signal `[decay] breadth_weight` exists to read — would
+ /// under-count exactly on the busy pages it matters for. Failures are
+ /// logged at warn but never surfaced to the caller.
fn spawn_access_bump(&self, ids: Vec<PageId>, actor: Option<&ai_memory_core::IdentityKey>) {
if ids.is_empty() {
return;
@@ -9722,6 +9816,7 @@ mod tests {
"memory_briefing",
"memory_explore",
"memory_status",
+ "memory_install_self_routing",
] {
assert!(!tool_call_is_write(read), "{read}");
}
@@ -9743,15 +9838,99 @@ mod tests {
#[test]
fn client_names_are_sanitized_and_bounded() {
assert_eq!(
- sanitize_client_name(" Visual Studio Code ").as_deref(),
+ sanitize_client_name(" Visual \t Studio\nCode ").as_deref(),
Some("Visual Studio Code"),
);
assert_eq!(
sanitize_client_name("evil\u{7}name").as_deref(),
Some("evilname")
);
+ assert_eq!(
+ sanitize_client_name("left\u{202e}right").as_deref(),
+ Some("leftright"),
+ "bidirectional display controls must not reach operator output"
+ );
assert_eq!(sanitize_client_name(" \u{0}\u{1} "), None);
let long = "x".repeat(500);
- assert_eq!(sanitize_client_name(&long).unwrap().chars().count(), 64);
+ assert_eq!(
+ sanitize_client_name(&long).unwrap().chars().count(),
+ CLIENT_ACTIVITY_MAX_NAME_CHARS
+ );
+ }
+
+ #[test]
+ fn client_activity_buffer_schedules_once_and_bounds_each_day() {
+ let mut buffer = ClientActivityBuffer::new();
+ assert!(buffer.record("client-000".into(), 7, false));
+ assert!(!buffer.record("client-000".into(), 7, true));
+ for idx in 1..CLIENT_ACTIVITY_MAX_CLIENTS_PER_DAY {
+ assert!(!buffer.record(format!("client-{idx:03}"), 7, false));
+ }
+ assert!(!buffer.record("overflow-a".into(), 7, false));
+ assert!(!buffer.record("overflow-b".into(), 7, true));
+
+ assert_eq!(
+ buffer.pending.len(),
+ CLIENT_ACTIVITY_MAX_CLIENTS_PER_DAY + 1
+ );
+ assert_eq!(
+ buffer
+ .pending
+ .get(&(CLIENT_ACTIVITY_OVERFLOW_CLIENT.to_string(), 7)),
+ Some(&(1, 1))
+ );
+ assert_eq!(buffer.pending.get(&("client-000".into(), 7)), Some(&(1, 1)));
+ }
+
+ #[test]
+ fn failed_client_activity_batch_restores_without_breaking_the_bound() {
+ let mut buffer = ClientActivityBuffer::new();
+ for idx in 0..CLIENT_ACTIVITY_MAX_CLIENTS_PER_DAY {
+ buffer.record_delta(format!("old-{idx:03}"), 7, 1, 0);
+ }
+ let failed = buffer.take_entries();
+
+ for idx in 0..CLIENT_ACTIVITY_MAX_CLIENTS_PER_DAY {
+ buffer.record_delta(format!("new-{idx:03}"), 7, 0, 1);
+ }
+ buffer.restore_entries(failed);
+
+ assert_eq!(
+ buffer.pending.len(),
+ CLIENT_ACTIVITY_MAX_CLIENTS_PER_DAY + 1,
+ "restoring a failed batch must not double the cardinality budget"
+ );
+ let totals = buffer.pending.values().fold((0_u64, 0_u64), |sum, delta| {
+ (sum.0 + u64::from(delta.0), sum.1 + u64::from(delta.1))
+ });
+ assert_eq!(
+ totals,
+ (
+ CLIENT_ACTIVITY_MAX_CLIENTS_PER_DAY as u64,
+ CLIENT_ACTIVITY_MAX_CLIENTS_PER_DAY as u64
+ ),
+ "retry coalescing must preserve every delta"
+ );
+ }
+
+ #[tokio::test]
+ async fn client_activity_flushes_without_a_later_tool_call() {
+ let tmp = tempfile::tempdir().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let buffer = Arc::new(Mutex::new(ClientActivityBuffer::new()));
+ {
+ let mut locked = buffer.lock().unwrap();
+ assert!(locked.record("quiet-client".into(), 99, false));
+ }
+
+ flush_client_activity_loop(buffer.clone(), store.writer.clone(), Duration::ZERO).await;
+
+ let rows = store.reader.client_activity_since(Some(99)).await.unwrap();
+ assert_eq!(rows.len(), 1);
+ assert_eq!(rows[0].client, "quiet-client");
+ assert_eq!((rows[0].reads, rows[0].writes), (1, 0));
+ let locked = buffer.lock().unwrap();
+ assert!(locked.pending.is_empty());
+ assert!(!locked.flush_scheduled);
}
}
diff --git a/crates/ai-memory-store/migrations/V46__client_activity.sql b/crates/ai-memory-store/migrations/V46__client_activity.sql
index 2c4f6614..a49d7d80 100644
--- a/crates/ai-memory-store/migrations/V46__client_activity.sql
+++ b/crates/ai-memory-store/migrations/V46__client_activity.sql
@@ -10,14 +10,15 @@
-- `client` is the sanitized MCP `clientInfo.name` from the initialize
-- handshake when the HTTP transport runs stateful, else the
-- `X-Memory-Actor-Agent` overlay when an ingress proxy asserts one,
--- else the literal 'unknown'. Free text on purpose: MCP client names
--- are an open set, and forcing them through the `AgentKind` CHECK
--- would misfile every client the enum has not met yet.
+-- else the literal 'unknown'. MCP client names remain an open set rather
+-- than being forced through the `AgentKind` CHECK, but the write boundary
+-- caps both label length and distinct labels per UTC day. Labels beyond
+-- that daily budget fold into the stable 'other' bucket.
--
--- One row per (client, day) keeps the table O(clients × days) — it
--- grows with the calendar, not with traffic.
+-- One row per (client, day), capped to 128 named clients plus 'other',
+-- keeps growth bounded by the calendar rather than request traffic.
CREATE TABLE client_activity (
- client TEXT NOT NULL,
+ client TEXT NOT NULL CHECK (length(client) BETWEEN 1 AND 64),
day INTEGER NOT NULL, -- UTC days since the epoch
reads INTEGER NOT NULL DEFAULT 0 CHECK (reads >= 0),
writes INTEGER NOT NULL DEFAULT 0 CHECK (writes >= 0),
diff --git a/crates/ai-memory-store/src/lib.rs b/crates/ai-memory-store/src/lib.rs
index 4012941d..54dbf29b 100644
--- a/crates/ai-memory-store/src/lib.rs
+++ b/crates/ai-memory-store/src/lib.rs
@@ -72,6 +72,14 @@ pub use writer::{StartupContextAcceptance, WriterHandle};
/// Filename used inside the data dir's `db/` subdirectory.
pub const DB_FILENAME: &str = "memory.sqlite";
+/// Maximum Unicode scalar count accepted for a persisted MCP client label.
+pub const CLIENT_ACTIVITY_MAX_NAME_CHARS: usize = 64;
+/// Maximum distinct named MCP clients persisted for one UTC day. Calls from
+/// additional labels are folded into [`CLIENT_ACTIVITY_OVERFLOW_CLIENT`].
+pub const CLIENT_ACTIVITY_MAX_CLIENTS_PER_DAY: usize = 128;
+/// Stable label used when a UTC day's client-cardinality budget is exhausted.
+pub const CLIENT_ACTIVITY_OVERFLOW_CLIENT: &str = "other";
+
/// Default soft cap for the read-only connection pool.
const READER_POOL_SOFT_CAP: usize = 4;
diff --git a/crates/ai-memory-store/src/ops.rs b/crates/ai-memory-store/src/ops.rs
index 7aaef04f..12bdfbd2 100644
--- a/crates/ai-memory-store/src/ops.rs
+++ b/crates/ai-memory-store/src/ops.rs
@@ -1111,19 +1111,97 @@ pub(crate) fn bump_client_activity(
if entries.is_empty() {
return Ok(());
}
+ for (client, _, _, _) in entries {
+ if !is_normalized_client_activity_label(client) {
+ return Err(StoreError::InvalidState(
+ "client activity label is not normalized".into(),
+ ));
+ }
+ }
let tx = conn.transaction()?;
{
let mut stmt = tx.prepare_cached(
- "INSERT INTO client_activity (client, day, reads, writes) VALUES (?1, ?2, ?3, ?4) ON CONFLICT(client, day) DO UPDATE SET reads = reads + excluded.reads, writes = writes + excluded.writes",
+ "INSERT INTO client_activity (client, day, reads, writes) \
+ VALUES ( \
+ CASE \
+ WHEN ?1 = ?5 \
+ OR EXISTS ( \
+ SELECT 1 FROM client_activity \
+ WHERE client = ?1 AND day = ?2 \
+ ) \
+ OR ( \
+ SELECT COUNT(*) FROM client_activity \
+ WHERE day = ?2 AND client <> ?5 \
+ ) < ?6 \
+ THEN ?1 \
+ ELSE ?5 \
+ END, \
+ ?2, ?3, ?4 \
+ ) \
+ ON CONFLICT(client, day) DO UPDATE SET \
+ reads = CASE \
+ WHEN reads > 9223372036854775807 - excluded.reads \
+ THEN 9223372036854775807 \
+ ELSE reads + excluded.reads \
+ END, \
+ writes = CASE \
+ WHEN writes > 9223372036854775807 - excluded.writes \
+ THEN 9223372036854775807 \
+ ELSE writes + excluded.writes \
+ END",
)?;
for (client, day, reads, writes) in entries {
- stmt.execute(params![client, day, reads, writes])?;
+ if *reads == 0 && *writes == 0 {
+ continue;
+ }
+ stmt.execute(params![
+ client,
+ day,
+ reads,
+ writes,
+ crate::CLIENT_ACTIVITY_OVERFLOW_CLIENT,
+ crate::CLIENT_ACTIVITY_MAX_CLIENTS_PER_DAY,
+ ])?;
}
}
tx.commit()?;
Ok(())
}
+fn is_normalized_client_activity_label(client: &str) -> bool {
+ if client.is_empty()
+ || client != client.trim()
+ || client.chars().count() > crate::CLIENT_ACTIVITY_MAX_NAME_CHARS
+ || client.chars().any(|c| c.is_control() || is_bidi_control(c))
+ {
+ return false;
+ }
+
+ let mut previous_space = false;
+ for c in client.chars() {
+ if c.is_whitespace() {
+ if c != ' ' || previous_space {
+ return false;
+ }
+ previous_space = true;
+ } else {
+ previous_space = false;
+ }
+ }
+ true
+}
+
+fn is_bidi_control(c: char) -> bool {
+ matches!(
+ c,
+ '\u{061c}'
+ | '\u{200e}'
+ | '\u{200f}'
+ | '\u{202a}'..='\u{202e}'
+ | '\u{2066}'..='\u{2069}'
+ )
+}
+
/// Bump `access_count` + `last_accessed_at` for the pages whose ids
/// appear in `page_ids`. Idempotent for unknown ids (no-op).
/// Used by the read path to feed the M8 reinforcement term.
diff --git a/crates/ai-memory-store/src/writer.rs b/crates/ai-memory-store/src/writer.rs
index 0c077054..558d5f71 100644
--- a/crates/ai-memory-store/src/writer.rs
+++ b/crates/ai-memory-store/src/writer.rs
@@ -901,10 +901,13 @@ impl WriterHandle {
}
/// Fold buffered per-client MCP tool-call counts into their
- /// `(client, day)` buckets. Entries are deltas, not totals.
+ /// `(client, day)` buckets. Entries are deltas, not totals. Labels must
+ /// already be normalized; each UTC day retains a bounded number of named
+ /// clients and folds later names into the stable overflow bucket.
///
/// # Errors
- /// Returns [`StoreError::WriterClosed`] or propagates SQL errors.
+ /// Returns [`StoreError::WriterClosed`], rejects malformed labels with
+ /// [`StoreError::InvalidState`], or propagates SQL errors.
pub async fn bump_client_activity(
&self,
entries: Vec<(String, i64, u32, u32)>,
diff --git a/crates/ai-memory-store/tests/client_activity.rs b/crates/ai-memory-store/tests/client_activity.rs
index f8a714a2..06b88e73 100644
--- a/crates/ai-memory-store/tests/client_activity.rs
+++ b/crates/ai-memory-store/tests/client_activity.rs
@@ -1,6 +1,8 @@
//! `client_activity` — per-client MCP tool-call buckets.
-use ai_memory_store::Store;
+use ai_memory_store::{
+ CLIENT_ACTIVITY_MAX_CLIENTS_PER_DAY, CLIENT_ACTIVITY_OVERFLOW_CLIENT, Store,
+};
#[tokio::test]
async fn buckets_accumulate_and_aggregate_deterministically() {
@@ -70,3 +72,79 @@ async fn equal_volumes_keep_a_stable_name_order() {
assert_eq!(first, again);
assert_eq!(first[0].client, "cursor", "name tiebreak, not scan order");
}
+
+#[tokio::test]
+async fn daily_client_cardinality_is_bounded_and_overflow_accumulates() {
+ let tmp = tempfile::tempdir().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let day = 42;
+
+ let named: Vec<_> = (0..CLIENT_ACTIVITY_MAX_CLIENTS_PER_DAY)
+ .map(|idx| (format!("client-{idx:03}"), day, 1, 0))
+ .collect();
+ store.writer.bump_client_activity(named).await.unwrap();
+ store
+ .writer
+ .bump_client_activity(vec![
+ ("client-000".into(), day, 2, 0),
+ ("overflow-a".into(), day, 1, 2),
+ ("overflow-b".into(), day, 3, 4),
+ ])
+ .await
+ .unwrap();
+
+ let rows = store.reader.client_activity_since(Some(day)).await.unwrap();
+ assert_eq!(rows.len(), CLIENT_ACTIVITY_MAX_CLIENTS_PER_DAY + 1);
+ let first = rows.iter().find(|row| row.client == "client-000").unwrap();
+ assert_eq!((first.reads, first.writes), (3, 0));
+ let overflow = rows
+ .iter()
+ .find(|row| row.client == CLIENT_ACTIVITY_OVERFLOW_CLIENT)
+ .unwrap();
+ assert_eq!((overflow.reads, overflow.writes), (4, 6));
+
+ store
+ .writer
+ .bump_client_activity(vec![("overflow-a".into(), day + 1, 2, 0)])
+ .await
+ .unwrap();
+ let next_day = store
+ .reader
+ .client_activity_since(Some(day + 1))
+ .await
+ .unwrap();
+ assert_eq!(next_day.len(), 1, "the client limit resets each UTC day");
+ assert_eq!(next_day[0].client, "overflow-a");
+}
+
+#[tokio::test]
+async fn malformed_client_labels_reject_the_whole_batch() {
+ for invalid in [
+ String::new(),
+ " leading".into(),
+ "double space".into(),
+ "bidi\u{202e}override".into(),
+ "x".repeat(65),
+ ] {
+ let tmp = tempfile::tempdir().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let error = store
+ .writer
+ .bump_client_activity(vec![
+ ("valid".into(), 10, 1, 0),
+ (invalid.clone(), 10, 1, 0),
+ ])
+ .await
+ .unwrap_err();
+ assert!(error.to_string().contains("not normalized"), "{invalid:?}");
+ assert!(
+ store
+ .reader
+ .client_activity_since(None)
+ .await
+ .unwrap()
+ .is_empty(),
+ "validation must happen before any entry is written: {invalid:?}"
+ );
+ }
+}
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 8731cdb0..61248d47 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -267,6 +267,7 @@ separately gated Claude Code assistant/Stop excerpt remains capped at 2 KB.
| `page_embeddings` | Optional vector rows for latest pages, with `(provider, model, dim)` denormalised so hybrid search can ignore stale vectors after an embedding config change and report missing-embedding diagnostics. |
| `page_feedback` | Append-only `memory_feedback` signals (`helpful` / `not_helpful` / `stale` / `wrong`) keyed by page *version*, with an optional sanitized reason and `salience_after`. Source of truth for the derived `pages.salience`; the lint pass reads unresolved stale/wrong rows joined against `is_latest = 1`, so a rewrite retires the finding. |
| `page_access` | One row per latest page and qualified operator identity. Supplies the optional access-breadth retention term without changing the existing shared access counter. |
+| `client_activity` | Server-wide MCP tool-call counters split into reads/writes and bucketed by UTC day. The MCP request choke point flushes buffered calls on a one-minute background interval; failed batches retry from bounded memory. Each day stores at most 128 sanitized client labels plus `other`, so an untrusted `clientInfo.name` cannot create traffic-proportional rows. |
| `auto_improve_proposals` | Staged learning and maintenance edits with immutable target snapshots and append-only decision events. Pending-target uniqueness is scoped by the qualified staging identity; unattributed proposals retain the historical shared bucket. |
| `entities`, `entity_page_links` | V38 noun index derived from canonical frontmatter. Names are normalized and unique per project; links target immutable page versions while retrieval filters to the latest version. Scope-pairing triggers prevent cross-project links. Powers the fourth RRF retrieval stream. |
| `audit_log` | Every mutation, addressable by `at DESC`. |
diff --git a/docs/users.md b/docs/users.md
index c5c118c6..8ace2c77 100644
--- a/docs/users.md
+++ b/docs/users.md
@@ -173,6 +173,25 @@ proxied caller on the single-operator escape hatch that waves admin through.
One question, every gate: the MCP admin tools, the `/admin/*` route layer, and
the ownership stamped on handoffs and sessions all ask it.
+## MCP client activity
+
+`GET /admin/activity/by-client` reports server-wide MCP tool calls rather than
+lifecycle sessions or project-owned data. Stateful HTTP and stdio use the
+sanitized MCP `clientInfo.name`; stateless requests fall back to an
+authenticated proxy's actor-agent label and then `unknown`. Results have the
+stable shape
+`{"by_client":[{"client":"claude-code","reads":12,"writes":3}]}` and are
+ordered by total calls, then client name.
+
+`since_days=N` includes every UTC day bucket intersecting that lookback; zero
+or omission means all history. Calls flush on a one-minute background interval
+even if no later request arrives, and retry failed batches once per interval;
+process exit can lose the current interval. Each UTC day stores at most 128
+distinct labels and folds additional labels into `other`. The endpoint takes
+no workspace or project because many MCP-only clients do not provide reliable
+per-call scope. Like every `/admin/*` route, it is root-only when the deployment
+distinguishes operators.
+
## Per-operator memory slots
The "absent means shared" rule extends to memory slots, so a single-operator