Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
feat(web): page history with diff and a paged session timeline
AkitaOnRails13fc291fec12
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 30e0fc53..e6a56008 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,27 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]### Added+- Added page history and session replay to the read-only web UI. Each page+ links to its history (`/web/w/<ws>/<proj>/h/<path>`): every stored version,+ newest first, superseded ones included, so a version a concurrent write+ replaced stays visible, with timestamps and the author of attributed writes,+ plus a server-side unified diff between any two versions (by default the+ latest against the version it replaced). Expired versions are hidden, and a+ page whose TTL has passed shows no history. The same data is available as JSON+ at `GET /api/v1/workspaces/{ws}/projects/{proj}/history/{*path}`. The version+ list is capped at 200 per request, and the diff refuses inputs over 512 KiB,+ 10,000 lines or 1,000 changed lines and stops at 2,000 output lines. The+ project page lists recent sessions, and each opens a timeline+ (`/web/w/<ws>/<proj>/s/<session-id>`) that pages through its observations in+ capture order with first/prev/next/last links and a jump field; with+ JavaScript, a slider and `j`/`k` keys step one observation at a time. It uses+ the same readers, owner filter and caps as the `/api/v1` session routes, and+ observations render as escaped text. Both views follow the per-project read+ rule: a non-grantee of a restricted project gets a 403, and a version id or+ session id from another project or workspace reads as not found. The+ `ai-memory-web` crate now has a `clippy.toml` that forbids the `Wiki` write+ and destructive methods, so a write path in the web UI or `/api/v1` fails+ `cargo clippy -D warnings`.- Added an opt-in observation stream to `memory_query` ranking:`[retrieval] observation_stream = true` (env`AI_MEMORY_RETRIEVAL__OBSERVATION_STREAM=true`, default off). A zero-LLMdiff --git a/crates/ai-memory-store/src/lib.rs b/crates/ai-memory-store/src/lib.rsindex 7c902338..7a05c6d0 100644--- a/crates/ai-memory-store/src/lib.rs+++ b/crates/ai-memory-store/src/lib.rs@@ -87,8 +87,9 @@ pub use reader::{ContaminationFinding, ContaminationReport, ContaminationSummary, ContradictionEdge,DecayCandidate, DecayTombstone, DerivedIndexStatus, EmbeddingTripleCount, FeedbackFinding,GraphVia, HealthDetail, HealthPage, InboxCount, InboxEntry, ObservationHit, ObservationOrder,- ObservationPage, ObservationPageResult, ObservationRecord, OpenSession, PageAuthor, PageHit,- PageHitWithMeta, PageLinks, PageMeta, PageSummary, ProjectCoordinateCollisionReason,+ ObservationPage, ObservationPageResult, ObservationRecord, OpenSession,+ PAGE_VERSIONS_MAX_LIMIT, PageAuthor, PageHit, PageHitWithMeta, PageLinks, PageMeta,+ PageSummary, PageVersion, PageVersionBody, PageVersions, ProjectCoordinateCollisionReason,ProjectCoordinateDiagnostic, ProjectCoordinateStatus, ProjectSummary, RELATED_WALK_MAX_DEPTH,RELATED_WALK_MAX_NODES, ReaderPool, ReindexTargetStatus, RelatedNode, RelatedPage,RrfContributions, ScopeRow, SearchExplain, SessionConsolidationSummary, SessionDependentRows,diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rsindex 19be1259..7324855b 100644--- a/crates/ai-memory-store/src/reader.rs+++ b/crates/ai-memory-store/src/reader.rs@@ -75,6 +75,25 @@ pub(crate) fn now_us() -> i64 {Timestamp::now().as_microsecond()}+/// Visibility guard for the page-history readers ([`ReaderPool::page_versions`],+/// [`ReaderPool::page_version_body`]). A version is hidden when its own TTL+/// has passed, the same per-row [`not_expired`] rule the superseded-inclusive+/// retrieval streams apply, and also when the live version at its path has+/// expired: the forget sweep hard-deletes every row at that path, so the+/// history of an expired page is as hidden as the page itself. The readers+/// also report a `supersedes` link to a hidden version as `None`, so an+/// expired version's id does not surface through its successor.+fn history_visible(table: &str, now_param: &str) -> String {+ format!(+ "{per_row} AND NOT EXISTS (SELECT 1 FROM pages live \+ WHERE live.workspace_id = {table}.workspace_id \+ AND live.project_id = {table}.project_id \+ AND live.path = {table}.path AND live.is_latest = 1 \+ AND live.expires_at IS NOT NULL AND live.expires_at <= {now_param})",+ per_row = not_expired(table, now_param),+ )+}+/// Restrict `project_column` to the repositories `viewer` may read (#708).////// Returns a fragment to append to a `WHERE` clause and the values it binds,@@ -981,6 +1000,56 @@ pub struct StoredPageBody {pub pinned: bool,}+/// Most versions [`ReaderPool::page_versions`] returns in one call.+pub const PAGE_VERSIONS_MAX_LIMIT: usize = 200;++/// One stored version of a page path, listed by [`ReaderPool::page_versions`].+#[derive(Debug, Clone, Serialize)]+pub struct PageVersion {+ /// This version's id (`pages.id`).+ pub id: PageId,+ /// The version this one replaced, if it replaced one.+ pub supersedes: Option<PageId>,+ /// Whether this is the live version of the path.+ pub is_latest: bool,+ /// Title stored on this version.+ pub title: String,+ /// Memory tier stored on this version.+ pub tier: String,+ /// ISO-8601 instant this version was written.+ pub created_at: String,+ /// Length of this version's body in characters.+ pub body_chars: u64,+ /// The user who wrote this version, when the write was attributed.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub author: Option<PageAuthor>,+}++/// One page of a path's version history, newest first.+#[derive(Debug, Clone, Serialize)]+pub struct PageVersions {+ /// Every version stored at the path.+ pub total: u64,+ /// The requested slice of versions.+ pub versions: Vec<PageVersion>,+}++/// The stored content of one page version, read by+/// [`ReaderPool::page_version_body`].+#[derive(Debug, Clone)]+pub struct PageVersionBody {+ /// The version's id.+ pub id: PageId,+ /// The version this one replaced, if it replaced one.+ pub supersedes: Option<PageId>,+ /// Title stored on this version.+ pub title: String,+ /// Body stored on this version (markdown without frontmatter).+ pub body: String,+ /// ISO-8601 instant this version was written.+ pub created_at: String,+}+/// Search hit with workspace/project names, used by the web UI to avoid/// per-hit metadata lookups after a global search.#[derive(Debug, Clone, Serialize)]@@ -8881,6 +8950,165 @@ impl ReaderPool {.await}+ /// List the stored versions of one fully scoped page path, newest first.+ ///+ /// Every row at the path is listed, superseded ones included, so a+ /// version a concurrent write replaced stays visible (invariant #16).+ /// The listing reads by `(workspace_id, project_id, path)` and nothing+ /// else, so another project's rows at the same path never appear.+ /// `limit` is clamped to `1..=`[`PAGE_VERSIONS_MAX_LIMIT`]; `total` counts+ /// every visible version at the path. Bodies are not read, only their+ /// length. Expired versions are hidden (see `history_visible`).+ ///+ /// # Errors+ /// Propagates any SQL or pool error.+ pub async fn page_versions(+ &self,+ workspace_id: WorkspaceId,+ project_id: ProjectId,+ path: String,+ limit: usize,+ offset: usize,+ ) -> StoreResult<PageVersions> {+ self.with_conn(move |conn| {+ let now = now_us();+ let total: i64 = conn.query_row(+ &format!(+ "SELECT COUNT(*) FROM pages pg \+ WHERE pg.workspace_id = ?1 AND pg.project_id = ?2 AND pg.path = ?3{visible}",+ visible = history_visible("pg", "?4"),+ ),+ params![workspace_id.as_bytes(), project_id.as_bytes(), path, now],+ |row| row.get(0),+ )?;+ let mut stmt = conn.prepare_cached(&format!(+ "SELECT pg.id, \+ (SELECT sp.id FROM pages sp WHERE sp.id = pg.supersedes{prev_visible}), \+ pg.is_latest, pg.title, pg.tier, \+ pg.created_at, length(pg.body), au.username, au.name, au.email \+ FROM pages pg \+ LEFT JOIN users au ON au.id = pg.author_id \+ WHERE pg.workspace_id = ?1 AND pg.project_id = ?2 AND pg.path = ?3{visible} \+ ORDER BY pg.created_at DESC, pg.rowid DESC \+ LIMIT ?5 OFFSET ?6",+ visible = history_visible("pg", "?4"),+ prev_visible = history_visible("sp", "?4"),+ ))?;+ let rows = stmt.query_map(+ params![+ workspace_id.as_bytes(),+ project_id.as_bytes(),+ path,+ now,+ limit.clamp(1, PAGE_VERSIONS_MAX_LIMIT) as i64,+ i64::try_from(offset).unwrap_or(i64::MAX),+ ],+ |row| {+ Ok((+ row.get::<_, Vec<u8>>(0)?,+ row.get::<_, Option<Vec<u8>>>(1)?,+ row.get::<_, i64>(2)?,+ row.get::<_, String>(3)?,+ row.get::<_, String>(4)?,+ row.get::<_, i64>(5)?,+ row.get::<_, i64>(6)?,+ row.get::<_, Option<String>>(7)?,+ row.get::<_, Option<String>>(8)?,+ row.get::<_, Option<String>>(9)?,+ ))+ },+ )?;+ let mut versions = Vec::new();+ for row in rows {+ let (id, supersedes, is_latest, title, tier, created_us, chars, user, name, email) =+ row?;+ versions.push(PageVersion {+ id: PageId::from_slice(&id)?,+ supersedes: supersedes.as_deref().map(PageId::from_slice).transpose()?,+ is_latest: is_latest != 0,+ title,+ tier,+ created_at: jiff::Timestamp::from_microsecond(created_us)+ .map(|ts| ts.to_string())+ .unwrap_or_default(),+ body_chars: u64::try_from(chars).unwrap_or(0),+ author: user.map(|username| PageAuthor {+ username,+ name,+ email,+ }),+ });+ }+ Ok(PageVersions {+ total: u64::try_from(total).unwrap_or(0),+ versions,+ })+ })+ .await+ }++ /// Read one stored version of a page by id, only if it belongs to the+ /// given `(workspace_id, project_id, path)`.+ ///+ /// A version id from another project, workspace or path returns `None`,+ /// exactly like an unknown id, so a raw id cannot read across scopes. An+ /// expired version (see `history_visible`) returns `None` the same way.+ ///+ /// # Errors+ /// Propagates any SQL or pool error.+ pub async fn page_version_body(+ &self,+ workspace_id: WorkspaceId,+ project_id: ProjectId,+ path: String,+ version: PageId,+ ) -> StoreResult<Option<PageVersionBody>> {+ self.with_conn(move |conn| {+ let row = conn+ .query_row(+ &format!(+ "SELECT pg.title, pg.body, pg.created_at, \+ (SELECT sp.id FROM pages sp \+ WHERE sp.id = pg.supersedes{prev_visible}) \+ FROM pages pg \+ WHERE pg.id = ?1 AND pg.workspace_id = ?2 AND pg.project_id = ?3 \+ AND pg.path = ?4{visible}",+ visible = history_visible("pg", "?5"),+ prev_visible = history_visible("sp", "?5"),+ ),+ params![+ version.as_bytes(),+ workspace_id.as_bytes(),+ project_id.as_bytes(),+ path,+ now_us()+ ],+ |row| {+ Ok((+ row.get::<_, String>(0)?,+ row.get::<_, String>(1)?,+ row.get::<_, i64>(2)?,+ row.get::<_, Option<Vec<u8>>>(3)?,+ ))+ },+ )+ .optional()?;+ let Some((title, body, created_us, supersedes)) = row else {+ return Ok(None);+ };+ Ok(Some(PageVersionBody {+ id: version,+ supersedes: supersedes.as_deref().map(PageId::from_slice).transpose()?,+ title,+ body,+ created_at: jiff::Timestamp::from_microsecond(created_us)+ .map(|ts| ts.to_string())+ .unwrap_or_default(),+ }))+ })+ .await+ }+/// Return the latest page version id for one fully scoped path.////// # Errorsdiff --git a/crates/ai-memory-store/tests/suite/multi_session.rs b/crates/ai-memory-store/tests/suite/multi_session.rsindex fb65be94..51e58bfb 100644--- a/crates/ai-memory-store/tests/suite/multi_session.rs+++ b/crates/ai-memory-store/tests/suite/multi_session.rs@@ -574,6 +574,91 @@ async fn concurrent_writes_to_one_path_supersede_rather_than_destroy() {);}+/// The history readers behind the web page-history view: every version at a+/// path, the overwritten one included, and nothing from another project or+/// workspace at the same path. A foreign version id reads as `None`, the+/// same as an unknown one.+#[tokio::test]+async fn page_history_keeps_the_overwritten_version_and_stays_in_scope() {+ let tmp = tempfile::tempdir().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let (ws, proj) = scope(&store).await;+ let sibling = store+ .writer+ .get_or_create_project(ws, "sibling".to_string(), None)+ .await+ .unwrap();+ let far_ws = store+ .writer+ .get_or_create_workspace("far".to_string())+ .await+ .unwrap();+ let far = store+ .writer+ .get_or_create_project(far_ws, "shared-app".to_string(), None)+ .await+ .unwrap();+ let path = "notes/shared.md";+ let first = store+ .writer+ .upsert_page(page(ws, proj, path, "Shared", "alice's text"))+ .await+ .unwrap();+ let second = store+ .writer+ .upsert_page(page(ws, proj, path, "Shared", "carol's text"))+ .await+ .unwrap();+ let foreign = store+ .writer+ .upsert_page(page(ws, sibling, path, "Shared", "sibling text"))+ .await+ .unwrap();+ let far_id = store+ .writer+ .upsert_page(page(far_ws, far, path, "Shared", "far text"))+ .await+ .unwrap();++ let history = store+ .reader+ .page_versions(ws, proj, path.to_string(), 50, 0)+ .await+ .unwrap();+ assert_eq!(history.total, 2);+ let ids: Vec<_> = history.versions.iter().map(|v| v.id).collect();+ assert_eq!(+ ids,+ [second, first],+ "newest first, the overwritten one kept"+ );+ assert_eq!(history.versions[0].supersedes, Some(first));+ assert!(history.versions[0].is_latest && !history.versions[1].is_latest);++ let body = |version| {+ let reader = store.reader.clone();+ async move {+ reader+ .page_version_body(ws, proj, path.to_string(), version)+ .await+ .unwrap()+ }+ };+ assert!(body(first).await.unwrap().body.contains("alice's text"));+ assert_eq!(body(second).await.unwrap().supersedes, Some(first));+ assert!(body(foreign).await.is_none(), "a sibling project's version");+ assert!(body(far_id).await.is_none(), "another workspace's version");+ assert!(+ store+ .reader+ .page_version_body(ws, proj, "notes/other.md".to_string(), first)+ .await+ .unwrap()+ .is_none(),+ "a version under a path it does not belong to"+ );+}+/// The batched path-existence probe the consolidation link guard validates/// proposed cross-scope wikilinks against (#1218): it reports exactly the/// paths with a latest row, in any input order, and never invents one.diff --git a/crates/ai-memory-web/clippy.toml b/crates/ai-memory-web/clippy.tomlnew file mode 100644index 00000000..f62b816a--- /dev/null+++ b/crates/ai-memory-web/clippy.toml@@ -0,0 +1,33 @@+# The web UI and `/api/v1` are read-only by design (docs/frontend-api.md §10).+# `WebState` holds a `Wiki`, which can write, so the lint keeps every mutating+# entry point out of this crate. Writes go through MCP tools or `/admin/*`,+# where admission, attribution and the audit trail apply. The integration+# tests seed fixtures through these methods and carry an `allow`.+disallowed-methods = [+ { path = "ai_memory_wiki::Wiki::write_page", reason = "the web surface is read-only" },+ { path = "ai_memory_wiki::Wiki::write_page_if", reason = "the web surface is read-only" },+ { path = "ai_memory_wiki::Wiki::apply_batch", reason = "the web surface is read-only" },+ { path = "ai_memory_wiki::Wiki::append_under_project", reason = "the web surface is read-only" },+ { path = "ai_memory_wiki::Wiki::commit_all", reason = "the web surface is read-only" },+ { path = "ai_memory_wiki::Wiki::ensure_upgrade_baseline_checkpoint", reason = "the web surface is read-only" },+ { path = "ai_memory_wiki::Wiki::move_project_workspace", reason = "the web surface is read-only" },+ { path = "ai_memory_wiki::Wiki::move_session_page", reason = "the web surface is read-only" },+ { path = "ai_memory_wiki::Wiki::restore_page_from_checkpoint", reason = "the web surface is read-only" },+ { path = "ai_memory_wiki::Wiki::delete_page", reason = "the web surface is read-only" },+ { path = "ai_memory_wiki::Wiki::delete_page_if_latest", reason = "the web surface is read-only" },+ { path = "ai_memory_wiki::Wiki::evict_page_if_latest", reason = "the web surface is read-only" },+ { path = "ai_memory_wiki::Wiki::hard_delete_decay_tombstone", reason = "the web surface is read-only" },+ { path = "ai_memory_wiki::Wiki::purge_project", reason = "the web surface is read-only" },+ { path = "ai_memory_wiki::Wiki::purge_session", reason = "the web surface is read-only" },+ { path = "ai_memory_wiki::Wiki::remove_project_dir", reason = "the web surface is read-only" },+ { path = "ai_memory_wiki::Wiki::remove_workspace_dir", reason = "the web surface is read-only" },+ { path = "ai_memory_wiki::Wiki::write_auto_improve_sidecar", reason = "the web surface is read-only" },+ { path = "ai_memory_wiki::Wiki::approve_auto_improve_proposal", reason = "the web surface is read-only; /web/pending posts to /admin/pending-writes/*" },+ { path = "ai_memory_wiki::Wiki::reindex_page", reason = "the web surface is read-only" },+ { path = "ai_memory_wiki::Wiki::reindex_all", reason = "the web surface is read-only" },+ { path = "ai_memory_wiki::Wiki::refresh_renamed_scope", reason = "the web surface is read-only" },+ { path = "ai_memory_wiki::Wiki::backfill_scope_manifests", reason = "the web surface is read-only" },+ { path = "ai_memory_wiki::Wiki::repair_date_only_stale_after", reason = "the web surface is read-only" },+ { path = "ai_memory_wiki::Wiki::writer", reason = "the web surface is read-only: the writer actor is not reachable from here" },+ { path = "ai_memory_wiki::Wiki::git", reason = "the web surface is read-only: the git adapter writes the wiki tree" },+]diff --git a/crates/ai-memory-web/src/diff.rs b/crates/ai-memory-web/src/diff.rsnew file mode 100644index 00000000..5ef367cd--- /dev/null+++ b/crates/ai-memory-web/src/diff.rs@@ -0,0 +1,482 @@+//! Bounded line diff for the page-history view.+//!+//! Myers' O((N+M)·D) algorithm over lines, after trimming the common prefix+//! and suffix. Every dimension is capped: input bytes and lines per side, the+//! edit distance the search may explore, and the rendered output lines. A+//! pair past a cap renders as [`Diff::TooLarge`] instead of spending memory+//! or CPU on a page nobody can read as a diff anyway.++use serde::Serialize;++/// Largest side, in bytes, the diff accepts.+pub(crate) const MAX_INPUT_BYTES: usize = 512 * 1024;+/// Largest side, in lines, the diff accepts.+pub(crate) const MAX_INPUT_LINES: usize = 10_000;+/// Most line edits the search explores before giving up. Its trace keeps one+/// frontier per edit step, so memory grows with the square of this.+pub(crate) const MAX_EDIT_DISTANCE: usize = 1_000;+/// Most diff lines (context and changes) one response carries.+pub(crate) const MAX_OUTPUT_LINES: usize = 2_000;+/// Unchanged lines shown around each change.+const CONTEXT: usize = 3;++/// One rendered diff line.+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]+pub(crate) struct DiffLine {+ /// `' '` context, `'-'` removed, `'+'` added.+ pub op: char,+ /// The line, without its newline.+ pub text: String,+}++/// One hunk: a run of changes with surrounding context.+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]+pub(crate) struct Hunk {+ /// 1-based first line in the old text (0 when the hunk is empty there).+ pub old_start: usize,+ /// Lines the hunk covers in the old text.+ pub old_len: usize,+ /// 1-based first line in the new text (0 when the hunk is empty there).+ pub new_start: usize,+ /// Lines the hunk covers in the new text.+ pub new_len: usize,+ /// The hunk's lines.+ pub lines: Vec<DiffLine>,+}++impl Hunk {+ /// The `@@ -a,b +c,d @@` header line.+ pub(crate) fn header(&self) -> String {+ format!(+ "@@ -{},{} +{},{} @@",+ self.old_start, self.old_len, self.new_start, self.new_len+ )+ }+}++/// Outcome of [`unified`].+#[derive(Debug, Clone, PartialEq, Eq)]+pub(crate) enum Diff {+ /// The two texts are identical.+ Same,+ /// Hunks in order. `truncated` is set when [`MAX_OUTPUT_LINES`] cut the+ /// list short.+ Changed { hunks: Vec<Hunk>, truncated: bool },+ /// A cap refused the pair; the string says which.+ TooLarge(&'static str),+}++#[derive(Clone, Copy, PartialEq, Eq)]+enum Op {+ Keep,+ Delete,+ Insert,+}++/// Unified line diff from `old` to `new`, bounded by this module's caps.+pub(crate) fn unified(old: &str, new: &str) -> Diff {+ if old == new {+ return Diff::Same;+ }+ if old.len() > MAX_INPUT_BYTES || new.len() > MAX_INPUT_BYTES {+ return Diff::TooLarge("a version is larger than the diff limit");+ }+ let a: Vec<&str> = old.lines().collect();+ let b: Vec<&str> = new.lines().collect();+ if a.len() > MAX_INPUT_LINES || b.len() > MAX_INPUT_LINES {+ return Diff::TooLarge("a version has more lines than the diff limit");+ }+ let Some(ops) = edit_script(&a, &b) else {+ return Diff::TooLarge("the versions differ in more lines than the diff limit");+ };+ if ops.iter().all(|op| *op == Op::Keep) {+ // Same lines, different line endings or trailing newline.+ return Diff::Changed {+ hunks: Vec::new(),+ truncated: false,+ };+ }+ let (hunks, truncated) = hunks(&a, &b, &ops);+ Diff::Changed { hunks, truncated }+}++/// The shortest edit script, or `None` past [`MAX_EDIT_DISTANCE`].+fn edit_script(a: &[&str], b: &[&str]) -> Option<Vec<Op>> {+ let prefix = a.iter().zip(b).take_while(|(x, y)| x == y).count();+ let suffix = a[prefix..]+ .iter()+ .rev()+ .zip(b[prefix..].iter().rev())+ .take_while(|(x, y)| x == y)+ .count();+ let mid_a = &a[prefix..a.len() - suffix];+ let mid_b = &b[prefix..b.len() - suffix];+ let mut ops = vec![Op::Keep; prefix];+ ops.extend(myers(mid_a, mid_b)?);+ ops.extend(std::iter::repeat_n(Op::Keep, suffix));+ Some(ops)+}++/// Myers' greedy forward search, keeping one frontier per edit step so the+/// path can be walked back.+fn myers(a: &[&str], b: &[&str]) -> Option<Vec<Op>> {+ let n = a.len();+ let m = b.len();+ let max = n + m;+ if max == 0 {+ return Some(Vec::new());+ }+ let limit = max.min(MAX_EDIT_DISTANCE);+ // `v[k + offset]` is the furthest x reached on diagonal k = x - y.+ let offset = limit + 1;+ let mut v = vec![0usize; 2 * limit + 3];+ let mut trace: Vec<Vec<usize>> = Vec::new();+ for d in 0..=limit {+ trace.push(v.clone());+ let d_i = d as isize;+ let mut k = -d_i;+ while k <= d_i {+ let idx = (k + offset as isize) as usize;+ let mut x = if k == -d_i || (k != d_i && v[idx - 1] < v[idx + 1]) {+ v[idx + 1]+ } else {+ v[idx - 1] + 1+ };+ let mut y = (x as isize - k) as usize;+ while x < n && y < m && a[x] == b[y] {+ x += 1;+ y += 1;+ }+ v[idx] = x;+ if x >= n && y >= m {+ return Some(backtrack(&trace, offset, n, m));+ }+ k += 2;+ }+ }+ None+}++fn backtrack(trace: &[Vec<usize>], offset: usize, n: usize, m: usize) -> Vec<Op> {+ let mut ops = Vec::with_capacity(n + m);+ let mut x = n as isize;+ let mut y = m as isize;+ for (d, v) in trace.iter().enumerate().rev() {+ let d = d as isize;+ let k = x - y;+ let at = |k: isize| v[(k + offset as isize) as usize] as isize;+ let prev_k = if k == -d || (k != d && at(k - 1) < at(k + 1)) {+ k + 1+ } else {+ k - 1+ };+ let prev_x = if d == 0 { 0 } else { at(prev_k) };+ let prev_y = if d == 0 { 0 } else { prev_x - prev_k };+ while x > prev_x && y > prev_y {+ ops.push(Op::Keep);+ x -= 1;+ y -= 1;+ }+ if d > 0 {+ ops.push(if x == prev_x { Op::Insert } else { Op::Delete });+ }+ x = prev_x;+ y = prev_y;+ }+ ops.reverse();+ ops+}++/// Group an edit script into hunks with [`CONTEXT`] lines around each run of+/// changes, stopping at [`MAX_OUTPUT_LINES`].+fn hunks(a: &[&str], b: &[&str], ops: &[Op]) -> (Vec<Hunk>, bool) {+ // Positions in each text before every op.+ let mut positions = Vec::with_capacity(ops.len());+ let (mut ia, mut ib) = (0usize, 0usize);+ for op in ops {+ positions.push((ia, ib));+ match op {+ Op::Keep => {+ ia += 1;+ ib += 1;+ }+ Op::Delete => ia += 1,+ Op::Insert => ib += 1,+ }+ }+ let changes: Vec<usize> = (0..ops.len()).filter(|&i| ops[i] != Op::Keep).collect();+ let mut out = Vec::new();+ let mut emitted = 0usize;+ let mut i = 0usize;+ while i < changes.len() {+ let start = changes[i].saturating_sub(CONTEXT);+ let mut end = changes[i];+ // Merge changes whose context windows touch.+ while i + 1 < changes.len() && changes[i + 1] <= end + 2 * CONTEXT + 1 {+ i += 1;+ end = changes[i];+ }+ let end = (end + CONTEXT + 1).min(ops.len());+ let (old_first, new_first) = positions[start];+ let mut lines = Vec::new();+ let (mut old_len, mut new_len) = (0usize, 0usize);+ for j in start..end {+ if emitted >= MAX_OUTPUT_LINES {+ if !lines.is_empty() {+ out.push(Hunk {+ old_start: start_of(old_first, old_len),+ old_len,+ new_start: start_of(new_first, new_len),+ new_len,+ lines,+ });+ }+ return (out, true);+ }+ let (pa, pb) = positions[j];+ let line = match ops[j] {+ Op::Keep => {+ old_len += 1;+ new_len += 1;+ DiffLine {+ op: ' ',+ text: a[pa].to_owned(),+ }+ }+ Op::Delete => {+ old_len += 1;+ DiffLine {+ op: '-',+ text: a[pa].to_owned(),+ }+ }+ Op::Insert => {+ new_len += 1;+ DiffLine {+ op: '+',+ text: b[pb].to_owned(),+ }+ }+ };+ lines.push(line);+ emitted += 1;+ }+ out.push(Hunk {+ old_start: start_of(old_first, old_len),+ old_len,+ new_start: start_of(new_first, new_len),+ new_len,+ lines,+ });+ i += 1;+ }+ (out, false)+}++/// Unified-diff convention: a side the hunk does not touch starts at the line+/// before it (0 at the top of the file).+fn start_of(first: usize, len: usize) -> usize {+ if len == 0 { first } else { first + 1 }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn render(diff: &Diff) -> String {+ match diff {+ Diff::Same => "same".into(),+ Diff::TooLarge(why) => format!("too large: {why}"),+ Diff::Changed { hunks, truncated } => {+ let mut out = String::new();+ for hunk in hunks {+ out.push_str(&hunk.header());+ out.push('\n');+ for line in &hunk.lines {+ out.push(line.op);+ out.push_str(&line.text);+ out.push('\n');+ }+ }+ if *truncated {+ out.push_str("[truncated]\n");+ }+ out+ }+ }+ }++ #[test]+ fn identical_texts_are_the_same() {+ assert_eq!(unified("a\nb\n", "a\nb\n"), Diff::Same);+ }++ #[test]+ fn one_changed_line_gets_context_and_headers() {+ let old = "1\n2\n3\n4\n5\n6\n7\n8\n9\n";+ let new = "1\n2\n3\n4\nfive\n6\n7\n8\n9\n";+ assert_eq!(+ render(&unified(old, new)),+ "@@ -2,7 +2,7 @@\n 2\n 3\n 4\n-5\n+five\n 6\n 7\n 8\n"+ );+ }++ #[test]+ fn insertions_and_deletions_at_the_edges() {+ assert_eq!(render(&unified("", "a\nb\n")), "@@ -0,0 +1,2 @@\n+a\n+b\n");+ assert_eq!(render(&unified("a\nb\n", "")), "@@ -1,2 +0,0 @@\n-a\n-b\n");+ assert_eq!(+ render(&unified("b\n", "a\nb\nc\n")),+ "@@ -1,1 +1,3 @@\n+a\n b\n+c\n"+ );+ }++ #[test]+ fn distant_changes_are_separate_hunks() {+ let old: String = (1..=30).map(|i| format!("{i}\n")).collect();+ let new: String = (1..=30)+ .map(|i| match i {+ 2 => "two\n".to_owned(),+ 28 => "twenty-eight\n".to_owned(),+ _ => format!("{i}\n"),+ })+ .collect();+ let Diff::Changed { hunks, truncated } = unified(&old, &new) else {+ panic!("expected a change");+ };+ assert!(!truncated);+ assert_eq!(hunks.len(), 2, "{}", render(&unified(&old, &new)));+ assert_eq!(hunks[0].header(), "@@ -1,5 +1,5 @@");+ assert_eq!(hunks[1].header(), "@@ -25,6 +25,6 @@");+ }++ #[test]+ fn the_script_is_minimal_and_reproduces_the_new_text() {+ let old = "a\nb\nc\na\nb\nb\na\n";+ let new = "c\nb\na\nb\na\nc\n";+ let Diff::Changed { hunks, .. } = unified(old, new) else {+ panic!("expected a change");+ };+ let lines: Vec<&DiffLine> = hunks.iter().flat_map(|h| &h.lines).collect();+ let edits = lines.iter().filter(|l| l.op != ' ').count();+ // The classic Myers example: five edits.+ assert_eq!(edits, 5);+ let rebuilt: Vec<&str> = lines+ .iter()+ .filter(|l| l.op != '-')+ .map(|l| l.text.as_str())+ .collect();+ assert_eq!(rebuilt, new.lines().collect::<Vec<_>>());+ let original: Vec<&str> = lines+ .iter()+ .filter(|l| l.op != '+')+ .map(|l| l.text.as_str())+ .collect();+ assert_eq!(original, old.lines().collect::<Vec<_>>());+ }++ /// Every pair over a small alphabet: the script must rebuild both texts+ /// and be as short as the LCS says it can be.+ #[test]+ fn scripts_are_valid_and_minimal_against_a_brute_force_lcs() {+ fn lcs(a: &[&str], b: &[&str]) -> usize {+ let mut t = vec![vec![0usize; b.len() + 1]; a.len() + 1];+ for i in 0..a.len() {+ for j in 0..b.len() {+ t[i + 1][j + 1] = if a[i] == b[j] {+ t[i][j] + 1+ } else {+ t[i][j + 1].max(t[i + 1][j])+ };+ }+ }+ t[a.len()][b.len()]+ }+ // A tiny deterministic generator; no new dependency for a test.+ let mut seed: u64 = 0x9e37_79b9_7f4a_7c15;+ let mut next = move || {+ seed ^= seed << 13;+ seed ^= seed >> 7;+ seed ^= seed << 17;+ seed+ };+ let alphabet = ["a", "b", "c"];+ for _ in 0..2_000 {+ let len_a = (next() % 9) as usize;+ let len_b = (next() % 9) as usize;+ let a: Vec<&str> = (0..len_a)+ .map(|_| alphabet[(next() % 3) as usize])+ .collect();+ let b: Vec<&str> = (0..len_b)+ .map(|_| alphabet[(next() % 3) as usize])+ .collect();+ let ops = edit_script(&a, &b).expect("small inputs stay under the cap");+ let (mut ia, mut ib) = (0, 0);+ for op in &ops {+ match op {+ Op::Keep => {+ assert_eq!(a[ia], b[ib], "{a:?} -> {b:?}");+ ia += 1;+ ib += 1;+ }+ Op::Delete => ia += 1,+ Op::Insert => ib += 1,+ }+ }+ assert_eq!((ia, ib), (a.len(), b.len()), "{a:?} -> {b:?}");+ let edits = ops.iter().filter(|op| **op != Op::Keep).count();+ assert_eq!(edits, a.len() + b.len() - 2 * lcs(&a, &b), "{a:?} -> {b:?}");+ }+ }++ #[test]+ fn caps_refuse_oversized_input_and_edit_distance() {+ let big = "x".repeat(MAX_INPUT_BYTES + 1);+ assert!(matches!(unified(&big, "y"), Diff::TooLarge(_)));++ let many: String = (0..=MAX_INPUT_LINES).map(|i| format!("{i}\n")).collect();+ assert!(matches!(unified(&many, "y"), Diff::TooLarge(_)));++ // Every line differs: the distance is twice the line count.+ let old: String = (0..MAX_EDIT_DISTANCE).map(|i| format!("a{i}\n")).collect();+ let new: String = (0..MAX_EDIT_DISTANCE).map(|i| format!("b{i}\n")).collect();+ assert!(matches!(unified(&old, &new), Diff::TooLarge(_)));+ // Under the distance cap the same shape diffs.+ let old: String = (0..100).map(|i| format!("a{i}\n")).collect();+ let new: String = (0..100).map(|i| format!("b{i}\n")).collect();+ assert!(matches!(unified(&old, &new), Diff::Changed { .. }));+ }++ #[test]+ fn output_is_cut_at_the_line_cap() {+ let old: String = (0..MAX_INPUT_LINES / 2).map(|i| format!("{i}\n")).collect();+ // 500 changed lines (an edit distance of 1000, inside the cap), close+ // enough that their context merges into one run longer than the cap.+ let new: String = (0..MAX_INPUT_LINES / 2)+ .map(|i| {+ if i % 7 == 0 && i < 3_500 {+ format!("changed {i}\n")+ } else {+ format!("{i}\n")+ }+ })+ .collect();+ let Diff::Changed { hunks, truncated } = unified(&old, &new) else {+ panic!("expected a change");+ };+ assert!(truncated);+ let lines: usize = hunks.iter().map(|h| h.lines.len()).sum();+ assert_eq!(lines, MAX_OUTPUT_LINES);+ }++ #[test]+ fn a_line_ending_only_change_reports_no_hunks() {+ assert_eq!(+ unified("a\nb", "a\nb\n"),+ Diff::Changed {+ hunks: Vec::new(),+ truncated: false+ }+ );+ }+}diff --git a/crates/ai-memory-web/src/lib.rs b/crates/ai-memory-web/src/lib.rsindex 81ec6748..79685722 100644--- a/crates/ai-memory-web/src/lib.rs+++ b/crates/ai-memory-web/src/lib.rs@@ -11,6 +11,8 @@//! - `GET /` → project list (cards)//! - `GET /w/:workspace/:project` → page tree + recent activity//! - `GET /w/:workspace/:project/p/*path` → rendered markdown + metadata+//! - `GET /w/:workspace/:project/h/*path` → version history + unified diff+//! - `GET /w/:workspace/:project/s/:session` → session timeline, paged//! - `GET /search?q=…` → FTS5 hit list//! - `GET /pending` → root-only pending-writes triage;//! its buttons post to `/admin/pending-writes/*`, not to this crate@@ -19,7 +21,8 @@//!//! The companion `api_router` exposes the same read-only data as JSON//! for custom frontends. It intentionally does not expose write/admin-//! operations.+//! operations. `clippy.toml` in this crate forbids the `Wiki` write and+//! destructive methods, so read-only holds at lint time, not only by review.//!//! Theme follows `prefers-color-scheme` via the included Tailwind//! stylesheet; no JS toggle, no cookie.@@ -30,6 +33,7 @@ use ai_memory_store::ReaderPool;use ai_memory_wiki::Wiki;use axum::Router;+mod diff;mod html_auth;mod markdown;pub mod mount;@@ -76,6 +80,9 @@ pub fn favicon_router() -> Router {// public API; `extern crate self` lets them keep addressing it by crate name.#[cfg(test)]extern crate self as ai_memory_web;+// The fixtures seed pages through `Wiki::write_page`, which `clippy.toml`+// forbids in this crate's own code.#[cfg(test)]+#[allow(clippy::disallowed_methods)]#[path = "../tests/suite/mod.rs"]mod integration;diff --git a/crates/ai-memory-web/src/mount.rs b/crates/ai-memory-web/src/mount.rsindex c40d91a2..3b93f6ee 100644--- a/crates/ai-memory-web/src/mount.rs+++ b/crates/ai-memory-web/src/mount.rs@@ -1229,6 +1229,51 @@ mod tests {let tmp = TempDir::new().unwrap();let store = Store::open(tmp.path()).unwrap();let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();+ // A page version and a session, so the history and timeline routes+ // answer 200 rather than an error page.+ let ws = store+ .writer+ .get_or_create_workspace("default")+ .await+ .unwrap();+ let proj = store+ .writer+ .get_or_create_project(ws, "scratch", None)+ .await+ .unwrap();+ store+ .writer+ .upsert_page(ai_memory_core::NewPage {+ workspace_id: ws,+ project_id: proj,+ path: ai_memory_core::PagePath::new("notes/a.md").unwrap(),+ title: "A".into(),+ body: "a".into(),+ tier: ai_memory_core::Tier::Semantic,+ frontmatter_json: serde_json::json!({}),+ pinned: false,+ links: Vec::new(),+ author_id: None,+ expires_at: None,+ entities: Vec::new(),+ evidence: Vec::new(),+ })+ .await+ .unwrap();+ let session = ai_memory_core::SessionId::new();+ store+ .writer+ .begin_session(ai_memory_core::NewSession {+ occurred_at: None,+ id: session,+ workspace_id: ws,+ project_id: proj,+ agent_kind: ai_memory_core::AgentKind::ClaudeCode,+ cwd: None,+ actor_user: None,+ })+ .await+ .unwrap();let base_href = web_base_href("", "/web");let router = mount_web_router(axum::Router::new(),@@ -1246,12 +1291,24 @@ mod tests {},).unwrap();- for uri in ["/web", "/web/pending", "/web/login", "/api/v1/projects"] {+ let session_uri = format!("/web/w/default/scratch/s/{session}");+ for uri in [+ "/web",+ "/web/pending",+ "/web/login",+ "/api/v1/projects",+ "/web/w/default/scratch/h/notes/a.md",+ session_uri.as_str(),+ "/api/v1/workspaces/default/projects/scratch/history/notes/a.md",+ ] {let resp = router.clone().oneshot(Request::builder().uri(uri).body(Body::empty()).unwrap()).await.unwrap();+ if uri.contains("/h/") || uri.contains("/s/") || uri.contains("/history/") {+ assert_eq!(resp.status(), StatusCode::OK, "{uri}");+ }let headers = resp.headers();assert_eq!(headers.get("x-frame-options").map(|v| v.to_str().unwrap()),diff --git a/crates/ai-memory-web/src/routes/api.rs b/crates/ai-memory-web/src/routes/api.rsindex 42ae0401..26647020 100644--- a/crates/ai-memory-web/src/routes/api.rs+++ b/crates/ai-memory-web/src/routes/api.rs@@ -43,6 +43,10 @@ pub(crate) fn build(state: Arc<WebState>) -> Router {"/search",axum::routing::get(search_handler).post(search_post_handler),)+ .route(+ "/workspaces/{workspace}/projects/{project}/history/{*path}",+ axum::routing::get(history_handler),+ ).route("/workspaces/{workspace}/projects/{project}/recent",axum::routing::get(recent_handler),@@ -283,6 +287,66 @@ async fn page_handler(Ok(resp)}+/// A page's stored versions, newest first, and a unified diff between two of+/// them (default: the newest against the version it replaced). See+/// `routes/history.rs`; the HTML view renders the same data.+async fn history_handler(+ State(state): State<Arc<WebState>>,+ viewer: Option<axum::Extension<ai_memory_core::AuthorizedViewer>>,+ Path((workspace, project, path)): Path<(String, String, String)>,+ Query(query): Query<super::history::HistoryQuery>,+) -> Result<Response, Response> {+ use super::history::HistoryError;+ let history = super::history::load(+ &state,+ viewer_of(viewer),+ &workspace,+ &project,+ &path,+ &query,+ )+ .await+ .map_err(|err| match err {+ HistoryError::Scope(ScopeResolutionError::ProjectNotFoundInWorkspace {+ project, ..+ }) => not_found(format!("project '{project}' not found")),+ HistoryError::Scope(other) => scope_error_response(other),+ HistoryError::BadRequest(message) => json_error(StatusCode::BAD_REQUEST, message),+ HistoryError::NotFound(message) => not_found(message),+ HistoryError::Internal(error) => internal_error(error),+ })?;+ let side = |side: &super::history::DiffSide| ApiHistorySide {+ id: side.id.to_string(),+ title: side.title.clone(),+ created_at: side.created_at.clone(),+ };+ let (status, reason, truncated, hunks) = match history.diff {+ crate::diff::Diff::Same => ("same", None, false, Vec::new()),+ crate::diff::Diff::TooLarge(why) => ("too_large", Some(why), false, Vec::new()),+ crate::diff::Diff::Changed { hunks, truncated } => ("changed", None, truncated, hunks),+ };+ Ok(with_no_store(+ Json(ApiHistory {+ workspace,+ project,+ path,+ total: history.total,+ offset: history.offset,+ limit: history.limit,+ diff: ApiHistoryDiff {+ from: history.from.as_ref().map(side),+ to: side(&history.to),+ status,+ reason,+ truncated,+ hunks,+ },+ versions: history.versions,+ })+ .into_response(),+ ))+}+async fn search_handler(State(state): State<Arc<WebState>>,viewer: Option<axum::Extension<ai_memory_core::AuthorizedViewer>>,@@ -778,7 +842,7 @@ async fn overview_handler(/// may leave `user` empty, and reading `user` here would file that operator as/// unattributed while the auth layer calls them a user — hiding their own/// handoffs, and the bodies of the shared ones, from them in their own UI.-fn owner_filter_for(+pub(crate) fn owner_filter_for(actor: Option<axum::Extension<ai_memory_core::ActorContext>>,) -> ai_memory_core::OwnerFilter {ai_memory_core::OwnerFilter::for_actor_context(@@ -1066,8 +1130,8 @@ async fn project_overview_handler(/// `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;+pub(crate) const SESSION_OBSERVATIONS_MAX_LIMIT: usize = 200;+pub(crate) 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;@@ -1208,7 +1272,7 @@ async fn session_observations_handler(/// `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 {+pub(crate) fn cap_body(body: &str, max_chars: usize) -> String {let total = body.chars().count();if total <= max_chars {return body.to_owned();@@ -1464,6 +1528,40 @@ struct SessionObservationsQuery {body_max_chars: Option<usize>,}+#[derive(Debug, Serialize)]+struct ApiHistory {+ workspace: String,+ project: String,+ path: String,+ total: u64,+ offset: usize,+ limit: usize,+ versions: Vec<ai_memory_store::PageVersion>,+ diff: ApiHistoryDiff,+}++#[derive(Debug, Serialize)]+struct ApiHistoryDiff {+ /// `None` when `to` replaced nothing at this path.+ from: Option<ApiHistorySide>,+ to: ApiHistorySide,+ /// `same`, `changed` or `too_large`.+ status: &'static str,+ /// Why a `too_large` diff was refused.+ #[serde(skip_serializing_if = "Option::is_none")]+ reason: Option<&'static str>,+ /// The output line cap cut `hunks` short.+ truncated: bool,+ hunks: Vec<crate::diff::Hunk>,+}++#[derive(Debug, Serialize)]+struct ApiHistorySide {+ id: String,+ title: String,+ created_at: String,+}+#[derive(Debug, Serialize)]struct ApiSessionList {sessions: Vec<SessionSummary>,diff --git a/crates/ai-memory-web/src/routes/history.rs b/crates/ai-memory-web/src/routes/history.rsnew file mode 100644index 00000000..cee3cd49--- /dev/null+++ b/crates/ai-memory-web/src/routes/history.rs@@ -0,0 +1,334 @@+//! `GET /w/:workspace/:project/h/*path` — a page's version history and a+//! server-side diff between two of its versions.+//!+//! Read-only: every row comes from `ReaderPool::page_versions` and+//! `ReaderPool::page_version_body`, which read by the resolved+//! `(workspace_id, project_id, path)`. A version id from anywhere else reads+//! as not found.++use std::sync::Arc;++use ai_memory_core::{PageId, PagePath};+use ai_memory_store::{PageVersion, ScopeResolutionError};+use askama::Template;+use axum::extract::{Path, Query, State};+use axum::http::StatusCode;+use axum::response::{Html, IntoResponse, Response};+use serde::Deserialize;++use crate::diff::{self, Diff};+use crate::state::WebState;+use crate::templates::{+ HistoryDiffLine, HistoryHunk, HistoryVersionRow, HistoryView, history_href, humanize,+ page_href, project_href,+};++/// Versions listed per page when the request names no `limit`.+pub(crate) const DEFAULT_VERSION_LIMIT: usize = 50;++/// Query string shared by the HTML and JSON history routes.+#[derive(Debug, Default, Deserialize)]+pub(crate) struct HistoryQuery {+ /// Older side of the diff. Defaults to the version `to` replaced.+ #[serde(default)]+ pub from: Option<String>,+ /// Newer side of the diff. Defaults to the newest version.+ #[serde(default)]+ pub to: Option<String>,+ /// Versions per listing page, clamped to+ /// `1..=`[`ai_memory_store::PAGE_VERSIONS_MAX_LIMIT`].+ #[serde(default)]+ pub limit: Option<usize>,+ /// Versions to skip, newest first.+ #[serde(default)]+ pub offset: usize,+}++/// One side of a diff.+pub(crate) struct DiffSide {+ pub id: PageId,+ pub title: String,+ pub created_at: String,+}++/// Everything both history routes render.+pub(crate) struct History {+ pub total: u64,+ pub limit: usize,+ pub offset: usize,+ pub versions: Vec<PageVersion>,+ /// `None` only for a path with a single version and no `from`.+ pub from: Option<DiffSide>,+ pub to: DiffSide,+ pub diff: Diff,+}++/// Why a history request was refused.+pub(crate) enum HistoryError {+ Scope(ScopeResolutionError),+ BadRequest(String),+ NotFound(&'static str),+ Internal(String),+}++/// Resolve the scope, list the versions and diff the selected pair.+pub(crate) async fn load(+ state: &WebState,+ viewer: Option<ai_memory_core::UserId>,+ workspace: &str,+ project: &str,+ path: &str,+ query: &HistoryQuery,+) -> Result<History, HistoryError> {+ let scope = super::resolve_read_scope(state, viewer, workspace, project)+ .await+ .map_err(HistoryError::Scope)?;+ let path = PagePath::new(path)+ .map_err(|e| HistoryError::BadRequest(format!("invalid path: {e}")))?+ .as_str()+ .to_owned();+ let parse = |raw: &Option<String>, name: &str| -> Result<Option<PageId>, HistoryError> {+ match raw.as_deref().map(str::trim).filter(|s| !s.is_empty()) {+ None => Ok(None),+ Some(raw) => raw+ .parse::<PageId>()+ .map(Some)+ .map_err(|_| HistoryError::BadRequest(format!("invalid {name} version id"))),+ }+ };+ let from_id = parse(&query.from, "from")?;+ let to_id = parse(&query.to, "to")?;+ let limit = query+ .limit+ .unwrap_or(DEFAULT_VERSION_LIMIT)+ .clamp(1, ai_memory_store::PAGE_VERSIONS_MAX_LIMIT);++ let internal = |e: ai_memory_store::StoreError| HistoryError::Internal(e.to_string());+ let listing = state+ .reader+ .page_versions(+ scope.workspace_id,+ scope.project_id,+ path.clone(),+ limit,+ query.offset,+ )+ .await+ .map_err(internal)?;+ if listing.total == 0 {+ return Err(HistoryError::NotFound("page not found"));+ }+ let body = |id: PageId| {+ let path = path.clone();+ async move {+ state+ .reader+ .page_version_body(scope.workspace_id, scope.project_id, path, id)+ .await+ .map_err(internal)?+ .ok_or(HistoryError::NotFound("version not found"))+ }+ };++ // The newer side: the named version, else the newest one at the path.+ let to_id = match to_id {+ Some(id) => id,+ None if query.offset == 0 => {+ listing+ .versions+ .first()+ .ok_or(HistoryError::NotFound("page not found"))?+ .id+ }+ None => {+ state+ .reader+ .page_versions(scope.workspace_id, scope.project_id, path.clone(), 1, 0)+ .await+ .map_err(internal)?+ .versions+ .first()+ .ok_or(HistoryError::NotFound("page not found"))?+ .id+ }+ };+ let to = body(to_id).await?;+ // The older side: the named version, else the one `to` replaced. A+ // predecessor stored at another path (a resurrected or moved page) is+ // not part of this path's history, so the default diff starts from empty+ // rather than failing; only a named `from` must exist here.+ let from = match (from_id, to.supersedes) {+ (Some(id), _) => Some(body(id).await?),+ (None, Some(prev)) => match body(prev).await {+ Ok(found) => Some(found),+ Err(HistoryError::NotFound(_)) => None,+ Err(other) => return Err(other),+ },+ (None, None) => None,+ };+ let diff = diff::unified(from.as_ref().map_or("", |f| f.body.as_str()), &to.body);+ Ok(History {+ total: listing.total,+ limit,+ offset: query.offset,+ versions: listing.versions,+ from: from.map(|f| DiffSide {+ id: f.id,+ title: f.title,+ created_at: f.created_at,+ }),+ to: DiffSide {+ id: to.id,+ title: to.title,+ created_at: to.created_at,+ },+ diff,+ })+}++/// Handler for `GET /w/:workspace/:project/h/*path`.+pub(crate) async fn handler(+ State(state): State<Arc<WebState>>,+ viewer: Option<axum::Extension<ai_memory_core::AuthorizedViewer>>,+ Path((workspace, project, path)): Path<(String, String, String)>,+ Query(query): Query<HistoryQuery>,+) -> Response {+ let viewer = viewer.map(|axum::Extension(viewer)| viewer.user());+ let history = match load(&state, viewer, &workspace, &project, &path, &query).await {+ Ok(history) => history,+ Err(HistoryError::Scope(refusal)) => return super::page::refusal_response(&refusal),+ Err(HistoryError::BadRequest(message)) => {+ return (StatusCode::BAD_REQUEST, message).into_response();+ }+ Err(HistoryError::NotFound(_)) => return super::page::not_found_response(),+ Err(HistoryError::Internal(error)) => {+ tracing::error!(%error, "web history read failed");+ return StatusCode::INTERNAL_SERVER_ERROR.into_response();+ }+ };+ render(&workspace, &project, &path, history)+}++fn render(workspace: &str, project: &str, path: &str, history: History) -> Response {+ let base = history_href(workspace, project, path);+ let from_id = history.from.as_ref().map(|f| f.id);+ let to_id = history.to.id;+ let versions = history+ .versions+ .iter()+ .map(|v| HistoryVersionRow {+ id: v.id.to_string(),+ short_id: short(v.id),+ supersedes_short: v.supersedes.map(short).unwrap_or_default(),+ is_latest: v.is_latest,+ title: v.title.clone(),+ created_at: v.created_at.clone(),+ created_relative: humanize(&v.created_at),+ author: v+ .author+ .as_ref()+ .map(|a| a.username.clone())+ .unwrap_or_default(),+ body_chars: v.body_chars,+ is_from: Some(v.id) == from_id,+ is_to: v.id == to_id,+ compare_href: v.supersedes.map_or_else(String::new, |prev| {+ format!("{base}?from={prev}&to={}", v.id)+ }),+ })+ .collect();+ let (same, too_large, truncated, hunks) = match history.diff {+ Diff::Same => (true, String::new(), false, Vec::new()),+ Diff::TooLarge(why) => (false, why.to_owned(), false, Vec::new()),+ Diff::Changed { hunks, truncated } => (+ false,+ String::new(),+ truncated,+ hunks+ .into_iter()+ .map(|h| HistoryHunk {+ header: h.header(),+ lines: h+ .lines+ .into_iter()+ .map(|l| HistoryDiffLine {+ sign: l.op.to_string(),+ text: l.text,+ })+ .collect(),+ })+ .collect(),+ ),+ };+ let page_param = |offset: usize| {+ let mut href = format!("{base}?offset={offset}&limit={}", history.limit);+ if let Some(from) = from_id {+ href.push_str(&format!("&from={from}"));+ }+ href.push_str(&format!("&to={to_id}"));+ href+ };+ let shown_end = history.offset + history.versions.len();+ let newer_href = if history.offset > 0 {+ page_param(history.offset.saturating_sub(history.limit))+ } else {+ String::new()+ };+ let older_href = if (shown_end as u64) < history.total {+ page_param(shown_end)+ } else {+ String::new()+ };+ let view = HistoryView {+ workspace: workspace.to_owned(),+ project: project.to_owned(),+ project_href: project_href(workspace, project),+ page_href: page_href(workspace, project, path),+ history_href: base,+ path: path.to_owned(),+ total: history.total,+ shown_start: if history.versions.is_empty() {+ 0+ } else {+ history.offset + 1+ },+ shown_end,+ limit: history.limit,+ newer_href,+ older_href,+ versions,+ from_short: history+ .from+ .as_ref()+ .map(|f| short(f.id))+ .unwrap_or_default(),+ from_created: history+ .from+ .as_ref()+ .map(|f| f.created_at.clone())+ .unwrap_or_default(),+ from_title: history+ .from+ .as_ref()+ .map(|f| f.title.clone())+ .unwrap_or_default(),+ to_short: short(to_id),+ to_created: history.to.created_at,+ to_title: history.to.title,+ same,+ too_large,+ truncated,+ hunks,+ };+ match view.render() {+ Ok(html) => Html(html).into_response(),+ Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),+ }+}++/// Last eight characters of a version id. Ids are UUIDv7, so their leading+/// characters are a timestamp that versions written close together share;+/// the tail is random and tells them apart.+fn short(id: PageId) -> String {+ crate::templates::short_id(&id.to_string())+}diff --git a/crates/ai-memory-web/src/routes/mod.rs b/crates/ai-memory-web/src/routes/mod.rsindex b352ee0c..bf36699e 100644--- a/crates/ai-memory-web/src/routes/mod.rs+++ b/crates/ai-memory-web/src/routes/mod.rs@@ -9,12 +9,14 @@ use crate::html_auth::HtmlAuthRedirectConfig;use crate::state::WebState;mod api;+mod history;mod index;mod login;mod page;mod pending;mod project;mod search;+mod session;mod statics;/// Whether the viewer may read `workspace/project` (#708).@@ -46,12 +48,39 @@ pub(crate) async fn authorize_read(.map(Some)}+/// Resolve `workspace/project` for a route that needs its ids, refusing a+/// viewer without read access (#708).+///+/// Unlike [`authorize_read`] it always resolves, viewer or not, because the+/// history and session views read by id. No-create and fail-closed, like+/// every read path.+pub(crate) async fn resolve_read_scope(+ state: &WebState,+ viewer: Option<ai_memory_core::UserId>,+ workspace: &str,+ project: &str,+) -> Result<ai_memory_store::ResolvedScope, ai_memory_store::ScopeResolutionError> {+ ai_memory_store::lookup_existing_scope_guarded(+ &state.reader,+ workspace,+ project,+ viewer,+ ai_memory_store::ProjectAccess::Read,+ )+ .await+}+/// Build the read-only wiki page router (no static assets — those are public).pub(crate) fn build(state: Arc<WebState>) -> Router {Router::new().route("/", get(index::handler)).route("/w/{workspace}/{project}", get(project::handler)).route("/w/{workspace}/{project}/p/{*path}", get(page::handler))+ .route("/w/{workspace}/{project}/h/{*path}", get(history::handler))+ .route(+ "/w/{workspace}/{project}/s/{session_id}",+ get(session::handler),+ ).route("/search", get(search::handler)).route("/pending", get(pending::handler)).with_state(state)diff --git a/crates/ai-memory-web/src/routes/page.rs b/crates/ai-memory-web/src/routes/page.rsindex be3ea857..376dd15a 100644--- a/crates/ai-memory-web/src/routes/page.rs+++ b/crates/ai-memory-web/src/routes/page.rs@@ -11,7 +11,7 @@ use axum::response::{Html, IntoResponse, Response};use crate::markdown;use crate::state::WebState;use crate::templates::{- NamespaceView, NotFoundView, PageRow, PageView, humanize, page_href, project_href,+ NamespaceView, NotFoundView, PageRow, PageView, history_href, humanize, page_href, project_href,};/// Handler for `GET /w/:workspace/:project/p/*path`.@@ -73,6 +73,7 @@ pub(crate) async fn handler(},);+ let history_href = history_href(&workspace, &project, &path);match (PageView {workspace,project,@@ -87,6 +88,7 @@ pub(crate) async fn handler(supersedes_path,supersedes_href,body_html,+ history_href,author_username,author_name,author_email,@@ -162,7 +164,7 @@ pub(crate) fn refusal_response(refusal: &ai_memory_store::ScopeResolutionError)}}-fn not_found_response() -> Response {+pub(crate) fn not_found_response() -> Response {let html = NotFoundView {}.render().unwrap_or_else(|_| "<h1>Not found</h1>".to_owned());diff --git a/crates/ai-memory-web/src/routes/project.rs b/crates/ai-memory-web/src/routes/project.rsindex 36014171..6d3e4c72 100644--- a/crates/ai-memory-web/src/routes/project.rs+++ b/crates/ai-memory-web/src/routes/project.rs@@ -12,12 +12,16 @@ use ai_memory_store::ResolvedScope;use crate::state::WebState;use crate::templates::{- Folder, MailboxRow, PageRow, ProjectView, humanize, page_href, project_href,+ Folder, MailboxRow, PageRow, ProjectView, SessionRow, humanize, page_href, project_href,+ session_href,};/// Pending messages listed on the project page before it says there are more.const MAILBOX_LIMIT: usize = 5;+/// Recent sessions listed on the project page.+const SESSION_LIMIT: usize = 10;+/// Leading body characters shown per message.const SNIPPET_CHARS: usize = 160;@@ -25,6 +29,7 @@ const SNIPPET_CHARS: usize = 160;pub(crate) async fn handler(State(state): State<Arc<WebState>>,viewer: Option<axum::Extension<ai_memory_core::AuthorizedViewer>>,+ actor: Option<axum::Extension<ai_memory_core::ActorContext>>,Path((workspace, project)): Path<(String, String)>,) -> Response {let viewer_id = viewer.as_ref().map(|axum::Extension(viewer)| viewer.user());@@ -32,7 +37,8 @@ pub(crate) async fn handler(Ok(authorized) => authorized,Err(refusal) => return super::page::refusal_response(&refusal),};- render(&state, workspace, project, viewer_id, authorized)+ let owner = super::api::owner_filter_for(actor);+ render(&state, workspace, project, viewer_id, authorized, owner).await.into_response()}@@ -43,8 +49,9 @@ async fn render(project: String,viewer: Option<ai_memory_core::UserId>,authorized: Option<ResolvedScope>,+ owner: ai_memory_core::OwnerFilter,) -> Result<Html<String>, StatusCode> {- let (pages, (mailbox, mailbox_total)) = tokio::try_join!(+ let (pages, (mailbox, mailbox_total), sessions) = tokio::try_join!(async {state.reader@@ -53,6 +60,7 @@ async fn render(.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)},mailbox(state, &workspace, &project, viewer, authorized),+ sessions(state, &workspace, &project, authorized, owner),)?;// Build sidebar folder trees (group by first path segment), split@@ -131,6 +139,7 @@ async fn render(mailbox,mailbox_total,mailbox_capped,+ sessions,}.render().map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;@@ -193,6 +202,47 @@ async fn mailbox(Ok((rows, total))}+/// The project's most recent sessions, open ones included, through the same+/// owner-filtered reader as `/api/v1/.../sessions`: a session another operator+/// owns is not listed.+async fn sessions(+ state: &WebState,+ workspace: &str,+ project: &str,+ authorized: Option<ResolvedScope>,+ owner: ai_memory_core::OwnerFilter,+) -> Result<Vec<SessionRow>, StatusCode> {+ let Some(scope) = mailbox_scope(state, workspace, project, authorized).await? else {+ return Ok(Vec::new());+ };+ let sessions = state+ .reader+ .sessions_for_scope(+ scope.workspace_id,+ scope.project_id,+ owner,+ true,+ SESSION_LIMIT,+ 0,+ )+ .await+ .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;+ Ok(sessions+ .into_iter()+ .map(|s| {+ let id = s.session_id.to_string();+ SessionRow {+ href: session_href(workspace, project, &id),+ agent_kind: s.agent_kind,+ short_id: crate::templates::short_id(&id),+ observation_count: s.observation_count,+ started_relative: humanize(&s.started_at),+ open: s.ended_at.is_none(),+ }+ })+ .collect())+}+/// The project whose pages this page lists, or `None` when there is none.////// Matches the exact name, as `list_pages` does, so an alias that resolves todiff --git a/crates/ai-memory-web/src/routes/session.rs b/crates/ai-memory-web/src/routes/session.rsnew file mode 100644index 00000000..5f655b1a--- /dev/null+++ b/crates/ai-memory-web/src/routes/session.rs@@ -0,0 +1,179 @@+//! `GET /w/:workspace/:project/s/:session_id` — one session's observations in+//! capture order, a page at a time, with a prev/next/jump scrubber.+//!+//! Reads through the same scoped readers and caps as the `/api/v1` sessions+//! routes: `session_summary_scoped` decides visibility (row or observation in+//! this project, owner filter passes), and `session_observations_scoped`+//! returns only this project's rows. Bodies were sanitized on ingest and are+//! still untrusted text: the template escapes every field.++use std::sync::Arc;++use ai_memory_core::SessionId;+use ai_memory_store::{ObservationOrder, ObservationPage};+use askama::Template;+use axum::extract::{Path, Query, State};+use axum::http::StatusCode;+use axum::response::{Html, IntoResponse, Response};+use serde::Deserialize;++use super::api::{+ SESSION_OBSERVATIONS_DEFAULT_BODY_CHARS, SESSION_OBSERVATIONS_MAX_LIMIT, cap_body,+ owner_filter_for,+};+use crate::state::WebState;+use crate::templates::{SessionObservationRow, SessionView, humanize, project_href, session_href};++/// Observations per page when the request names no `limit`.+pub(crate) const DEFAULT_PAGE_SIZE: usize = 50;++/// Query string for the session view.+#[derive(Debug, Default, Deserialize)]+pub(crate) struct SessionQuery {+ /// Observations to skip, in capture order.+ #[serde(default)]+ pub offset: Option<usize>,+ /// Observations per page, clamped like the API's `limit`.+ #[serde(default)]+ pub limit: Option<usize>,+ /// 1-based position to jump to; overrides `offset` with the page that+ /// holds it.+ #[serde(default)]+ pub at: Option<usize>,+}++/// Handler for `GET /w/:workspace/:project/s/:session_id`.+pub(crate) async fn handler(+ State(state): State<Arc<WebState>>,+ viewer: Option<axum::Extension<ai_memory_core::AuthorizedViewer>>,+ actor: Option<axum::Extension<ai_memory_core::ActorContext>>,+ Path((workspace, project, raw_session)): Path<(String, String, String)>,+ Query(query): Query<SessionQuery>,+) -> Response {+ let viewer = viewer.map(|axum::Extension(viewer)| viewer.user());+ let scope = match super::resolve_read_scope(&state, viewer, &workspace, &project).await {+ Ok(scope) => scope,+ Err(refusal) => return super::page::refusal_response(&refusal),+ };+ let Ok(session_id) = raw_session.parse::<SessionId>() else {+ return (StatusCode::BAD_REQUEST, "invalid session id").into_response();+ };+ let internal = |error: ai_memory_store::StoreError| {+ tracing::error!(%error, "web session read failed");+ StatusCode::INTERNAL_SERVER_ERROR.into_response()+ };+ // Same predicate as the API: a session that left nothing in this project,+ // or that the owner filter hides, reads as not found.+ let session = match state+ .reader+ .session_summary_scoped(+ scope.workspace_id,+ scope.project_id,+ session_id,+ owner_filter_for(actor),+ )+ .await+ {+ Ok(Some(session)) => session,+ Ok(None) => return super::page::not_found_response(),+ Err(error) => return internal(error),+ };++ let limit = query+ .limit+ .unwrap_or(DEFAULT_PAGE_SIZE)+ .clamp(1, SESSION_OBSERVATIONS_MAX_LIMIT);+ let total = session.observation_count;+ let offset = match query.at {+ Some(at) => {+ let at = at.clamp(1, usize::try_from(total).unwrap_or(usize::MAX).max(1));+ (at - 1) / limit * limit+ }+ // Past the end is an empty page; clamping keeps the arithmetic below+ // from overflowing on a hostile offset.+ None => query+ .offset+ .unwrap_or(0)+ .min(usize::try_from(total).unwrap_or(usize::MAX)),+ };+ let page = match state+ .reader+ .session_observations_scoped(+ scope.workspace_id,+ scope.project_id,+ session_id,+ ObservationPage {+ limit,+ offset,+ order: ObservationOrder::Asc,+ kinds: None,+ query: None,+ },+ )+ .await+ {+ Ok(page) => page,+ Err(error) => return internal(error),+ };++ let base = session_href(&workspace, &project, &session_id.to_string());+ let total = page.total;+ let total_usize = usize::try_from(total).unwrap_or(usize::MAX);+ let shown = page.records.len();+ let rows: Vec<SessionObservationRow> = page+ .records+ .into_iter()+ .enumerate()+ .map(|(i, record)| SessionObservationRow {+ position: offset + i + 1,+ kind: record.kind,+ title: record.title,+ body: cap_body(&record.body, SESSION_OBSERVATIONS_DEFAULT_BODY_CHARS),+ created_at: record.created_at.clone(),+ created_relative: humanize(&record.created_at),+ })+ .collect();+ let page_href = |offset: usize| format!("{base}?offset={offset}&limit={limit}");+ let last_offset = total_usize.saturating_sub(1) / limit * limit;+ let view = SessionView {+ workspace: workspace.clone(),+ project: project.clone(),+ project_href: project_href(&workspace, &project),+ session_href: base.clone(),+ session_id: session_id.to_string(),+ agent_kind: session.agent_kind,+ started_at: session.started_at,+ ended_at: session.ended_at.unwrap_or_default(),+ total,+ limit,+ shown_start: if shown == 0 { 0 } else { offset + 1 },+ shown_end: offset + shown,+ elided_other_scope: page.elided_other_scope,+ first_href: if offset > 0 {+ page_href(0)+ } else {+ String::new()+ },+ prev_href: if offset > 0 {+ page_href(offset.saturating_sub(limit))+ } else {+ String::new()+ },+ next_href: if offset + shown < total_usize {+ page_href(offset + limit)+ } else {+ String::new()+ },+ last_href: if offset + shown < total_usize {+ page_href(last_offset)+ } else {+ String::new()+ },+ jump_value: offset + 1,+ observations: rows,+ };+ match view.render() {+ Ok(html) => Html(html).into_response(),+ Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),+ }+}diff --git a/crates/ai-memory-web/src/templates.rs b/crates/ai-memory-web/src/templates.rsindex 05e1a1e3..2c596e1c 100644--- a/crates/ai-memory-web/src/templates.rs+++ b/crates/ai-memory-web/src/templates.rs@@ -36,6 +36,34 @@ pub(crate) fn page_href(workspace: &str, project: &str, path: &str) -> String {)}+/// Build a page-history URL (`w/{ws}/{proj}/h/{path}`), percent-encoded.+#[must_use]+pub(crate) fn history_href(workspace: &str, project: &str, path: &str) -> String {+ format!(+ "{}/h/{}",+ project_href(workspace, project),+ encode_path(path)+ )+}++/// Build a session-timeline URL (`w/{ws}/{proj}/s/{id}`), percent-encoded.+#[must_use]+pub(crate) fn session_href(workspace: &str, project: &str, session_id: &str) -> String {+ format!(+ "{}/s/{}",+ project_href(workspace, project),+ encode_segment(session_id)+ )+}++/// The last eight characters of a UUID, for display. The ids here are+/// UUIDv7, whose leading characters are a shared timestamp prefix.+#[must_use]+pub(crate) fn short_id(id: &str) -> String {+ let skip = id.chars().count().saturating_sub(8);+ id.chars().skip(skip).collect()+}+fn encode_path(path: &str) -> String {path.split('/').map(encode_segment)@@ -226,6 +254,24 @@ pub(crate) struct ProjectView {pub mailbox_total: u64,/// `mailbox` lists fewer messages than are pending.pub mailbox_capped: bool,+ /// The project's most recent sessions the viewer may see.+ pub sessions: Vec<SessionRow>,+}++/// One recent session on the project page.+pub(crate) struct SessionRow {+ /// Link to the session timeline.+ pub href: String,+ /// Agent kind as stored (`claude-code`, `codex`, …).+ pub agent_kind: String,+ /// Last eight characters of the session id.+ pub short_id: String,+ /// Observations this session left in the project.+ pub observation_count: u64,+ /// Humanised start timestamp.+ pub started_relative: String,+ /// The session has not ended.+ pub open: bool,}/// View-model for a namespace (directory) listing — `GET@@ -280,6 +326,8 @@ pub(crate) struct PageView {pub supersedes_href: String,/// Rendered markdown body (HTML, trusted).pub body_html: String,+ /// Link to this page's version history.+ pub history_href: String,/// Username of the page's last author. Empty string when the page/// was authored anonymously / by root / pre-multi-user — the/// template uses the empty check to omit the "Last edited by"@@ -294,6 +342,171 @@ pub(crate) struct PageView {pub author_email: String,}+// ---------------------------------------------------------------------------+// history.html+// ---------------------------------------------------------------------------++/// One stored version in the history list.+pub(crate) struct HistoryVersionRow {+ /// Full version id, submitted by the compare form.+ pub id: String,+ /// Last eight characters of the id.+ pub short_id: String,+ /// Short id of the version this one replaced, or empty.+ pub supersedes_short: String,+ /// The live version of the path.+ pub is_latest: bool,+ /// Title stored on this version.+ pub title: String,+ /// ISO-8601 write instant.+ pub created_at: String,+ /// Humanised write instant.+ pub created_relative: String,+ /// Username of an attributed write, or empty.+ pub author: String,+ /// Body length in characters.+ pub body_chars: u64,+ /// Selected as the older side of the diff.+ pub is_from: bool,+ /// Selected as the newer side of the diff.+ pub is_to: bool,+ /// Link diffing this version against the one it replaced, or empty.+ pub compare_href: String,+}++/// One diff line; `text` is untrusted page content and is escaped.+pub(crate) struct HistoryDiffLine {+ /// `+`, `-` or a space.+ pub sign: String,+ /// The line itself.+ pub text: String,+}++/// One diff hunk.+pub(crate) struct HistoryHunk {+ /// `@@ -a,b +c,d @@`.+ pub header: String,+ /// The hunk's lines.+ pub lines: Vec<HistoryDiffLine>,+}++/// View-model for `GET /w/:workspace/:project/h/*path`.+#[derive(Template)]+#[template(path = "history.html")]+pub(crate) struct HistoryView {+ /// Workspace name.+ pub workspace: String,+ /// Project name.+ pub project: String,+ /// Link to the project.+ pub project_href: String,+ /// Link to the live page.+ pub page_href: String,+ /// This route, without a query string (the compare form's action).+ pub history_href: String,+ /// Wiki path.+ pub path: String,+ /// Every version stored at the path.+ pub total: u64,+ /// 1-based position of the first listed version (0 when none).+ pub shown_start: usize,+ /// 1-based position of the last listed version.+ pub shown_end: usize,+ /// Versions per listing page.+ pub limit: usize,+ /// Link to newer versions, or empty.+ pub newer_href: String,+ /// Link to older versions, or empty.+ pub older_href: String,+ /// The listed versions, newest first.+ pub versions: Vec<HistoryVersionRow>,+ /// Short id of the older side, or empty when the diff starts from nothing.+ pub from_short: String,+ /// Write instant of the older side, or empty.+ pub from_created: String,+ /// Title of the older side, or empty.+ pub from_title: String,+ /// Short id of the newer side.+ pub to_short: String,+ /// Write instant of the newer side.+ pub to_created: String,+ /// Title of the newer side.+ pub to_title: String,+ /// The two bodies are identical.+ pub same: bool,+ /// Why the diff was refused, or empty.+ pub too_large: String,+ /// The output line cap cut the diff short.+ pub truncated: bool,+ /// Diff hunks.+ pub hunks: Vec<HistoryHunk>,+}++// ---------------------------------------------------------------------------+// session.html+// ---------------------------------------------------------------------------++/// One observation on the session timeline; every text field is untrusted+/// captured text and is escaped by the template.+pub(crate) struct SessionObservationRow {+ /// 1-based position in capture order within this project.+ pub position: usize,+ /// Observation kind.+ pub kind: String,+ /// Observation title.+ pub title: String,+ /// Body, capped like the API's default `body_max_chars`.+ pub body: String,+ /// ISO-8601 capture instant.+ pub created_at: String,+ /// Humanised capture instant.+ pub created_relative: String,+}++/// View-model for `GET /w/:workspace/:project/s/:session_id`.+#[derive(Template)]+#[template(path = "session.html")]+pub(crate) struct SessionView {+ /// Workspace name.+ pub workspace: String,+ /// Project name.+ pub project: String,+ /// Link to the project.+ pub project_href: String,+ /// This route, without a query string (the jump form's action).+ pub session_href: String,+ /// Session id.+ pub session_id: String,+ /// Agent kind as stored.+ pub agent_kind: String,+ /// ISO-8601 start.+ pub started_at: String,+ /// ISO-8601 end, or empty while open.+ pub ended_at: String,+ /// Observations in this project.+ pub total: u64,+ /// Observations per page.+ pub limit: usize,+ /// 1-based position of the first shown observation (0 when none).+ pub shown_start: usize,+ /// 1-based position of the last shown observation.+ pub shown_end: usize,+ /// Rows the session left in other projects (not shown here).+ pub elided_other_scope: u64,+ /// Link to the first page, or empty on it.+ pub first_href: String,+ /// Link to the previous page, or empty.+ pub prev_href: String,+ /// Link to the next page, or empty.+ pub next_href: String,+ /// Link to the last page, or empty on it.+ pub last_href: String,+ /// Prefilled value of the jump field.+ pub jump_value: usize,+ /// This page's observations.+ pub observations: Vec<SessionObservationRow>,+}+// ---------------------------------------------------------------------------// search.html// ---------------------------------------------------------------------------diff --git a/crates/ai-memory-web/static/tailwind.css b/crates/ai-memory-web/static/tailwind.cssindex 0c5956e1..7f67edbf 100644--- a/crates/ai-memory-web/static/tailwind.css+++ b/crates/ai-memory-web/static/tailwind.css@@ -1 +1 @@-*,:after,:before{--tw-border-spacing-x:0;--tw-border-spacing-y:0;--tw-translate-x:0;--tw-translate-y:0;--tw-rotate:0;--tw-skew-x:0;--tw-skew-y:0;--tw-scale-x:1;--tw-scale-y:1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness:proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:rgba(59,130,246,.5);--tw-ring-offset-shadow:0 0 #0000;--tw-ring-shadow:0 0 #0000;--tw-shadow:0 0 #0000;--tw-shadow-colored:0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x:0;--tw-border-spacing-y:0;--tw-translate-x:0;--tw-translate-y:0;--tw-rotate:0;--tw-skew-x:0;--tw-skew-y:0;--tw-scale-x:1;--tw-scale-y:1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness:proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:rgba(59,130,246,.5);--tw-ring-offset-shadow:0 0 #0000;--tw-ring-shadow:0 0 #0000;--tw-shadow:0 0 #0000;--tw-shadow-colored:0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }/*! tailwindcss v3.4.17 | MIT License | https://tailwindcss.com*/*,:after,:before{border:0 solid #e5e7eb;box-sizing:border-box}:after,:before{--tw-content:""}:host,html{line-height:1.5;-webkit-text-size-adjust:100%;font-family:ui-sans-serif,system-ui,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;font-feature-settings:normal;font-variation-settings:normal;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-tap-highlight-color:transparent}body{line-height:inherit;margin:0}hr{border-top-width:1px;color:inherit;height:0}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,pre,samp{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-size:1em;font-variation-settings:normal}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{border-collapse:collapse;border-color:inherit;text-indent:0}button,input,optgroup,select,textarea{color:inherit;font-family:inherit;font-feature-settings:inherit;font-size:100%;font-variation-settings:inherit;font-weight:inherit;letter-spacing:inherit;line-height:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dd,dl,figure,h1,h2,h3,h4,h5,h6,hr,p,pre{margin:0}fieldset{margin:0}fieldset,legend{padding:0}menu,ol,ul{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{color:#9ca3af;opacity:1}input::placeholder,textarea::placeholder{color:#9ca3af;opacity:1}[role=button],button{cursor:pointer}:disabled{cursor:default}audio,canvas,embed,iframe,img,object,svg,video{display:block;vertical-align:middle}img,video{height:auto;max-width:100%}[hidden]:where(:not([hidden=until-found])){display:none}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.sticky{position:sticky}.inset-0{inset:0}.right-2{right:.5rem}.top-0{top:0}.top-2{top:.5rem}.z-10{z-index:10}.z-50{z-index:50}.mx-auto{margin-left:auto;margin-right:auto}.mb-1{margin-bottom:.25rem}.mb-2{margin-bottom:.5rem}.mb-3{margin-bottom:.75rem}.mb-4{margin-bottom:1rem}.mb-6{margin-bottom:1.5rem}.mb-8{margin-bottom:2rem}.ml-1{margin-left:.25rem}.mt-1{margin-top:.25rem}.mt-16{margin-top:4rem}.mt-2{margin-top:.5rem}.mt-3{margin-top:.75rem}.mt-4{margin-top:1rem}.mt-5{margin-top:1.25rem}.mt-6{margin-top:1.5rem}.block{display:block}.inline-block{display:inline-block}.flex{display:flex}.inline-flex{display:inline-flex}.grid{display:grid}.hidden{display:none}.h-14{height:3.5rem}.h-4{height:1rem}.h-5{height:1.25rem}.h-7{height:1.75rem}.h-full{height:100%}.max-h-96{max-height:24rem}.min-h-full{min-height:100%}.w-4{width:1rem}.w-40{width:10rem}.w-auto{width:auto}.w-full{width:100%}.min-w-0{min-width:0}.max-w-3xl{max-width:48rem}.max-w-7xl{max-width:80rem}.max-w-md{max-width:28rem}.max-w-xl{max-width:36rem}.max-w-xs{max-width:20rem}.flex-1{flex:1 1 0%}.shrink-0{flex-shrink:0}.cursor-pointer{cursor:pointer}.select-none{-webkit-user-select:none;-moz-user-select:none;user-select:none}.list-inside{list-style-position:inside}.list-decimal{list-style-type:decimal}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-start{align-items:flex-start}.items-end{align-items:flex-end}.items-center{align-items:center}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.gap-1{gap:.25rem}.gap-2{gap:.5rem}.gap-3{gap:.75rem}.gap-4{gap:1rem}.gap-8{gap:2rem}.gap-x-3{-moz-column-gap:.75rem;column-gap:.75rem}.gap-y-1{row-gap:.25rem}.space-y-0\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse:0;margin-bottom:calc(.125rem*var(--tw-space-y-reverse));margin-top:calc(.125rem*(1 - var(--tw-space-y-reverse)))}.space-y-1>:not([hidden])~:not([hidden]){--tw-space-y-reverse:0;margin-bottom:calc(.25rem*var(--tw-space-y-reverse));margin-top:calc(.25rem*(1 - var(--tw-space-y-reverse)))}.space-y-3>:not([hidden])~:not([hidden]){--tw-space-y-reverse:0;margin-bottom:calc(.75rem*var(--tw-space-y-reverse));margin-top:calc(.75rem*(1 - var(--tw-space-y-reverse)))}.space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse:0;margin-bottom:calc(1rem*var(--tw-space-y-reverse));margin-top:calc(1rem*(1 - var(--tw-space-y-reverse)))}.divide-y>:not([hidden])~:not([hidden]){--tw-divide-y-reverse:0;border-bottom-width:calc(1px*var(--tw-divide-y-reverse));border-top-width:calc(1px*(1 - var(--tw-divide-y-reverse)))}.divide-slate-100>:not([hidden])~:not([hidden]){--tw-divide-opacity:1;border-color:rgb(241 245 249/var(--tw-divide-opacity,1))}.overflow-auto{overflow:auto}.truncate{overflow:hidden;text-overflow:ellipsis}.truncate,.whitespace-nowrap{white-space:nowrap}.whitespace-pre-wrap{white-space:pre-wrap}.break-words{overflow-wrap:break-word}.break-all{word-break:break-all}.rounded{border-radius:.25rem}.rounded-lg{border-radius:.5rem}.rounded-md{border-radius:.375rem}.border{border-width:1px}.border-b{border-bottom-width:1px}.border-t{border-top-width:1px}.border-dashed{border-style:dashed}.border-amber-200{--tw-border-opacity:1;border-color:rgb(253 230 138/var(--tw-border-opacity,1))}.border-blue-200{--tw-border-opacity:1;border-color:rgb(191 219 254/var(--tw-border-opacity,1))}.border-slate-100{--tw-border-opacity:1;border-color:rgb(241 245 249/var(--tw-border-opacity,1))}.border-slate-200{--tw-border-opacity:1;border-color:rgb(226 232 240/var(--tw-border-opacity,1))}.border-slate-300{--tw-border-opacity:1;border-color:rgb(203 213 225/var(--tw-border-opacity,1))}.bg-amber-100{--tw-bg-opacity:1;background-color:rgb(254 243 199/var(--tw-bg-opacity,1))}.bg-amber-50{--tw-bg-opacity:1;background-color:rgb(255 251 235/var(--tw-bg-opacity,1))}.bg-blue-50{--tw-bg-opacity:1;background-color:rgb(239 246 255/var(--tw-bg-opacity,1))}.bg-blue-600{--tw-bg-opacity:1;background-color:rgb(37 99 235/var(--tw-bg-opacity,1))}.bg-green-50{--tw-bg-opacity:1;background-color:rgb(240 253 244/var(--tw-bg-opacity,1))}.bg-red-50{--tw-bg-opacity:1;background-color:rgb(254 242 242/var(--tw-bg-opacity,1))}.bg-red-600{--tw-bg-opacity:1;background-color:rgb(220 38 38/var(--tw-bg-opacity,1))}.bg-slate-100{--tw-bg-opacity:1;background-color:rgb(241 245 249/var(--tw-bg-opacity,1))}.bg-slate-50{--tw-bg-opacity:1;background-color:rgb(248 250 252/var(--tw-bg-opacity,1))}.bg-slate-900{--tw-bg-opacity:1;background-color:rgb(15 23 42/var(--tw-bg-opacity,1))}.bg-slate-900\/50{background-color:rgba(15,23,42,.5)}.bg-white{--tw-bg-opacity:1;background-color:rgb(255 255 255/var(--tw-bg-opacity,1))}.p-1{padding:.25rem}.p-12{padding:3rem}.p-3{padding:.75rem}.p-4{padding:1rem}.p-5{padding:1.25rem}.p-6{padding:1.5rem}.px-1{padding-left:.25rem;padding-right:.25rem}.px-1\.5{padding-left:.375rem;padding-right:.375rem}.px-2{padding-left:.5rem;padding-right:.5rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.py-0\.5{padding-bottom:.125rem;padding-top:.125rem}.py-1{padding-bottom:.25rem;padding-top:.25rem}.py-1\.5{padding-bottom:.375rem;padding-top:.375rem}.py-2{padding-bottom:.5rem;padding-top:.5rem}.py-20{padding-bottom:5rem;padding-top:5rem}.py-3{padding-bottom:.75rem;padding-top:.75rem}.py-4{padding-bottom:1rem;padding-top:1rem}.py-8{padding-bottom:2rem;padding-top:2rem}.pl-2{padding-left:.5rem}.pr-10{padding-right:2.5rem}.text-center{text-align:center}.align-middle{vertical-align:middle}.font-mono{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace}.text-2xl{font-size:1.5rem;line-height:2rem}.text-3xl{font-size:1.875rem;line-height:2.25rem}.text-6xl{font-size:3.75rem;line-height:1}.text-base{font-size:1rem;line-height:1.5rem}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xs{font-size:.75rem;line-height:1rem}.font-bold{font-weight:700}.font-medium{font-weight:500}.font-semibold{font-weight:600}.uppercase{text-transform:uppercase}.leading-relaxed{line-height:1.625}.tracking-wide{letter-spacing:.025em}.text-amber-700{--tw-text-opacity:1;color:rgb(180 83 9/var(--tw-text-opacity,1))}.text-amber-800{--tw-text-opacity:1;color:rgb(146 64 14/var(--tw-text-opacity,1))}.text-amber-900{--tw-text-opacity:1;color:rgb(120 53 15/var(--tw-text-opacity,1))}.text-blue-600{--tw-text-opacity:1;color:rgb(37 99 235/var(--tw-text-opacity,1))}.text-blue-700{--tw-text-opacity:1;color:rgb(29 78 216/var(--tw-text-opacity,1))}.text-green-800{--tw-text-opacity:1;color:rgb(22 101 52/var(--tw-text-opacity,1))}.text-red-800{--tw-text-opacity:1;color:rgb(153 27 27/var(--tw-text-opacity,1))}.text-slate-200{--tw-text-opacity:1;color:rgb(226 232 240/var(--tw-text-opacity,1))}.text-slate-400{--tw-text-opacity:1;color:rgb(148 163 184/var(--tw-text-opacity,1))}.text-slate-500{--tw-text-opacity:1;color:rgb(100 116 139/var(--tw-text-opacity,1))}.text-slate-600{--tw-text-opacity:1;color:rgb(71 85 105/var(--tw-text-opacity,1))}.text-slate-700{--tw-text-opacity:1;color:rgb(51 65 85/var(--tw-text-opacity,1))}.text-slate-800{--tw-text-opacity:1;color:rgb(30 41 59/var(--tw-text-opacity,1))}.text-slate-900{--tw-text-opacity:1;color:rgb(15 23 42/var(--tw-text-opacity,1))}.text-white{--tw-text-opacity:1;color:rgb(255 255 255/var(--tw-text-opacity,1))}.underline{text-decoration-line:underline}.placeholder-slate-400::-moz-placeholder{--tw-placeholder-opacity:1;color:rgb(148 163 184/var(--tw-placeholder-opacity,1))}.placeholder-slate-400::placeholder{--tw-placeholder-opacity:1;color:rgb(148 163 184/var(--tw-placeholder-opacity,1))}.shadow-xl{--tw-shadow:0 20px 25px -5px rgba(0,0,0,.1),0 8px 10px -6px rgba(0,0,0,.1);--tw-shadow-colored:0 20px 25px -5px var(--tw-shadow-color),0 8px 10px -6px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow,0 0 #0000),var(--tw-ring-shadow,0 0 #0000),var(--tw-shadow)}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.transition-all{transition-duration:.15s;transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1)}.hover\:border-blue-400:hover{--tw-border-opacity:1;border-color:rgb(96 165 250/var(--tw-border-opacity,1))}.hover\:bg-amber-100:hover{--tw-bg-opacity:1;background-color:rgb(254 243 199/var(--tw-bg-opacity,1))}.hover\:bg-blue-700:hover{--tw-bg-opacity:1;background-color:rgb(29 78 216/var(--tw-bg-opacity,1))}.hover\:bg-red-700:hover{--tw-bg-opacity:1;background-color:rgb(185 28 28/var(--tw-bg-opacity,1))}.hover\:bg-slate-700:hover{--tw-bg-opacity:1;background-color:rgb(51 65 85/var(--tw-bg-opacity,1))}.hover\:text-amber-950:hover{--tw-text-opacity:1;color:rgb(69 26 3/var(--tw-text-opacity,1))}.hover\:text-blue-600:hover{--tw-text-opacity:1;color:rgb(37 99 235/var(--tw-text-opacity,1))}.hover\:underline:hover{text-decoration-line:underline}.hover\:shadow-sm:hover{--tw-shadow:0 1px 2px 0 rgba(0,0,0,.05);--tw-shadow-colored:0 1px 2px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow,0 0 #0000),var(--tw-ring-shadow,0 0 #0000),var(--tw-shadow)}.focus\:outline-none:focus{outline:2px solid transparent;outline-offset:2px}.focus\:ring-2:focus{--tw-ring-offset-shadow:var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow:var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow,0 0 #0000)}.focus\:ring-blue-500:focus{--tw-ring-opacity:1;--tw-ring-color:rgb(59 130 246/var(--tw-ring-opacity,1))}.disabled\:opacity-50:disabled{opacity:.5}@media (min-width:640px){.sm\:inline{display:inline}.sm\:w-64{width:16rem}.sm\:px-6{padding-left:1.5rem;padding-right:1.5rem}}@media (min-width:768px){.md\:w-56{width:14rem}.md\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.md\:flex-row{flex-direction:row}}@media (min-width:1024px){.lg\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.lg\:px-8{padding-left:2rem;padding-right:2rem}}@media (prefers-color-scheme:dark){.dark\:divide-slate-800>:not([hidden])~:not([hidden]){--tw-divide-opacity:1;border-color:rgb(30 41 59/var(--tw-divide-opacity,1))}.dark\:border-amber-800{--tw-border-opacity:1;border-color:rgb(146 64 14/var(--tw-border-opacity,1))}.dark\:border-amber-900\/50{border-color:rgba(120,53,15,.5)}.dark\:border-blue-800{--tw-border-opacity:1;border-color:rgb(30 64 175/var(--tw-border-opacity,1))}.dark\:border-slate-600{--tw-border-opacity:1;border-color:rgb(71 85 105/var(--tw-border-opacity,1))}.dark\:border-slate-700{--tw-border-opacity:1;border-color:rgb(51 65 85/var(--tw-border-opacity,1))}.dark\:border-slate-800{--tw-border-opacity:1;border-color:rgb(30 41 59/var(--tw-border-opacity,1))}.dark\:bg-amber-900{--tw-bg-opacity:1;background-color:rgb(120 53 15/var(--tw-bg-opacity,1))}.dark\:bg-amber-900\/40{background-color:rgba(120,53,15,.4)}.dark\:bg-amber-950{--tw-bg-opacity:1;background-color:rgb(69 26 3/var(--tw-bg-opacity,1))}.dark\:bg-amber-950\/30{background-color:rgba(69,26,3,.3)}.dark\:bg-blue-950{--tw-bg-opacity:1;background-color:rgb(23 37 84/var(--tw-bg-opacity,1))}.dark\:bg-slate-100{--tw-bg-opacity:1;background-color:rgb(241 245 249/var(--tw-bg-opacity,1))}.dark\:bg-slate-800{--tw-bg-opacity:1;background-color:rgb(30 41 59/var(--tw-bg-opacity,1))}.dark\:bg-slate-800\/60{background-color:rgba(30,41,59,.6)}.dark\:bg-slate-900{--tw-bg-opacity:1;background-color:rgb(15 23 42/var(--tw-bg-opacity,1))}.dark\:bg-slate-950{--tw-bg-opacity:1;background-color:rgb(2 6 23/var(--tw-bg-opacity,1))}.dark\:text-amber-200{--tw-text-opacity:1;color:rgb(253 230 138/var(--tw-text-opacity,1))}.dark\:text-amber-300{--tw-text-opacity:1;color:rgb(252 211 77/var(--tw-text-opacity,1))}.dark\:text-amber-300\/90{color:rgba(252,211,77,.9)}.dark\:text-blue-300{--tw-text-opacity:1;color:rgb(147 197 253/var(--tw-text-opacity,1))}.dark\:text-blue-400{--tw-text-opacity:1;color:rgb(96 165 250/var(--tw-text-opacity,1))}.dark\:text-slate-100{--tw-text-opacity:1;color:rgb(241 245 249/var(--tw-text-opacity,1))}.dark\:text-slate-200{--tw-text-opacity:1;color:rgb(226 232 240/var(--tw-text-opacity,1))}.dark\:text-slate-300{--tw-text-opacity:1;color:rgb(203 213 225/var(--tw-text-opacity,1))}.dark\:text-slate-400{--tw-text-opacity:1;color:rgb(148 163 184/var(--tw-text-opacity,1))}.dark\:text-slate-500{--tw-text-opacity:1;color:rgb(100 116 139/var(--tw-text-opacity,1))}.dark\:text-slate-600{--tw-text-opacity:1;color:rgb(71 85 105/var(--tw-text-opacity,1))}.dark\:text-slate-800{--tw-text-opacity:1;color:rgb(30 41 59/var(--tw-text-opacity,1))}.dark\:text-slate-900{--tw-text-opacity:1;color:rgb(15 23 42/var(--tw-text-opacity,1))}.dark\:hover\:border-blue-600:hover{--tw-border-opacity:1;border-color:rgb(37 99 235/var(--tw-border-opacity,1))}.dark\:hover\:bg-amber-900\/40:hover{background-color:rgba(120,53,15,.4)}.dark\:hover\:bg-slate-300:hover{--tw-bg-opacity:1;background-color:rgb(203 213 225/var(--tw-bg-opacity,1))}.dark\:hover\:text-amber-100:hover{--tw-text-opacity:1;color:rgb(254 243 199/var(--tw-text-opacity,1))}.dark\:hover\:text-blue-400:hover{--tw-text-opacity:1;color:rgb(96 165 250/var(--tw-text-opacity,1))}}.\[\&_a\]\:text-blue-600 a{--tw-text-opacity:1;color:rgb(37 99 235/var(--tw-text-opacity,1))}.\[\&_a\]\:underline a{text-decoration-line:underline}@media (prefers-color-scheme:dark){.\[\&_a\]\:dark\:text-blue-400 a{--tw-text-opacity:1;color:rgb(96 165 250/var(--tw-text-opacity,1))}}.\[\&_blockquote\]\:my-3 blockquote{margin-bottom:.75rem;margin-top:.75rem}.\[\&_blockquote\]\:border-l-4 blockquote{border-left-width:4px}.\[\&_blockquote\]\:border-slate-300 blockquote{--tw-border-opacity:1;border-color:rgb(203 213 225/var(--tw-border-opacity,1))}.\[\&_blockquote\]\:pl-4 blockquote{padding-left:1rem}.\[\&_blockquote\]\:italic blockquote{font-style:italic}.\[\&_blockquote\]\:text-slate-600 blockquote{--tw-text-opacity:1;color:rgb(71 85 105/var(--tw-text-opacity,1))}@media (prefers-color-scheme:dark){.\[\&_blockquote\]\:dark\:border-slate-700 blockquote{--tw-border-opacity:1;border-color:rgb(51 65 85/var(--tw-border-opacity,1))}.\[\&_blockquote\]\:dark\:text-slate-400 blockquote{--tw-text-opacity:1;color:rgb(148 163 184/var(--tw-text-opacity,1))}}.\[\&_code\]\:rounded code{border-radius:.25rem}.\[\&_code\]\:bg-slate-100 code{--tw-bg-opacity:1;background-color:rgb(241 245 249/var(--tw-bg-opacity,1))}.\[\&_code\]\:px-1 code{padding-left:.25rem;padding-right:.25rem}.\[\&_code\]\:py-0\.5 code{padding-bottom:.125rem;padding-top:.125rem}.\[\&_code\]\:font-mono code{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace}.\[\&_code\]\:text-sm code{font-size:.875rem;line-height:1.25rem}@media (prefers-color-scheme:dark){.\[\&_code\]\:dark\:bg-slate-800 code{--tw-bg-opacity:1;background-color:rgb(30 41 59/var(--tw-bg-opacity,1))}}.\[\&_h1\]\:mb-3 h1{margin-bottom:.75rem}.\[\&_h1\]\:mt-6 h1{margin-top:1.5rem}.\[\&_h1\]\:text-3xl h1{font-size:1.875rem;line-height:2.25rem}.\[\&_h1\]\:font-bold h1{font-weight:700}.\[\&_h2\]\:mb-2 h2{margin-bottom:.5rem}.\[\&_h2\]\:mt-5 h2{margin-top:1.25rem}.\[\&_h2\]\:text-2xl h2{font-size:1.5rem;line-height:2rem}.\[\&_h2\]\:font-semibold h2{font-weight:600}.\[\&_h3\]\:mb-2 h3{margin-bottom:.5rem}.\[\&_h3\]\:mt-4 h3{margin-top:1rem}.\[\&_h3\]\:text-xl h3{font-size:1.25rem;line-height:1.75rem}.\[\&_h3\]\:font-semibold h3{font-weight:600}.\[\&_h4\]\:mb-1 h4{margin-bottom:.25rem}.\[\&_h4\]\:mt-3 h4{margin-top:.75rem}.\[\&_h4\]\:text-lg h4{font-size:1.125rem;line-height:1.75rem}.\[\&_h4\]\:font-semibold h4{font-weight:600}.\[\&_hr\]\:my-6 hr{margin-bottom:1.5rem;margin-top:1.5rem}.\[\&_hr\]\:border-slate-200 hr{--tw-border-opacity:1;border-color:rgb(226 232 240/var(--tw-border-opacity,1))}@media (prefers-color-scheme:dark){.\[\&_hr\]\:dark\:border-slate-800 hr{--tw-border-opacity:1;border-color:rgb(30 41 59/var(--tw-border-opacity,1))}}.\[\&_li\]\:my-1 li{margin-bottom:.25rem;margin-top:.25rem}.\[\&_mark\]\:bg-yellow-200 mark{--tw-bg-opacity:1;background-color:rgb(254 240 138/var(--tw-bg-opacity,1))}.\[\&_mark\]\:px-0\.5 mark{padding-left:.125rem;padding-right:.125rem}@media (prefers-color-scheme:dark){.\[\&_mark\]\:dark\:bg-yellow-800 mark{--tw-bg-opacity:1;background-color:rgb(133 77 14/var(--tw-bg-opacity,1))}}.\[\&_ol\]\:my-3 ol{margin-bottom:.75rem;margin-top:.75rem}.\[\&_ol\]\:list-decimal ol{list-style-type:decimal}.\[\&_ol\]\:pl-5 ol{padding-left:1.25rem}.\[\&_p\]\:my-3 p{margin-bottom:.75rem;margin-top:.75rem}.\[\&_p\]\:leading-relaxed p{line-height:1.625}.\[\&_pre\]\:my-3 pre{margin-bottom:.75rem;margin-top:.75rem}.\[\&_pre\]\:overflow-x-auto pre{overflow-x:auto}.\[\&_pre\]\:rounded pre{border-radius:.25rem}.\[\&_pre\]\:bg-slate-100 pre{--tw-bg-opacity:1;background-color:rgb(241 245 249/var(--tw-bg-opacity,1))}.\[\&_pre\]\:p-3 pre{padding:.75rem}@media (prefers-color-scheme:dark){.\[\&_pre\]\:dark\:bg-slate-800 pre{--tw-bg-opacity:1;background-color:rgb(30 41 59/var(--tw-bg-opacity,1))}}.\[\&_pre_code\]\:bg-transparent pre code{background-color:transparent}.\[\&_pre_code\]\:p-0 pre code{padding:0}.\[\&_table\]\:my-3 table{margin-bottom:.75rem;margin-top:.75rem}.\[\&_table\]\:w-full table{width:100%}.\[\&_table\]\:border-collapse table{border-collapse:collapse}.\[\&_td\]\:border td{border-width:1px}.\[\&_td\]\:border-slate-300 td{--tw-border-opacity:1;border-color:rgb(203 213 225/var(--tw-border-opacity,1))}.\[\&_td\]\:px-3 td{padding-left:.75rem;padding-right:.75rem}.\[\&_td\]\:py-2 td{padding-bottom:.5rem;padding-top:.5rem}@media (prefers-color-scheme:dark){.\[\&_td\]\:dark\:border-slate-700 td{--tw-border-opacity:1;border-color:rgb(51 65 85/var(--tw-border-opacity,1))}}.\[\&_th\]\:border th{border-width:1px}.\[\&_th\]\:border-slate-300 th{--tw-border-opacity:1;border-color:rgb(203 213 225/var(--tw-border-opacity,1))}.\[\&_th\]\:bg-slate-50 th{--tw-bg-opacity:1;background-color:rgb(248 250 252/var(--tw-bg-opacity,1))}.\[\&_th\]\:px-3 th{padding-left:.75rem;padding-right:.75rem}.\[\&_th\]\:py-2 th{padding-bottom:.5rem;padding-top:.5rem}.\[\&_th\]\:text-left th{text-align:left}@media (prefers-color-scheme:dark){.\[\&_th\]\:dark\:border-slate-700 th{--tw-border-opacity:1;border-color:rgb(51 65 85/var(--tw-border-opacity,1))}.\[\&_th\]\:dark\:bg-slate-800 th{--tw-bg-opacity:1;background-color:rgb(30 41 59/var(--tw-bg-opacity,1))}}.\[\&_ul\]\:my-3 ul{margin-bottom:.75rem;margin-top:.75rem}.\[\&_ul\]\:list-disc ul{list-style-type:disc}.\[\&_ul\]\:pl-5 ul{padding-left:1.25rem}\ No newline at end of file+*,:after,:before{--tw-border-spacing-x:0;--tw-border-spacing-y:0;--tw-translate-x:0;--tw-translate-y:0;--tw-rotate:0;--tw-skew-x:0;--tw-skew-y:0;--tw-scale-x:1;--tw-scale-y:1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness:proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:rgba(59,130,246,.5);--tw-ring-offset-shadow:0 0 #0000;--tw-ring-shadow:0 0 #0000;--tw-shadow:0 0 #0000;--tw-shadow-colored:0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x:0;--tw-border-spacing-y:0;--tw-translate-x:0;--tw-translate-y:0;--tw-rotate:0;--tw-skew-x:0;--tw-skew-y:0;--tw-scale-x:1;--tw-scale-y:1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness:proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:rgba(59,130,246,.5);--tw-ring-offset-shadow:0 0 #0000;--tw-ring-shadow:0 0 #0000;--tw-shadow:0 0 #0000;--tw-shadow-colored:0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }/*! tailwindcss v3.4.17 | MIT License | https://tailwindcss.com*/*,:after,:before{border:0 solid #e5e7eb;box-sizing:border-box}:after,:before{--tw-content:""}:host,html{line-height:1.5;-webkit-text-size-adjust:100%;font-family:ui-sans-serif,system-ui,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;font-feature-settings:normal;font-variation-settings:normal;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-tap-highlight-color:transparent}body{line-height:inherit;margin:0}hr{border-top-width:1px;color:inherit;height:0}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,pre,samp{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-size:1em;font-variation-settings:normal}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{border-collapse:collapse;border-color:inherit;text-indent:0}button,input,optgroup,select,textarea{color:inherit;font-family:inherit;font-feature-settings:inherit;font-size:100%;font-variation-settings:inherit;font-weight:inherit;letter-spacing:inherit;line-height:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dd,dl,figure,h1,h2,h3,h4,h5,h6,hr,p,pre{margin:0}fieldset{margin:0}fieldset,legend{padding:0}menu,ol,ul{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{color:#9ca3af;opacity:1}input::placeholder,textarea::placeholder{color:#9ca3af;opacity:1}[role=button],button{cursor:pointer}:disabled{cursor:default}audio,canvas,embed,iframe,img,object,svg,video{display:block;vertical-align:middle}img,video{height:auto;max-width:100%}[hidden]:where(:not([hidden=until-found])){display:none}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.sticky{position:sticky}.inset-0{inset:0}.right-2{right:.5rem}.top-0{top:0}.top-14{top:3.5rem}.top-2{top:.5rem}.z-10{z-index:10}.z-50{z-index:50}.mx-auto{margin-left:auto;margin-right:auto}.mb-1{margin-bottom:.25rem}.mb-10{margin-bottom:2.5rem}.mb-2{margin-bottom:.5rem}.mb-3{margin-bottom:.75rem}.mb-4{margin-bottom:1rem}.mb-6{margin-bottom:1.5rem}.mb-8{margin-bottom:2rem}.ml-1{margin-left:.25rem}.ml-auto{margin-left:auto}.mt-1{margin-top:.25rem}.mt-16{margin-top:4rem}.mt-2{margin-top:.5rem}.mt-3{margin-top:.75rem}.mt-4{margin-top:1rem}.mt-5{margin-top:1.25rem}.mt-6{margin-top:1.5rem}.block{display:block}.inline-block{display:inline-block}.flex{display:flex}.inline-flex{display:inline-flex}.table{display:table}.grid{display:grid}.hidden{display:none}.h-14{height:3.5rem}.h-4{height:1rem}.h-5{height:1.25rem}.h-7{height:1.75rem}.h-full{height:100%}.max-h-96{max-height:24rem}.min-h-full{min-height:100%}.w-20{width:5rem}.w-32{width:8rem}.w-4{width:1rem}.w-40{width:10rem}.w-auto{width:auto}.w-full{width:100%}.min-w-0{min-width:0}.max-w-3xl{max-width:48rem}.max-w-7xl{max-width:80rem}.max-w-md{max-width:28rem}.max-w-xl{max-width:36rem}.max-w-xs{max-width:20rem}.flex-1{flex:1 1 0%}.shrink-0{flex-shrink:0}.cursor-pointer{cursor:pointer}.select-none{-webkit-user-select:none;-moz-user-select:none;user-select:none}.list-inside{list-style-position:inside}.list-decimal{list-style-type:decimal}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-start{align-items:flex-start}.items-end{align-items:flex-end}.items-center{align-items:center}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.gap-1{gap:.25rem}.gap-2{gap:.5rem}.gap-3{gap:.75rem}.gap-4{gap:1rem}.gap-8{gap:2rem}.gap-x-3{-moz-column-gap:.75rem;column-gap:.75rem}.gap-y-1{row-gap:.25rem}.space-y-0\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse:0;margin-bottom:calc(.125rem*var(--tw-space-y-reverse));margin-top:calc(.125rem*(1 - var(--tw-space-y-reverse)))}.space-y-1>:not([hidden])~:not([hidden]){--tw-space-y-reverse:0;margin-bottom:calc(.25rem*var(--tw-space-y-reverse));margin-top:calc(.25rem*(1 - var(--tw-space-y-reverse)))}.space-y-3>:not([hidden])~:not([hidden]){--tw-space-y-reverse:0;margin-bottom:calc(.75rem*var(--tw-space-y-reverse));margin-top:calc(.75rem*(1 - var(--tw-space-y-reverse)))}.space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse:0;margin-bottom:calc(1rem*var(--tw-space-y-reverse));margin-top:calc(1rem*(1 - var(--tw-space-y-reverse)))}.divide-y>:not([hidden])~:not([hidden]){--tw-divide-y-reverse:0;border-bottom-width:calc(1px*var(--tw-divide-y-reverse));border-top-width:calc(1px*(1 - var(--tw-divide-y-reverse)))}.divide-slate-100>:not([hidden])~:not([hidden]){--tw-divide-opacity:1;border-color:rgb(241 245 249/var(--tw-divide-opacity,1))}.overflow-auto{overflow:auto}.overflow-x-auto{overflow-x:auto}.truncate{overflow:hidden;text-overflow:ellipsis}.truncate,.whitespace-nowrap{white-space:nowrap}.whitespace-pre{white-space:pre}.whitespace-pre-wrap{white-space:pre-wrap}.break-words{overflow-wrap:break-word}.break-all{word-break:break-all}.rounded{border-radius:.25rem}.rounded-lg{border-radius:.5rem}.rounded-md{border-radius:.375rem}.border{border-width:1px}.border-b{border-bottom-width:1px}.border-t{border-top-width:1px}.border-dashed{border-style:dashed}.border-amber-200{--tw-border-opacity:1;border-color:rgb(253 230 138/var(--tw-border-opacity,1))}.border-blue-200{--tw-border-opacity:1;border-color:rgb(191 219 254/var(--tw-border-opacity,1))}.border-slate-100{--tw-border-opacity:1;border-color:rgb(241 245 249/var(--tw-border-opacity,1))}.border-slate-200{--tw-border-opacity:1;border-color:rgb(226 232 240/var(--tw-border-opacity,1))}.border-slate-300{--tw-border-opacity:1;border-color:rgb(203 213 225/var(--tw-border-opacity,1))}.bg-amber-100{--tw-bg-opacity:1;background-color:rgb(254 243 199/var(--tw-bg-opacity,1))}.bg-amber-50{--tw-bg-opacity:1;background-color:rgb(255 251 235/var(--tw-bg-opacity,1))}.bg-blue-50{--tw-bg-opacity:1;background-color:rgb(239 246 255/var(--tw-bg-opacity,1))}.bg-blue-600{--tw-bg-opacity:1;background-color:rgb(37 99 235/var(--tw-bg-opacity,1))}.bg-emerald-50{--tw-bg-opacity:1;background-color:rgb(236 253 245/var(--tw-bg-opacity,1))}.bg-green-50{--tw-bg-opacity:1;background-color:rgb(240 253 244/var(--tw-bg-opacity,1))}.bg-red-50{--tw-bg-opacity:1;background-color:rgb(254 242 242/var(--tw-bg-opacity,1))}.bg-red-600{--tw-bg-opacity:1;background-color:rgb(220 38 38/var(--tw-bg-opacity,1))}.bg-rose-50{--tw-bg-opacity:1;background-color:rgb(255 241 242/var(--tw-bg-opacity,1))}.bg-slate-100{--tw-bg-opacity:1;background-color:rgb(241 245 249/var(--tw-bg-opacity,1))}.bg-slate-50{--tw-bg-opacity:1;background-color:rgb(248 250 252/var(--tw-bg-opacity,1))}.bg-slate-900{--tw-bg-opacity:1;background-color:rgb(15 23 42/var(--tw-bg-opacity,1))}.bg-slate-900\/50{background-color:rgba(15,23,42,.5)}.bg-white{--tw-bg-opacity:1;background-color:rgb(255 255 255/var(--tw-bg-opacity,1))}.p-1{padding:.25rem}.p-12{padding:3rem}.p-3{padding:.75rem}.p-4{padding:1rem}.p-5{padding:1.25rem}.p-6{padding:1.5rem}.px-1{padding-left:.25rem;padding-right:.25rem}.px-1\.5{padding-left:.375rem;padding-right:.375rem}.px-2{padding-left:.5rem;padding-right:.5rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.py-0\.5{padding-bottom:.125rem;padding-top:.125rem}.py-1{padding-bottom:.25rem;padding-top:.25rem}.py-1\.5{padding-bottom:.375rem;padding-top:.375rem}.py-2{padding-bottom:.5rem;padding-top:.5rem}.py-20{padding-bottom:5rem;padding-top:5rem}.py-3{padding-bottom:.75rem;padding-top:.75rem}.py-4{padding-bottom:1rem;padding-top:1rem}.py-8{padding-bottom:2rem;padding-top:2rem}.pl-2{padding-left:.5rem}.pr-10{padding-right:2.5rem}.pr-2{padding-right:.5rem}.pr-4{padding-right:1rem}.text-left{text-align:left}.text-center{text-align:center}.align-middle{vertical-align:middle}.font-mono{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace}.font-sans{font-family:ui-sans-serif,system-ui,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji}.text-2xl{font-size:1.5rem;line-height:2rem}.text-3xl{font-size:1.875rem;line-height:2.25rem}.text-6xl{font-size:3.75rem;line-height:1}.text-base{font-size:1rem;line-height:1.5rem}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xs{font-size:.75rem;line-height:1rem}.font-bold{font-weight:700}.font-medium{font-weight:500}.font-semibold{font-weight:600}.uppercase{text-transform:uppercase}.leading-5{line-height:1.25rem}.leading-relaxed{line-height:1.625}.tracking-wide{letter-spacing:.025em}.text-amber-700{--tw-text-opacity:1;color:rgb(180 83 9/var(--tw-text-opacity,1))}.text-amber-800{--tw-text-opacity:1;color:rgb(146 64 14/var(--tw-text-opacity,1))}.text-amber-900{--tw-text-opacity:1;color:rgb(120 53 15/var(--tw-text-opacity,1))}.text-blue-600{--tw-text-opacity:1;color:rgb(37 99 235/var(--tw-text-opacity,1))}.text-blue-700{--tw-text-opacity:1;color:rgb(29 78 216/var(--tw-text-opacity,1))}.text-emerald-900{--tw-text-opacity:1;color:rgb(6 78 59/var(--tw-text-opacity,1))}.text-green-800{--tw-text-opacity:1;color:rgb(22 101 52/var(--tw-text-opacity,1))}.text-red-800{--tw-text-opacity:1;color:rgb(153 27 27/var(--tw-text-opacity,1))}.text-rose-900{--tw-text-opacity:1;color:rgb(136 19 55/var(--tw-text-opacity,1))}.text-slate-200{--tw-text-opacity:1;color:rgb(226 232 240/var(--tw-text-opacity,1))}.text-slate-300{--tw-text-opacity:1;color:rgb(203 213 225/var(--tw-text-opacity,1))}.text-slate-400{--tw-text-opacity:1;color:rgb(148 163 184/var(--tw-text-opacity,1))}.text-slate-500{--tw-text-opacity:1;color:rgb(100 116 139/var(--tw-text-opacity,1))}.text-slate-600{--tw-text-opacity:1;color:rgb(71 85 105/var(--tw-text-opacity,1))}.text-slate-700{--tw-text-opacity:1;color:rgb(51 65 85/var(--tw-text-opacity,1))}.text-slate-800{--tw-text-opacity:1;color:rgb(30 41 59/var(--tw-text-opacity,1))}.text-slate-900{--tw-text-opacity:1;color:rgb(15 23 42/var(--tw-text-opacity,1))}.text-white{--tw-text-opacity:1;color:rgb(255 255 255/var(--tw-text-opacity,1))}.underline{text-decoration-line:underline}.placeholder-slate-400::-moz-placeholder{--tw-placeholder-opacity:1;color:rgb(148 163 184/var(--tw-placeholder-opacity,1))}.placeholder-slate-400::placeholder{--tw-placeholder-opacity:1;color:rgb(148 163 184/var(--tw-placeholder-opacity,1))}.shadow-xl{--tw-shadow:0 20px 25px -5px rgba(0,0,0,.1),0 8px 10px -6px rgba(0,0,0,.1);--tw-shadow-colored:0 20px 25px -5px var(--tw-shadow-color),0 8px 10px -6px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow,0 0 #0000),var(--tw-ring-shadow,0 0 #0000),var(--tw-shadow)}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.transition-all{transition-duration:.15s;transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1)}.hover\:border-blue-400:hover{--tw-border-opacity:1;border-color:rgb(96 165 250/var(--tw-border-opacity,1))}.hover\:border-blue-500:hover{--tw-border-opacity:1;border-color:rgb(59 130 246/var(--tw-border-opacity,1))}.hover\:bg-amber-100:hover{--tw-bg-opacity:1;background-color:rgb(254 243 199/var(--tw-bg-opacity,1))}.hover\:bg-blue-700:hover{--tw-bg-opacity:1;background-color:rgb(29 78 216/var(--tw-bg-opacity,1))}.hover\:bg-red-700:hover{--tw-bg-opacity:1;background-color:rgb(185 28 28/var(--tw-bg-opacity,1))}.hover\:bg-slate-700:hover{--tw-bg-opacity:1;background-color:rgb(51 65 85/var(--tw-bg-opacity,1))}.hover\:text-amber-950:hover{--tw-text-opacity:1;color:rgb(69 26 3/var(--tw-text-opacity,1))}.hover\:text-blue-600:hover{--tw-text-opacity:1;color:rgb(37 99 235/var(--tw-text-opacity,1))}.hover\:underline:hover{text-decoration-line:underline}.hover\:shadow-sm:hover{--tw-shadow:0 1px 2px 0 rgba(0,0,0,.05);--tw-shadow-colored:0 1px 2px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow,0 0 #0000),var(--tw-ring-shadow,0 0 #0000),var(--tw-shadow)}.focus\:outline-none:focus{outline:2px solid transparent;outline-offset:2px}.focus\:ring-2:focus{--tw-ring-offset-shadow:var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow:var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow,0 0 #0000)}.focus\:ring-blue-500:focus{--tw-ring-opacity:1;--tw-ring-color:rgb(59 130 246/var(--tw-ring-opacity,1))}.disabled\:opacity-50:disabled{opacity:.5}@media (min-width:640px){.sm\:inline{display:inline}.sm\:w-48{width:12rem}.sm\:w-64{width:16rem}.sm\:px-6{padding-left:1.5rem;padding-right:1.5rem}}@media (min-width:768px){.md\:w-56{width:14rem}.md\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.md\:flex-row{flex-direction:row}}@media (min-width:1024px){.lg\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.lg\:px-8{padding-left:2rem;padding-right:2rem}}@media (prefers-color-scheme:dark){.dark\:divide-slate-800>:not([hidden])~:not([hidden]){--tw-divide-opacity:1;border-color:rgb(30 41 59/var(--tw-divide-opacity,1))}.dark\:border-amber-800{--tw-border-opacity:1;border-color:rgb(146 64 14/var(--tw-border-opacity,1))}.dark\:border-amber-900\/50{border-color:rgba(120,53,15,.5)}.dark\:border-blue-800{--tw-border-opacity:1;border-color:rgb(30 64 175/var(--tw-border-opacity,1))}.dark\:border-slate-600{--tw-border-opacity:1;border-color:rgb(71 85 105/var(--tw-border-opacity,1))}.dark\:border-slate-700{--tw-border-opacity:1;border-color:rgb(51 65 85/var(--tw-border-opacity,1))}.dark\:border-slate-800{--tw-border-opacity:1;border-color:rgb(30 41 59/var(--tw-border-opacity,1))}.dark\:bg-amber-900{--tw-bg-opacity:1;background-color:rgb(120 53 15/var(--tw-bg-opacity,1))}.dark\:bg-amber-900\/40{background-color:rgba(120,53,15,.4)}.dark\:bg-amber-950{--tw-bg-opacity:1;background-color:rgb(69 26 3/var(--tw-bg-opacity,1))}.dark\:bg-amber-950\/30{background-color:rgba(69,26,3,.3)}.dark\:bg-blue-950{--tw-bg-opacity:1;background-color:rgb(23 37 84/var(--tw-bg-opacity,1))}.dark\:bg-emerald-950\/40{background-color:rgba(2,44,34,.4)}.dark\:bg-rose-950\/40{background-color:rgba(76,5,25,.4)}.dark\:bg-slate-100{--tw-bg-opacity:1;background-color:rgb(241 245 249/var(--tw-bg-opacity,1))}.dark\:bg-slate-800{--tw-bg-opacity:1;background-color:rgb(30 41 59/var(--tw-bg-opacity,1))}.dark\:bg-slate-800\/60{background-color:rgba(30,41,59,.6)}.dark\:bg-slate-900{--tw-bg-opacity:1;background-color:rgb(15 23 42/var(--tw-bg-opacity,1))}.dark\:bg-slate-950{--tw-bg-opacity:1;background-color:rgb(2 6 23/var(--tw-bg-opacity,1))}.dark\:text-amber-200{--tw-text-opacity:1;color:rgb(253 230 138/var(--tw-text-opacity,1))}.dark\:text-amber-300{--tw-text-opacity:1;color:rgb(252 211 77/var(--tw-text-opacity,1))}.dark\:text-amber-300\/90{color:rgba(252,211,77,.9)}.dark\:text-blue-300{--tw-text-opacity:1;color:rgb(147 197 253/var(--tw-text-opacity,1))}.dark\:text-blue-400{--tw-text-opacity:1;color:rgb(96 165 250/var(--tw-text-opacity,1))}.dark\:text-emerald-200{--tw-text-opacity:1;color:rgb(167 243 208/var(--tw-text-opacity,1))}.dark\:text-rose-200{--tw-text-opacity:1;color:rgb(254 205 211/var(--tw-text-opacity,1))}.dark\:text-slate-100{--tw-text-opacity:1;color:rgb(241 245 249/var(--tw-text-opacity,1))}.dark\:text-slate-200{--tw-text-opacity:1;color:rgb(226 232 240/var(--tw-text-opacity,1))}.dark\:text-slate-300{--tw-text-opacity:1;color:rgb(203 213 225/var(--tw-text-opacity,1))}.dark\:text-slate-400{--tw-text-opacity:1;color:rgb(148 163 184/var(--tw-text-opacity,1))}.dark\:text-slate-500{--tw-text-opacity:1;color:rgb(100 116 139/var(--tw-text-opacity,1))}.dark\:text-slate-600{--tw-text-opacity:1;color:rgb(71 85 105/var(--tw-text-opacity,1))}.dark\:text-slate-700{--tw-text-opacity:1;color:rgb(51 65 85/var(--tw-text-opacity,1))}.dark\:text-slate-800{--tw-text-opacity:1;color:rgb(30 41 59/var(--tw-text-opacity,1))}.dark\:text-slate-900{--tw-text-opacity:1;color:rgb(15 23 42/var(--tw-text-opacity,1))}.dark\:hover\:border-blue-600:hover{--tw-border-opacity:1;border-color:rgb(37 99 235/var(--tw-border-opacity,1))}.dark\:hover\:bg-amber-900\/40:hover{background-color:rgba(120,53,15,.4)}.dark\:hover\:bg-slate-300:hover{--tw-bg-opacity:1;background-color:rgb(203 213 225/var(--tw-bg-opacity,1))}.dark\:hover\:text-amber-100:hover{--tw-text-opacity:1;color:rgb(254 243 199/var(--tw-text-opacity,1))}.dark\:hover\:text-blue-400:hover{--tw-text-opacity:1;color:rgb(96 165 250/var(--tw-text-opacity,1))}}.\[\&_a\]\:text-blue-600 a{--tw-text-opacity:1;color:rgb(37 99 235/var(--tw-text-opacity,1))}.\[\&_a\]\:underline a{text-decoration-line:underline}@media (prefers-color-scheme:dark){.\[\&_a\]\:dark\:text-blue-400 a{--tw-text-opacity:1;color:rgb(96 165 250/var(--tw-text-opacity,1))}}.\[\&_blockquote\]\:my-3 blockquote{margin-bottom:.75rem;margin-top:.75rem}.\[\&_blockquote\]\:border-l-4 blockquote{border-left-width:4px}.\[\&_blockquote\]\:border-slate-300 blockquote{--tw-border-opacity:1;border-color:rgb(203 213 225/var(--tw-border-opacity,1))}.\[\&_blockquote\]\:pl-4 blockquote{padding-left:1rem}.\[\&_blockquote\]\:italic blockquote{font-style:italic}.\[\&_blockquote\]\:text-slate-600 blockquote{--tw-text-opacity:1;color:rgb(71 85 105/var(--tw-text-opacity,1))}@media (prefers-color-scheme:dark){.\[\&_blockquote\]\:dark\:border-slate-700 blockquote{--tw-border-opacity:1;border-color:rgb(51 65 85/var(--tw-border-opacity,1))}.\[\&_blockquote\]\:dark\:text-slate-400 blockquote{--tw-text-opacity:1;color:rgb(148 163 184/var(--tw-text-opacity,1))}}.\[\&_code\]\:rounded code{border-radius:.25rem}.\[\&_code\]\:bg-slate-100 code{--tw-bg-opacity:1;background-color:rgb(241 245 249/var(--tw-bg-opacity,1))}.\[\&_code\]\:px-1 code{padding-left:.25rem;padding-right:.25rem}.\[\&_code\]\:py-0\.5 code{padding-bottom:.125rem;padding-top:.125rem}.\[\&_code\]\:font-mono code{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace}.\[\&_code\]\:text-sm code{font-size:.875rem;line-height:1.25rem}@media (prefers-color-scheme:dark){.\[\&_code\]\:dark\:bg-slate-800 code{--tw-bg-opacity:1;background-color:rgb(30 41 59/var(--tw-bg-opacity,1))}}.\[\&_h1\]\:mb-3 h1{margin-bottom:.75rem}.\[\&_h1\]\:mt-6 h1{margin-top:1.5rem}.\[\&_h1\]\:text-3xl h1{font-size:1.875rem;line-height:2.25rem}.\[\&_h1\]\:font-bold h1{font-weight:700}.\[\&_h2\]\:mb-2 h2{margin-bottom:.5rem}.\[\&_h2\]\:mt-5 h2{margin-top:1.25rem}.\[\&_h2\]\:text-2xl h2{font-size:1.5rem;line-height:2rem}.\[\&_h2\]\:font-semibold h2{font-weight:600}.\[\&_h3\]\:mb-2 h3{margin-bottom:.5rem}.\[\&_h3\]\:mt-4 h3{margin-top:1rem}.\[\&_h3\]\:text-xl h3{font-size:1.25rem;line-height:1.75rem}.\[\&_h3\]\:font-semibold h3{font-weight:600}.\[\&_h4\]\:mb-1 h4{margin-bottom:.25rem}.\[\&_h4\]\:mt-3 h4{margin-top:.75rem}.\[\&_h4\]\:text-lg h4{font-size:1.125rem;line-height:1.75rem}.\[\&_h4\]\:font-semibold h4{font-weight:600}.\[\&_hr\]\:my-6 hr{margin-bottom:1.5rem;margin-top:1.5rem}.\[\&_hr\]\:border-slate-200 hr{--tw-border-opacity:1;border-color:rgb(226 232 240/var(--tw-border-opacity,1))}@media (prefers-color-scheme:dark){.\[\&_hr\]\:dark\:border-slate-800 hr{--tw-border-opacity:1;border-color:rgb(30 41 59/var(--tw-border-opacity,1))}}.\[\&_li\]\:my-1 li{margin-bottom:.25rem;margin-top:.25rem}.\[\&_mark\]\:bg-yellow-200 mark{--tw-bg-opacity:1;background-color:rgb(254 240 138/var(--tw-bg-opacity,1))}.\[\&_mark\]\:px-0\.5 mark{padding-left:.125rem;padding-right:.125rem}@media (prefers-color-scheme:dark){.\[\&_mark\]\:dark\:bg-yellow-800 mark{--tw-bg-opacity:1;background-color:rgb(133 77 14/var(--tw-bg-opacity,1))}}.\[\&_ol\]\:my-3 ol{margin-bottom:.75rem;margin-top:.75rem}.\[\&_ol\]\:list-decimal ol{list-style-type:decimal}.\[\&_ol\]\:pl-5 ol{padding-left:1.25rem}.\[\&_p\]\:my-3 p{margin-bottom:.75rem;margin-top:.75rem}.\[\&_p\]\:leading-relaxed p{line-height:1.625}.\[\&_pre\]\:my-3 pre{margin-bottom:.75rem;margin-top:.75rem}.\[\&_pre\]\:overflow-x-auto pre{overflow-x:auto}.\[\&_pre\]\:rounded pre{border-radius:.25rem}.\[\&_pre\]\:bg-slate-100 pre{--tw-bg-opacity:1;background-color:rgb(241 245 249/var(--tw-bg-opacity,1))}.\[\&_pre\]\:p-3 pre{padding:.75rem}@media (prefers-color-scheme:dark){.\[\&_pre\]\:dark\:bg-slate-800 pre{--tw-bg-opacity:1;background-color:rgb(30 41 59/var(--tw-bg-opacity,1))}}.\[\&_pre_code\]\:bg-transparent pre code{background-color:transparent}.\[\&_pre_code\]\:p-0 pre code{padding:0}.\[\&_table\]\:my-3 table{margin-bottom:.75rem;margin-top:.75rem}.\[\&_table\]\:w-full table{width:100%}.\[\&_table\]\:border-collapse table{border-collapse:collapse}.\[\&_td\]\:border td{border-width:1px}.\[\&_td\]\:border-slate-300 td{--tw-border-opacity:1;border-color:rgb(203 213 225/var(--tw-border-opacity,1))}.\[\&_td\]\:px-3 td{padding-left:.75rem;padding-right:.75rem}.\[\&_td\]\:py-2 td{padding-bottom:.5rem;padding-top:.5rem}@media (prefers-color-scheme:dark){.\[\&_td\]\:dark\:border-slate-700 td{--tw-border-opacity:1;border-color:rgb(51 65 85/var(--tw-border-opacity,1))}}.\[\&_th\]\:border th{border-width:1px}.\[\&_th\]\:border-slate-300 th{--tw-border-opacity:1;border-color:rgb(203 213 225/var(--tw-border-opacity,1))}.\[\&_th\]\:bg-slate-50 th{--tw-bg-opacity:1;background-color:rgb(248 250 252/var(--tw-bg-opacity,1))}.\[\&_th\]\:px-3 th{padding-left:.75rem;padding-right:.75rem}.\[\&_th\]\:py-2 th{padding-bottom:.5rem;padding-top:.5rem}.\[\&_th\]\:text-left th{text-align:left}@media (prefers-color-scheme:dark){.\[\&_th\]\:dark\:border-slate-700 th{--tw-border-opacity:1;border-color:rgb(51 65 85/var(--tw-border-opacity,1))}.\[\&_th\]\:dark\:bg-slate-800 th{--tw-bg-opacity:1;background-color:rgb(30 41 59/var(--tw-bg-opacity,1))}}.\[\&_ul\]\:my-3 ul{margin-bottom:.75rem;margin-top:.75rem}.\[\&_ul\]\:list-disc ul{list-style-type:disc}.\[\&_ul\]\:pl-5 ul{padding-left:1.25rem}\ No newline at end of filediff --git a/crates/ai-memory-web/templates/history.html b/crates/ai-memory-web/templates/history.htmlnew file mode 100644index 00000000..fa1f44ee--- /dev/null+++ b/crates/ai-memory-web/templates/history.html@@ -0,0 +1,87 @@+{% extends "base.html" %}++{% block title %}History of {{ path }} — ai-memory{% endblock %}++{% block content %}+<nav class="mb-6 flex items-center gap-1 text-sm text-slate-500 dark:text-slate-400">+ <a href="." class="hover:text-blue-600 dark:hover:text-blue-400">home</a>+ <span>/</span>+ <a href="{{ project_href }}" class="hover:text-blue-600 dark:hover:text-blue-400">{{ workspace }}/{{ project }}</a>+ <span>/</span>+ <a href="{{ page_href }}" class="hover:text-blue-600 dark:hover:text-blue-400 truncate max-w-xs">{{ path }}</a>+ <span>/</span>+ <span class="text-slate-700 dark:text-slate-200">history</span>+</nav>++<h1 class="text-2xl font-bold text-slate-900 dark:text-slate-100 mb-1">History of {{ path }}</h1>+<p class="mb-6 text-sm text-slate-500 dark:text-slate-400">{{ total }} version{% if total != 1 %}s{% endif %}, newest first. Superseded versions stay in the record; nothing here can change them.</p>++<section class="mb-10" aria-labelledby="diff-heading">+ <h2 id="diff-heading" class="text-xs font-semibold uppercase tracking-wide text-slate-400 dark:text-slate-500 mb-3">+ {% if from_short != "" %}Changes from <span class="font-mono">{{ from_short }}</span> to <span class="font-mono">{{ to_short }}</span>{% else %}Content of <span class="font-mono">{{ to_short }}</span> (no earlier version at this path){% endif %}+ </h2>+ <p class="mb-3 text-xs text-slate-500 dark:text-slate-400">+ {% if from_short != "" %}<span title="{{ from_created }}">{{ from_title }}</span> → {% endif %}<span title="{{ to_created }}">{{ to_title }}</span>+ </p>+ {% if same %}+ <p class="text-sm text-slate-500 dark:text-slate-400">The two versions have the same body.</p>+ {% else if too_large != "" %}+ <p class="text-sm text-amber-700 dark:text-amber-300">No diff shown: {{ too_large }}.</p>+ {% else if hunks.is_empty() %}+ <p class="text-sm text-slate-500 dark:text-slate-400">The bodies differ only in line endings.</p>+ {% else %}+ <div class="overflow-x-auto rounded border border-slate-200 dark:border-slate-800">+ <pre class="text-xs font-mono leading-5">{% for hunk in hunks %}<span class="block px-3 bg-slate-100 dark:bg-slate-800 text-slate-500 dark:text-slate-400">{{ hunk.header }}</span>{% for line in hunk.lines %}<span class="block px-3 whitespace-pre {% if line.sign == "+" %}bg-emerald-50 text-emerald-900 dark:bg-emerald-950/40 dark:text-emerald-200{% else if line.sign == "-" %}bg-rose-50 text-rose-900 dark:bg-rose-950/40 dark:text-rose-200{% else %}text-slate-600 dark:text-slate-400{% endif %}">{{ line.sign }}{{ line.text }}</span>{% endfor %}{% endfor %}</pre>+ </div>+ {% if truncated %}+ <p class="mt-2 text-xs text-amber-700 dark:text-amber-300">Diff cut short at the line limit.</p>+ {% endif %}+ {% endif %}+</section>++<section aria-labelledby="versions-heading">+ <h2 id="versions-heading" class="text-xs font-semibold uppercase tracking-wide text-slate-400 dark:text-slate-500 mb-3">Versions {{ shown_start }}–{{ shown_end }} of {{ total }}</h2>+ <form action="{{ history_href }}" method="get">+ <input type="hidden" name="limit" value="{{ limit }}">+ <div class="overflow-x-auto">+ <table class="w-full text-sm">+ <thead>+ <tr class="text-left text-xs text-slate-400 dark:text-slate-500 border-b border-slate-200 dark:border-slate-800">+ <th class="py-2 pr-2 font-medium">From</th>+ <th class="py-2 pr-4 font-medium">To</th>+ <th class="py-2 pr-4 font-medium">Version</th>+ <th class="py-2 pr-4 font-medium">Written</th>+ <th class="py-2 pr-4 font-medium">Author</th>+ <th class="py-2 pr-4 font-medium">Title</th>+ <th class="py-2 pr-4 font-medium">Size</th>+ <th class="py-2 font-medium"></th>+ </tr>+ </thead>+ <tbody class="divide-y divide-slate-100 dark:divide-slate-800">+ {% for version in versions %}+ <tr data-version="{{ version.id }}">+ <td class="py-2 pr-2"><input type="radio" name="from" value="{{ version.id }}" aria-label="Diff from {{ version.short_id }}"{% if version.is_from %} checked{% endif %}></td>+ <td class="py-2 pr-4"><input type="radio" name="to" value="{{ version.id }}" aria-label="Diff to {{ version.short_id }}"{% if version.is_to %} checked{% endif %}></td>+ <td class="py-2 pr-4 font-mono text-xs whitespace-nowrap">+ {{ version.short_id }}+ {% if version.is_latest %}<span class="ml-1 inline-flex items-center rounded px-1.5 py-0.5 font-sans font-medium bg-blue-50 dark:bg-blue-950 text-blue-700 dark:text-blue-300 border border-blue-200 dark:border-blue-800">latest</span>{% endif %}+ {% if version.supersedes_short != "" %}<span class="block text-slate-400 dark:text-slate-500">replaced {{ version.supersedes_short }}</span>{% endif %}+ </td>+ <td class="py-2 pr-4 whitespace-nowrap text-slate-500 dark:text-slate-400" title="{{ version.created_at }}">{{ version.created_relative }}</td>+ <td class="py-2 pr-4 text-slate-600 dark:text-slate-300">{% if version.author != "" %}{{ version.author }}{% else %}<span class="text-slate-400 dark:text-slate-600">—</span>{% endif %}</td>+ <td class="py-2 pr-4 text-slate-700 dark:text-slate-200">{{ version.title }}</td>+ <td class="py-2 pr-4 whitespace-nowrap text-slate-500 dark:text-slate-400">{{ version.body_chars }} chars</td>+ <td class="py-2 whitespace-nowrap">{% if version.compare_href != "" %}<a href="{{ version.compare_href }}" class="text-blue-600 dark:text-blue-400 underline text-xs">vs previous</a>{% endif %}</td>+ </tr>+ {% endfor %}+ </tbody>+ </table>+ </div>+ <div class="mt-4 flex flex-wrap items-center gap-3">+ <button type="submit" class="rounded-md border border-slate-300 dark:border-slate-700 bg-white dark:bg-slate-900 px-3 py-1.5 text-sm font-medium text-slate-700 dark:text-slate-200 hover:border-blue-500">Compare selected</button>+ {% if newer_href != "" %}<a href="{{ newer_href }}" class="text-sm text-blue-600 dark:text-blue-400 underline">Newer versions</a>{% endif %}+ {% if older_href != "" %}<a href="{{ older_href }}" class="text-sm text-blue-600 dark:text-blue-400 underline">Older versions</a>{% endif %}+ </div>+ </form>+</section>+{% endblock %}diff --git a/crates/ai-memory-web/templates/page.html b/crates/ai-memory-web/templates/page.htmlindex a727c164..84e29d66 100644--- a/crates/ai-memory-web/templates/page.html+++ b/crates/ai-memory-web/templates/page.html@@ -29,6 +29,8 @@{% endif %}<span class="ml-1">Updated {{ updated_relative }}</span><span>·</span>+ <a href="{{ history_href }}" class="text-blue-600 dark:text-blue-400 underline">History</a>+ <span>·</span><span>Created {{ created_relative }}</span>{% if supersedes_path != "" %}<span>·</span>diff --git a/crates/ai-memory-web/templates/project.html b/crates/ai-memory-web/templates/project.htmlindex d2ccc1b7..c7517759 100644--- a/crates/ai-memory-web/templates/project.html+++ b/crates/ai-memory-web/templates/project.html@@ -97,6 +97,23 @@</p>{% endif %}</section>+ {% if !sessions.is_empty() %}+ <section class="mb-8" aria-labelledby="sessions-heading">+ <h2 id="sessions-heading" class="text-xs font-semibold uppercase tracking-wide text-slate-400 dark:text-slate-500 mb-3">Recent Sessions</h2>+ <ul class="divide-y divide-slate-100 dark:divide-slate-800">+ {% for session in sessions %}+ <li class="py-2 flex items-center justify-between gap-4">+ <a href="{{ session.href }}" class="min-w-0 flex items-center gap-2 text-sm text-slate-800 dark:text-slate-100 hover:text-blue-600 dark:hover:text-blue-400">+ <span class="inline-flex items-center rounded px-1.5 py-0.5 text-xs font-medium bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-400">{{ session.agent_kind }}</span>+ <span class="font-mono text-xs">{{ session.short_id }}</span>+ <span class="text-xs text-slate-400 dark:text-slate-500">{{ session.observation_count }} observation{% if session.observation_count != 1 %}s{% endif %}{% if session.open %} · open{% endif %}</span>+ </a>+ <span class="text-xs text-slate-400 dark:text-slate-500 whitespace-nowrap shrink-0">{{ session.started_relative }}</span>+ </li>+ {% endfor %}+ </ul>+ </section>+ {% endif %}<h2 class="text-xs font-semibold uppercase tracking-wide text-slate-400 dark:text-slate-500 mb-3">Recent Activity</h2>{% if recent.is_empty() %}<p class="text-sm text-slate-400 dark:text-slate-600">No pages yet.</p>diff --git a/crates/ai-memory-web/templates/session.html b/crates/ai-memory-web/templates/session.htmlnew file mode 100644index 00000000..ef9bc5c3--- /dev/null+++ b/crates/ai-memory-web/templates/session.html@@ -0,0 +1,114 @@+{% extends "base.html" %}++{% block title %}Session {{ session_id }} — ai-memory{% endblock %}++{% block content %}+<nav class="mb-6 flex items-center gap-1 text-sm text-slate-500 dark:text-slate-400">+ <a href="." class="hover:text-blue-600 dark:hover:text-blue-400">home</a>+ <span>/</span>+ <a href="{{ project_href }}" class="hover:text-blue-600 dark:hover:text-blue-400">{{ workspace }}/{{ project }}</a>+ <span>/</span>+ <span class="text-slate-700 dark:text-slate-200 font-mono text-xs truncate max-w-xs">session {{ session_id }}</span>+</nav>++<h1 class="text-2xl font-bold text-slate-900 dark:text-slate-100 mb-1">Session timeline</h1>+<p class="mb-1 text-sm text-slate-500 dark:text-slate-400">+ <span class="inline-flex items-center rounded px-1.5 py-0.5 text-xs font-medium bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-400">{{ agent_kind }}</span>+ started <span title="{{ started_at }}">{{ started_at }}</span>{% if ended_at != "" %}, ended <span title="{{ ended_at }}">{{ ended_at }}</span>{% else %}, still open{% endif %}+</p>+<p class="mb-6 text-xs text-slate-400 dark:text-slate-500">+ Captured observations, in order. They were sanitized when captured and are shown as plain text.+ {% if elided_other_scope > 0 %}This session also left {{ elided_other_scope }} observation{% if elided_other_scope != 1 %}s{% endif %} in another project, not shown here.{% endif %}+</p>++<nav id="scrubber" aria-label="Session scrubber" data-total="{{ total }}" data-limit="{{ limit }}" data-start="{{ shown_start }}"+ class="sticky top-14 z-10 mb-6 flex flex-wrap items-center gap-3 rounded border border-slate-200 dark:border-slate-800 bg-white dark:bg-slate-950 px-3 py-2 text-sm">+ {% if first_href != "" %}<a href="{{ first_href }}" class="text-blue-600 dark:text-blue-400" rel="first">« First</a>{% else %}<span class="text-slate-300 dark:text-slate-700">« First</span>{% endif %}+ {% if prev_href != "" %}<a href="{{ prev_href }}" class="text-blue-600 dark:text-blue-400" rel="prev" data-scrub="prev">‹ Prev</a>{% else %}<span class="text-slate-300 dark:text-slate-700">‹ Prev</span>{% endif %}+ <span class="text-slate-500 dark:text-slate-400">{{ shown_start }}–{{ shown_end }} of {{ total }}</span>+ {% if next_href != "" %}<a href="{{ next_href }}" class="text-blue-600 dark:text-blue-400" rel="next" data-scrub="next">Next ›</a>{% else %}<span class="text-slate-300 dark:text-slate-700">Next ›</span>{% endif %}+ {% if last_href != "" %}<a href="{{ last_href }}" class="text-blue-600 dark:text-blue-400" rel="last">Last »</a>{% else %}<span class="text-slate-300 dark:text-slate-700">Last »</span>{% endif %}+ <form action="{{ session_href }}" method="get" class="flex items-center gap-2 ml-auto">+ <input type="hidden" name="limit" value="{{ limit }}">+ <label for="scrub-at" class="text-slate-500 dark:text-slate-400">Jump to</label>+ <input id="scrub-range" type="range" min="1" max="{{ total }}" value="{{ jump_value }}" hidden aria-label="Scrub through the session" class="w-32 sm:w-48">+ <input id="scrub-at" name="at" type="number" min="1" max="{{ total }}" value="{{ jump_value }}"+ class="w-20 rounded-md border border-slate-300 dark:border-slate-700 bg-white dark:bg-slate-900 px-2 py-1 text-sm">+ <button type="submit" class="rounded-md border border-slate-300 dark:border-slate-700 px-2 py-1 text-sm font-medium text-slate-700 dark:text-slate-200 hover:border-blue-500">Go</button>+ </form>+</nav>++{% if observations.is_empty() %}+<p class="text-sm text-slate-400 dark:text-slate-600">No observations on this page.</p>+{% else %}+<ol class="space-y-4">+ {% for obs in observations %}+ <li id="obs-{{ obs.position }}" data-position="{{ obs.position }}" tabindex="-1"+ class="rounded border border-slate-200 dark:border-slate-800 p-3 focus:outline-none focus:ring-2 focus:ring-blue-500">+ <div class="flex flex-wrap items-center gap-2 mb-2 text-xs text-slate-500 dark:text-slate-400">+ <a href="{{ session_href }}?at={{ obs.position }}&limit={{ limit }}#obs-{{ obs.position }}" class="font-mono text-slate-400 dark:text-slate-500 hover:text-blue-600 dark:hover:text-blue-400">#{{ obs.position }}</a>+ <span class="inline-flex items-center rounded px-1.5 py-0.5 font-medium bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-400">{{ obs.kind }}</span>+ <span class="font-medium text-slate-700 dark:text-slate-200">{{ obs.title }}</span>+ <span class="ml-auto whitespace-nowrap" title="{{ obs.created_at }}">{{ obs.created_relative }}</span>+ </div>+ <pre class="whitespace-pre-wrap break-words text-xs font-mono text-slate-700 dark:text-slate-300">{{ obs.body }}</pre>+ </li>+ {% endfor %}+</ol>+{% endif %}++<script>+// Progressive enhancement only: the links and the jump form above work+// without it. Adds a range slider bound to the jump field and j/k (or the+// arrow keys) to step one observation at a time, crossing page edges.+(function () {+ var nav = document.getElementById("scrubber");+ if (!nav) return;+ var range = document.getElementById("scrub-range");+ var at = document.getElementById("scrub-at");+ var total = parseInt(nav.getAttribute("data-total"), 10) || 0;+ if (range && at && total > 1) {+ range.hidden = false;+ range.addEventListener("input", function () { at.value = range.value; });+ range.addEventListener("change", function () { at.form.submit(); });+ at.addEventListener("input", function () { range.value = at.value; });+ }+ var items = Array.prototype.slice.call(document.querySelectorAll("li[data-position]"));+ if (!items.length) return;+ var current = -1;+ var wanted = new URLSearchParams(location.search).get("at");+ var hash = location.hash.replace("#obs-", "");+ var target = parseInt(hash || wanted || "", 10);+ if (target) {+ current = items.findIndex(function (li) {+ return parseInt(li.getAttribute("data-position"), 10) === target;+ });+ if (current >= 0) items[current].focus();+ }+ function show(i) {+ current = i;+ items[i].focus();+ items[i].scrollIntoView({ block: "start" });+ if (at) at.value = items[i].getAttribute("data-position");+ if (range) range.value = at.value;+ }+ function follow(rel, position) {+ var link = nav.querySelector('a[data-scrub="' + rel + '"]');+ if (link) location.assign(link.getAttribute("href") + "#obs-" + position);+ }+ document.addEventListener("keydown", function (event) {+ var tag = (event.target && event.target.tagName) || "";+ if (tag === "INPUT" || tag === "TEXTAREA" || event.metaKey || event.ctrlKey || event.altKey) return;+ var first = parseInt(items[0].getAttribute("data-position"), 10);+ var last = parseInt(items[items.length - 1].getAttribute("data-position"), 10);+ if (event.key === "j" || event.key === "ArrowRight") {+ event.preventDefault();+ if (current < items.length - 1) show(current + 1); else follow("next", last + 1);+ } else if (event.key === "k" || event.key === "ArrowLeft") {+ event.preventDefault();+ if (current > 0) show(current - 1); else follow("prev", first - 1);+ }+ });+})();+</script>+{% endblock %}diff --git a/crates/ai-memory-web/tests/suite/history_replay.rs b/crates/ai-memory-web/tests/suite/history_replay.rsnew file mode 100644index 00000000..0c2808f3--- /dev/null+++ b/crates/ai-memory-web/tests/suite/history_replay.rs@@ -0,0 +1,884 @@+//! Page history and diff (`/w/{ws}/{proj}/h/*path`, `/api/v1/.../history/*path`)+//! and the session timeline (`/w/{ws}/{proj}/s/{session_id}`).+//!+//! Both views read by id, so each boundary is tested adversarially: a path,+//! version id or session id from another project or workspace must read as+//! not found, a restricted project must refuse a non-grantee, and captured+//! text must render inert. Every refusal has a legitimate control beside it.++use ai_memory_core::{+ ActorContext, AgentKind, AuthorizedViewer, IdentityKey, NewObservation, NewPage, NewSession,+ NewUser, ObservationKind, PageId, PagePath, ProjectId, Sanitized, Sanitizer, SessionId, Tier,+ UserId, UserRole, WorkspaceId,+};+use ai_memory_store::{GrantLevel, Store};+use ai_memory_web::{api_router, router};+use ai_memory_wiki::Wiki;+use axum::body::Body;+use axum::http::{Request, StatusCode};+use serde_json::Value;+use tempfile::TempDir;+use tower::ServiceExt;++struct Fixture {+ _tmp: TempDir,+ store: Store,+ wiki: Wiki,+}++impl Fixture {+ async fn new() -> Self {+ let tmp = TempDir::new().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();+ Self {+ _tmp: tmp,+ store,+ wiki,+ }+ }++ async fn scope(&self, workspace: &str, project: &str) -> (WorkspaceId, ProjectId) {+ let ws = self+ .store+ .writer+ .get_or_create_workspace(workspace)+ .await+ .unwrap();+ let proj = self+ .store+ .writer+ .get_or_create_project(ws, project, None)+ .await+ .unwrap();+ (ws, proj)+ }++ async fn write(+ &self,+ scope: (WorkspaceId, ProjectId),+ path: &str,+ body: &str,+ author: Option<UserId>,+ ) -> PageId {+ self.write_expiring(scope, path, body, author, None).await+ }++ async fn write_expiring(+ &self,+ (ws, proj): (WorkspaceId, ProjectId),+ path: &str,+ body: &str,+ author: Option<UserId>,+ expires_at: Option<jiff::Timestamp>,+ ) -> PageId {+ self.store+ .writer+ .upsert_page(NewPage {+ workspace_id: ws,+ project_id: proj,+ path: PagePath::new(path).unwrap(),+ title: "Plan".into(),+ body: body.into(),+ tier: Tier::Semantic,+ frontmatter_json: serde_json::json!({"kind": "fact"}),+ pinned: false,+ links: Vec::new(),+ author_id: author,+ expires_at,+ entities: Vec::new(),+ evidence: Vec::new(),+ })+ .await+ .unwrap()+ }++ async fn user(&self, name: &str) -> UserId {+ self.store+ .writer+ .create_human_user(+ NewUser {+ username: name.into(),+ name: None,+ email: None,+ },+ UserRole::User,+ None,+ false,+ )+ .await+ .unwrap()+ }++ async fn session(+ &self,+ (ws, proj): (WorkspaceId, ProjectId),+ owner: Option<&str>,+ rows: &[(&str, &str)],+ ) -> SessionId {+ let id = SessionId::new();+ self.store+ .writer+ .begin_session(NewSession {+ occurred_at: None,+ id,+ workspace_id: ws,+ project_id: proj,+ agent_kind: AgentKind::ClaudeCode,+ cwd: None,+ actor_user: owner.map(|name| IdentityKey::User(name.into()).storage_key()),+ })+ .await+ .unwrap();+ for (title, body) in rows {+ self.store+ .writer+ .insert_observation(Sanitized::new(+ NewObservation {+ occurred_at: None,+ session_id: id,+ workspace_id: ws,+ project_id: proj,+ kind: ObservationKind::UserPrompt,+ extension: None,+ source_event: None,+ title: (*title).to_owned(),+ body: (*body).to_owned(),+ importance: 5,+ },+ &Sanitizer::builtin(),+ ))+ .await+ .unwrap();+ }+ id+ }++ fn web(&self) -> axum::Router {+ router(self.store.reader.clone(), self.wiki.clone())+ }++ fn api(&self) -> axum::Router {+ api_router(self.store.reader.clone(), self.wiki.clone())+ }+}++/// GET `uri`, stamping what the auth layer would: a grant-checked viewer and+/// an actor identity.+async fn get_as(+ app: &axum::Router,+ uri: &str,+ viewer: Option<UserId>,+ actor: Option<&str>,+) -> (StatusCode, String) {+ let mut req = Request::builder().uri(uri);+ if let Some(viewer) = viewer {+ req = req.extension(AuthorizedViewer(viewer));+ }+ if let Some(user) = actor {+ req = req.extension(ActorContext {+ user: Some(user.to_owned()),+ ..ActorContext::default()+ });+ }+ let resp = app+ .clone()+ .oneshot(req.body(Body::empty()).unwrap())+ .await+ .unwrap();+ let status = resp.status();+ let body = axum::body::to_bytes(resp.into_body(), usize::MAX)+ .await+ .unwrap();+ (status, String::from_utf8_lossy(&body).into_owned())+}++async fn get(app: &axum::Router, uri: &str) -> (StatusCode, String) {+ get_as(app, uri, None, None).await+}++async fn get_json(app: &axum::Router, uri: &str) -> Value {+ let (status, body) = get(app, uri).await;+ assert_eq!(status, StatusCode::OK, "{uri}: {body}");+ serde_json::from_str(&body).unwrap()+}++/// `/w/{ws}/{proj}/h/{rest}` as its `/api/v1` twin.+fn api_history_uri(web: &str) -> String {+ let rest = web.strip_prefix("/w/").unwrap();+ let (ws, rest) = rest.split_once('/').unwrap();+ let (proj, rest) = rest.split_once('/').unwrap();+ let rest = rest.strip_prefix("h/").unwrap();+ format!("/workspaces/{ws}/projects/{proj}/history/{rest}")+}++// ---------------------------------------------------------------------------+// V1: page history and diff+// ---------------------------------------------------------------------------++/// K supersessions leave K+1 versions, listed newest first in both views, and+/// the default diff is the latest against the version it replaced.+#[tokio::test]+async fn history_lists_k_plus_one_versions_newest_first_and_diffs_the_latest() {+ let f = Fixture::new().await;+ let scope = f.scope("default", "app").await;+ const K: usize = 4;+ let mut ids = Vec::new();+ for i in 0..=K {+ ids.push(+ f.write(+ scope,+ "notes/plan.md",+ &format!("# Plan\n\nshared line\nrevision {i}\n"),+ None,+ )+ .await,+ );+ }++ let json = get_json(+ &f.api(),+ "/workspaces/default/projects/app/history/notes/plan.md",+ )+ .await;+ assert_eq!(json["total"], (K + 1) as u64);+ let listed: Vec<String> = json["versions"]+ .as_array()+ .unwrap()+ .iter()+ .map(|v| v["id"].as_str().unwrap().to_owned())+ .collect();+ let expected: Vec<String> = ids.iter().rev().map(ToString::to_string).collect();+ assert_eq!(listed, expected, "newest first, every version");+ let latest: Vec<bool> = json["versions"]+ .as_array()+ .unwrap()+ .iter()+ .map(|v| v["is_latest"].as_bool().unwrap())+ .collect();+ assert!(latest[0]);+ assert!(latest[1..].iter().all(|l| !l), "{latest:?}");+ // Each version names the one it replaced: an unbroken chain.+ for pair in json["versions"].as_array().unwrap().windows(2) {+ assert_eq!(pair[0]["supersedes"], pair[1]["id"]);+ }++ let diff = &json["diff"];+ assert_eq!(diff["status"], "changed");+ assert_eq!(diff["to"]["id"], ids[K].to_string());+ assert_eq!(diff["from"]["id"], ids[K - 1].to_string());+ let lines: Vec<String> = diff["hunks"][0]["lines"]+ .as_array()+ .unwrap()+ .iter()+ .map(|l| {+ format!(+ "{}{}",+ l["op"].as_str().unwrap(),+ l["text"].as_str().unwrap()+ )+ })+ .collect();+ assert!(lines.contains(&format!("-revision {}", K - 1)), "{lines:?}");+ assert!(lines.contains(&format!("+revision {K}")), "{lines:?}");+ assert!(lines.contains(&" shared line".to_owned()), "{lines:?}");++ // The HTML view lists the same K+1 versions in the same order.+ let (status, html) = get(&f.web(), "/w/default/app/h/notes/plan.md").await;+ assert_eq!(status, StatusCode::OK, "{html}");+ let positions: Vec<usize> = ids+ .iter()+ .rev()+ .map(|id| {+ html.find(&format!("data-version=\"{id}\""))+ .unwrap_or_else(|| panic!("version {id} missing"))+ })+ .collect();+ assert!(positions.windows(2).all(|w| w[0] < w[1]), "{positions:?}");+ assert_eq!(html.matches("data-version=").count(), K + 1);+ assert!(html.contains(&format!("-revision {}", K - 1)));+ assert!(html.contains(&format!("+revision {K}")));++ // The page view links to its history. It reads the body from disk, so+ // this page goes through the wiki.+ f.wiki+ .write_page(ai_memory_wiki::WritePageRequest {+ workspace_id: scope.0,+ project_id: scope.1,+ path: PagePath::new("notes/on-disk.md").unwrap(),+ frontmatter: serde_json::json!({"kind": "fact"}),+ body: "on disk".into(),+ tier: Tier::Semantic,+ pinned: false,+ title: None,+ admission_ctx: None,+ author_id: None,+ actor: ActorContext::anonymous(),+ evidence: Vec::new(),+ })+ .await+ .unwrap();+ let (status, page) = get(&f.web(), "/w/default/app/p/notes/on-disk.md").await;+ assert_eq!(status, StatusCode::OK, "{page}");+ assert!(+ page.contains(+ "href=\"w/default/app/h/notes/on-disk.md\" class=\"text-blue-600 dark:text-blue-400 underline\">History</a>"+ ),+ "{page}"+ );+}++/// Invariant #16: two operators write the same page from the same base. The+/// later write holds `is_latest`, and the other stays in the history with its+/// author — the loser is reachable and diffable, not gone.+#[tokio::test]+async fn history_keeps_both_sides_of_a_concurrent_divergent_write() {+ let f = Fixture::new().await;+ let scope = f.scope("default", "app").await;+ let alice = f.user("alice").await;+ let carol = f.user("carol").await;+ let base = f.write(scope, "notes/shared.md", "base text\n", None).await;+ let (a, c) = tokio::join!(+ f.write(scope, "notes/shared.md", "alice's text\n", Some(alice)),+ f.write(scope, "notes/shared.md", "carol's text\n", Some(carol)),+ );++ let json = get_json(+ &f.api(),+ "/workspaces/default/projects/app/history/notes/shared.md",+ )+ .await;+ assert_eq!(json["total"], 3);+ let versions = json["versions"].as_array().unwrap();+ let ids: Vec<&str> = versions.iter().map(|v| v["id"].as_str().unwrap()).collect();+ for id in [base, a, c] {+ assert!(+ ids.contains(&id.to_string().as_str()),+ "{id} missing: {ids:?}"+ );+ }+ let authors: Vec<&str> = versions+ .iter()+ .filter_map(|v| v["author"]["username"].as_str())+ .collect();+ assert!(+ authors.contains(&"alice") && authors.contains(&"carol"),+ "{authors:?}"+ );+ assert_eq!(+ versions.iter().filter(|v| v["is_latest"] == true).count(),+ 1,+ "exactly one live version"+ );++ // Diff the two writers' versions against each other, by id.+ let (winner, loser) = if versions[0]["id"] == a.to_string() {+ (a, c)+ } else {+ (c, a)+ };+ let json = get_json(+ &f.api(),+ &format!(+ "/workspaces/default/projects/app/history/notes/shared.md?from={loser}&to={winner}"+ ),+ )+ .await;+ let rendered = serde_json::to_string(&json["diff"]["hunks"]).unwrap();+ assert!(rendered.contains("alice's text") && rendered.contains("carol's text"));++ let (status, html) = get(&f.web(), "/w/default/app/h/notes/shared.md").await;+ assert_eq!(status, StatusCode::OK);+ assert!(html.contains("alice") && html.contains("carol"), "{html}");+ assert_eq!(html.matches("data-version=").count(), 3);+}++/// A path, a workspace and a raw version id from elsewhere all read as not+/// found; the history of a path never mixes in another project's rows at the+/// same path.+#[tokio::test]+async fn history_refuses_foreign_project_workspace_and_version_ids() {+ let f = Fixture::new().await;+ let home = f.scope("default", "home").await;+ let other = f.scope("default", "other").await;+ let far = f.scope("elsewhere", "home").await;+ let home_v1 = f.write(home, "notes/same.md", "home one\n", None).await;+ let home_v2 = f.write(home, "notes/same.md", "home two\n", None).await;+ let foreign = f+ .write(other, "notes/same.md", "OTHER-PROJECT-SECRET\n", None)+ .await;+ f.write(other, "notes/only-other.md", "OTHER-ONLY-SECRET\n", None)+ .await;+ let far_id = f+ .write(far, "notes/same.md", "OTHER-WORKSPACE-SECRET\n", None)+ .await;+ f.write(far, "notes/only-far.md", "FAR-ONLY-SECRET\n", None)+ .await;++ let web = f.web();+ let api = f.api();+ // Control: the home history is readable and holds home's two rows only.+ let json = get_json(+ &api,+ "/workspaces/default/projects/home/history/notes/same.md",+ )+ .await;+ assert_eq!(json["total"], 2, "{json}");+ let listed = json.to_string();+ assert!(listed.contains(&home_v1.to_string()) && listed.contains(&home_v2.to_string()));+ assert!(!listed.contains(&foreign.to_string()) && !listed.contains(&far_id.to_string()));+ let (status, html) = get(&web, "/w/default/home/h/notes/same.md").await;+ assert_eq!(status, StatusCode::OK);+ assert!(!html.contains("SECRET"), "{html}");+ // Control: an explicit home pair diffs.+ let (status, _) = get(+ &web,+ &format!("/w/default/home/h/notes/same.md?from={home_v1}&to={home_v2}"),+ )+ .await;+ assert_eq!(status, StatusCode::OK);++ let refused = [+ // Another project's path, under the home project.+ "/w/default/home/h/notes/only-other.md".to_owned(),+ // Another workspace's path, under the home workspace.+ "/w/default/home/h/notes/only-far.md".to_owned(),+ // A project or workspace that does not exist.+ "/w/default/missing/h/notes/same.md".to_owned(),+ "/w/nowhere/home/h/notes/same.md".to_owned(),+ // A raw version id from another project or workspace, as either side.+ format!("/w/default/home/h/notes/same.md?to={foreign}"),+ format!("/w/default/home/h/notes/same.md?from={foreign}"),+ format!("/w/default/home/h/notes/same.md?to={far_id}"),+ format!("/w/default/home/h/notes/same.md?from={far_id}&to={home_v2}"),+ // A home version id under a different path.+ format!("/w/default/home/h/notes/only-other.md?to={home_v2}"),+ ];+ for uri in &refused {+ let (status, body) = get(&web, uri).await;+ assert_eq!(status, StatusCode::NOT_FOUND, "{uri}: {body}");+ assert!(!body.contains("SECRET"), "{uri} leaked: {body}");+ let api_uri = api_history_uri(uri);+ let (status, body) = get(&api, &api_uri).await;+ assert_eq!(status, StatusCode::NOT_FOUND, "{api_uri}: {body}");+ assert!(!body.contains("SECRET"), "{api_uri} leaked: {body}");+ }++ // A malformed id is the caller's error, not a lookup.+ let (status, _) = get(&web, "/w/default/home/h/notes/same.md?to=not-a-uuid").await;+ assert_eq!(status, StatusCode::BAD_REQUEST);+}++/// A restricted project follows the ProjectAuthz read rule on both history+/// routes: a non-grantee is refused with a 403, a grantee and root read it.+#[tokio::test]+async fn history_and_timeline_honour_grants_in_a_restricted_project() {+ let f = Fixture::new().await;+ f.store+ .writer+ .set_new_project_mode(ai_memory_store::AccessMode::Restricted)+ .await+ .unwrap();+ let scope = f.scope("default", "client").await;+ f.write(scope, "secrets/rates.md", "rate one confidential\n", None)+ .await;+ f.write(scope, "secrets/rates.md", "rate two confidential\n", None)+ .await;+ let session = f+ .session(scope, None, &[("prompt", "confidential prompt")])+ .await;+ let alice = f.user("alice").await;+ let bob = f.user("bob").await;+ f.store+ .writer+ .grant_memory(alice, scope.1, GrantLevel::Read, None)+ .await+ .unwrap();++ let web = f.web();+ let api = f.api();+ let session_uri = format!("/w/default/client/s/{session}");+ for (app, uri) in [+ (&web, "/w/default/client/h/secrets/rates.md"),+ (+ &api,+ "/workspaces/default/projects/client/history/secrets/rates.md",+ ),+ (&web, session_uri.as_str()),+ ] {+ let (status, body) = get_as(app, uri, Some(bob), None).await;+ assert_eq!(status, StatusCode::FORBIDDEN, "{uri}: {body}");+ assert!(!body.contains("confidential"), "{uri} leaked: {body}");+ let (status, body) = get_as(app, uri, Some(alice), None).await;+ assert_eq!(status, StatusCode::OK, "{uri}: {body}");+ assert!(body.contains("confidential"), "{uri}: {body}");+ let (status, _) = get_as(app, uri, None, None).await;+ assert_eq!(status, StatusCode::OK, "{uri}");+ }+}++/// The version listing and the diff are both bounded: `limit` clamps and+/// pages, and a version past the diff's input cap renders as too large+/// instead of being diffed.+#[tokio::test]+async fn history_bounds_the_version_count_and_the_diff_size() {+ let f = Fixture::new().await;+ let scope = f.scope("default", "app").await;+ let mut ids = Vec::new();+ for i in 0..5 {+ ids.push(f.write(scope, "notes/p.md", &format!("v{i}\n"), None).await);+ }+ let api = f.api();+ let json = get_json(+ &api,+ "/workspaces/default/projects/app/history/notes/p.md?limit=2&offset=2",+ )+ .await;+ assert_eq!(json["total"], 5);+ assert_eq!(json["limit"], 2);+ let listed: Vec<&str> = json["versions"]+ .as_array()+ .unwrap()+ .iter()+ .map(|v| v["id"].as_str().unwrap())+ .collect();+ assert_eq!(listed, [ids[2].to_string(), ids[1].to_string()]);+ // The default diff still compares the newest version, not the slice's.+ assert_eq!(json["diff"]["to"]["id"], ids[4].to_string());+ let json = get_json(+ &api,+ "/workspaces/default/projects/app/history/notes/p.md?limit=1000000",+ )+ .await;+ assert_eq!(json["limit"], ai_memory_store::PAGE_VERSIONS_MAX_LIMIT);+ let json = get_json(+ &api,+ "/workspaces/default/projects/app/history/notes/p.md?limit=0",+ )+ .await;+ assert_eq!(json["versions"].as_array().unwrap().len(), 1);+ // An offset past the end lists nothing and still diffs the newest pair.+ let json = get_json(+ &api,+ &format!(+ "/workspaces/default/projects/app/history/notes/p.md?offset={}",+ usize::MAX+ ),+ )+ .await;+ assert!(json["versions"].as_array().unwrap().is_empty());+ assert_eq!(json["diff"]["to"]["id"], ids[4].to_string());+ let (status, _) = get(+ &f.web(),+ &format!("/w/default/app/h/notes/p.md?offset={}", usize::MAX),+ )+ .await;+ assert_eq!(status, StatusCode::OK);++ // HTML paging links.+ let (_, html) = get(&f.web(), "/w/default/app/h/notes/p.md?limit=2").await;+ assert_eq!(html.matches("data-version=").count(), 2);+ assert!(html.contains("Older versions") && !html.contains("Newer versions"));++ let huge = "line\n".repeat(200_000);+ f.write(scope, "notes/p.md", &huge, None).await;+ let json = get_json(&api, "/workspaces/default/projects/app/history/notes/p.md").await;+ assert_eq!(json["diff"]["status"], "too_large", "{}", json["diff"]);+ assert!(json["diff"]["hunks"].as_array().unwrap().is_empty());+ let (status, html) = get(&f.web(), "/w/default/app/h/notes/p.md").await;+ assert_eq!(status, StatusCode::OK);+ assert!(html.contains("No diff shown"));+ assert!(+ html.len() < 200_000,+ "the huge body is not echoed: {}",+ html.len()+ );+}++/// The TTL promise: an expired page is hidden from normal reads until the+/// forget sweep deletes it, and its history is hidden the same way. A+/// version whose own TTL passed is neither listed nor diffable, and once the+/// live version expires the whole path reads as not found (the sweep deletes+/// every row there). Expired ids read as not found, like foreign ones.+#[tokio::test]+async fn history_hides_expired_versions_and_expired_pages() {+ let f = Fixture::new().await;+ let scope = f.scope("default", "app").await;+ let past = jiff::Timestamp::now() - jiff::SignedDuration::from_hours(1);+ let future = jiff::Timestamp::now() + jiff::SignedDuration::from_hours(24);++ // A live page whose live version expired: its whole history is gone.+ let kept = f+ .write(scope, "notes/gone.md", "EXPIRED-PAGE-OLD\n", None)+ .await;+ let expired = f+ .write_expiring(+ scope,+ "notes/gone.md",+ "EXPIRED-PAGE-NEW\n",+ None,+ Some(past),+ )+ .await;+ // An expired superseded version under an unexpired live one.+ let old_expired = f+ .write_expiring(+ scope,+ "notes/mixed.md",+ "EXPIRED-VERSION\n",+ None,+ Some(past),+ )+ .await;+ let live = f.write(scope, "notes/mixed.md", "live text\n", None).await;+ // Control: a TTL in the future is still visible.+ let not_yet = f+ .write_expiring(+ scope,+ "notes/later.md",+ "not yet expired\n",+ None,+ Some(future),+ )+ .await;++ let web = f.web();+ let api = f.api();+ for uri in [+ "/w/default/app/h/notes/gone.md".to_owned(),+ format!("/w/default/app/h/notes/gone.md?to={kept}"),+ format!("/w/default/app/h/notes/gone.md?to={expired}"),+ format!("/w/default/app/h/notes/mixed.md?from={old_expired}"),+ format!("/w/default/app/h/notes/mixed.md?to={old_expired}"),+ ] {+ for uri in [uri.clone(), api_history_uri(&uri)] {+ let app = if uri.starts_with("/w/") { &web } else { &api };+ let (status, body) = get(app, &uri).await;+ assert_eq!(status, StatusCode::NOT_FOUND, "{uri}: {body}");+ assert!(!body.contains("EXPIRED"), "{uri} leaked: {body}");+ }+ }++ let json = get_json(+ &api,+ "/workspaces/default/projects/app/history/notes/mixed.md",+ )+ .await;+ assert_eq!(json["total"], 1, "{json}");+ assert_eq!(json["versions"][0]["id"], live.to_string());+ assert!(!json.to_string().contains(&old_expired.to_string()));+ // The live version's predecessor expired, so the default diff starts+ // from empty rather than exposing it.+ assert!(json["diff"]["from"].is_null(), "{}", json["diff"]);+ assert!(!json.to_string().contains("EXPIRED"));+ let (status, html) = get(&web, "/w/default/app/h/notes/mixed.md").await;+ assert_eq!(status, StatusCode::OK);+ assert!(!html.contains("EXPIRED") && !html.contains(&old_expired.to_string()));++ let json = get_json(+ &api,+ "/workspaces/default/projects/app/history/notes/later.md",+ )+ .await;+ assert_eq!(json["versions"][0]["id"], not_yet.to_string());+ let (status, _) = get(+ &web,+ &format!("/w/default/app/h/notes/later.md?to={not_yet}"),+ )+ .await;+ assert_eq!(status, StatusCode::OK);+}++/// Page text in a diff is escaped: a line of markup renders as text.+#[tokio::test]+async fn history_diff_renders_page_markup_inert() {+ let f = Fixture::new().await;+ let scope = f.scope("default", "app").await;+ f.write(scope, "notes/x.md", "safe\n", None).await;+ f.write(+ scope,+ "notes/x.md",+ "safe\n<script>alert('diff')</script>\n\"><img src=x onerror=alert(1)>\n",+ None,+ )+ .await;+ let (status, html) = get(&f.web(), "/w/default/app/h/notes/x.md").await;+ assert_eq!(status, StatusCode::OK);+ assert!(!html.contains("<script>alert('diff')"), "{html}");+ assert!(!html.contains("<img src=x"), "{html}");+ assert!(html.contains("<script>"), "{html}");+}++// ---------------------------------------------------------------------------+// V2: session timeline+// ---------------------------------------------------------------------------++/// A 500-observation session renders a bounded page at a time, in capture+/// order, with working prev/next/jump; every render stays under a time bound.+#[tokio::test]+async fn session_timeline_pages_a_500_observation_session() {+ let f = Fixture::new().await;+ let scope = f.scope("default", "app").await;+ let rows: Vec<(String, String)> = (1..=500)+ .map(|i| (format!("step {i}"), format!("body of observation {i}")))+ .collect();+ let borrowed: Vec<(&str, &str)> = rows.iter().map(|(t, b)| (t.as_str(), b.as_str())).collect();+ let session = f.session(scope, None, &borrowed).await;+ let web = f.web();+ let base = format!("/w/default/app/s/{session}");++ let mut timings = Vec::new();+ let render = |uri: String| {+ let web = web.clone();+ async move {+ let started = std::time::Instant::now();+ let (status, html) = get(&web, &uri).await;+ (status, html, started.elapsed())+ }+ };++ let (status, html, took) = render(base.clone()).await;+ timings.push(took);+ assert_eq!(status, StatusCode::OK, "{html}");+ assert_eq!(+ html.matches("<li id=\"obs-").count(),+ 50,+ "default page size"+ );+ assert!(html.contains("id=\"obs-1\"") && html.contains("id=\"obs-50\""));+ assert!(!html.contains("id=\"obs-51\""));+ assert!(html.find("step 1<").unwrap() < html.find("step 2<").unwrap());+ assert!(html.contains("1–50 of 500"));+ assert!(html.contains("offset=50&limit=50"), "next link");+ assert!(html.contains("offset=450&limit=50"), "last link");++ // Jump to an observation: the page that holds it.+ let (_, html, took) = render(format!("{base}?at=480")).await;+ timings.push(took);+ assert!(html.contains("id=\"obs-451\"") && html.contains("id=\"obs-480\""));+ assert!(html.contains("id=\"obs-500\"") && !html.contains("id=\"obs-450\""));+ // Out-of-range jumps clamp.+ let (_, html, _) = render(format!("{base}?at=99999")).await;+ assert!(html.contains("id=\"obs-500\""));+ let (_, html, _) = render(format!("{base}?at=0")).await;+ assert!(html.contains("id=\"obs-1\""));++ // A huge limit clamps to the API's maximum page size.+ let (_, html, took) = render(format!("{base}?limit=100000")).await;+ timings.push(took);+ assert_eq!(html.matches("<li id=\"obs-").count(), 200);++ // Walk every default page: ten pages, 500 rows, none twice.+ let mut seen = 0;+ for page in 0..10 {+ let (status, html, took) = render(format!("{base}?offset={}", page * 50)).await;+ timings.push(took);+ assert_eq!(status, StatusCode::OK);+ seen += html.matches("<li id=\"obs-").count();+ }+ assert_eq!(seen, 500);+ // Past the end is an empty page, not an error.+ for offset in ["10000", &usize::MAX.to_string()] {+ let (status, html, _) = render(format!("{base}?offset={offset}")).await;+ assert_eq!(status, StatusCode::OK, "{offset}");+ assert_eq!(html.matches("<li id=\"obs-").count(), 0);+ }++ timings.sort();+ let p95 = timings[(timings.len() * 95).div_ceil(100) - 1];+ assert!(+ p95 < std::time::Duration::from_secs(2),+ "session page render p95 {p95:?}: {timings:?}"+ );+}++/// "Guilty until proven": a raw session id from another project or another+/// workspace reads as not found under the home project, and so does an owned+/// session for a different operator. Controls: the home session, and the+/// owner reading their own.+#[tokio::test]+async fn session_timeline_refuses_foreign_session_ids() {+ let f = Fixture::new().await;+ let home = f.scope("default", "home").await;+ let other = f.scope("default", "other").await;+ let far = f.scope("elsewhere", "home").await;+ let own = f.session(home, None, &[("home", "home prompt")]).await;+ let foreign = f+ .session(other, None, &[("x", "OTHER-PROJECT-PROMPT")])+ .await;+ let far_id = f+ .session(far, None, &[("x", "OTHER-WORKSPACE-PROMPT")])+ .await;+ let owned = f+ .session(home, Some("alice"), &[("mine", "ALICE-ONLY-PROMPT")])+ .await;+ let web = f.web();++ let (status, body) = get(&web, &format!("/w/default/home/s/{own}")).await;+ assert_eq!(status, StatusCode::OK, "{body}");+ assert!(body.contains("home prompt"));++ for uri in [+ format!("/w/default/home/s/{foreign}"),+ format!("/w/default/home/s/{far_id}"),+ format!("/w/default/home/s/{}", SessionId::new()),+ format!("/w/elsewhere/other/s/{foreign}"),+ ] {+ let (status, body) = get(&web, &uri).await;+ assert_eq!(status, StatusCode::NOT_FOUND, "{uri}: {body}");+ assert!(!body.contains("PROMPT"), "{uri} leaked: {body}");+ }+ let (status, _) = get(&web, "/w/default/home/s/not-a-session").await;+ assert_eq!(status, StatusCode::BAD_REQUEST);++ let owned_uri = format!("/w/default/home/s/{owned}");+ let (status, body) = get_as(&web, &owned_uri, None, Some("bob")).await;+ assert_eq!(status, StatusCode::NOT_FOUND, "{body}");+ assert!(!body.contains("ALICE-ONLY"));+ let (status, body) = get_as(&web, &owned_uri, None, Some("alice")).await;+ assert_eq!(status, StatusCode::OK, "{body}");+ assert!(body.contains("ALICE-ONLY-PROMPT"));++ // The project page lists the visible sessions and links to them, never+ // another operator's.+ let (_, project) = get_as(&web, "/w/default/home", None, Some("bob")).await;+ let link = |id: SessionId| format!("href=\"w/default/home/s/{id}\"");+ assert!(project.contains(&link(own)), "{project}");+ assert!(!project.contains(&link(owned)), "{project}");+ assert!(!project.contains(&link(foreign)));+ let (_, project) = get_as(&web, "/w/default/home", None, Some("alice")).await;+ assert!(project.contains(&link(owned)), "{project}");+}++/// Captured text is untrusted: markup and attribute-injection payloads in an+/// observation's title and body render as inert text.+#[tokio::test]+async fn session_timeline_renders_captured_markup_inert() {+ let f = Fixture::new().await;+ let scope = f.scope("default", "app").await;+ let title = "<script>alert('title')</script>";+ let body =+ "<script>alert('body')</script>\n\"><img src=x onerror=alert(1)>\n' onmouseover='alert(2)";+ let session = f.session(scope, None, &[(title, body)]).await;+ // The payload must survive ingest, or this test proves nothing.+ let stored = f+ .store+ .reader+ .observations_for_session(session)+ .await+ .unwrap();+ assert!(stored[0].body.contains("<script>"), "{:?}", stored[0].body);+ assert!(+ stored[0].title.contains("<script>"),+ "{:?}",+ stored[0].title+ );++ let (status, html) = get(&f.web(), &format!("/w/default/app/s/{session}")).await;+ assert_eq!(status, StatusCode::OK);+ assert!(!html.contains("<script>alert("), "{html}");+ assert!(!html.contains("<img src=x"), "{html}");+ assert!(!html.contains("' onmouseover='"), "{html}");+ assert!(!html.contains("\"><img"), "{html}");+ assert!(html.contains("<script>alert("), "{html}");+}diff --git a/crates/ai-memory-web/tests/suite/mod.rs b/crates/ai-memory-web/tests/suite/mod.rsindex aa665b2b..687f5d8c 100644--- a/crates/ai-memory-web/tests/suite/mod.rs+++ b/crates/ai-memory-web/tests/suite/mod.rs@@ -2,5 +2,6 @@//! test harness (see the `integration` module in `src/lib.rs`), so they cost//! no extra binary; a new file must be declared below.+mod history_replay;mod pending;mod routes;diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex 17f47322..8e05adf8 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -1276,12 +1276,20 @@ embeddings spec, and is not covered by a live test against Copilot here.keeping deletes and semantic rewrites review-gated.* **Richer read surfaces for the web UI.** The multi-workspace read-onlywiki browser shipped in `ai-memory-web` (`/web`: project list, page- tree, page view, search, and the root-only `/web/pending` triage page,+ tree, page view, page history with a server-side unified diff, a paged+ session timeline, search, and the root-only `/web/pending` triage page,whose approve and reject buttons post to the existing`/admin/pending-writes/*` routes). It stays read-only by design: the wiki is amachine-authored record, and a browser edit surface would break the- invariant the whole store rests on (#482). Better *reading* (richer- navigation, diff/history views, graph exploration) is open. See+ invariant the whole store rests on (#482). The crate's `clippy.toml` forbids+ the `Wiki` write and destructive methods there, so a write path fails+ `cargo clippy -D warnings`. History reads every version at a path (`ReaderPool::page_versions`,+ `page_version_body`, both keyed by workspace, project and path), so a version+ a concurrent write replaced stays visible (invariant #16). TTL expiry still+ applies: an expired version is neither listed nor readable by id, and a page+ whose live version expired shows no history, since the forget sweep deletes+ every row at its path. Better *reading*+ (graph exploration, recall traces) is open. See[`docs/frontend-api.md`](frontend-api.md#10-known-gaps-and-deliberate-non-goals).* **Real LongMemEval-S harness.** The recall-eval framework exists([`crates/ai-memory-consolidate/tests/suite/recall_eval.rs`](../crates/ai-memory-consolidate/tests/suite/recall_eval.rs));diff --git a/docs/frontend-api.md b/docs/frontend-api.mdindex 06bd55bf..b63dab7d 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; 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. |+| `/api/v1/*` | Browse workspaces, projects, pages; read full page markdown + frontmatter + back-links; list a page's stored versions and diff two of them; 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, and `crates/ai-memory-web/clippy.toml` forbids the `Wiki` write and destructive methods anywhere in the crate, so adding one fails `cargo clippy -D warnings`. 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@@ -40,6 +40,13 @@ builtin wiki exposes public `GET {web_slug}/login` and`GET {web_slug}/change-password` HTML pages that call the same `/auth/*`endpoints; navigational browser GETs to protected wiki routes redirect thereinstead of returning bare JSON 401/403. `/api/v1` stays JSON either way.+The builtin wiki also serves `GET {web_slug}/w/{workspace}/{project}/h/{*path}`+(a page's version history and diff, the HTML twin of §4.13) and+`GET {web_slug}/w/{workspace}/{project}/s/{session_id}` (a session's+observations in capture order, a page at a time, through the same readers,+visibility rule and caps as §4.11 and §4.12; `offset`, `limit` clamped+`1..=200`, default `50`, and `at` to jump to the page holding a 1-based+position). Both follow the same per-project read rule as the page view.The builtin wiki also serves the root-only `GET {web_slug}/pending` page. Itlists pending auto-improvement proposals and posts approve and reject to theexisting `/admin/pending-writes/*` routes. A signed-in non-root user gets a@@ -592,10 +599,90 @@ historical text. Never cached (`no-store`). Same payload as the MCP tool}```+### 4.13 Page history and diff++```http+GET /api/v1/workspaces/{workspace}/projects/{project}/history/{*path}?limit=50&offset=0&from={id}&to={id}+```++Every stored version of one page path, newest first, and a unified diff+between two of them. Superseded versions (`is_latest: false`) are listed: a+version another write replaced stays readable, so two concurrent writers+both show up. `limit` clamped `1..=200`, default `50`; `offset` default `0`;+`total` counts every version at the path. `to` defaults to the newest+version, `from` to the version `to` replaced (none for a first version, which+then diffs against empty). Both are version ids from this listing (the `id`+also returned by §4.4). An id from another project, workspace or path is a+`404`, the same as an unknown one; a malformed id is a `400`. A path with no+versions is a `404`. Expired versions follow the TTL rule of every other read:+a version whose `expires_at` has passed is not listed and its id is a `404`,+and a page whose live version expired has no history at all (`404`), because+the next forget sweep deletes every row at its path. A `supersedes` link to a+hidden version is `null`. Never cached (`no-store`).++The diff is bounded. A side larger than 512 KiB or 10,000 lines, or a pair+more than 1,000 changed lines apart, returns `status: "too_large"` with a+`reason` and no hunks. Otherwise `hunks` carries at most 2,000 lines, with+three lines of context, and `truncated: true` when the cap cut it short.+Bodies are untrusted page text; render them escaped.++**Response:**++```json+{+ "workspace": "default",+ "project": "app",+ "path": "notes/plan.md",+ "total": 2,+ "offset": 0,+ "limit": 50,+ "versions": [+ {+ "id": "01a1…b2",+ "supersedes": "01a1…a7",+ "is_latest": true,+ "title": "Plan",+ "tier": "semantic",+ "created_at": "2026-10-12T09:12:00.000Z",+ "body_chars": 412,+ "author": { "username": "carol" }+ },+ {+ "id": "01a1…a7",+ "supersedes": null,+ "is_latest": false,+ "title": "Plan",+ "tier": "semantic",+ "created_at": "2026-10-11T17:40:12.000Z",+ "body_chars": 380+ }+ ],+ "diff": {+ "from": { "id": "01a1…a7", "title": "Plan", "created_at": "2026-10-11T17:40:12.000Z" },+ "to": { "id": "01a1…b2", "title": "Plan", "created_at": "2026-10-12T09:12:00.000Z" },+ "status": "changed",+ "truncated": false,+ "hunks": [+ {+ "old_start": 3, "old_len": 2, "new_start": 3, "new_len": 2,+ "lines": [+ { "op": " ", "text": "shared line" },+ { "op": "-", "text": "revision 0" },+ { "op": "+", "text": "revision 1" }+ ]+ }+ ]+ }+}+```++`author` is omitted for an unattributed write. `status` is `same`, `changed`+or `too_large`; `from` is `null` when `to` replaced nothing at this path.+## 5. Limits and pagination-- Most `limit` query params clamp to `1..=100`; handoff history and- session observations clamp to `1..=200`. Session listing and session+- Most `limit` query params clamp to `1..=100`; handoff history, session+ observations and page history clamp to `1..=200`. Session listing and sessionobservations 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.@@ -606,7 +693,7 @@ historical text. Never cached (`no-store`). Same payload as the MCP tool`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 NotModified`. Briefing, overview, handoff-list, session-list and session- observation responses depend on the authenticated actor and therefore use+ observation and page-history 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 the@@ -777,6 +864,7 @@ Read these:| Route registration + handler bodies | `crates/ai-memory-web/src/routes/api.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` |+| Page-history readers (`page_versions`, `page_version_body`) and the bounded diff | `crates/ai-memory-store/src/reader.rs`, `crates/ai-memory-web/src/diff.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`) |@@ -816,7 +904,8 @@ accepting wildcard. The layer allows `GET / POST / OPTIONS`,everything else (pages supersede on body change). The line is betweenadding to the record through the normal path and editing it fromoutside. A human-editable wiki is a reasonable thing to want and a- separate product; see #482.+ separate product; see #482. The history view shows what changed between+ versions; it has no restore button, for the same reason.- **Rate limiting** is shared with `/mcp` + `/admin` (only the bodycap is enforced today). A future global limiter would tighten theauthenticated-misbehaviour case.diff --git a/docs/security-boundaries.md b/docs/security-boundaries.mdindex 39093a8a..df234083 100644--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@ -22,7 +22,7 @@ means the boundary is not built yet.| # | Boundary | Enforcing code | Adversarial test(s) | Coverage ||---|----------|----------------|---------------------|----------|-| 1 | Per-project isolation (3-tuple) | `ai-memory-store/src/scope.rs` `ScopeResolver::resolve_read_args`/`resolve_write_args`, no-create `lookup_existing_scope`; reader queries filter by `(workspace_id, project_id)`; `reader.rs` `sessions_for_scope_filtered` joins only consolidation jobs in the requested workspace and project; `reader.rs` `incremental_pages` filters workspace and project before its keyset and limit; `reader.rs` `session_counts_by_agent` filters mixed-source observations by the requested workspace and project; `reader.rs` `observation_stream_votes` (opt-in `[retrieval] observation_stream`) filters both the matching observations and the `sessions/<id>.md` page they vote for to the queried workspace and project | `store` `scope.rs` read-resolution table tests; `tests/suite/multi_session.rs`; `session_observations.rs` `consolidation_summary_latest_generation_is_scope_and_owner_bound` (a foreign-scope job is absent; the own latest generation and owner controls pass), `incremental_pages_equal_timestamps_cutoff_expiry_and_foreign_scope` (foreign scope absent with a same-scope control), `mixed_capture_count_scopes_observations_and_preserves_owner_and_window` (foreign-scope observations cannot turn an own session into a mixed one; same-scope control can); handoff receiver-session scope: see row 4, `multi_session.rs` `handoff_accept_rejects_foreign_or_missing_receiver_session` (cross-project and cross-workspace receivers refused); `multi_session.rs` `observation_stream_never_crosses_a_project_or_workspace` (a home observation cannot vote for a same-path session page in another project or workspace, and a foreign project's observation cannot lift a home page; control: home's own page receives the vote), fails with either the observation or the page scope filter removed | STRONG |+| 1 | Per-project isolation (3-tuple) | `ai-memory-store/src/scope.rs` `ScopeResolver::resolve_read_args`/`resolve_write_args`, no-create `lookup_existing_scope`; reader queries filter by `(workspace_id, project_id)`; `reader.rs` `sessions_for_scope_filtered` joins only consolidation jobs in the requested workspace and project; `reader.rs` `incremental_pages` filters workspace and project before its keyset and limit; `reader.rs` `session_counts_by_agent` filters mixed-source observations by the requested workspace and project; `reader.rs` `observation_stream_votes` (opt-in `[retrieval] observation_stream`) filters both the matching observations and the `sessions/<id>.md` page they vote for to the queried workspace and project; `reader.rs` `page_versions` / `page_version_body` (web page history) read by `(workspace_id, project_id, path)` and take a caller's version id only inside that triple; `ai-memory-web` `routes/session.rs` takes a raw session id only through `session_summary_scoped` (row or observation in the project, owner filter) and `session_observations_scoped` | `store` `scope.rs` read-resolution table tests; `tests/suite/multi_session.rs`; `session_observations.rs` `consolidation_summary_latest_generation_is_scope_and_owner_bound` (a foreign-scope job is absent; the own latest generation and owner controls pass), `incremental_pages_equal_timestamps_cutoff_expiry_and_foreign_scope` (foreign scope absent with a same-scope control), `mixed_capture_count_scopes_observations_and_preserves_owner_and_window` (foreign-scope observations cannot turn an own session into a mixed one; same-scope control can); handoff receiver-session scope: see row 4, `multi_session.rs` `handoff_accept_rejects_foreign_or_missing_receiver_session` (cross-project and cross-workspace receivers refused); `multi_session.rs` `observation_stream_never_crosses_a_project_or_workspace` (a home observation cannot vote for a same-path session page in another project or workspace, and a foreign project's observation cannot lift a home page; control: home's own page receives the vote), fails with either the observation or the page scope filter removed; `multi_session.rs` `page_history_keeps_the_overwritten_version_and_stays_in_scope` (a sibling project's or another workspace's version id, or a home id under another path, reads as `None`; control: both home versions); `ai-memory-web` `history_replay.rs` `history_refuses_foreign_project_workspace_and_version_ids` (another project's or workspace's path, and a foreign version id as `from` or `to`, answer 404 on `/web/w/…/h/*path` and `/api/v1/…/history/*path` without the foreign text; control: the home history lists only home's rows at a path a sibling also uses, and an explicit home pair diffs) and `session_timeline_refuses_foreign_session_ids` (a sibling project's or another workspace's session id and an unknown id → 404, another operator's owned session → 404; controls: the home session, and the owner reading theirs); bite: dropping the scope filter from `page_version_body` or the project filter from `page_versions`, or replacing the `session_summary_scoped` check or its owner filter, fails them | STRONG || 1b | Reserved `_global` scope union never leaks a foreign project (#930) | `ai-memory-mcp/src/server.rs` `memory_query` — the union runs for single-project queries (`scopes` empty) and searches **only** `lookup_global_scope`'s reserved `(workspace_id, project_id)`, never an arbitrary project; the double-search guard resolves the *queried* project (named or active) so it can't be tricked into skipping | `server.rs` `global_union_never_leaks_a_foreign_projects_pages` (a third real project's page must not surface via the union; reserved page must), `single_project_query_unions_global_scope_and_multi_scope_skips_it` | STRONG || 1c | Reserved `_global` scope is read-open, write-gated (GHSA-7qj3-7wqw-m5w6) | `ai-memory-store/src/project_authz.rs` `ProjectAuthz::authorize` (a write to `default/_global` needs root or a `write` grant in either access mode; creator ignored) fed by `resolve_project_authz`/`read_project_row` (`reserved_global`, grant read for the global scope regardless of mode); `ai-memory-mcp/src/server.rs` `memory_write_page` resolves `scope: "global"` through `write_target_ids_with_actor` like an explicit `default/_global` | `project_authz.rs` `the_global_scope_admits_writes_only_from_root_or_a_write_grant`; `server.rs` `a_user_without_a_global_grant_cannot_change_the_global_scope` (both spellings and delete refused for an ungranted user and for `_global`'s creator; page survives; reads stay open), `a_global_write_grant_admits_writes_and_the_union_stays_readable` (legitimate control: write grant admits both spellings, another user's restricted-project query still unions the page); bite-checked with the authz rule removed and with the raw `create_global_scope` path restored | STRONG || 1d | A private cross-project profile is readable and writable by its operator alone (`[profile] share = "user"`) | `ai-memory-store/src/ops.rs` `initial_access_mode` (a `_profile.<user id>` project is always created `restricted`, creator recorded in the same transaction); `ai-memory-store/src/scope.rs` `lookup_profile_scope` / `create_profile_scope` (the project name derives from the authenticated viewer's id; no database user, no private profile); `ai-memory-mcp/src/server.rs` `profile_target_ids` and the `memory_query` profile union (resolved per viewer through the per-project choke point); `scope.rs` `refuse_foreign_profile_name` (called by `ScopeResolver` explicit writes and `create_explicit_scope_guarded`: a database user may name only their own `default/_profile.<id>`, so nobody can create another operator's private profile first and lock its owner out); `ops.rs` `rename_project` (no rename onto or away from a profile name); `admin.rs` `handle_project_access` (a profile project's mode is fixed) and `move_project_core` (a private profile cannot leave `default`) | store `integration::profile` `a_private_profile_refuses_every_other_operator` (another operator's read and write by name refused; owner control admitted), `reserved_profile_projects_get_their_fixed_access_modes`; `server.rs` `a_private_profile_is_private_to_its_operator` (no union leak; read, write and delete by name refused; owner and own-profile controls); `multi_session.rs` `two_harnesses_of_one_operator_share_one_private_profile`; both fail with the restricted-mode guard removed; `server.rs` `a_user_cannot_squat_another_operators_private_profile` (another user's explicit write naming the owner's private profile refused and creates nothing; owner's profile and explicit own-name controls; fails with the name guard removed); `ops.rs` `rename_project_refuses_profile_names_both_ways`; `admin.rs` `project_access_sets_the_mode_and_refuses_what_it_must`; `admin_move.rs` `move_project_refuses_a_private_profile` | STRONG |@@ -30,7 +30,7 @@ means the boundary is not built yet.| 1f | Event capture never lands in a profile project, and the sweep keeps them | `ai-memory-hooks/src/router.rs` project resolution refuses `ai_memory_core::profile::is_reserved_scope_project` (`_global`, `_profile`, `_profile.*`) from a directory or a marker override, falling back to the server default; `ops.rs` `sweep_hollow_projects` exempts `_profile` and `_profile.%` | `router.rs` `capture_is_never_attributed_to_a_profile_project` (override and directory spellings refused; ordinary `my_profile` control resolves), fails with the check narrowed to `_global`; store `integration::profile` `the_hollow_project_sweep_keeps_empty_profile_projects` | STRONG || 1g | The profile reaches only the sessions it is meant for: off by default on a multi-user server, suppressed by `[profile] consume = false`, and an opt-out is sticky | `ai_memory_core::profile::ProfileSettings::effective_share` (`enabled = auto` is off once operators are distinguished); `router.rs` `persist_profile_flags` (flags are tri-state: an absent forwarded value keeps the stored one, so a client that sends nothing never undoes an opt-out; every front door sends explicit `0`/`1` once a marker resolved) and `render_requested_profile_digest` (a team profile is headed "team defaults"); `server.rs` `memory_query` drops `profile/` hits for a project whose stored `profile_consume` is off; `admin_profile.rs` `handle_apply` (`ai-memory profile apply`) returns no lines for such a project and sits behind the root-only `/admin/*` gate on a multi-user server | `router.rs` `a_multi_user_server_has_no_profile_digest_by_default`, `profile_digest_honours_consume_once_per_session_and_the_server_switch`, `session_start_records_the_marker_profile_flags` (a session start with no flags after an opt-out keeps the project out of the harvest and the digest; fails when an absent flag defaults to on); `server.rs` `the_single_user_profile_lives_in_global_and_honours_consume` (fails with the consume filter removed); `admin_profile_routes.rs` `apply_lists_the_lines_for_a_project_and_honours_consume`, `apply_is_root_only_on_a_multi_user_server` (database user refused, root control admitted); core `profile::tests::effective_share_matrix` | STRONG || 1h | The profile learns only from what it may: the user's own prompts and curated pages, from contributing projects, never another operator's words in a private profile and never a restricted project in a shared one; stored text stays data | `ai-memory-store/src/profile.rs` `profile_prompts_since` (only `user-prompt` observations), `auto_improve_decided_by` (the decider agent a page's `auto_improve_proposal_id` resolves to), `profile_harvest_projects` / `profile_candidates` (`profile_contribute = 0` excluded, including candidates recorded before the opt-out); `ai-memory-consolidate/src/profile.rs` `user_written` (a harness turn or Codex's injected instructions stored as a prompt is skipped whole, and ai-memory's routing and untrusted-history blocks, fenced by markers on their own lines, are cut out before any sentence is read), the auto-approved-proposal skip in `harvest_project` (a page the auto-improve scheduler auto-approved is model output nobody reviewed and never becomes a candidate; a human-approved page, or one whose proposal id has no row, stays curated, #1211), `convergence_targets` (a `user` target keeps only candidates whose `contributor` is that operator, from projects the per-project choke point lets them read; a `global`/`workspace` target on an operator-distinguishing server drops restricted projects), `min_contributors` / `converge` (a team profile admits a statement only on evidence from at least two distinct operators, so one operator cannot plant a default in everyone's session start) (never rewrites a page without its `generated_by` stamp or whose body changed; `profile_entry_ledger` keeps a forgotten entry out), `classify_batch` / `merge_entry` (sanitized, JSON-encoded input; the evidence quote is always the user's sentence) | consolidate `integration::profile_harvest` `tool_output_is_never_a_candidate`, `an_opted_out_project_is_never_harvested`, `a_private_profile_never_harvests_another_operator`, `a_team_profile_never_harvests_a_restricted_project`, `a_team_profile_needs_more_than_one_operator` (one operator in two open projects not admitted; a second operator admits it; fails with the threshold at one), `a_personal_profile_admits_one_operators_habit` (control), `a_hand_edited_entry_is_never_clobbered`, `a_forgotten_entry_is_not_recreated_until_said_again`, `injected_instructions_stay_data`, `injected_instructions_and_ai_memory_blocks_are_never_candidates`, `page_metadata_fields_are_never_candidates`, `auto_approved_auto_improve_pages_are_never_candidates` (an auto-approved page refused; human-approved and hand-written controls admitted; fails with the decider check removed), consolidate `profile::tests::a_stored_page_metadata_field_is_not_a_waiting_habit` (each with a legitimate control; each fails with its guard removed); mcp `integration::admin_profile_routes` `review_and_rebuild_are_root_only_on_a_multi_user_server` | STRONG |-| 2 | Workspace isolation | same as #1; same-named project → distinct ids per workspace | `scope.rs` cross-workspace resolution rows; `multi_scope` dedup/validate | STRONG |+| 2 | Workspace isolation | same as #1; same-named project → distinct ids per workspace | `scope.rs` cross-workspace resolution rows; `multi_scope` dedup/validate; `ai-memory-web` `history_replay.rs` (another workspace's page path, version id and session id answer 404, same tests and bites as row 1) | STRONG || 2b | Managed-workstream discovery stays checkout-local, including pagination | `ai-memory-workstream/src/repository.rs` `inspect_repository_fingerprints` shares the launch identity derivation without checkpoint scans; `ai-memory-cli/src/commands/resume.rs` `candidates_for_checkout` queries only the cwd, never registry links; the explicit `--all` walk (`candidates_across_checkouts`) lists each linked checkout through its own fingerprint-scoped request and applies `--workspace` before any request; `ai-memory-hooks/src/workstream.rs` `list_recent_workstreams` resolves an authorized explicit scope on every page; `ai-memory-store/src/workstream.rs` `list_recent` applies workspace/project/repository/worktree predicates before `LIMIT`/`OFFSET` | `resume.rs` `resume_lists_all_current_checkout_rows_not_registered_foreign_checkouts` (same scope/remote foreign checkout refused, 125 local rows visible), `empty_current_checkout_does_not_fall_back_to_the_registry`, `resume_all_walks_every_linked_checkout_and_honours_the_workspace_filter` (a foreign workspace filter sends no request; the default picker still ignores the registry); `workstream.rs` `recent_workstream_pages_reach_older_rows_without_crossing_checkout_or_scope` (foreign repo, worktree, project and workspace excluded on every page; 105 legitimate rows reach the client, huge offsets return nothing); store `recent_workstreams_are_checkout_local_and_include_linked_harnesses` (page two keeps native harness links); `repository.rs` `reports_origin_push_url_and_linked_worktree` verifies lightweight/full fingerprint parity and distinct worktree keys; CLI `resume_yolo_displays_picker_without_scanning_git_status` verifies listing skips status scans | STRONG || 3 | Multi-user auth ladder | `ai-memory-core/src/actor.rs` `AuthLevel::authorize`; `ai-memory-mcp/src/auth.rs` middleware; `admin.rs` `require_root_for_multiuser_admin` / `require_root`; `identity.rs` authorizes `NormalRead` behind the same machine bearer middleware as MCP; `serve.rs` mounts API-only and web+API protected routers behind `require_dual_auth` | `admin.rs` `multiuser_admin_routes_reject_db_user_tier` / `…reject_anonymous` / `create_user_as_user_tier_returns_403`; `auth.rs` unknown-bearer 401; `actor.rs` `skip_admission_chain_rejects_db_users`; `identity.rs` `identity_real_auth_isolates_users_root_and_revoked_keys`, `identity_anonymous_ignores_forged_headers_and_proxy_qualifies_oidc` (distinct users and root, invalid/revoked keys, forged headers, anonymous control); `serve.rs` `api_only_mode_keeps_data_authenticated_and_web_absent` (anonymous API read refused, authenticated control admitted, browser route absent; #986) | STRONG || 3b | Browser triage of pending writes (#855) | `ai-memory-web/src/routes/pending.rs` `require_admin` (`AuthLevel::authorize(Capability::Admin, distinguishes_operators)`, trusted-proxy flag from `WebMountSpec`) gates `GET {web_slug}/pending`; `html_auth.rs` `AdminRequired` keeps a non-root 403 off the change-password redirect; decisions post to the existing `/admin/pending-writes/{id}/approve\|reject` behind `require_dual_auth` (session + CSRF) and `require_root_for_multiuser_admin`. `ai-memory-web` has no write route | `ai-memory-web` `tests/suite/pending.rs` — anonymous refused (401, login redirect), DB user refused (403, no proposal text, no redirect), trusted-proxy flag reaches the gate, single-operator control admits, POSTs to `/pending*` refused, project filter keys do not collide on `/` in names, projects past the 500-row read cap stay counted and reachable; `ai-memory-mcp` `tests/suite/admin_pending_writes_session.rs` — anonymous and DB-user sessions refused, root session without a matching CSRF header refused (each leaves the proposal pending and no file), root approval keeps `auto_improve_proposal_id`/`auto_improve_run_id` and records the approver, root reject writes no file (each proven to fail with its guard removed); `ai-memory-mcp` `admin.rs` `pending_write_approve_foreign_scope_returns_404` and `pending_write_reject_foreign_scope_returns_404` — an id staged in workspace `alpha` requested through an existing `default` scope is 404 (never approved or rejected across the boundary), with the in-scope reject as the legitimate control (each proven to fail with 500 with the `pending_detail` guard removed, #1205) | STRONG |@@ -44,7 +44,7 @@ means the boundary is not built yet.| 4g | `memory_handoff_accept` `status` never points a caller at another session's baton | `ai-memory-store/src/reader.rs` `handoff_claimed_by_live_session` — the caller-supplied session id (header or native `_meta`, routing-only per row 6b) selects which claim to check, but the answer is bounded by the resolved `(workspace_id, project_id)`, the authenticated `handoff_owner_sql` owner filter, `state='accepted'`, and a still-open receiving session; `ai-memory-mcp/src/server.rs` `unclaimed_handoff` reports `consumed_by_hook` only on that match (and, for a requested `handoff_id`, only when it is the matched row), `none_pending` otherwise | `handoff_ownership.rs` `a_session_start_claim_is_confirmed_only_to_its_own_live_session` (forged session id under another operator, unattributed reader, foreign project, sibling session and ended session all empty; owner and root controls see the claim); `ai-memory-mcp` `tests/suite/handoff_identity.rs` `consumed_by_hook_is_reported_only_to_the_session_that_claimed_it` (over the production transport: a colleague forwarding the session id, the owner from another session, and a request with no session id all get `none_pending`; the claiming session gets `consumed_by_hook`) | STRONG || 4h | Offer-mode SessionStart never consumes or injects handoff-controlled text | `ai-memory-hooks/src/router.rs` `fetch_and_accept_handoff_at` branches on the startup configuration before admission/claim and `render_handoff_notice` emits only typed metadata (`HandoffId`, `AgentKind`, computed age); the normal writer CAS remains the only later claim path | `router.rs` `handoff_notice_is_metadata_only_and_never_carries_the_summary` plants hostile summary/questions/steps/files; `offer_mode_leaves_the_baton_open_and_notice_omits_the_summary` exercises the production hook route, asserts the row remains open, then proves the legitimate exact-id writer claim still consumes it (#1030) | STRONG || 5a | Pages shared: `author_id` is never a read filter (invariant #16) | `ai-memory-store/src/reader.rs` `search_pages`/`page_body_by_ids` — `author_id` is an attribution JOIN only, never a WHERE term; `observation_stream_votes` takes no owner or author coordinate | `multi_session.rs` — a page with a **non-null** `author_id` (operator A) is readable by operator B in the same project; `multi_session.rs` `another_operators_observations_lift_their_session_page_in_a_shared_project` (operator B's owned session, authored page and observations lift that page for operator A's query); `ai-memory-mcp` `server.rs` `observation_stream_evidence_stays_inside_a_restricted_project` (a second operator with only a read grant gets the session page lifted by the first operator's observation) | STRONG |-| 5b | Page supersession (loser stays reachable) | `ai-memory-store/src/ops.rs` `upsert_page_in_tx` — demote `is_latest=0` (never delete) + `supersedes` chain | `multi_session.rs` `concurrent_writes_to_one_path_supersede_rather_than_destroy`; `retrieval_superseded.rs` | STRONG |+| 5b | Page supersession (loser stays reachable) | `ai-memory-store/src/ops.rs` `upsert_page_in_tx` — demote `is_latest=0` (never delete) + `supersedes` chain; read side: `reader.rs` `page_versions` lists every row at the path, with no `is_latest` filter, for `/web/w/…/h/*path` and `/api/v1/…/history/*path`. It does apply TTL expiry (`reader.rs` `history_visible`): a version whose own `expires_at` passed is neither listed nor readable by id, a path whose live version expired shows no history at all (the forget sweep hard-deletes every row there), and a `supersedes` link to a hidden version reads as `null`. Expiry is the only thing that hides a superseded version; a concurrent write never does | `multi_session.rs` `concurrent_writes_to_one_path_supersede_rather_than_destroy`; `retrieval_superseded.rs`; `multi_session.rs` `page_history_keeps_the_overwritten_version_and_stays_in_scope`; `ai-memory-web` `history_replay.rs` `history_keeps_both_sides_of_a_concurrent_divergent_write` (two attributed writers on one base: all three versions and both authors listed, one `is_latest`, the two writers' versions diff by id) and `history_lists_k_plus_one_versions_newest_first_and_diffs_the_latest`; bite: an `is_latest = 1` filter in `page_versions` fails both; `history_hides_expired_versions_and_expired_pages` (an expired superseded version and every version of a page whose live version expired answer 404 by path and by id on HTML and JSON, and the live successor's `supersedes` is `null`; control: a TTL in the future is listed and diffable; bites with the per-row predicate removed, with the live-version clause disabled, and with the `supersedes` hiding removed) | STRONG || 5c | Watcher reindex and Wiki writes share per-page serialization (invariant #16) | `ai-memory-wiki/src/wiki.rs` `reindex_page` takes `mutation_lock.read` before `reindex_page_locked` takes `lock_page`, covering disk read through the single-writer upsert; callers already holding the exclusive global guard do not reacquire it. `write_page` uses the same page mutex and `apply_batch` retains sorted, deduplicated locks; embedding runs after both guards are released | `wiki.rs` `reindex_page_lock_waits_before_reading_and_allows_another_path` (transient snapshot refused while locked, another path progresses, release indexes the committed bytes without rewriting disk), `reindex_page_lock_serializes_write_through_the_upsert` and `reindex_page_lock_and_reversed_duplicate_batches_do_not_deadlock` (real concurrent operations, final disk/SQL winner and supersession ancestry preserved); all three fail with the reindex page guard removed. `reindex_page_lock_releases_both_guards_before_embedding` checks both body and abstract embedding; `decay_cleanup_reindex_does_not_embed_under_the_exclusive_lock` covers the exclusive caller | STRONG for a shared Wiki handle and its clones. External editors and independently constructed Wiki handles do not participate in these locks || 5d | Wiki project-tree filesystem confinement | `ai-memory-wiki/src/confinement.rs` checks the wiki root, workspace/project roots, every existing ancestor, the final component, and the in-root ordinary `.git` directory with link-aware metadata; repository workdir/gitdir/commondir are containment-checked after opening, and write parents are created one component at a time and rechecked. `Wiki` checks before admission and again under mutation/page locks, while `GitAdapter` rechecks immediately before writes, appends, renames, and removals. Direct reindex, checkpoint restore, manifests, auto-improvement artifacts, ledger append, startup repair, purge/session moves, rollback, migrations, and git tree staging use the same boundary. Confinement is a distinct `WikiError` and therefore cannot trigger missing-file DB fallback | `wiki.rs` `page_reads_refuse_leaf_and_ancestor_symlinks_without_fallback_classification`, `ai-memory-mcp` `admin_read_page.rs` `read_page_does_not_db_fallback_through_a_symlink`, `page_mutations_refuse_ancestor_symlink_and_leave_outside_and_store_unchanged`, `confinement_refusal_happens_before_blocking_and_observer_admission`, `restore_and_reindex_refuse_ancestor_symlink_without_touching_canary_or_db`; `git.rs` `git_metadata_link_is_refused_without_touching_external_repository`, `gitfile_redirect_outside_is_refused_without_touching_target`, `git_metadata_redirect_files_are_refused_before_repository_open`, `configured_worktree_outside_the_wiki_root_is_refused`, `linked_git_metadata_never_reaches_commit_fallback`, `gitfile_metadata_never_reaches_commit_fallback`, `out_of_root_worktree_never_reaches_commit_fallback`, `fallback_preflight_refuses_invalid_git_metadata`, `windows_commit_fallback_accepts_established_eligible_errors`, `eligible_windows_open_error_dispatches_the_fallback_after_validation`, `windows_init_error_dispatches_fallback_after_root_preflight`, `invalid_root_never_reaches_init_fallback`, `checkpoint_and_revision_reads_refuse_a_replaced_git_directory`, and ordinary-repository/API controls `init_is_idempotent_and_creates_dotgit`; `linked_wiki_root_is_refused_during_construction`, `linked_or_dangling_scope_roots_are_refused_but_real_roots_work`, existing `decay_cleanup_refuses_to_reindex_a_symlinked_recreation` and `reindex_rejects_symlinked_scope_manifest`; `ai-memory-mcp` `admin_move.rs` `true_move_refuses_an_invalid_destination_namespace_without_db_changes` and `delete_workspace_refuses_invalid_namespace_before_db_or_notification`; `admin_backup.rs` `backup_refuses_redirected_git_metadata_before_returning_an_archive`, `backup_refuses_wiki_leaf_links_before_returning_an_archive`, `backup_refuses_linked_wiki_directories_before_returning_an_archive`, and ordinary archive controls; `watcher.rs` `direct_file_event_skips_symlink`, `walk_markdown_skips_linked_directories_and_their_ledgers`, and `shared_link_like_helper_accepts_regular_files_and_directories` (Windows directory-link coverage exercises reparse metadata when privilege is available); `backup.rs` `a_pre_migration_backup_refuses_a_linked_wiki_tree_without_an_archive`; `confinement.rs` metadata-helper controls run on every platform | STRONG for imported/static links and same-process mutations. Component checks do not claim descriptor-relative protection against a concurrently malicious same-user process; Windows reparse behavior requires the `windows` PR label/full CI || 5e | Conditional page mutation (#986, invariant #16) | `ai-memory-store/src/ops.rs` `upsert_page_if` reads the latest version and writes in one transaction, the authority; `ai-memory-wiki/src/wiki.rs` `write_page_if` pre-checks under the per-page lock before touching disk and restores the file when the store check fails; conditional deletes reuse `delete_page_if_latest` (exclusive mutation lock plus an in-transaction check). `ai-memory-mcp/src/server.rs` checks the precondition only after scope resolution and the write grant, against the resolved scope's own latest row, and returns `precondition_failed` with no write, checkpoint or webhook dispatch | `multi_session.rs` `conditional_writers_on_one_base_exactly_one_wins_and_nothing_is_destroyed` (two writers from one version: one wins, the base stays reachable, no loser row; fails with the store check removed); `server.rs` `conditional_page_writes::*` (stale id, `create_only` on an existing page, a version id from another project, and conditional deletes are refused and change nothing, with and without the wiki pre-check; the store check proven to bite with the reader pre-check off); `a_reader_may_read_everything_and_change_nothing` (a read-only user's conditional write or delete, with the right id or a wrong one, gets the authorization error and no version data; the page is unchanged) | STRONG |@@ -80,11 +80,12 @@ means the boundary is not built yet.| 12 | Network/auth posture | `config.rs` loopback `DEFAULT_BIND`; `serve.rs` `validate_http_exposure`, `require_allowed_host`; `auth.rs` `require_bearer`; `serve.rs` mounts `/identity` inside the host and machine-auth gates even with web disabled; `nix/nixos-module.nix` treats only literal `127.0.0.1`/`::1` as loopback, requires exactly one secret environment source for other binds, keeps secret auth and `llm_headers` values out of the Nix store, and brackets IPv6 in `ExecStart` | `serve.rs` host-guard (missing→400 / forged→403), non-loopback-requires-token; `auth.rs` wrong-token 401; `serve.rs` `machine_identity_remains_authenticated_with_web_disabled_and_expired_keys` (wrong and expired keys refused, valid machine key accepted, web remains disabled); `flake.nix` `nixos-module-eval` refuses `localhost` and `0.0.0.0` without a secret source, refuses two secret sources, `settings.auth` secrets, and `settings.llm_headers`, with literal IPv4/IPv6 loopback and one-source controls | STRONG || 12b | Managed-workstream provenance privacy, stable replay identity and server event namespace | `ai-memory-core/src/workstream.rs` `scrub_workstream_provenance`; `ai-memory-hooks/src/workstream.rs` `finish_run` reserved client-id check and `sanitize_events` before immutable segments, with `sanitize_events` and `append_boundary_events` scrubbing event/checkpoint/losses content *before* the 64 KiB cap so a cap-straddling secret is never cut into an unmatchable prefix (#1113); `ai-memory-store/src/workstream.rs` `finish_run` stable identity check and `stored_event`, scrubbing content with the explicitly supplied configured sanitizer before its 16 KiB store-boundary bound; no changes to the typed observation boundary | `store/tests/suite/workstream_provenance.rs` `workstream_provenance_is_bounded_scrubbed_and_idempotent_before_storage` (hostile and oversized source ids, unknown metadata, legitimate correlation, retry and distinct event ids), `workstream_provenance_legacy_reads_strip_secrets_and_unknown_metadata` (search and tail, malformed/oversized legacy JSON), `workstream_provenance_reused_event_id_retains_data_and_refuses_identity_change` (first indexed version retained, identity refusal and batch rollback), `workstream_provenance_replay_survives_sanitizer_changes` (new extra patterns and removal of a built-in-pattern allowlist exemption, with identity-refusal control), `workstream_provenance_replay_preserves_legacy_rows_above_bounds`, `workstream_provenance_finished_run_ignores_late_events`, `workstream_provenance_retry_with_marker_matching_pattern_is_idempotent`, `workstream_content_is_scrubbed_before_the_store_cap` (a credential straddling the 16 KiB store cap is redacted, not persisted as an unmatchable prefix; benign control verbatim; #1113); `hooks` `workstream_provenance_finish_scrubs_before_raw_segment_and_search` (custom sanitizer, immutable segment, SQL recovery and finished-run no-op), `workstream_provenance_client_cannot_use_server_event_ids` (reserved ids refused before raw writes, normal client event and server-generated checkpoint/loss controls), `finish_run_scrubs_event_content_before_the_byte_cap` and `finish_run_scrubs_boundary_events_before_the_byte_cap` (a credential straddling the 64 KiB event cap is redacted in the raw segment and never reaches the index; checkpoint/losses and benign controls; #1113); `cli/tests/suite/workstream_provenance.rs` (text/JSON and old server DTOs) | STRONG: privacy, stable-identity and reserved-namespace regressions fail with their guards bypassed; an isolated allowlist bypass fails on the unknown key, and bypassing the raw-id search authorization returns 200 where its test requires 403. No provenance is emitted in startup packets, and old raw segments are not rewritten || 12c | Browser cross-origin writes refused on an unauthenticated server (a foreign page in the operator's browser, DNS rebinding, and a LAN host where browsers send no fetch metadata) | `serve.rs` `refuse_cross_origin_browser_requests` / `is_cross_origin_browser_request`, layered on the machine (`/mcp`, `/hook*`, `/handoff`, `/workstream/*`, `/identity`) and admin (`/admin/*`) routes when auth is off: `Sec-Fetch-Site` other than `same-origin`/`none` → 403, or, without fetch metadata, an `Origin` whose authority is not the `Host` → 403; and `is_non_script_browser_request`: any `Sec-Fetch-Dest` other than `empty` (case-insensitive; non-UTF-8 refused) → 403 whatever `Sec-Fetch-Site` says, so links, images, navigations, iframes and form posts are refused even as `same-origin` or `none`. Browsers send fetch metadata over plain HTTP only to a potentially trustworthy host, so on any other `Host` (a LAN address or name in the allowlist, `0.0.0.0`, `host.docker.internal`; `is_loopback_host` admits only `localhost`, `*.localhost`, `127.0.0.0/8` and `[::1]`) `handoff_fetch_lacks_client_marker` also refuses `GET`/`HEAD /handoff` without a non-empty `X-AI-Memory-Client` header (`ai_memory_hooks::CLIENT_MARKER_HEADER`) → 403 whose body names both remedies (re-stage hooks, or set a bearer token). A page cannot add that header without a preflight these routes never answer. `/handoff` is the one state-changing `GET` on these routes; the other `GET`s are reads a foreign page cannot see the answer to, and every cross-origin `POST` carries `Origin`. Every first-party client sends the marker: the native hook (`hook_capture.rs` `post_hook`/`post_batch`/`get_handoff`), CLI subcommands (`http_client.rs` `ServerEndpoint::authenticate`), every curl in `hooks/_lib.sh`, both header tables in `hooks/lib/ai-memory-hook.ps1`, and the generated TypeScript integrations (`render_shared.rs` `ts_auth_headers_fn` plus the spool drain). Loopback hosts keep accepting a fetch without it, so hooks staged before the header existed still work on a default install, except that a request carrying any proxy forwarding header (`Forwarded`, `X-Forwarded-For`/`-Host`/`-Proto`/`-Server`/`-Port`, `X-Original-Forwarded-For`, `X-Real-IP`, `X-Client-IP`, `CF-Connecting-IP`, `True-Client-IP`, `Via`; `PROXY_HEADERS`) counts as non-loopback, since a plain-HTTP proxy can rewrite `Host` to loopback while the browser behind it sent no fetch metadata. No first-party client sends those headers. Hooks, the CLI and MCP clients send none of these headers; the web UI's same-origin `/admin/pending-writes` calls are `fetch()` (`Sec-Fetch-Dest: empty`) and pass. Behind it, axum `Json` and rmcp's `Content-Type: application/json` check refuse the preflight-free content types (`text/plain`, form-urlencoded, multipart) with 415; `require_allowed_host` (and rmcp `allowed_hosts` on `/mcp`) refuses a rebinding `Host`; machine/admin routes carry no CORS layer, so a preflight never comes back permissive. A stored wiki page viewed in the built-in web UI could otherwise turn the guard's same-origin allowance into a claim: `ai-memory-web/src/markdown.rs` `safe_image_url` / `is_safe_image_target` render as `#` any image target that is root-relative, a network path, carries a `..` segment (also percent-encoded), or, for a UI mounted at the base-path root, starts with a server route segment Every `/web` surface (built-in pages including `/web/pending`, the login page, a custom SPA and `/api/v1`) answers `X-Frame-Options: DENY` and `Content-Security-Policy: frame-ancestors 'none'` (`ai-memory-web/src/mount.rs` `deny_framing`), because a framed page's own Approve/Reject `fetch()` is same-origin and the guard rightly lets it through | `cli/tests/suite/cross_origin_e2e.rs` `browser_cross_origin_requests_cannot_write_to_an_unauthenticated_loopback_server`, against the shipped `serve`: every write route (`/hook`, `/hook/batch`, MCP `memory_write_page`/`memory_delete_page`/`memory_message_send`/`memory_handoff_accept`, `/admin/write-page`/`delete-page`/`purge-project`/`messages/send`, `/workstream/runs`) × each simple content type × modern, Origin-only and fetch-metadata-only browser shapes → 4xx; body-less `GET /handoff` (which claims the single-use baton), `POST /admin/profile/rebuild` and `POST /admin/backup` → 403; a rebinding `Host` → 403; preflights answer no `Access-Control-Allow-*`; `GET /handoff` as a same-origin `document` or `image` and as a `Sec-Fetch-Site: none` `document` → 403 with the baton still open. Then a canary scan of the whole data dir, page/project/handoff survival, and legitimate controls (JSON MCP calls, a JSON hook → 202, the web UI's same-origin `/admin/pending-writes` list and approve reach their handlers, the anonymous active-project pointer is unmoved after the refused `/handoff` fetches while the closing hook-style fetch claims the baton and moves it). `serve.rs` `cross_origin_browser_request_detection` and `non_script_browser_request_detection` (header tables) and `cross_origin_browser_guard_applies_only_without_auth` (same-origin `image` and `none` `document` refused, same-origin `empty` passes, both pass with auth on); `ai-memory-web` `markdown.rs` `neutralises_images_that_reach_server_routes` (`/handoff?…`, `/admin/backup`, `//host/…`, `../` and `%2e%2e/` traversal, root-mounted route names refused) with `preserves_relative_images` as the legitimate control. `cross_origin_e2e.rs` `handoff_fetch_on_a_lan_host_requires_the_client_marker`, against a `serve` that allowlists a LAN name and address: `GET` and `HEAD /handoff` through either without the marker, and with an empty one → 403 carrying the remedy text, with the baton still open and the active-project pointer unmoved; controls: a marked fetch through the LAN name claims the baton, and a marker-less fetch through `127.0.0.1` (a hook staged before the marker) claims the next one; then a `127.0.0.1` fetch carrying each proxy forwarding header and no marker → 403 with the baton still open, and the same fetch with the marker claims it. `serve.rs` `loopback_host_detection`, `handoff_fetch_client_marker_decision` (incl. a loopback `Host` with each proxy header, refused without the marker and admitted with it, and a named row per header so none can drop out of the list) and `handoff_client_marker_guard_on_lan_hosts_and_under_a_base_path` (also under a `--base-path` nest; inactive with auth on). Front-door parity: `hook_capture.rs` `every_native_hook_request_carries_the_client_marker` (handoff GET, hook POST, batch POST), `http_client.rs` `authenticate_no_token_sets_only_the_client_marker`, the client-marker block of `tests/hooks/test_lib.sh` (every curl branch of the GET, the POST and the drain, plus a static check that every PowerShell header table carries it and every `Invoke-WebRequest` passes one), `render_shared.rs` `assert_every_ts_request_carries_client_marker` run for OpenCode, OpenCode 2, OMP, Pi and OpenClaw, `external_capture_ts.rs` (the rendered OpenCode plugin under Node sends no unmarked request) and `external_capture_powershell.rs` `every_request_carries_the_client_marker` (Windows leg); `ai-memory-web/src/mount.rs` `web_surfaces_refuse_to_be_framed` (`/web`, `/web/pending`, `/web/login`, `/api/v1/projects` all carry both headers; bites with `deny_framing` neutralized) | STRONG with listed residuals. Bite checks: with the marker check disabled, the LAN e2e marker-less `GET /handoff` returns 200 and the unit layer test fails; with the proxy-header rule disabled, the proxied loopback e2e fetch claims the baton and the unit decision test fails; dropping the marker from the native handoff GET, the shell token-drain curl, a PowerShell header table or the TypeScript spool drain fails the matching front-door test. With the guard removed, the cross-origin `GET /handoff` returns 200, consumes the baton and moves the active-project pointer (the pre-fix behaviour); with the guard treating `same-origin` as foreign, the web UI control gets 403; with the `Sec-Fetch-Dest` check removed, the same-origin `document` `GET /handoff` returns 200 and the unit guard test lets a same-origin image through; with the host layer removed, a rebound `/hook` returns 202; a permissive `CorsLayer` fails the preflight assertion; reverting `is_safe_image_target` to the pre-fix rule fails the markdown test on `/handoff?…`, dropping the percent-decoding fails it on `%2e%2e/`, and emptying the route list fails it on a root-mounted `handoff`. To reproduce the bite on the 415 layer, remove the guard and make `/hook` read a raw body instead of `Json`: a `text/plain` hook then returns 202 and the test fails. Residual, closed by setting a bearer token: a browser that sends no fetch metadata even to a loopback host (Safari before 16.4) sends no `Sec-Fetch-*` header and no `Origin` on an image `GET` or a link click, so such a request to a loopback host still reaches `/handoff` (loopback keeps accepting marker-less legacy hooks) and the other, read-only `GET` routes. On a non-loopback host the marker requirement closes `/handoff` for every browser. A plain-HTTP proxy that rewrites `Host` to its loopback upstream and adds no forwarding header (nginx's default `proxy_pass`) looks exactly like a local client, so in front of an unauthenticated server it must add `X-Forwarded-For` or keep `proxy_set_header Host $host`, or the server must sit behind TLS or use a bearer token (`security.md`, `https-via-proxy.md`). Browsers that send fetch metadata no longer have the earlier link residuals: a link opened from another app (`Sec-Fetch-Site: none`) and a link clicked in a stored page (`same-origin` navigation) both carry a non-`empty` destination and are refused. With auth on, the bearer token and the session CSRF token are the gate and this layer is a no-op |+| 12d | The web UI and `/api/v1` cannot write, and render stored text inert | `crates/ai-memory-web/clippy.toml` `disallowed-methods`: every `Wiki` write and destructive method (`write_page`, `write_page_if`, `apply_batch`, the delete/evict/purge/restore/move/reindex/remove-dir helpers, `commit_all`, `approve_auto_improve_proposal`) and the `writer()` / `git()` accessors are lint errors in the crate, so the `Wiki` held by `WebState` stays read-only under `cargo clippy -D warnings`; only the integration-test module carries the `allow`, for fixtures. Templates are askama with HTML auto-escaping; the history diff (`templates/history.html`) and the session timeline (`templates/session.html`) print page lines, observation titles and bodies escaped, with no `|safe`, and no captured value is interpolated into a script | `ai-memory-web` `history_replay.rs` `session_timeline_renders_captured_markup_inert` (a `<script>` title and body plus `"><img onerror>` and `' onmouseover='` payloads, checked to survive ingest first, render escaped) and `history_diff_renders_page_markup_inert` (the same payloads in a page version's diff lines); `mount.rs` `web_surfaces_refuse_to_be_framed` covers the history, timeline and history-API routes (200 with both anti-framing headers) | STRONG. Bite checks: a `Wiki::write_page` and a `Wiki::delete_page` call added to `routes/history.rs` fail `cargo clippy -p ai-memory-web --all-targets -- -D warnings` with `use of a disallowed method`; `|safe` on the observation body or a diff line fails the matching inert-render test. The lint is per crate: a write reached through another crate's helper is outside it, which review and the `/api/v1` "zero writer calls" rule still cover || 13 | Managed-run transcript attribution (concurrent launches in one checkout, invariant #16) | `ai-memory-store/src/workstream.rs` `link_native_session` stamps `native_session_linked_at` on its own run only, both `finish` updates drop the stamp when the session changes, `run_status` reports it; `ai-memory-cli/src/commands/run.rs` `resolve_native_session_after_run` takes a linked session only when `ai-memory-workstream` `native_session_in_checkout` holds it for this checkout (OpenCode by recorded directory), never falls back to a link it set aside, and turns an `AmbiguousNativeSession` into a warning with nothing imported; for Claude it moves the run's own session to a background session only when `ai-memory-workstream` `claude_continued_session` finds a `sessionKind: "bg"` record that names that exact session as its attached client and this checkout as `cwd` (#1050), and to a `/clear`ed session only when that session's own transcript records the `/clear` command and names the run's session as its launch `session_id` from this checkout or below it; `ai-memory-workstream/src/transcript.rs` `discover_crush` claims only the one top-level session created (or, with `--continue`, touched) during the run, and in a data directory outside the project only one that edited a file in it | `multi_session.rs` `a_session_linked_by_one_managed_run_is_not_another_runs`; `run.rs` `a_session_linked_during_the_run_wins_over_discovery` (concurrent newer session, another checkout's link refused, no fallback to it, unlinked control); `transcript.rs` `claude_continued_session_follows_only_this_checkouts_bg_records` (a concurrent launch's background session, another checkout's, and a non-background record refused; own attachment control); `transcript.rs` `claude_continued_session_follows_only_this_launchs_clear` (an uncleared transcript, a quoted `/clear`, another checkout's clear, a concurrent launch's clear, a subagent file, and a pre-run clear refused; own clear and the newest of two as controls); `run.rs` `a_claude_run_that_attached_to_a_background_session_follows_it`, `a_claude_run_that_was_cleared_follows_the_new_session`; `transcript.rs` `native_session_in_checkout_checks_the_opencode_directory`; `store/src/lib.rs` `managed_run_status_reports_a_link_made_during_the_run`; `run.rs` `ambiguous_crush_discovery_keeps_the_run`; `transcript.rs` `crush_discovery_claims_only_the_session_the_run_created`, `crush_discovery_in_a_shared_store_claims_only_an_edit_here` | PARTIAL: a run whose child links nothing still falls back to discovering the newest session in the checkout; Crush, which has no hooks, relies on that discovery alone and claims nothing when it is ambiguous || 13a | Managed Codex stale-daemon run recovery (#987; concurrent launches, project/worktree isolation, operator isolation) | `managed_runs.owner_user` (V71) uses the topology-aware `IdentityKey` owner stamp; `router.rs` resolves and authorizes the SessionStart repository before handling the untrusted run id; store `link_or_adopt_native_session` selects and links in one writer transaction and admits only the sole live, undelivered, never-linked Codex run in the exact workspace/project/checkout-cwd/owner bucket. An active supplied id must itself match every boundary; another harness, an ambiguity, or a second native session is refused | `multi_session.rs` `stale_codex_run_recovery_cannot_cross_project_owner_or_session_boundaries` (foreign owner, foreign checkout, and cross-project candidates refused; project-local controls and racing rebind), `stale_codex_run_recovery_fails_closed_on_ambiguity_and_active_mismatch` (two candidates and active foreign id refused, exact control); `workstream.rs` `prepare_stamps_the_operator_bucket_used_by_session_start_recovery` (HTTP actor stamp with foreign and legitimate controls); `router.rs` `managed_session_start_delivers_ledger_and_pending_handoff` supplies a finished stale id and proves the new run is linked and delivered | STRONG for SessionStart recovery. No candidate is selected from a run id's stale scope, another checkout, or another operator bucket; ambiguity deliberately falls back to no managed packet || 13b | Managed-run lease exclusivity and explicit recovery (one active run per workstream, invariant #16) | `ai-memory-store/src/workstream.rs` `prepare_run` expires lapsed leases and otherwise refuses an `active` run inside the writer transaction (`StoreError::WorkstreamBusy`). The explicit `force_unlock` path may expire and replace that row in the same transaction only when its durable `owner_user` equals the incoming actor's attribution; different operators remain isolated. `heartbeat` renews only `active` rows. `ai-memory-cli/src/commands/run.rs` normally uses `wait_out_held_lease`; `--force-unlock` instead asks once and fails immediately when refused. Neither path treats the informational `lease_owner` label as authority | `multi_session.rs` `force_unlock_replaces_only_the_same_operators_active_run` (foreign operator refused with live control, same operator succeeds, old run loses heartbeat, unattributed single-user control); hooks `workstream.rs` `force_unlock_cannot_evict_another_operator` exercises the HTTP actor boundary; CLI `run.rs` `force_unlock_asks_once_instead_of_waiting_out_the_lease`; existing controls `managed_workstream_batches_are_idempotent_and_release_the_lease`, `a_renewed_lease_is_reported_as_a_live_owner_not_taken_over`, `interactive_launch_waits_out_a_lapsing_lease_then_proceeds`, and `ctrl_c_aborts_the_held_lease_wait_immediately` | STRONG for exclusivity. The `lease_owner` label (`host:pid`) is informational only and not unique inside ai-jail (every jailed launcher reports `ai-sandbox:<ns-pid>`), so it must never become an ownership key. A shared unattributed/root context is intentionally one operator bucket; deployments needing person-level refusal must authenticate DB users || 13c | A native store shared by every project yields only this checkout's records (Antigravity `history.jsonl`) | `ai-memory-workstream/src/transcript.rs` `export_antigravity` — the conversation must first pass `locate_session_file` (UUID file name + `.db` workspace == `cwd`); every `history.jsonl` line must match both that `conversationId` and, by `same_path`, this `cwd` (a conversation resumed in another directory keeps its id but records that directory, so the id alone is not enough); an id-less opening prompt is attributed only when exactly one same-workspace candidate falls within 5 s of the `.db` creation time and no other conversation of this checkout was created within 5 s of it; slash/shell entries and oversized lines are dropped, and only records naming this conversation are reported as its losses | `transcript.rs` `antigravity_history_exports_only_this_conversations_prompts_in_this_workspace` (other conversation in this and another workspace refused; own control passes), `antigravity_history_drops_prompts_from_a_resumed_conversation_in_another_workspace` (same id, foreign workspace refused), `antigravity_export_rejects_a_conversation_from_another_workspace`, `antigravity_export_rejects_unknown_or_traversal_ids`, `antigravity_opening_prompt_is_refused_when_another_conversation_started_with_it` (an opener another conversation of this checkout could own is refused), `antigravity_opening_prompt_covers_a_single_prompt_conversation` (control), `antigravity_history_reports_no_losses_for_foreign_records`; `backfill_e2e.rs` `backfill_imports_antigravity_prompts_from_history_and_nothing_foreign` (foreign prompts absent from wiki and db) | STRONG |-| 14 | Per-project authorization (#708) | `ai-memory-store/src/project_authz.rs` `authorize_project` / `ProjectAuthz::authorize` choke point (V68 `project_grants` + `projects.access_mode`, default `open`; V69 `projects.created_by` feeds `is_creator`); `scope.rs` `ScopeResolver::with_project_authz` (reader pool for reads, writer actor for writes) and its free forms `authorize_scope_for` / `*_guarded`, attached for every DB user by `ai-memory-mcp` `scope_resolver_as`, `ai-memory-web` `authorize_read` / `lookup_project`, and `ai-memory-hooks` (`grants.rs` `authorize_resolved` for run/workstream ids, the capture check in `router.rs`); read-shaped mutations resolve at `ProjectAccess::Write` (`resolve_existing_args(.., need)`); unscoped reads filtered before `LIMIT` by `reader.rs` `readable_repository_sql`; `WriterHandle::authorize_project` as defense in depth. Page ids are never taken from a caller (only derived from already-authorized hits), so there is no page-id entry point to guard; incremental `recent` resolves and authorizes the requested project before decoding its scope-bound cursor; batch outcomes do not bypass the capture grant or session owner check | `tests/suite/project_authz.rs` (decision matrix, ship-inert, resolver gate); `tests/suite/access_mode.rs` `every_caller_against_both_modes`, `a_restricted_project_admits_the_team_and_refuses_the_outsider`, `new_projects_follow_the_server_default_and_admit_their_creator`; `scope.rs` `the_argument_shape_does_not_decide_the_level`, `a_user_reaches_only_what_they_were_granted`, `creating_authorizes_against_a_project_that_already_exists`, `a_refused_scope_fails_the_search_instead_of_shortening_it`; `grants.rs` `search_finds_only_what_the_viewer_may_read`, `the_limit_counts_only_what_the_viewer_may_see`, `the_workspace_handoff_comes_only_from_readable_repositories`; `ai-memory-mcp` `server.rs` `a_reader_may_read_everything_and_change_nothing`, `bob_cannot_read_alices_page_in_a_restricted_project`, `bob_cannot_find_alices_page_by_searching_in_a_restricted_project`, `observation_stream_evidence_stays_inside_a_restricted_project` (with `[retrieval] observation_stream` on, a non-grantee naming the restricted project, listing it in `scopes`, or searching their own project never sees the session page or its observation excerpt; the writer and a read-grant holder do; fails with the read check in `ProjectAuthz::authorize` neutralized), `bob_cannot_consolidate_a_session_in_alices_repository`, `a_restricted_projects_queues_need_write`; `ai-memory-hooks` `a_capture_needs_writer_on_the_repository_it_lands_in`, `session_start_delivers_nothing_from_a_repository_the_viewer_cannot_read`, `run_and_workstream_ids_only_answer_someone_who_may_reach_the_repository` (foreign raw workstream id refuses populated provenance; granted reader receives the source record and tool correlation); `ai-memory-web` `web_reads_honour_grants_in_a_restricted_project`, `metadata_shows_only_what_the_viewer_may_read` — each with a granted or open-project control, and proven to fail with the choke point (19 tests) or the SQL filter (9 tests) neutralized; `routes.rs` `api_recent_incremental_rechecks_restricted_scope_on_cursor` (a valid cursor cannot bypass a revoked grant; granted control passes), `api_recent_incremental_paginates_over_120_pages_and_binds_cursor`; `mcp_stateless_http.rs` `generic_machine_client_writes_queries_and_claims_a_handoff` (real machine key, foreign scope and partial scope refused); `router.rs` `an_unauthorized_batch_item_is_consumed_rather_than_retried`, `batch_acknowledges_foreign_collision_then_commits_next_item` (refused foreign item followed by a legitimate stored item) | STRONG — slice 3 closed both bypass classes (unscoped reads, raw-id entry points) and added the root-only management surface. Out of scope by design: per-project administrators (granting/restricting is root-only), and access modes, creators and grants live only in SQLite, so `reindex` resets them |+| 14 | Per-project authorization (#708) | `ai-memory-store/src/project_authz.rs` `authorize_project` / `ProjectAuthz::authorize` choke point (V68 `project_grants` + `projects.access_mode`, default `open`; V69 `projects.created_by` feeds `is_creator`); `scope.rs` `ScopeResolver::with_project_authz` (reader pool for reads, writer actor for writes) and its free forms `authorize_scope_for` / `*_guarded`, attached for every DB user by `ai-memory-mcp` `scope_resolver_as`, `ai-memory-web` `authorize_read` / `lookup_project`, and `ai-memory-hooks` (`grants.rs` `authorize_resolved` for run/workstream ids, the capture check in `router.rs`); read-shaped mutations resolve at `ProjectAccess::Write` (`resolve_existing_args(.., need)`); unscoped reads filtered before `LIMIT` by `reader.rs` `readable_repository_sql`; `WriterHandle::authorize_project` as defense in depth. Page ids are otherwise never taken from a caller (only derived from already-authorized hits); the one exception, the web page-history `from`/`to` version ids, is looked up only inside the scope `routes/mod.rs` `resolve_read_scope` (`lookup_existing_scope_guarded`, `ProjectAccess::Read`) has already authorized and the requested path (`page_version_body`), so a foreign id reads as not found; incremental `recent` resolves and authorizes the requested project before decoding its scope-bound cursor; batch outcomes do not bypass the capture grant or session owner check | `tests/suite/project_authz.rs` (decision matrix, ship-inert, resolver gate); `tests/suite/access_mode.rs` `every_caller_against_both_modes`, `a_restricted_project_admits_the_team_and_refuses_the_outsider`, `new_projects_follow_the_server_default_and_admit_their_creator`; `scope.rs` `the_argument_shape_does_not_decide_the_level`, `a_user_reaches_only_what_they_were_granted`, `creating_authorizes_against_a_project_that_already_exists`, `a_refused_scope_fails_the_search_instead_of_shortening_it`; `grants.rs` `search_finds_only_what_the_viewer_may_read`, `the_limit_counts_only_what_the_viewer_may_see`, `the_workspace_handoff_comes_only_from_readable_repositories`; `ai-memory-mcp` `server.rs` `a_reader_may_read_everything_and_change_nothing`, `bob_cannot_read_alices_page_in_a_restricted_project`, `bob_cannot_find_alices_page_by_searching_in_a_restricted_project`, `observation_stream_evidence_stays_inside_a_restricted_project` (with `[retrieval] observation_stream` on, a non-grantee naming the restricted project, listing it in `scopes`, or searching their own project never sees the session page or its observation excerpt; the writer and a read-grant holder do; fails with the read check in `ProjectAuthz::authorize` neutralized), `bob_cannot_consolidate_a_session_in_alices_repository`, `a_restricted_projects_queues_need_write`; `ai-memory-hooks` `a_capture_needs_writer_on_the_repository_it_lands_in`, `session_start_delivers_nothing_from_a_repository_the_viewer_cannot_read`, `run_and_workstream_ids_only_answer_someone_who_may_reach_the_repository` (foreign raw workstream id refuses populated provenance; granted reader receives the source record and tool correlation); `ai-memory-web` `web_reads_honour_grants_in_a_restricted_project`, `metadata_shows_only_what_the_viewer_may_read` — each with a granted or open-project control, and proven to fail with the choke point (19 tests) or the SQL filter (9 tests) neutralized; `routes.rs` `api_recent_incremental_rechecks_restricted_scope_on_cursor` (a valid cursor cannot bypass a revoked grant; granted control passes), `api_recent_incremental_paginates_over_120_pages_and_binds_cursor`; `mcp_stateless_http.rs` `generic_machine_client_writes_queries_and_claims_a_handoff` (real machine key, foreign scope and partial scope refused); `router.rs` `an_unauthorized_batch_item_is_consumed_rather_than_retried`, `batch_acknowledges_foreign_collision_then_commits_next_item` (refused foreign item followed by a legitimate stored item); `ai-memory-web` `history_replay.rs` `history_and_timeline_honour_grants_in_a_restricted_project` (page history in HTML and JSON and the session timeline: a non-grantee gets 403 without the body, a grantee and root get 200; bite: resolving through the unguarded `lookup_existing_scope` fails it) | STRONG — slice 3 closed both bypass classes (unscoped reads, raw-id entry points) and added the root-only management surface. Out of scope by design: per-project administrators (granting/restricting is root-only), and access modes, creators and grants live only in SQLite, so `reindex` resets them || 14aa | Companion capture privacy before persistence and delivery | `companions/ai-memory-client/src/lib.rs` `reject_sensitive`, `sanitize_external_value`, `check_body`; `src/scrub.rs` `sanitize_external_text`; relay `identity::validate`, `check_scope`, `relay::init` and `flush_locked`; importer `plan_external_conversation`, `planned_hook_event`, `truncate_utf8`, `ImportClient::post_hook_batch` | SDK secret-position, nested key, numeric metric (11 names plus numeric `*_tokens` counts; string values still redact), bounded schema and literal-marker tests; relay `sensitive_envelope_is_rejected_before_enqueue_with_clean_control`, `new_native_bodies_are_sanitized_before_hash_enqueue_and_exact_retry`, `unsafe_legacy_pending_is_dropped_locally_and_never_blocks_its_session`, `unsafe_legacy_native_identity_is_dropped_and_its_session_continues`, `legacy_binding_scope_spaces_are_preserved_on_delivery`; importer `sensitive_native_identity_is_refused_before_manifest_and_http_with_unicode_control`, `shared_key_sanitation_precedes_plan_manifest_transport_and_exact_retry`, `preview_and_manifest_use_scrubbed_bodies_and_digest`, `forged_body_authority_is_refused_before_transport`, `sanitized_redaction_markers_survive_utf8_byte_caps_in_bodies_and_titles`. Controls preserve opaque native Unicode IDs, metric representation and untrusted provenance. An unsafe item queued before these checks never reaches the wire (body or request line); it leaves the queue as a local `dropped_policy` receipt so the rest of its session ships. Guard-removal runtime probes target the final formatted sources and restore identical hashes. | Client-side privacy only; server scope, auth, admission and capture-policy guards remain authoritative || 14ap | Managed-run mutation owner and current project access (finish, cancel, heartbeat, native-session link, context acceptance) | `hooks/src/workstream.rs` `authorize_run_owner` derives `ManagedRunAuthority` only from authenticated middleware extensions and checks the real run before any mutation — for finish before status/payload/segment handling; cancel, heartbeat, link and context acceptance go through the same helper, so none is a side door around finish's rule; `ReaderPool::authorize_managed_run` and `store/src/workstream.rs` `authorize_run_mutation` use a read snapshot and the existing writer transaction, respectively. Strict resolution (`project_authz.rs` `resolve_project_authz_strict`, the canonical decision with a fail-closed resolution mode, so the reserved global-scope write gate applies here too) requires the actual workspace/project pair, current user existence and current Write decision for DB principals. The private trusted-proxy policy requires authenticated User capability, a canonical identity, no DB principal and server proxy configuration; it retains legacy project admission after strict scope validation, with ownership still enforced. Human-login disable does not revoke API keys. The legacy resolver and auth middleware remain unchanged. Both writer entry paths, including finished retries, require the same authority; no cross-owner bypass | MCP `auth.rs` `owner_finish_http_refuses_another_writer_before_payload_or_segment`, `owner_finish_http_trusted_proxy_preserves_restricted_lifecycle`, `owner_finish_http_active_api_key_survives_disabled_human_login`; store `multi_session.rs` `owner_finish_store_refuses_another_writer_including_finished_retry`, `owner_finish_store_rechecks_write_after_preflight`, `owner_finish_store_refuses_a_deleted_user_after_preflight`, `owner_finish_store_proxy_policy_requires_server_and_authenticated_identity`, `owner_finish_store_raw_ids_use_the_actual_project_and_workspace`, `owner_finish_store_topology_reload_and_phase_controls`, `owner_finish_store_strict_resolution_refuses_pairing_missing_and_sql_failure`, `owner_finish_store_keeps_qualified_identity_namespaces`; hooks `workstream.rs` `owner_finish_revocation_between_preflight_and_both_writer_paths`; MCP `auth.rs` `owner_finish_http_real_auth_rungs_shared_and_project_controls`, `owner_finish_http_preserves_late_active_terminal_and_missing_phases`; hooks `workstream.rs` `run_mutation_routes_refuse_another_operator` (another operator and root under another identity refused on heartbeat/link/accept/cancel, run left active; owner admitted); store `project_authz.rs` `strict_resolution_shares_the_global_gate_and_fails_closed_on_a_gap`. Guard-neutralization recipes and results accompany the local frozen patch | SQL refusal is atomic within finish's writer transaction; a revocation after preflight can leave an unindexed raw segment. Cancel, heartbeat, link and acceptance check one read snapshot immediately before a single-row update (a run's owner never changes). A later hook event carrying `AI_MEMORY_RUN_ID` links its native session only through `link_native_session_in_scope`, which applies the SessionStart boundary (`ManagedRunBoundaryRow::admits`: the run's own project and operator) and refuses a foreign run id while the event itself is still captured (`router.rs` `hook_event_links_a_managed_run_only_from_its_operator`, `hook_event_in_another_project_does_not_link_the_run`, control `hook_event_links_a_shared_run_on_a_single_operator_server`; #1082). Shared NULL ownership, trusted-proxy project admission and late still-active finishes remain intentional || 14au | Exact native managed identity and privacy (invariant #16) | `core/src/workstream.rs` `NativeSessionIdentity` validates original bytes and exact scrub equality; `workstream/src/harness.rs` and `transcript.rs` retain selector/path restrictions; CLI `run.rs` validates old-server prepare/status, planned selectors and finish transport; hooks `workstream.rs` checks payload and selected identity before raw segments, with the existing owner/current Write preflight first; `router.rs` validates both managed auto-links while preserving legacy shared capture; store `workstream.rs` carries validated identities into link/finish SQL after finish authority and before mutation. Store, HTTP search and CLI search project invalid historical identity to empty String without rewriting history | Core `native_identity_original_bytes_limits_privacy_and_collisions`; harness `native_identity_selector_rejects_original_before_resume_arguments`; transcript `native_identity_adapter_preserves_exact_and_rejects_privacy_changes`, `copilot_discovery_requires_uuid_directory_header_and_checkout` (another checkout's session, a `session.start` naming a different session than its directory, and non-UUID or `../` ids refused; exact-checkout control), `claude_transcript_is_located_by_the_real_folder_name` (a server-linked Claude id probed across project folders still resolves only to a transcript whose own header names this checkout; another checkout's transcript and a subagent sidechain with the same id are refused); store multi-session `native_identity_store_link_refuses_original_dirty_bytes`, `native_identity_store_adoption_refuses_before_link`, `native_identity_store_finish_refuses_without_sql_or_index_mutation`, `native_identity_store_history_projects_unknown_without_rewriting`; hooks `native_identity_http_link_refuses_before_status_or_sql`, `native_identity_http_finish_refuses_before_segment_or_sql`, `native_identity_http_event_guard_and_configured_history_projection`, `native_identity_http_stored_identity_refuses_before_raw_segment`, router `native_identity_managed_start_refuses_but_keeps_shared_legacy_capture`; CLI `native_identity_run_preflight_refuses_before_resume_or_private_path`, `native_identity_run_old_server_refusal_prevents_child_and_transport`, `native_identity_finish_transport_refuses_before_request_and_preserves_exact_control`, `native_identity_run_status_and_expected_refuse_before_discovery`, `native_identity_run_configured_selector_refuses_before_link_or_child`, `native_identity_run_configured_old_status_refuses_before_native_io_and_finish`, `native_identity_run_configured_discovery_refuses_before_export`, suite `native_identity_search_old_server_json_projects_unknown_and_keeps_history` | Representation/privacy only: no native authenticity, file-existence, run/event correlation or outcome proof. Original legacy rows and shared observation semantics remain intact; parent finish owner/current Write rules remain mandatory |diff --git a/docs/usage.md b/docs/usage.mdindex 5c1df9b9..48bd2edb 100644--- a/docs/usage.md+++ b/docs/usage.md@@ -513,7 +513,17 @@ command: ["serve", "--transport", "http", "--bind", "0.0.0.0:49374", "--enable-w```The web UI is read-only: project list, per-project page tree,-breadcrumbs, rendered markdown, metadata, and FTS5 search. In rendered+breadcrumbs, rendered markdown, metadata, and FTS5 search. Each page links+to its history (`/web/w/<ws>/<proj>/h/<path>`): every stored version, newest+first, with the author where the write was attributed, and a unified diff+between any two of them (by default the latest against the version it+replaced). A version another write replaced stays listed; an expired one does+not, and a page whose TTL has passed has no history. The project page+lists recent sessions, and each opens a timeline+(`/web/w/<ws>/<proj>/s/<session-id>`) that pages through the session's+captured observations in order, with first/prev/next/last links, a jump field+and, when JavaScript runs, a slider and `j`/`k` keys to step one observation+at a time. Observations are shown as plain text. In renderedpages, `[[wiki links]]` become clickable links to the target page.`[[path]]`, `[[path|label]]`, `[[project:path]]`,`[[workspace/project:path]]`, and `[[_global:path]]` are all supported