Skip to content

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

Rust

feat(store): scoped per-session observation reads and session summaries (#401)

Sergio Aguirref4c28f0fc470
diff --git a/crates/ai-memory-store/src/lib.rs b/crates/ai-memory-store/src/lib.rs
index 333077c1..7b8d0169 100644
--- a/crates/ai-memory-store/src/lib.rs
+++ b/crates/ai-memory-store/src/lib.rs
@@ -52,11 +52,12 @@ pub use reader::{
ActivityWindow, AgentSessionCount, AutoImproveCandidateSession, BriefPageBody, BriefingPage,
BriefingSnapshot, ClientActivity, ContaminationFinding, ContaminationReport,
ContaminationSummary, DecayCandidate, DecayTombstone, DerivedIndexStatus, EmbeddingTripleCount,
- FeedbackFinding, GraphVia, HealthDetail, HealthPage, ObservationHit, OpenSession, PageAuthor,
- PageHit, PageHitWithMeta, PageLinks, PageMeta, PageSummary, ProjectSummary, ReaderPool,
+ FeedbackFinding, GraphVia, HealthDetail, HealthPage, ObservationHit, ObservationOrder,
+ ObservationPage, ObservationPageResult, ObservationRecord, OpenSession, PageAuthor, PageHit,
+ PageHitWithMeta, PageLinks, PageMeta, PageSummary, ProjectSummary, ReaderPool,
ReindexTargetStatus, RelatedPage, RrfContributions, ScopeRow, SearchExplain,
- SessionEndDisposition, StatusCounts, StoredEmbedding, StoredPageBody, WorkspaceScopeRow,
- WorkspaceSummary, f32_vec_to_bytes,
+ SessionEndDisposition, SessionSummary, 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 5ccad44c..1b1a3d62 100644
--- a/crates/ai-memory-store/src/reader.rs
+++ b/crates/ai-memory-store/src/reader.rs
@@ -19,7 +19,7 @@ use jiff::Timestamp;
use parking_lot::Mutex;
use rusqlite::types::Value;
use rusqlite::{Connection, OpenFlags, OptionalExtension, params, params_from_iter};
-use serde::Serialize;
+use serde::{Deserialize, Serialize};
use uuid::Uuid;
// `ai_memory_core::Tier` is referenced via fully-qualified path inside the
// DecayCandidate struct definition above to avoid a top-level import
@@ -430,6 +430,27 @@ pub struct OpenSession {
pub cwd: Option<String>,
}
+/// One session as listed from a scope by [`ReaderPool::sessions_for_scope`]
+/// and [`ReaderPool::session_summary_scoped`].
+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
+pub struct SessionSummary {
+ /// Session id.
+ pub session_id: SessionId,
+ /// Captured session cwd, if available.
+ pub cwd: Option<String>,
+ /// `AgentKind` as stored (`claude-code`, `cursor`, ...).
+ pub agent_kind: String,
+ /// ISO-8601 session start timestamp.
+ pub started_at: String,
+ /// ISO-8601 session end timestamp; `None` while the session is open.
+ pub ended_at: Option<String>,
+ /// Observations of this session that landed in the queried scope. A
+ /// session that crossed repositories mid-flight has more rows elsewhere.
+ pub observation_count: u64,
+ /// Operator the session belongs to, as stored on the `sessions` row.
+ pub actor_user: Option<String>,
+}
+
/// Aggregate MCP tool-call counts for one client, from
/// `client_activity` — the MCP-only complement to
/// [`AgentSessionCount`]: hook-less clients (VS Code Copilot, Claude
@@ -532,6 +553,74 @@ pub struct ObservationHit {
pub created_at: String,
}
+/// One raw observation with its full stored body, as returned by
+/// [`ReaderPool::session_observations_scoped`]. Bodies were sanitized and
+/// bounded on the way in, so this is a read of what the store holds; callers
+/// that need a smaller payload cap the body themselves.
+#[derive(Debug, Clone, Serialize)]
+pub struct ObservationRecord {
+ /// Stable observation identifier.
+ pub id: ObservationId,
+ /// Owning session identifier.
+ pub session_id: SessionId,
+ /// Observation kind as stored on the lifecycle row.
+ pub kind: String,
+ /// Observation title.
+ pub title: String,
+ /// Full sanitized observation body.
+ pub body: String,
+ /// Importance in `1..=10`.
+ pub importance: u8,
+ /// ISO-8601 creation timestamp.
+ pub created_at: String,
+ /// Third-party extension namespace that supplied `source_event`, if any.
+ pub extension: Option<String>,
+ /// Source event name from an opt-in extension vocabulary, if any.
+ pub source_event: Option<String>,
+}
+
+/// Sort direction for [`ObservationPage`].
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum ObservationOrder {
+ /// Oldest first (capture order).
+ #[default]
+ Asc,
+ /// Newest first.
+ Desc,
+}
+
+/// Paging and filtering for [`ReaderPool::session_observations_scoped`].
+/// The store applies `limit` and `offset` as given; callers clamp.
+#[derive(Debug, Clone)]
+pub struct ObservationPage {
+ /// Maximum rows to return. Zero returns no rows but still counts.
+ pub limit: usize,
+ /// Rows to skip before the first returned one.
+ pub offset: usize,
+ /// Sort direction over `created_at` (with the id as tiebreak).
+ pub order: ObservationOrder,
+ /// Keep only these kinds. `None` or an empty list keeps every kind.
+ pub kinds: Option<Vec<ObservationKind>>,
+ /// Optional full-text query over title and body. Ignored when it
+ /// normalizes to nothing searchable.
+ pub query: Option<String>,
+}
+
+/// One page of a session's observations plus the counts a caller needs to
+/// paginate and to notice that the session has rows outside the scope.
+#[derive(Debug, Clone, Serialize)]
+pub struct ObservationPageResult {
+ /// The requested page, in the requested order.
+ pub records: Vec<ObservationRecord>,
+ /// Rows in scope matching the kind and query filters, across all pages.
+ pub total: u64,
+ /// Rows of the same session that landed in a different
+ /// `(workspace, project)`, unfiltered. Non-zero means the session crossed
+ /// repositories and this scope holds only part of it.
+ pub elided_other_scope: u64,
+}
+
/// Aggregate counts surfaced by [`ReaderPool::status_counts`] and consumed
/// by `ai-memory status`.
#[derive(Debug, Clone, Default, Serialize)]
@@ -1646,6 +1735,126 @@ impl ReaderPool {
.await
}
+ /// Page through one session's raw observations as seen from one scope.
+ ///
+ /// Only the rows that landed in `(workspace_id, project_id)` are returned:
+ /// a session that crossed repositories mid-flight has observations in more
+ /// than one scope, and a caller resolved to one of them must not read the
+ /// other. `elided_other_scope` reports how many rows were left out so the
+ /// caller can tell a short session from a partially visible one. `total`
+ /// counts the in-scope rows matching the page's kind and query filters, so
+ /// paginating needs no second round-trip; a zero `limit` returns no rows
+ /// but still reports both counts.
+ ///
+ /// The query goes through the same FTS5 normalization as
+ /// [`Self::search_observations_for_project`] and is dropped when nothing
+ /// searchable remains, so a punctuation-only query lists the session
+ /// instead of matching nothing.
+ ///
+ /// # Errors
+ /// Propagates any SQL or pool error.
+ pub async fn session_observations_scoped(
+ &self,
+ workspace_id: WorkspaceId,
+ project_id: ProjectId,
+ session_id: SessionId,
+ page: ObservationPage,
+ ) -> StoreResult<ObservationPageResult> {
+ let fts_query = page
+ .query
+ .as_deref()
+ .map(normalize_fts_query)
+ .filter(|q| !q.is_empty());
+ let kinds: Vec<&'static str> = page
+ .kinds
+ .iter()
+ .flatten()
+ .map(ObservationKind::as_str)
+ .collect();
+ let direction = match page.order {
+ ObservationOrder::Asc => "ASC",
+ ObservationOrder::Desc => "DESC",
+ };
+ let (limit, offset) = (page.limit, page.offset);
+ self.with_conn(move |conn| {
+ // `?` is positional-by-order: session, scope, then the optional
+ // MATCH term and kind list, then LIMIT/OFFSET on the page query.
+ let mut sql_params: Vec<Value> = Vec::with_capacity(kinds.len() + 6);
+ sql_params.push(Value::Blob(session_id.as_bytes().to_vec()));
+ sql_params.push(Value::Blob(workspace_id.as_bytes().to_vec()));
+ sql_params.push(Value::Blob(project_id.as_bytes().to_vec()));
+ let mut source = String::from("FROM observations");
+ let mut predicate = String::from(
+ " WHERE observations.session_id = ? \
+ AND observations.workspace_id = ? \
+ AND observations.project_id = ?",
+ );
+ if let Some(q) = fts_query {
+ source.push_str(
+ " JOIN observations_fts ON observations_fts.rowid = observations.rowid",
+ );
+ predicate.push_str(" AND observations_fts MATCH ?");
+ sql_params.push(Value::Text(q));
+ }
+ if !kinds.is_empty() {
+ predicate.push_str(" AND observations.kind IN (");
+ for (idx, kind) in kinds.iter().enumerate() {
+ if idx > 0 {
+ predicate.push_str(", ");
+ }
+ predicate.push('?');
+ sql_params.push(Value::Text((*kind).to_string()));
+ }
+ predicate.push(')');
+ }
+
+ let total: i64 = conn.query_row(
+ &format!("SELECT COUNT(*) {source}{predicate}"),
+ params_from_iter(sql_params.iter()),
+ |row| row.get(0),
+ )?;
+ let elided: i64 = conn.query_row(
+ "SELECT COUNT(*) FROM observations \
+ WHERE session_id = ?1 AND NOT (workspace_id = ?2 AND project_id = ?3)",
+ params![
+ session_id.as_bytes(),
+ workspace_id.as_bytes(),
+ project_id.as_bytes()
+ ],
+ |row| row.get(0),
+ )?;
+
+ let mut records = Vec::new();
+ if limit > 0 {
+ sql_params.push(Value::Integer(i64::try_from(limit).unwrap_or(i64::MAX)));
+ sql_params.push(Value::Integer(i64::try_from(offset).unwrap_or(i64::MAX)));
+ let sql = format!(
+ "SELECT observations.id, observations.session_id, observations.kind, \
+ observations.title, observations.body, observations.importance, \
+ observations.created_at, observations.extension, \
+ observations.source_event \
+ {source}{predicate} \
+ ORDER BY observations.created_at {direction}, observations.id {direction} \
+ LIMIT ? OFFSET ?"
+ );
+ let mut stmt = conn.prepare(&sql)?;
+ let rows = stmt.query_map(
+ params_from_iter(sql_params.iter()),
+ row_to_observation_record,
+ )?;
+ for row in rows {
+ records.push(row??);
+ }
+ }
+ Ok(ObservationPageResult {
+ records,
+ total: u64::try_from(total).unwrap_or(0),
+ elided_other_scope: u64::try_from(elided).unwrap_or(0),
+ })
+ })
+ .await
+ }
+
/// Return the latest completed session for a project.
///
/// Used by read-only review tools that need a natural default when the user
@@ -1978,6 +2187,175 @@ impl ReaderPool {
.await
}
+ /// List the sessions that touched one scope, newest first.
+ ///
+ /// A session is listed when its `sessions` row is anchored in the scope OR
+ /// at least one of its observations landed there. The second half matters
+ /// for a session that changed repositories mid-flight: its row stays
+ /// frozen on the starting scope (`begin_session` is `ON CONFLICT DO
+ /// NOTHING`), so listing by row alone would hide it from the very scope
+ /// that holds its work. `observation_count` counts only the rows in this
+ /// scope. `include_open == false` keeps sessions with `ended_at` set.
+ ///
+ /// The owner predicate follows the rest of the session surface: shared
+ /// (`actor_user IS NULL`) rows are visible to everyone, owned rows only to
+ /// their operator unless the caller passes [`OwnerFilter::Any`].
+ ///
+ /// # Errors
+ /// Propagates any SQL or pool error.
+ pub async fn sessions_for_scope(
+ &self,
+ workspace_id: WorkspaceId,
+ project_id: ProjectId,
+ owner_filter: OwnerFilter,
+ include_open: bool,
+ limit: usize,
+ offset: usize,
+ ) -> StoreResult<Vec<SessionSummary>> {
+ self.sessions_for_scope_filtered(
+ workspace_id,
+ project_id,
+ owner_filter,
+ include_open,
+ limit,
+ offset,
+ None,
+ )
+ .await
+ }
+
+ /// Return one session as seen from one scope, or `None` when the session
+ /// has neither its row nor any observation there, or when the owner
+ /// filter rejects it. The id narrows the same predicates
+ /// [`Self::sessions_for_scope`] applies (open sessions included); it
+ /// never replaces them, so a known id cannot read across scopes or
+ /// operators.
+ ///
+ /// # Errors
+ /// Propagates any SQL or pool error.
+ pub async fn session_summary_scoped(
+ &self,
+ workspace_id: WorkspaceId,
+ project_id: ProjectId,
+ session_id: SessionId,
+ owner_filter: OwnerFilter,
+ ) -> StoreResult<Option<SessionSummary>> {
+ let mut sessions = self
+ .sessions_for_scope_filtered(
+ workspace_id,
+ project_id,
+ owner_filter,
+ true,
+ 1,
+ 0,
+ Some(session_id),
+ )
+ .await?;
+ Ok(sessions.pop())
+ }
+
+ #[allow(clippy::too_many_arguments)]
+ async fn sessions_for_scope_filtered(
+ &self,
+ workspace_id: WorkspaceId,
+ project_id: ProjectId,
+ owner_filter: OwnerFilter,
+ include_open: bool,
+ limit: usize,
+ offset: usize,
+ exact_session_id: Option<SessionId>,
+ ) -> StoreResult<Vec<SessionSummary>> {
+ self.with_conn(move |conn| {
+ // The point lookup lets the primary key narrow first so the scope
+ // test is one indexed probe; the listing materializes the scope's
+ // session ids once instead of probing every session in the table.
+ let membership = if exact_session_id.is_some() {
+ " AND s.id = :sid \
+ AND ((s.workspace_id = :ws AND s.project_id = :proj) \
+ OR EXISTS (SELECT 1 FROM observations o \
+ WHERE o.session_id = s.id \
+ AND o.workspace_id = :ws AND o.project_id = :proj))"
+ } else {
+ " AND s.id IN (SELECT id FROM sessions \
+ WHERE workspace_id = :ws AND project_id = :proj \
+ UNION \
+ SELECT session_id FROM observations \
+ WHERE workspace_id = :ws AND project_id = :proj)"
+ };
+ let owner_clause = match &owner_filter {
+ OwnerFilter::Any => "",
+ OwnerFilter::User(_) => " AND (s.actor_user IS NULL OR s.actor_user = :actor)",
+ OwnerFilter::Unattributed => " AND s.actor_user IS NULL",
+ };
+ let ended_clause = if include_open {
+ ""
+ } else {
+ " AND s.ended_at IS NOT NULL"
+ };
+ let sql = format!(
+ "SELECT s.id, s.cwd, s.agent_kind, s.started_at, s.ended_at, s.actor_user, \
+ (SELECT COUNT(*) FROM observations o \
+ WHERE o.session_id = s.id \
+ AND o.workspace_id = :ws AND o.project_id = :proj) AS n \
+ FROM sessions s \
+ WHERE 1 = 1{membership}{owner_clause}{ended_clause} \
+ ORDER BY s.started_at DESC, s.id DESC \
+ LIMIT :limit OFFSET :offset"
+ );
+ let mut stmt = conn.prepare_cached(&sql)?;
+ let ws_bytes = workspace_id.as_bytes();
+ let proj_bytes = project_id.as_bytes();
+ let limit = i64::try_from(limit).unwrap_or(i64::MAX);
+ let offset = i64::try_from(offset).unwrap_or(i64::MAX);
+ let sid_bytes = exact_session_id.map(|sid| *sid.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),
+ (":limit", &limit),
+ (":offset", &offset),
+ ];
+ if let Some(sid) = &sid_bytes {
+ named.push((":sid", sid));
+ }
+ if let OwnerFilter::User(user) = &owner_filter {
+ named.push((":actor", user));
+ }
+ let rows = stmt.query_map(named.as_slice(), |row| {
+ let id_bytes: Vec<u8> = row.get(0)?;
+ let cwd: Option<String> = row.get(1)?;
+ let agent_kind: String = row.get(2)?;
+ let started_us: i64 = row.get(3)?;
+ let ended_us: Option<i64> = row.get(4)?;
+ let actor_user: Option<String> = row.get(5)?;
+ let n: i64 = row.get(6)?;
+ Ok((
+ id_bytes, cwd, agent_kind, started_us, ended_us, actor_user, n,
+ ))
+ })?;
+ let mut out = Vec::new();
+ for row in rows {
+ let (id_bytes, cwd, agent_kind, started_us, ended_us, actor_user, n) = row?;
+ let started_at = jiff::Timestamp::from_microsecond(started_us)
+ .map(|ts| ts.to_string())
+ .unwrap_or_default();
+ let ended_at = ended_us
+ .and_then(|us| jiff::Timestamp::from_microsecond(us).ok())
+ .map(|ts| ts.to_string());
+ out.push(SessionSummary {
+ session_id: SessionId::from_slice(&id_bytes)?,
+ cwd,
+ agent_kind,
+ started_at,
+ ended_at,
+ observation_count: u64::try_from(n).unwrap_or(0),
+ actor_user,
+ });
+ }
+ Ok(out)
+ })
+ .await
+ }
+
/// The `(workspace_id, project_id, cwd)` a session was created under,
/// or `None` when no such session exists. The hook router uses this for
/// session-sticky attribution: mid-session events inherit the session's
@@ -6245,6 +6623,37 @@ fn row_to_observation(row: &rusqlite::Row<'_>) -> rusqlite::Result<StoreResult<O
))
}
+fn row_to_observation_record(
+ row: &rusqlite::Row<'_>,
+) -> rusqlite::Result<StoreResult<ObservationRecord>> {
+ let id_bytes: Vec<u8> = row.get(0)?;
+ let session_bytes: Vec<u8> = row.get(1)?;
+ let kind: String = row.get(2)?;
+ let title: String = row.get(3)?;
+ let body: String = row.get(4)?;
+ let importance: i64 = row.get(5)?;
+ let created_us: i64 = row.get(6)?;
+ let extension: Option<String> = row.get(7)?;
+ let source_event: Option<String> = row.get(8)?;
+ let created_at = jiff::Timestamp::from_microsecond(created_us)
+ .map(|ts| ts.to_string())
+ .unwrap_or_default();
+ let record = ObservationId::from_slice(&id_bytes).and_then(|id| {
+ SessionId::from_slice(&session_bytes).map(|session_id| ObservationRecord {
+ id,
+ session_id,
+ kind,
+ title,
+ body,
+ importance: u8::try_from(importance.clamp(1, 10)).unwrap_or(1),
+ created_at,
+ extension,
+ source_event,
+ })
+ });
+ Ok(record.map_err(StoreError::from))
+}
+
#[allow(clippy::too_many_arguments)]
fn materialise_observation(
id_bytes: Vec<u8>,
diff --git a/crates/ai-memory-store/tests/session_observations.rs b/crates/ai-memory-store/tests/session_observations.rs
new file mode 100644
index 00000000..8a13f3ff
--- /dev/null
+++ b/crates/ai-memory-store/tests/session_observations.rs
@@ -0,0 +1,568 @@
+//! Scoped per-session observation reads and the session listing behind them
+//! (`session_observations_scoped`, `sessions_for_scope`,
+//! `session_summary_scoped`).
+//!
+//! A session that crossed repositories mid-flight has observations in two
+//! scopes while its `sessions` row stays frozen on the first one. A caller
+//! resolved to one scope must see exactly that scope's rows, learn that more
+//! exist elsewhere, and still find the session in the listing of the scope
+//! that holds its work.
+
+use ai_memory_core::{
+ ActorContext, IdentityKey, ObservationKind, OwnerFilter, ProjectId, SessionId, WorkspaceId,
+};
+use ai_memory_store::{ObservationOrder, ObservationPage, Store};
+use rusqlite::{Connection, params};
+
+const NOW: i64 = 1_700_000_000_000_000;
+
+fn id(n: u8) -> [u8; 16] {
+ let mut b = [0u8; 16];
+ b[15] = n;
+ b
+}
+
+fn ws() -> WorkspaceId {
+ WorkspaceId::from_slice(&id(1)).unwrap()
+}
+
+fn proj_a() -> ProjectId {
+ ProjectId::from_slice(&id(2)).unwrap()
+}
+
+fn proj_b() -> ProjectId {
+ ProjectId::from_slice(&id(3)).unwrap()
+}
+
+fn session(n: u8) -> SessionId {
+ SessionId::from_slice(&id(n)).unwrap()
+}
+
+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()
+ })
+}
+
+fn page(limit: usize) -> ObservationPage {
+ ObservationPage {
+ limit,
+ offset: 0,
+ order: ObservationOrder::Asc,
+ kinds: None,
+ query: None,
+ }
+}
+
+/// Session ids: 10 crossed from `proj-a` into `proj-b`; 11 is open in
+/// `proj-a`; 12 is alice's, anchored in `proj-b` but with one observation in
+/// `proj-a`; 13 is bob's, anchored in `proj-a`, with no observations at all.
+/// Observation ids: 20..=22 in `proj-a` and 23 in `proj-b` for session 10; 24
+/// for session 11; 25 (`proj-a`) and 26 (`proj-b`) for session 12.
+fn seed(db_path: &std::path::Path) {
+ let conn = Connection::open(db_path).unwrap();
+ let (ws, a, b) = (id(1), id(2), id(3));
+
+ conn.execute(
+ "INSERT INTO workspaces (id, name, created_at) VALUES (?1, 'w', ?2)",
+ params![&ws[..], NOW],
+ )
+ .unwrap();
+ for (pid, name, rp) in [(&a, "proj-a", "/w/a"), (&b, "proj-b", "/w/b")] {
+ conn.execute(
+ "INSERT INTO projects (id, workspace_id, name, repo_path, created_at) \
+ VALUES (?1, ?2, ?3, ?4, ?5)",
+ params![&pid[..], &ws[..], name, rp, NOW],
+ )
+ .unwrap();
+ }
+ let sessions = [
+ (10, &a, "claude-code", "/w/a", NOW, Some(NOW + 100), None),
+ (11, &a, "codex", "/w/a", NOW + 10, None, None),
+ (
+ 12,
+ &b,
+ "cursor",
+ "/w/b",
+ NOW + 20,
+ Some(NOW + 30),
+ Some(operator("alice")),
+ ),
+ (
+ 13,
+ &a,
+ "claude-code",
+ "/w/a",
+ NOW + 30,
+ Some(NOW + 40),
+ Some(operator("bob")),
+ ),
+ ];
+ for (n, proj, agent, cwd, started, ended, owner) in sessions {
+ conn.execute(
+ "INSERT INTO sessions \
+ (id, workspace_id, project_id, agent_kind, cwd, started_at, ended_at, actor_user) \
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
+ params![
+ &id(n)[..],
+ &ws[..],
+ &proj[..],
+ agent,
+ cwd,
+ started,
+ ended,
+ owner
+ ],
+ )
+ .unwrap();
+ }
+ let observations = [
+ (
+ 20,
+ 10,
+ &a,
+ "user-prompt",
+ "alpha prompt",
+ "deploy the widget",
+ NOW + 1,
+ ),
+ (
+ 21,
+ 10,
+ &a,
+ "post-tool-use",
+ "tool result",
+ "cargo build ok",
+ NOW + 2,
+ ),
+ (
+ 22,
+ 10,
+ &a,
+ "user-prompt",
+ "beta prompt",
+ "widget colors",
+ NOW + 3,
+ ),
+ (
+ 23,
+ 10,
+ &b,
+ "user-prompt",
+ "crossed",
+ "widget elsewhere",
+ NOW + 4,
+ ),
+ (
+ 24,
+ 11,
+ &a,
+ "user-prompt",
+ "open work",
+ "still running",
+ NOW + 11,
+ ),
+ (
+ 25,
+ 12,
+ &a,
+ "post-tool-use",
+ "alice tool",
+ "touched proj-a",
+ NOW + 21,
+ ),
+ (
+ 26,
+ 12,
+ &b,
+ "user-prompt",
+ "alice prompt",
+ "home scope",
+ NOW + 22,
+ ),
+ ];
+ for (n, sid, proj, kind, title, body, ts) in observations {
+ conn.execute(
+ "INSERT INTO observations \
+ (id, session_id, workspace_id, project_id, kind, title, body, importance, \
+ created_at) \
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, 7, ?8)",
+ params![
+ &id(n)[..],
+ &id(sid)[..],
+ &ws[..],
+ &proj[..],
+ kind,
+ title,
+ body,
+ ts
+ ],
+ )
+ .unwrap();
+ }
+}
+
+fn open_seeded() -> (tempfile::TempDir, Store) {
+ let tmp = tempfile::tempdir().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ seed(store.db_path());
+ (tmp, store)
+}
+
+fn last_byte(sid: SessionId) -> u8 {
+ sid.as_bytes()[15]
+}
+
+#[tokio::test]
+async fn page_reads_only_the_callers_scope_and_reports_the_rest() {
+ let (_tmp, store) = open_seeded();
+
+ let from_a = store
+ .reader
+ .session_observations_scoped(ws(), proj_a(), session(10), page(50))
+ .await
+ .unwrap();
+ assert_eq!(from_a.total, 3);
+ assert_eq!(from_a.elided_other_scope, 1, "one row landed in proj-b");
+ let ids: Vec<u8> = from_a.records.iter().map(|r| r.id.as_bytes()[15]).collect();
+ assert_eq!(ids, vec![20, 21, 22], "capture order by default");
+ let first = &from_a.records[0];
+ assert_eq!(first.session_id, session(10));
+ assert_eq!(first.kind, "user-prompt");
+ assert_eq!(first.title, "alpha prompt");
+ assert_eq!(first.body, "deploy the widget", "the full body is returned");
+ assert_eq!(first.importance, 7);
+ assert_eq!(first.extension, None);
+ assert_eq!(first.source_event, None);
+ assert_eq!(
+ first.created_at,
+ jiff::Timestamp::from_microsecond(NOW + 1)
+ .unwrap()
+ .to_string()
+ );
+
+ // The same session read from the other scope shows the mirror image.
+ let from_b = store
+ .reader
+ .session_observations_scoped(ws(), proj_b(), session(10), page(50))
+ .await
+ .unwrap();
+ assert_eq!(from_b.total, 1);
+ assert_eq!(from_b.elided_other_scope, 3);
+ assert_eq!(from_b.records[0].id.as_bytes()[15], 23);
+}
+
+#[tokio::test]
+async fn limit_offset_and_order_shape_the_page_without_changing_the_counts() {
+ let (_tmp, store) = open_seeded();
+
+ let desc = store
+ .reader
+ .session_observations_scoped(
+ ws(),
+ proj_a(),
+ session(10),
+ ObservationPage {
+ limit: 2,
+ offset: 1,
+ order: ObservationOrder::Desc,
+ kinds: None,
+ query: None,
+ },
+ )
+ .await
+ .unwrap();
+ let ids: Vec<u8> = desc.records.iter().map(|r| r.id.as_bytes()[15]).collect();
+ assert_eq!(ids, vec![21, 20], "newest first, skipping the newest one");
+ assert_eq!(desc.total, 3, "total ignores the page window");
+ assert_eq!(desc.elided_other_scope, 1);
+
+ let none = store
+ .reader
+ .session_observations_scoped(ws(), proj_a(), session(10), page(0))
+ .await
+ .unwrap();
+ assert!(none.records.is_empty(), "limit 0 returns no rows");
+ assert_eq!(none.total, 3, "but still counts");
+ assert_eq!(none.elided_other_scope, 1);
+}
+
+#[tokio::test]
+async fn kinds_filter_narrows_rows_and_total() {
+ let (_tmp, store) = open_seeded();
+
+ let prompts = store
+ .reader
+ .session_observations_scoped(
+ ws(),
+ proj_a(),
+ session(10),
+ ObservationPage {
+ kinds: Some(vec![ObservationKind::UserPrompt]),
+ ..page(50)
+ },
+ )
+ .await
+ .unwrap();
+ let ids: Vec<u8> = prompts
+ .records
+ .iter()
+ .map(|r| r.id.as_bytes()[15])
+ .collect();
+ assert_eq!(ids, vec![20, 22]);
+ assert_eq!(prompts.total, 2);
+ assert_eq!(
+ prompts.elided_other_scope, 1,
+ "the cross-scope count is not filtered by kind"
+ );
+
+ let empty_list = store
+ .reader
+ .session_observations_scoped(
+ ws(),
+ proj_a(),
+ session(10),
+ ObservationPage {
+ kinds: Some(Vec::new()),
+ ..page(50)
+ },
+ )
+ .await
+ .unwrap();
+ assert_eq!(empty_list.total, 3, "an empty kind list is no filter");
+}
+
+#[tokio::test]
+async fn query_matches_within_the_session_and_scope_only() {
+ let (_tmp, store) = open_seeded();
+
+ let widget = store
+ .reader
+ .session_observations_scoped(
+ ws(),
+ proj_a(),
+ session(10),
+ ObservationPage {
+ query: Some("widget".into()),
+ ..page(50)
+ },
+ )
+ .await
+ .unwrap();
+ let ids: Vec<u8> = widget.records.iter().map(|r| r.id.as_bytes()[15]).collect();
+ assert_eq!(
+ ids,
+ vec![20, 22],
+ "row 23 also says widget but lives in proj-b"
+ );
+ assert_eq!(widget.total, 2);
+ assert_eq!(widget.elided_other_scope, 1);
+
+ let cargo = store
+ .reader
+ .session_observations_scoped(
+ ws(),
+ proj_a(),
+ session(10),
+ ObservationPage {
+ query: Some("cargo".into()),
+ kinds: Some(vec![ObservationKind::PostToolUse]),
+ ..page(50)
+ },
+ )
+ .await
+ .unwrap();
+ assert_eq!(cargo.records.len(), 1);
+ assert_eq!(cargo.records[0].id.as_bytes()[15], 21);
+
+ let blank = store
+ .reader
+ .session_observations_scoped(
+ ws(),
+ proj_a(),
+ session(10),
+ ObservationPage {
+ query: Some(" ".into()),
+ ..page(50)
+ },
+ )
+ .await
+ .unwrap();
+ assert_eq!(blank.total, 3, "a query with nothing searchable is ignored");
+}
+
+#[tokio::test]
+async fn unknown_session_yields_an_empty_page() {
+ let (_tmp, store) = open_seeded();
+ let result = store
+ .reader
+ .session_observations_scoped(ws(), proj_a(), SessionId::new(), page(50))
+ .await
+ .unwrap();
+ assert!(result.records.is_empty());
+ assert_eq!(result.total, 0);
+ assert_eq!(result.elided_other_scope, 0);
+}
+
+#[tokio::test]
+async fn sessions_for_scope_lists_touched_sessions_newest_first() {
+ let (_tmp, store) = open_seeded();
+
+ let all = store
+ .reader
+ .sessions_for_scope(ws(), proj_a(), OwnerFilter::Any, true, 10, 0)
+ .await
+ .unwrap();
+ let seen: Vec<(u8, u64)> = all
+ .iter()
+ .map(|s| (last_byte(s.session_id), s.observation_count))
+ .collect();
+ assert_eq!(
+ seen,
+ vec![(13, 0), (12, 1), (11, 1), (10, 3)],
+ "started_at desc; 12 is anchored in proj-b but touched proj-a; \
+ counts are per scope",
+ );
+ let crossed = &all[3];
+ assert_eq!(crossed.agent_kind, "claude-code");
+ assert_eq!(crossed.cwd.as_deref(), Some("/w/a"));
+ assert!(crossed.ended_at.is_some());
+ assert_eq!(crossed.actor_user, None);
+ assert_eq!(
+ crossed.started_at,
+ jiff::Timestamp::from_microsecond(NOW).unwrap().to_string()
+ );
+ assert!(all[2].ended_at.is_none(), "session 11 is still open");
+
+ let ended_only = store
+ .reader
+ .sessions_for_scope(ws(), proj_a(), OwnerFilter::Any, false, 10, 0)
+ .await
+ .unwrap();
+ let seen: Vec<u8> = ended_only.iter().map(|s| last_byte(s.session_id)).collect();
+ assert_eq!(seen, vec![13, 12, 10]);
+
+ let window = store
+ .reader
+ .sessions_for_scope(ws(), proj_a(), OwnerFilter::Any, true, 2, 1)
+ .await
+ .unwrap();
+ let seen: Vec<u8> = window.iter().map(|s| last_byte(s.session_id)).collect();
+ assert_eq!(seen, vec![12, 11]);
+
+ let from_b = store
+ .reader
+ .sessions_for_scope(ws(), proj_b(), OwnerFilter::Any, true, 10, 0)
+ .await
+ .unwrap();
+ let seen: Vec<(u8, u64)> = from_b
+ .iter()
+ .map(|s| (last_byte(s.session_id), s.observation_count))
+ .collect();
+ assert_eq!(
+ seen,
+ vec![(12, 1), (10, 1)],
+ "10 is anchored in proj-a but one row crossed into proj-b",
+ );
+}
+
+#[tokio::test]
+async fn sessions_for_scope_respects_the_owner_filter() {
+ let (_tmp, store) = open_seeded();
+
+ let alice = store
+ .reader
+ .sessions_for_scope(ws(), proj_a(), filter_for("alice"), true, 10, 0)
+ .await
+ .unwrap();
+ let seen: Vec<u8> = alice.iter().map(|s| last_byte(s.session_id)).collect();
+ assert_eq!(
+ seen,
+ vec![12, 11, 10],
+ "own rows plus shared rows, never bob's"
+ );
+ assert_eq!(
+ alice[0].actor_user.as_deref(),
+ Some(operator("alice").as_str())
+ );
+
+ let anonymous = store
+ .reader
+ .sessions_for_scope(ws(), proj_a(), OwnerFilter::Unattributed, true, 10, 0)
+ .await
+ .unwrap();
+ let seen: Vec<u8> = anonymous.iter().map(|s| last_byte(s.session_id)).collect();
+ assert_eq!(seen, vec![11, 10], "shared rows only");
+}
+
+#[tokio::test]
+async fn session_summary_scoped_narrows_the_listing_predicates() {
+ let (_tmp, store) = open_seeded();
+
+ let anchored = store
+ .reader
+ .session_summary_scoped(ws(), proj_a(), session(10), OwnerFilter::Any)
+ .await
+ .unwrap()
+ .expect("session 10 is anchored in proj-a");
+ assert_eq!(anchored.observation_count, 3);
+ assert_eq!(anchored.agent_kind, "claude-code");
+
+ let touched = store
+ .reader
+ .session_summary_scoped(ws(), proj_a(), session(12), OwnerFilter::Any)
+ .await
+ .unwrap()
+ .expect("session 12 touched proj-a through an observation");
+ assert_eq!(touched.observation_count, 1);
+
+ let open = store
+ .reader
+ .session_summary_scoped(ws(), proj_a(), session(11), OwnerFilter::Any)
+ .await
+ .unwrap()
+ .expect("open sessions are visible by id");
+ assert!(open.ended_at.is_none());
+
+ assert!(
+ store
+ .reader
+ .session_summary_scoped(ws(), proj_b(), session(13), OwnerFilter::Any)
+ .await
+ .unwrap()
+ .is_none(),
+ "no row and no observation in proj-b",
+ );
+ assert!(
+ store
+ .reader
+ .session_summary_scoped(ws(), proj_a(), session(12), OwnerFilter::Unattributed)
+ .await
+ .unwrap()
+ .is_none(),
+ "alice's session is not an unidentified caller's to read",
+ );
+ assert!(
+ store
+ .reader
+ .session_summary_scoped(ws(), proj_a(), session(12), filter_for("bob"))
+ .await
+ .unwrap()
+ .is_none(),
+ "nor bob's",
+ );
+ assert!(
+ store
+ .reader
+ .session_summary_scoped(ws(), proj_a(), SessionId::new(), OwnerFilter::Any)
+ .await
+ .unwrap()
+ .is_none(),
+ "unknown id",
+ );
+}