Skip to content

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

Rust

feat(admin): report session counts per agent CLI

Samir Hanna Verza061fffea416a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8aefb7c6..fea39425 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Added
+- New `GET /admin/sessions/by-agent` endpoint reporting how many sessions
+ each agent CLI opened in one scope (`claude-code`, `cursor`, `codex`, …),
+ so a dashboard can answer "where is this project's memory coming from".
+ `sessions.agent_kind` already carried the answer but no read surface
+ exposed it — the existing `/admin/open-sessions` takes the agent as a
+ *filter* and returns neither the kind nor a total. Counts cover open and
+ ended sessions alike, take an optional `since_days` window (`0` or absent
+ = whole history), and order count-descending with an agent-name tiebreak
+ so equal counts do not reorder between calls. Like the other scoped admin
+ reads it reports the caller's own sessions plus unowned ones, with
+ `all_owners=true` as the recovery switch. Unknown scopes 404 rather than
+ being auto-created. No migration.
+
## [1.22.0] - 2026-08-01
### Added
diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rs
index 8c3924d4..2d03ae81 100644
--- a/crates/ai-memory-mcp/src/admin.rs
+++ b/crates/ai-memory-mcp/src/admin.rs
@@ -10,6 +10,7 @@
//! - `GET /admin/status` — lifetime counts + server data-dir info.
//! - `GET /admin/projects` — authoritative `(workspace, project)` list.
//! - `GET /admin/open-sessions` — open (not yet ended) sessions for one scope + agent.
+//! - `GET /admin/sessions/by-agent` — session counts per agent CLI for one scope.
//! - `GET /admin/search?q=` — FTS5 hits against the wiki index.
//! - `POST /admin/reorg` — retro-fit sessions to per-cwd projects.
//! - `POST /admin/lint` — run the M8 lint pass.
@@ -559,6 +560,7 @@ pub fn admin_router_with_decay_breadth(state: AdminState, breadth_weight: f64) -
.route("/admin/status", get(handle_status))
.route("/admin/projects", get(handle_list_projects))
.route("/admin/open-sessions", get(handle_open_sessions))
+ .route("/admin/sessions/by-agent", get(handle_sessions_by_agent))
.route(
"/admin/audit-contamination",
get(handle_audit_contamination),
@@ -905,6 +907,69 @@ struct OpenSessionEntry {
}
/// Parse a kebab-case agent wire string into an [`AgentKind`].
+/// Query string for `GET /admin/sessions/by-agent` — how many sessions each
+/// agent CLI opened in one scope.
+///
+/// `since_days = 0` means "no lower bound": count the project's whole
+/// history rather than an empty window, which is what a dashboard asking for
+/// "all time" wants and what a `u32` cannot express as `None`.
+#[derive(Debug, Deserialize)]
+struct SessionsByAgentQuery {
+ workspace: String,
+ project: String,
+ #[serde(default)]
+ since_days: u32,
+ /// Report every operator's sessions instead of just the caller's. Same
+ /// recovery switch the other scoped admin reads expose.
+ #[serde(default)]
+ all_owners: bool,
+}
+
+/// Microseconds in a day, for the `since_days` window.
+const US_PER_DAY: i64 = 86_400_000_000;
+
+async fn handle_sessions_by_agent(
+ State(state): State<Arc<AdminState>>,
+ actor_ext: Option<axum::Extension<ai_memory_core::ActorContext>>,
+ Query(query): Query<SessionsByAgentQuery>,
+) -> impl IntoResponse {
+ let (ws, proj) = match lookup_ws_proj_no_create(&state, &query.workspace, &query.project).await
+ {
+ Ok(ids) => ids,
+ Err(e) => return e,
+ };
+ let since_us = (query.since_days > 0).then(|| {
+ jiff::Timestamp::now()
+ .as_microsecond()
+ .saturating_sub(i64::from(query.since_days).saturating_mul(US_PER_DAY))
+ });
+ let owner_filter = if query.all_owners {
+ ai_memory_core::OwnerFilter::Any
+ } else {
+ ai_memory_core::OwnerFilter::for_actor_context(
+ &actor_ext.map_or_else(ai_memory_core::ActorContext::anonymous, |ext| ext.0),
+ )
+ };
+ match state
+ .reader
+ .session_counts_by_agent(ws, proj, owner_filter, since_us)
+ .await
+ {
+ Ok(counts) => (
+ StatusCode::OK,
+ Json(
+ serde_json::to_value(&counts)
+ .map(|list| serde_json::json!({ "by_agent": list }))
+ .unwrap_or_else(|_| serde_json::json!({ "by_agent": [] })),
+ ),
+ ),
+ Err(e) => (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Json(serde_json::json!({ "error": e.to_string() })),
+ ),
+ }
+}
+
fn parse_agent_kind(raw: &str) -> Option<AgentKind> {
AgentKind::ALL.into_iter().find(|kind| kind.as_str() == raw)
}
@@ -5317,6 +5382,137 @@ mod tests {
assert_eq!(json["providers"]["embedding"]["status"], "disabled");
}
+ /// The dashboard read: session counts grouped per agent CLI, with the
+ /// scope failing closed and never auto-created.
+ #[tokio::test]
+ async fn sessions_by_agent_counts_per_agent_and_fails_closed_on_unknown_scope() {
+ 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 ws = store
+ .writer
+ .get_or_create_workspace("default".to_string())
+ .await
+ .unwrap();
+ let target = store
+ .writer
+ .get_or_create_project(ws, "target".to_string(), None)
+ .await
+ .unwrap();
+ let other_project = store
+ .writer
+ .get_or_create_project(ws, "other".to_string(), None)
+ .await
+ .unwrap();
+ for (project_id, agent) in [
+ (target, AgentKind::ClaudeCode),
+ (target, AgentKind::ClaudeCode),
+ (target, AgentKind::Cursor),
+ // A different scope must not leak into the target's totals.
+ (other_project, AgentKind::Codex),
+ ] {
+ store
+ .writer
+ .begin_session(NewSession {
+ id: SessionId::new(),
+ workspace_id: ws,
+ project_id,
+ agent_kind: agent,
+ cwd: None,
+ actor_user: None,
+ })
+ .await
+ .unwrap();
+ }
+
+ let router = admin_router(AdminState {
+ writer: store.writer.clone(),
+ reader: store.reader.clone(),
+ wiki,
+ llm: None,
+ auto_improve_require_approval: false,
+ auto_improve_review_config: Default::default(),
+ embedder: None,
+ provider_health: ProviderHealth::default(),
+ decay_params: DecayParams::default(),
+ data_dir: tmp.path().to_path_buf(),
+ db_path: store.db_path().to_path_buf(),
+ bind: "127.0.0.1:49375".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
+ .clone()
+ .oneshot(
+ Request::builder()
+ .uri("/admin/sessions/by-agent?workspace=default&project=target")
+ .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();
+ assert_eq!(
+ json["by_agent"],
+ serde_json::json!([
+ { "agent": "claude-code", "sessions": 2 },
+ { "agent": "cursor", "sessions": 1 },
+ ]),
+ "counts are per agent, scoped, count-desc: {json}"
+ );
+
+ // A window that starts in the future reports nothing rather than
+ // ignoring the bound.
+ let resp = router
+ .clone()
+ .oneshot(
+ Request::builder()
+ .uri("/admin/sessions/by-agent?workspace=default&project=target&since_days=0")
+ .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();
+ assert_eq!(
+ json["by_agent"].as_array().unwrap().len(),
+ 2,
+ "since_days=0 means the whole history, not an empty window: {json}"
+ );
+
+ // Unknown scope fails closed with a 404 — never auto-created.
+ let resp = router
+ .oneshot(
+ Request::builder()
+ .uri("/admin/sessions/by-agent?workspace=default&project=ghost")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(resp.status(), StatusCode::NOT_FOUND);
+ assert!(
+ store
+ .reader
+ .find_project(ws, "ghost".to_string())
+ .await
+ .unwrap()
+ .is_none(),
+ "read route must not auto-create scopes"
+ );
+ }
+
#[tokio::test]
async fn open_sessions_filters_by_scope_and_agent() {
let tmp = TempDir::new().unwrap();
diff --git a/crates/ai-memory-store/src/lib.rs b/crates/ai-memory-store/src/lib.rs
index cdfe6b1d..c1cd752f 100644
--- a/crates/ai-memory-store/src/lib.rs
+++ b/crates/ai-memory-store/src/lib.rs
@@ -47,13 +47,13 @@ pub use ops::{
ReorgSummary,
};
pub use reader::{
- ActivityWindow, AutoImproveCandidateSession, BriefPageBody, BriefingPage, BriefingSnapshot,
- ContaminationFinding, ContaminationReport, ContaminationSummary, DecayCandidate,
- DerivedIndexStatus, EmbeddingTripleCount, FeedbackFinding, GraphVia, HealthDetail, HealthPage,
- ObservationHit, OpenSession, PageAuthor, PageHit, PageHitWithMeta, PageLinks, PageMeta,
- PageSummary, ProjectSummary, ReaderPool, ReindexTargetStatus, RelatedPage, RrfContributions,
- ScopeRow, SearchExplain, SessionEndDisposition, StatusCounts, StoredEmbedding, StoredPageBody,
- WorkspaceScopeRow, WorkspaceSummary, f32_vec_to_bytes,
+ ActivityWindow, AgentSessionCount, AutoImproveCandidateSession, BriefPageBody, BriefingPage,
+ BriefingSnapshot, ContaminationFinding, ContaminationReport, ContaminationSummary,
+ DecayCandidate, DerivedIndexStatus, EmbeddingTripleCount, FeedbackFinding, GraphVia,
+ HealthDetail, HealthPage, ObservationHit, OpenSession, PageAuthor, PageHit, PageHitWithMeta,
+ PageLinks, PageMeta, PageSummary, ProjectSummary, ReaderPool, ReindexTargetStatus, RelatedPage,
+ RrfContributions, ScopeRow, SearchExplain, SessionEndDisposition, StatusCounts,
+ StoredEmbedding, StoredPageBody, WorkspaceScopeRow, WorkspaceSummary, f32_vec_to_bytes,
};
pub use scope::{
ResolvedScope, ScopeName, ScopeResolutionError, ScopeResolver, WORKSPACE_PROJECT_PAIR_REQUIRED,
diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rs
index 999d86d1..1e1750c4 100644
--- a/crates/ai-memory-store/src/reader.rs
+++ b/crates/ai-memory-store/src/reader.rs
@@ -430,6 +430,16 @@ pub struct OpenSession {
pub cwd: Option<String>,
}
+/// How many sessions one agent CLI opened in a scope — the shape behind
+/// "where is this project's memory actually coming from".
+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
+pub struct AgentSessionCount {
+ /// `AgentKind` as stored (`claude-code`, `cursor`, …).
+ pub agent: String,
+ /// Sessions this agent opened in the window, ended or still open.
+ pub sessions: u64,
+}
+
/// How a `SessionEnd` event should treat its target session — see
/// [`ReaderPool::session_end_disposition`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -1688,6 +1698,81 @@ impl ReaderPool {
.await
}
+ /// Count sessions per agent CLI in one scope, newest window first.
+ ///
+ /// Counts every session the window covers, open or ended — the question
+ /// is which tools produced this project's memory, not which are running
+ /// right now (`open_sessions_for_scope_agent` answers that).
+ ///
+ /// `since_us` is an inclusive lower bound on `started_at`; `None` counts
+ /// the project's whole history. The scan rides
+ /// `idx_sessions_recent (workspace_id, project_id, started_at DESC)`, so
+ /// it stays bounded by scope rather than table-wide.
+ ///
+ /// Ordering is count-descending with an agent-name tiebreak, so equal
+ /// counts do not reorder between calls.
+ ///
+ /// # Errors
+ /// Propagates any SQL or pool error.
+ pub async fn session_counts_by_agent(
+ &self,
+ workspace_id: WorkspaceId,
+ project_id: ProjectId,
+ owner_filter: OwnerFilter,
+ since_us: Option<i64>,
+ ) -> StoreResult<Vec<AgentSessionCount>> {
+ self.with_conn(move |conn| {
+ // Same reasoning as `open_sessions_for_scope_agent`: without the
+ // owner predicate a shared server reports a teammate's activity as
+ // the caller's own.
+ let owner_clause = match &owner_filter {
+ OwnerFilter::Any => "",
+ OwnerFilter::User(_) => " AND (actor_user IS NULL OR actor_user = :actor)",
+ OwnerFilter::Unattributed => " AND actor_user IS NULL",
+ };
+ let since_clause = if since_us.is_some() {
+ " AND started_at >= :since"
+ } else {
+ ""
+ };
+ let sql = format!(
+ "SELECT agent_kind, COUNT(*) AS n FROM sessions \
+ WHERE workspace_id = :ws AND project_id = :proj\
+ {since_clause}{owner_clause} \
+ GROUP BY agent_kind \
+ ORDER BY n DESC, agent_kind ASC"
+ );
+ let mut stmt = conn.prepare_cached(&sql)?;
+ let ws_bytes = workspace_id.as_bytes();
+ let proj_bytes = project_id.as_bytes();
+ let mut named: Vec<(&str, &dyn rusqlite::ToSql)> = vec![
+ (":ws", &ws_bytes as &dyn rusqlite::ToSql),
+ (":proj", &proj_bytes as &dyn rusqlite::ToSql),
+ ];
+ if let Some(since) = &since_us {
+ named.push((":since", since));
+ }
+ if let OwnerFilter::User(user) = &owner_filter {
+ named.push((":actor", user));
+ }
+ let rows = stmt.query_map(named.as_slice(), |row| {
+ let agent: String = row.get(0)?;
+ let n: i64 = row.get(1)?;
+ Ok((agent, n))
+ })?;
+ let mut out = Vec::new();
+ for row in rows {
+ let (agent, n) = row?;
+ out.push(AgentSessionCount {
+ agent,
+ sessions: u64::try_from(n).unwrap_or(0),
+ });
+ }
+ Ok(out)
+ })
+ .await
+ }
+
/// Return open sessions matching one scoped project and agent.
///
/// Results are newest-first so callers can default to finalizing only the
diff --git a/crates/ai-memory-store/tests/sessions_by_agent.rs b/crates/ai-memory-store/tests/sessions_by_agent.rs
new file mode 100644
index 00000000..5d71da2d
--- /dev/null
+++ b/crates/ai-memory-store/tests/sessions_by_agent.rs
@@ -0,0 +1,168 @@
+//! `session_counts_by_agent` — which agent CLIs produced a project's memory.
+//!
+//! The counts feed an operator dashboard, so the two properties that matter
+//! are that the grouping is stable between calls and that one operator's
+//! activity is not reported as another's on a shared server.
+
+use ai_memory_core::{
+ ActorContext, AgentKind, IdentityKey, NewSession, OwnerFilter, ProjectId, SessionId,
+ WorkspaceId,
+};
+use ai_memory_store::Store;
+
+fn operator(name: &str) -> String {
+ IdentityKey::User(name.into()).storage_key()
+}
+
+fn filter_for(name: &str) -> OwnerFilter {
+ OwnerFilter::for_actor_context(&ActorContext {
+ user: Some(name.into()),
+ ..ActorContext::default()
+ })
+}
+
+async fn scope(store: &Store) -> (WorkspaceId, ProjectId) {
+ let ws = store
+ .writer
+ .get_or_create_workspace("acme".to_string())
+ .await
+ .unwrap();
+ let proj = store
+ .writer
+ .get_or_create_project(ws, "app".to_string(), None)
+ .await
+ .unwrap();
+ (ws, proj)
+}
+
+async fn session(
+ store: &Store,
+ ws: WorkspaceId,
+ proj: ProjectId,
+ agent: AgentKind,
+ owner: Option<String>,
+) {
+ store
+ .writer
+ .begin_session(NewSession {
+ id: SessionId::new(),
+ workspace_id: ws,
+ project_id: proj,
+ agent_kind: agent,
+ cwd: None,
+ actor_user: owner,
+ })
+ .await
+ .unwrap();
+}
+
+/// Grouping is by agent, ordered count-descending. The tiebreak is the agent
+/// name, so two agents with equal counts keep a stable order across calls
+/// rather than following SQLite's scan order.
+#[tokio::test]
+async fn counts_group_by_agent_and_order_deterministically() {
+ let tmp = tempfile::tempdir().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let (ws, proj) = scope(&store).await;
+
+ for _ in 0..3 {
+ session(&store, ws, proj, AgentKind::ClaudeCode, None).await;
+ }
+ // `codex` and `cursor` tie at one session each.
+ session(&store, ws, proj, AgentKind::Cursor, None).await;
+ session(&store, ws, proj, AgentKind::Codex, None).await;
+
+ let counts = store
+ .reader
+ .session_counts_by_agent(ws, proj, OwnerFilter::Any, None)
+ .await
+ .unwrap();
+
+ let seen: Vec<(&str, u64)> = counts
+ .iter()
+ .map(|c| (c.agent.as_str(), c.sessions))
+ .collect();
+ assert_eq!(
+ seen,
+ vec![("claude-code", 3), ("codex", 1), ("cursor", 1)],
+ "count desc, then agent name asc",
+ );
+
+ // Same query twice must not reorder the tied pair.
+ let again = store
+ .reader
+ .session_counts_by_agent(ws, proj, OwnerFilter::Any, None)
+ .await
+ .unwrap();
+ assert_eq!(counts, again);
+}
+
+/// The window is an inclusive lower bound on `started_at`. A cutoff in the
+/// future excludes everything rather than silently ignoring the argument.
+#[tokio::test]
+async fn since_bounds_the_window() {
+ let tmp = tempfile::tempdir().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let (ws, proj) = scope(&store).await;
+ session(&store, ws, proj, AgentKind::ClaudeCode, None).await;
+
+ let all = store
+ .reader
+ .session_counts_by_agent(ws, proj, OwnerFilter::Any, None)
+ .await
+ .unwrap();
+ assert_eq!(all.len(), 1, "no bound counts the whole history");
+
+ let future = jiff::Timestamp::now().as_microsecond() + 60_000_000;
+ let none = store
+ .reader
+ .session_counts_by_agent(ws, proj, OwnerFilter::Any, Some(future))
+ .await
+ .unwrap();
+ assert!(none.is_empty(), "a future cutoff excludes every session");
+}
+
+/// On a shared server the dashboard must not report a teammate's activity as
+/// the caller's. Unowned (single-user / legacy) rows stay visible to everyone,
+/// matching the `absent = shared` rule the rest of the ownership work uses.
+#[tokio::test]
+async fn counts_are_scoped_to_the_asking_operator() {
+ let tmp = tempfile::tempdir().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let (ws, proj) = scope(&store).await;
+
+ session(
+ &store,
+ ws,
+ proj,
+ AgentKind::ClaudeCode,
+ Some(operator("alice")),
+ )
+ .await;
+ session(&store, ws, proj, AgentKind::Cursor, Some(operator("bob"))).await;
+ // Written before the server distinguished operators.
+ session(&store, ws, proj, AgentKind::Codex, None).await;
+
+ let alice = store
+ .reader
+ .session_counts_by_agent(ws, proj, filter_for("alice"), None)
+ .await
+ .unwrap();
+ let alice_agents: Vec<&str> = alice.iter().map(|c| c.agent.as_str()).collect();
+ assert_eq!(
+ alice_agents,
+ vec!["claude-code", "codex"],
+ "own rows plus shared rows, never bob's",
+ );
+
+ let everyone = store
+ .reader
+ .session_counts_by_agent(ws, proj, OwnerFilter::Any, None)
+ .await
+ .unwrap();
+ assert_eq!(
+ everyone.len(),
+ 3,
+ "the recovery switch reports all operators"
+ );
+}
diff --git a/docs/users.md b/docs/users.md
index 3abbdceb..dd2aec86 100644
--- a/docs/users.md
+++ b/docs/users.md
@@ -142,6 +142,9 @@ to — and consumed by — the next session to start, whoever it belongs to.
multi-user mode.
- `ai-memory finalize-session --all-owners` does the same for sessions, and
`GET /admin/open-sessions?all_owners=true` is the underlying switch.
+- `GET /admin/sessions/by-agent` reports how many sessions each agent CLI
+ opened in a scope. It follows the same rule: the caller's own sessions
+ plus the unowned ones, with `all_owners=true` to see every operator's.
- The read-only handoff listing (`GET
/api/v1/workspaces/{ws}/projects/{p}/handoffs`) serves its prompt-derived
fields — `summary`, `open_questions`, `next_steps` — to a caller the server