Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(web): session listing and per-session observation routes on /api/v1 (#401)
Sergio Aguirredb6bc13a47a4
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4a0bba80..b1a984e2 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,21 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Added+- Added a read path for one session's raw hook observations, before any+ consolidation: the MCP tool `memory_read_session_observations` and the+ `/api/v1` routes `GET .../projects/{project}/sessions` and+ `GET .../sessions/{session_id}/observations`. Both return only the rows that+ landed in the resolved `(workspace, project)`, report `elided_other_scope`+ for a session that crossed repositories, and apply the same owner filter as+ handoffs; a session id from another project or operator reads as not found.+ Pagination is `limit`/`offset` with `total` (default 50, max 200; the+ session list defaults to 20, max 100), `order` is `asc` or `desc`, `kinds`+ and a full-text query narrow the rows, and `body_max_chars` (default 4000,+ `200..=16384`) caps each body with a visible truncation marker. The MCP tool+ reads the latest completed visible session when `session_id` is omitted+ (#401).+## [1.27.0] - 2026-08-16### Addeddiff --git a/crates/ai-memory-web/src/routes/api.rs b/crates/ai-memory-web/src/routes/api.rsindex 5f3d99c0..d65a29df 100644--- a/crates/ai-memory-web/src/routes/api.rs+++ b/crates/ai-memory-web/src/routes/api.rs@@ -3,10 +3,11 @@use std::collections::HashMap;use std::sync::Arc;-use ai_memory_core::{PageId, PagePath, ProjectId, WorkspaceId};+use ai_memory_core::{ObservationKind, PageId, PagePath, ProjectId, SessionId, WorkspaceId};use ai_memory_store::{- BriefingSnapshot, HealthPage, PageHit, RelatedPage, ScopeName, ScopeResolutionError,- lookup_existing_scope, resolve_many_existing_scopes,+ BriefingSnapshot, HealthPage, ObservationOrder, ObservationPage, ObservationRecord, PageHit,+ RelatedPage, ScopeName, ScopeResolutionError, SessionSummary, lookup_existing_scope,+ resolve_many_existing_scopes,};use axum::extract::{Path, Query, RawQuery, State};use axum::http::{HeaderValue, StatusCode, header};@@ -61,6 +62,14 @@ pub(crate) fn build(state: Arc<WebState>) -> Router {"/workspaces/{workspace}/projects/{project}/handoffs",axum::routing::get(handoffs_handler),)+ .route(+ "/workspaces/{workspace}/projects/{project}/sessions",+ axum::routing::get(sessions_handler),+ )+ .route(+ "/workspaces/{workspace}/projects/{project}/sessions/{session_id}/observations",+ axum::routing::get(session_observations_handler),+ ).route("/graph", axum::routing::get(graph_handler)).with_state(state)}@@ -826,6 +835,161 @@ async fn project_overview_handler())}+/// Bounds for the session routes. They mirror the MCP+/// `memory_read_session_observations` tool so a frontend and an agent see+/// the same page sizes and body caps.+const SESSION_LIST_MAX_LIMIT: usize = 100;+const SESSION_OBSERVATIONS_MAX_LIMIT: usize = 200;+const SESSION_OBSERVATIONS_DEFAULT_BODY_CHARS: usize = 4_000;+const SESSION_OBSERVATIONS_MIN_BODY_CHARS: usize = 200;+const SESSION_OBSERVATIONS_MAX_BODY_CHARS: usize = 16_384;++async fn sessions_handler(+ State(state): State<Arc<WebState>>,+ actor: Option<axum::Extension<ai_memory_core::ActorContext>>,+ Path((workspace, project)): Path<(String, String)>,+ Query(query): Query<SessionListQuery>,+) -> Result<Response, Response> {+ let (workspace_id, project_id) = lookup_project(&state, &workspace, &project).await?;+ let sessions = state+ .reader+ .sessions_for_scope(+ workspace_id,+ project_id,+ owner_filter_for(actor),+ query.include_open,+ query.limit.clamp(1, SESSION_LIST_MAX_LIMIT),+ query.offset,+ )+ .await+ .map_err(internal_error)?;+ Ok(with_no_store(+ Json(ApiSessionList { sessions }).into_response(),+ ))+}++async fn session_observations_handler(+ State(state): State<Arc<WebState>>,+ actor: Option<axum::Extension<ai_memory_core::ActorContext>>,+ Path((workspace, project, session_id)): Path<(String, String, String)>,+ Query(query): Query<SessionObservationsQuery>,+) -> Result<Response, Response> {+ let (workspace_id, project_id) = lookup_project(&state, &workspace, &project).await?;+ let session_id = session_id.parse::<SessionId>().map_err(|_| {+ json_error(+ StatusCode::BAD_REQUEST,+ format!("invalid session id: {session_id}"),+ )+ })?;+ let limit = query.limit.clamp(1, SESSION_OBSERVATIONS_MAX_LIMIT);+ let body_max_chars = query+ .body_max_chars+ .unwrap_or(SESSION_OBSERVATIONS_DEFAULT_BODY_CHARS)+ .clamp(+ SESSION_OBSERVATIONS_MIN_BODY_CHARS,+ SESSION_OBSERVATIONS_MAX_BODY_CHARS,+ );+ let order = match query.order.as_deref().map(str::trim) {+ None | Some("") => ObservationOrder::Asc,+ Some(raw) if raw.eq_ignore_ascii_case("asc") => ObservationOrder::Asc,+ Some(raw) if raw.eq_ignore_ascii_case("desc") => ObservationOrder::Desc,+ Some(raw) => {+ return Err(json_error(+ StatusCode::BAD_REQUEST,+ format!("unknown order: {raw} (expected asc or desc)"),+ ));+ }+ };+ let mut kinds = Vec::new();+ for kind in query+ .kinds+ .as_deref()+ .unwrap_or_default()+ .split(',')+ .map(str::trim)+ .filter(|kind| !kind.is_empty())+ {+ let Ok(parsed) = kind.parse::<ObservationKind>() else {+ return Err(json_error(+ StatusCode::BAD_REQUEST,+ format!("unknown observation kind: {kind}"),+ ));+ };+ kinds.push(parsed);+ }+ let kinds = (!kinds.is_empty()).then_some(kinds);++ // Same visibility predicate as the MCP tool: the session must have its+ // row or at least one observation in this scope and pass the owner+ // filter, otherwise the id reads as not found so a known uuid cannot+ // probe another project or operator.+ let session = state+ .reader+ .session_summary_scoped(+ workspace_id,+ project_id,+ session_id,+ owner_filter_for(actor),+ )+ .await+ .map_err(internal_error)?+ .ok_or_else(|| not_found(format!("session '{session_id}' not found")))?;+ let page = state+ .reader+ .session_observations_scoped(+ workspace_id,+ project_id,+ session_id,+ ObservationPage {+ limit,+ offset: query.offset,+ order,+ kinds,+ query: query.q.clone(),+ },+ )+ .await+ .map_err(internal_error)?;+ let observations = page+ .records+ .into_iter()+ .map(|mut record| {+ record.body = cap_body(&record.body, body_max_chars);+ record+ })+ .collect();+ Ok(with_no_store(+ Json(ApiSessionObservations {+ session,+ observations,+ total: page.total,+ offset: query.offset,+ limit,+ order,+ elided_other_scope: page.elided_other_scope,+ body_max_chars,+ })+ .into_response(),+ ))+}++/// Cap one observation body with a visible marker. Same shape as+/// `ai_memory_consolidate::projection::cap_text_with_marker`, which the MCP+/// tool uses; duplicated here because the web crate does not depend on the+/// consolidation pipeline.+fn cap_body(body: &str, max_chars: usize) -> String {+ let total = body.chars().count();+ if total <= max_chars {+ return body.to_owned();+ }+ let mut out: String = body.chars().take(max_chars).collect();+ out.push_str(&format!(+ "\n[body truncated; {} chars omitted]",+ total - max_chars+ ));+ out+}+async fn lookup_project(state: &WebState,workspace: &str,@@ -1004,6 +1168,62 @@ struct LimitQuery {limit: usize,}+fn default_session_list_limit() -> usize {+ 20+}++fn default_session_observations_limit() -> usize {+ 50+}++#[derive(Debug, Deserialize)]+struct SessionListQuery {+ #[serde(default = "default_session_list_limit")]+ limit: usize,+ #[serde(default)]+ offset: usize,+ /// Also list sessions that have not ended yet. Default false.+ #[serde(default)]+ include_open: bool,+}++#[derive(Debug, Deserialize)]+struct SessionObservationsQuery {+ #[serde(default = "default_session_observations_limit")]+ limit: usize,+ #[serde(default)]+ offset: usize,+ /// `asc` (capture order, default) or `desc`.+ #[serde(default)]+ order: Option<String>,+ /// Comma-separated observation kinds, e.g. `user-prompt,stop`.+ #[serde(default)]+ kinds: Option<String>,+ /// Full-text query restricted to the session.+ #[serde(default)]+ q: Option<String>,+ /// Per-body character cap; clamped to `200..=16384`, default `4000`.+ #[serde(default)]+ body_max_chars: Option<usize>,+}++#[derive(Debug, Serialize)]+struct ApiSessionList {+ sessions: Vec<SessionSummary>,+}++#[derive(Debug, Serialize)]+struct ApiSessionObservations {+ session: SessionSummary,+ observations: Vec<ObservationRecord>,+ total: u64,+ offset: usize,+ limit: usize,+ order: ObservationOrder,+ elided_other_scope: u64,+ body_max_chars: usize,+}+#[derive(Debug, Serialize)]struct ApiPage {workspace: String,diff --git a/crates/ai-memory-web/tests/routes.rs b/crates/ai-memory-web/tests/routes.rsindex 699e6080..9d561dc0 100644--- a/crates/ai-memory-web/tests/routes.rs+++ b/crates/ai-memory-web/tests/routes.rs@@ -1072,6 +1072,355 @@ async fn api_recent_and_briefing_return_project_data() {assert_eq!(json["recent_pages"][0]["path"], "foo.md");}+/// Seed one session in `(ws, proj)` with `(kind, title, body)` rows, ended+/// when `completed`. Returns the session id.+async fn seed_session(+ store: &Store,+ ws: ai_memory_core::WorkspaceId,+ proj: ai_memory_core::ProjectId,+ completed: bool,+ rows: &[(ai_memory_core::ObservationKind, &str, &str)],+) -> ai_memory_core::SessionId {+ let session_id = ai_memory_core::SessionId::new();+ store+ .writer+ .begin_session(ai_memory_core::NewSession {+ id: session_id,+ workspace_id: ws,+ project_id: proj,+ agent_kind: AgentKind::OpenCode,+ cwd: None,+ actor_user: None,+ })+ .await+ .unwrap();+ for (kind, title, body) in rows {+ store+ .writer+ .insert_observation(ai_memory_core::Sanitized::new(+ ai_memory_core::NewObservation {+ session_id,+ workspace_id: ws,+ project_id: proj,+ kind: *kind,+ extension: None,+ source_event: None,+ title: (*title).to_owned(),+ body: (*body).to_owned(),+ importance: 5,+ },+ &ai_memory_core::Sanitizer::builtin(),+ ))+ .await+ .unwrap();+ }+ if completed {+ store.writer.end_session(session_id, None).await.unwrap();+ }+ session_id+}++async fn json_body(resp: axum::response::Response) -> Value {+ let body = axum::body::to_bytes(resp.into_body(), usize::MAX)+ .await+ .unwrap();+ serde_json::from_slice(&body).unwrap()+}++#[tokio::test]+async fn api_sessions_lists_completed_sessions_for_the_scope() {+ use ai_memory_core::ObservationKind;+ let (_tmp, store, wiki) = setup().await;+ let ws = store+ .writer+ .get_or_create_workspace("default")+ .await+ .unwrap();+ let proj = store+ .writer+ .get_or_create_project(ws, "scratch", None)+ .await+ .unwrap();+ let other = store+ .writer+ .get_or_create_project(ws, "other", None)+ .await+ .unwrap();+ let completed = seed_session(+ &store,+ ws,+ proj,+ true,+ &[(ObservationKind::UserPrompt, "done", "completed work")],+ )+ .await;+ let open = seed_session(+ &store,+ ws,+ proj,+ false,+ &[(ObservationKind::UserPrompt, "live", "still running")],+ )+ .await;+ seed_session(+ &store,+ ws,+ other,+ true,+ &[(ObservationKind::UserPrompt, "elsewhere", "other project")],+ )+ .await;++ let app = api_router(store.reader.clone(), wiki.clone());+ let resp = app+ .clone()+ .oneshot(+ Request::builder()+ .uri("/workspaces/default/projects/scratch/sessions")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(resp.status(), StatusCode::OK);+ assert_eq!(+ resp.headers().get(header::CACHE_CONTROL).unwrap(),+ "private, no-store"+ );+ let json = json_body(resp).await;+ let sessions = json["sessions"].as_array().unwrap();+ assert_eq!(+ sessions.len(),+ 1,+ "open and other-project sessions are hidden"+ );+ assert_eq!(sessions[0]["session_id"], completed.to_string());+ assert_eq!(sessions[0]["observation_count"], 1);+ assert!(sessions[0]["ended_at"].is_string());++ let resp = app+ .oneshot(+ Request::builder()+ .uri("/workspaces/default/projects/scratch/sessions?include_open=true&limit=1")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(resp.status(), StatusCode::OK);+ let json = json_body(resp).await;+ let sessions = json["sessions"].as_array().unwrap();+ assert_eq!(sessions.len(), 1, "limit=1 must cap the list");+ assert_eq!(+ sessions[0]["session_id"],+ open.to_string(),+ "newest first, and include_open surfaces the open one"+ );+}++#[tokio::test]+async fn api_session_observations_pages_orders_and_caps() {+ use ai_memory_core::ObservationKind;+ let (_tmp, store, wiki) = setup().await;+ let ws = store+ .writer+ .get_or_create_workspace("default")+ .await+ .unwrap();+ let proj = store+ .writer+ .get_or_create_project(ws, "scratch", None)+ .await+ .unwrap();+ let long_body = "x".repeat(1_000);+ let session_id = seed_session(+ &store,+ ws,+ proj,+ true,+ &[+ (ObservationKind::UserPrompt, "first", "one quokka"),+ (ObservationKind::PostToolUse, "second", long_body.as_str()),+ (ObservationKind::Stop, "third", "three"),+ ],+ )+ .await;++ let app = api_router(store.reader.clone(), wiki.clone());+ let base = format!("/workspaces/default/projects/scratch/sessions/{session_id}/observations");+ let resp = app+ .clone()+ .oneshot(+ Request::builder()+ .uri(format!("{base}?limit=2"))+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(resp.status(), StatusCode::OK);+ assert_eq!(+ resp.headers().get(header::CACHE_CONTROL).unwrap(),+ "private, no-store"+ );+ let json = json_body(resp).await;+ assert_eq!(json["session"]["session_id"], session_id.to_string());+ assert_eq!(json["total"], 3);+ assert_eq!(json["limit"], 2);+ assert_eq!(json["offset"], 0);+ assert_eq!(json["order"], "asc");+ assert_eq!(json["elided_other_scope"], 0);+ assert_eq!(json["body_max_chars"], 4000);+ let titles: Vec<&str> = json["observations"]+ .as_array()+ .unwrap()+ .iter()+ .map(|o| o["title"].as_str().unwrap())+ .collect();+ assert_eq!(titles, ["first", "second"]);+ assert_eq!(json["observations"][1]["body"], long_body);++ let resp = app+ .clone()+ .oneshot(+ Request::builder()+ .uri(format!(+ "{base}?order=desc&kinds=post-tool-use,stop&body_max_chars=50"+ ))+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(resp.status(), StatusCode::OK);+ let json = json_body(resp).await;+ assert_eq!(json["order"], "desc");+ assert_eq!(json["total"], 2);+ assert_eq!(json["body_max_chars"], 200, "cap clamps up to the floor");+ let titles: Vec<&str> = json["observations"]+ .as_array()+ .unwrap()+ .iter()+ .map(|o| o["title"].as_str().unwrap())+ .collect();+ assert_eq!(titles, ["third", "second"]);+ let body = json["observations"][1]["body"].as_str().unwrap();+ assert!(body.starts_with(&"x".repeat(200)));+ assert!(+ body.ends_with("[body truncated; 800 chars omitted]"),+ "got {body}"+ );++ let resp = app+ .oneshot(+ Request::builder()+ .uri(format!("{base}?q=quokka"))+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(resp.status(), StatusCode::OK);+ let json = json_body(resp).await;+ assert_eq!(json["total"], 1);+ assert_eq!(json["observations"][0]["title"], "first");+}++#[tokio::test]+async fn api_session_routes_return_404_for_missing_project_and_foreign_session() {+ use ai_memory_core::ObservationKind;+ let (_tmp, store, wiki) = setup().await;+ let ws = store+ .writer+ .get_or_create_workspace("default")+ .await+ .unwrap();+ store+ .writer+ .get_or_create_project(ws, "scratch", None)+ .await+ .unwrap();+ let other = store+ .writer+ .get_or_create_project(ws, "other", None)+ .await+ .unwrap();+ let foreign = seed_session(+ &store,+ ws,+ other,+ true,+ &[(ObservationKind::UserPrompt, "hidden", "in other")],+ )+ .await;++ let app = api_router(store.reader.clone(), wiki.clone());+ for uri in [+ "/workspaces/default/projects/missing/sessions".to_owned(),+ format!("/workspaces/default/projects/missing/sessions/{foreign}/observations"),+ format!("/workspaces/default/projects/scratch/sessions/{foreign}/observations"),+ format!(+ "/workspaces/default/projects/scratch/sessions/{}/observations",+ ai_memory_core::SessionId::new()+ ),+ ] {+ let resp = app+ .clone()+ .oneshot(Request::builder().uri(&uri).body(Body::empty()).unwrap())+ .await+ .unwrap();+ assert_eq!(resp.status(), StatusCode::NOT_FOUND, "{uri}");+ }+}++#[tokio::test]+async fn api_session_observations_reject_bad_params() {+ use ai_memory_core::ObservationKind;+ let (_tmp, store, wiki) = setup().await;+ let ws = store+ .writer+ .get_or_create_workspace("default")+ .await+ .unwrap();+ let proj = store+ .writer+ .get_or_create_project(ws, "scratch", None)+ .await+ .unwrap();+ let session_id = seed_session(+ &store,+ ws,+ proj,+ true,+ &[(ObservationKind::UserPrompt, "p", "b")],+ )+ .await;++ let app = api_router(store.reader.clone(), wiki.clone());+ let base = format!("/workspaces/default/projects/scratch/sessions/{session_id}/observations");+ for (uri, needle) in [+ (+ "/workspaces/default/projects/scratch/sessions/not-a-uuid/observations".to_owned(),+ "invalid session id",+ ),+ (+ format!("{base}?kinds=user-prompt,bogus"),+ "unknown observation kind",+ ),+ (format!("{base}?order=sideways"), "unknown order"),+ ] {+ let resp = app+ .clone()+ .oneshot(Request::builder().uri(&uri).body(Body::empty()).unwrap())+ .await+ .unwrap();+ assert_eq!(resp.status(), StatusCode::BAD_REQUEST, "{uri}");+ let json = json_body(resp).await;+ let msg = json["error"].as_str().unwrap();+ assert!(msg.contains(needle), "{uri}: got {msg}");+ }+}+#[tokio::test]async fn api_workspace_overview_returns_aggregated_overview() {let (_tmp, store, wiki) = setup().await;diff --git a/docs/frontend-api.md b/docs/frontend-api.mdindex 13d91192..f55e7142 100644--- a/docs/frontend-api.md+++ b/docs/frontend-api.md@@ -11,7 +11,7 @@| | What you can do | What you can't do ||---|---|---|-| `/api/v1/*` | Browse workspaces, projects, pages; read full page markdown + frontmatter + back-links; FTS5 search (global or scoped, single or multi-project); aggregate "overview" snapshots; drill into stale / duplicate / orphan pages. | Write, delete, rename, lint, consolidate, run sweeps, manage handoffs. The `/api/v1` surface is **read-only by construction** — the handlers contain zero writer calls. Writes still go through `/admin/*` (used by the CLI) or MCP tools. |+| `/api/v1/*` | Browse workspaces, projects, pages; read full page markdown + frontmatter + back-links; FTS5 search (global or scoped, single or multi-project); aggregate "overview" snapshots; drill into stale / duplicate / orphan pages; list a project's sessions and read one session's raw observations. | Write, delete, rename, lint, consolidate, run sweeps, manage handoffs. The `/api/v1` surface is **read-only by construction** — the handlers contain zero writer calls. Writes still go through `/admin/*` (used by the CLI) or MCP tools. || `--web-ui-dir` | Host any SPA at `/web` (or `--web-slug`), same-origin with the API, behind the same auth. The default built-in `/web` browser stays the fallback when the flag is absent. | Host the SPA on a *different* origin without a reverse proxy — use same-origin hosting or configure CORS deliberately (see §9). |## 2. Auth model@@ -67,10 +67,10 @@ with one of these statuses:| Status | When ||---|---|-| `400 Bad Request` | invalid query params, malformed `Authorization`, partial scope (workspace without project or vice versa), too many scopes in `POST /search` (>25), empty `q`. |+| `400 Bad Request` | invalid query params, malformed `Authorization`, partial scope (workspace without project or vice versa), too many scopes in `POST /search` (>25), empty `q`, malformed session id, unknown observation `kinds` or `order`. || `401 Unauthorized` | bearer missing or wrong. || `403 Forbidden` | Host header not in allowlist; or a non-root caller requests `all_owners=true`. |-| `404 Not Found` | workspace, project, or page doesn't exist; or page file missing on disk. |+| `404 Not Found` | workspace, project, or page doesn't exist; page file missing on disk; or a session id that is not visible in that project for the caller. || `500 Internal Server Error` | reader pool / SQLite failure. Body is always the fixed `{"error":"internal server error"}`; the underlying cause is logged server-side rather than returned, so it cannot leak paths or configuration to a browser. |## 4. Endpoint reference@@ -443,18 +443,113 @@ fresh tab gets the icon without an HTTP Basic prompt, and theembedded PNG is the same one any visitor to `/web` already sees, sothe info-leak surface is nil.+### 4.11 Sessions++```http+GET /api/v1/workspaces/{workspace}/projects/{project}/sessions?limit=20&offset=0&include_open=false+```++Sessions that touched the project, newest first: a session is listed when its+row is anchored in the project OR at least one of its observations landed+there, so a session that changed repositories mid-flight shows up in both.+`observation_count` counts only this project's rows. `limit` clamped+`1..=100`, default `20`; `offset` default `0`; `include_open` default+`false` (only sessions with `ended_at` set). Owner-filtered like handoffs: a+caller the server can name sees their own sessions plus unattributed ones;+an unnamed caller sees unattributed ones only. Never cached (`no-store`).++**Response:** `{ "sessions": [SessionSummary, ...] }`++```json+{+ "sessions": [+ {+ "session_id": "0198f0a2-3c4d-7e5f-8a9b-0c1d2e3f4a5b",+ "cwd": "/home/me/src/app",+ "agent_kind": "claude-code",+ "started_at": "2026-08-16T09:12:03.412Z",+ "ended_at": "2026-08-16T10:47:55.001Z",+ "observation_count": 143,+ "actor_user": null+ }+ ]+}+```++### 4.12 Session observations++```http+GET /api/v1/workspaces/{workspace}/projects/{project}/sessions/{session_id}/observations?limit=50&offset=0&order=asc&kinds=user-prompt,stop&q=migration&body_max_chars=4000+```++One session's raw hook observations (prompts, tool calls, stops) as stored,+paged. Only rows that landed in `{workspace}/{project}` are returned;+`elided_other_scope` counts rows the same session left in another project.+The session must be visible under the same predicate as 4.11 (row or+observation in the project, owner filter passes), otherwise `404`. `limit`+clamped `1..=200`, default `50`; `offset` default `0`; `order` is `asc`+(capture order, default) or `desc`; `kinds` is a comma-separated list of+`session-start`, `user-prompt`, `pre-tool-use`, `post-tool-use`,+`pre-compact`, `post-compaction`, `notification`, `stop`, `session-end`,+`other`; `q` is an FTS5 query restricted to the session; `body_max_chars`+clamped `200..=16384`, default `4000`, and a longer body ends with a visible+`[body truncated; N chars omitted]` marker. `total` counts the in-scope+rows matching `kinds` and `q`, so paginate on `offset` without a second+call. Bodies were sanitized and bounded on ingest; treat them as untrusted+historical text. Never cached (`no-store`). Same payload as the MCP tool+`memory_read_session_observations`.++**Response:** `{ "session": SessionSummary, "observations": [ObservationRecord, ...], "total", "offset", "limit", "order", "elided_other_scope", "body_max_chars" }`++```json+{+ "session": {+ "session_id": "0198f0a2-3c4d-7e5f-8a9b-0c1d2e3f4a5b",+ "cwd": "/home/me/src/app",+ "agent_kind": "claude-code",+ "started_at": "2026-08-16T09:12:03.412Z",+ "ended_at": "2026-08-16T10:47:55.001Z",+ "observation_count": 143,+ "actor_user": null+ },+ "observations": [+ {+ "id": "0198f0a2-4d5e-7f60-9a0b-1c2d3e4f5a6b",+ "session_id": "0198f0a2-3c4d-7e5f-8a9b-0c1d2e3f4a5b",+ "kind": "user-prompt",+ "title": "User prompt",+ "body": "Add a migration for the sessions table ...",+ "importance": 5,+ "created_at": "2026-08-16T09:12:10.020Z",+ "extension": null,+ "source_event": null+ }+ ],+ "total": 12,+ "offset": 0,+ "limit": 50,+ "order": "asc",+ "elided_other_scope": 0,+ "body_max_chars": 4000+}+```+## 5. Limits and pagination-- Most `limit` query params clamp to `1..=100`; handoff history clamps to- `1..=200`.+- Most `limit` query params clamp to `1..=100`; handoff history and+ session observations clamp to `1..=200`. Session listing and session+ observations take an `offset`; observations also report `total`.+- Session observation bodies are capped per row by `body_max_chars`+ (`200..=16384`, default `4000`) with a visible truncation marker.- `POST /api/v1/search`: at most **25 scopes** per request.- HTTP body cap: **10 MB** (shared with the MCP body limit; you won'thit this for normal API traffic).- **Cache-Control + ETag.** Identity-independent read endpoints use`Cache-Control: private, max-age=N` with an endpoint-specific TTL; page readsalso carry a SHA-256 `ETag`, and a matching `If-None-Match` receives `304 Not- Modified`. Briefing, overview and handoff-list responses depend on the- authenticated actor and therefore use `Cache-Control: private, no-store`, so+ Modified`. Briefing, overview, handoff-list, session-list and session+ observation responses depend on the authenticated actor and therefore use+ `Cache-Control: private, no-store`, soa browser cannot reuse Alice's prompt-derived response after credentials atthe same URL switch to Bob. Search responses are not cacheable because therequest body affects the result.@@ -588,7 +683,8 @@ Read these:| | Location ||---|---|| Route registration + handler bodies | `crates/ai-memory-web/src/routes/api.rs` |-| Response structs (`PageHit`, `WorkspaceSummary`, `BriefingSnapshot`, `HealthPage`, …) | `crates/ai-memory-store/src/reader.rs` |+| Response structs (`PageHit`, `WorkspaceSummary`, `BriefingSnapshot`, `HealthPage`, `SessionSummary`, `ObservationRecord`, …) | `crates/ai-memory-store/src/reader.rs` |+| Session listing + per-session observation readers (`sessions_for_scope`, `session_summary_scoped`, `session_observations_scoped`) | `crates/ai-memory-store/src/reader.rs` || 27 integration tests covering every endpoint (auth, 400s, 404s, multi-scope correctness, SPA fallback) | `crates/ai-memory-web/tests/routes.rs` || Auth + middleware layering | `crates/ai-memory-cli/src/commands/serve.rs` (`mount_web_router`, `apply_http_layers`) || Custom-UI dir validation | `crates/ai-memory-cli/src/commands/serve.rs` (`validate_web_ui_args`) |