Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
ai-memory-web: read-only HTTP wiki browser
AkitaOnRails2a57644430bd
diff --git a/Cargo.lock b/Cargo.lockindex c9b05e43..f8fd060f 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -39,6 +39,7 @@ dependencies = ["ai-memory-llm","ai-memory-mcp","ai-memory-store",+ "ai-memory-web","ai-memory-wiki","anyhow","axum",@@ -199,6 +200,28 @@ dependencies = ["uuid",]+[[package]]+name = "ai-memory-web"+version = "0.1.0"+dependencies = [+ "ai-memory-core",+ "ai-memory-store",+ "ai-memory-wiki",+ "anyhow",+ "askama",+ "axum",+ "jiff",+ "pulldown-cmark",+ "serde",+ "serde_json",+ "syntect",+ "tempfile",+ "thiserror 2.0.18",+ "tokio",+ "tower",+ "tracing",+]+[[package]]name = "ai-memory-wiki"version = "0.1.0"@@ -285,6 +308,50 @@ version = "1.0.102"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c"+[[package]]+name = "askama"+version = "0.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b79091df18a97caea757e28cd2d5fda49c6cd4bd01ddffd7ff01ace0c0ad2c28"+dependencies = [+ "askama_derive",+ "askama_escape",+ "humansize",+ "num-traits",+ "percent-encoding",+]++[[package]]+name = "askama_derive"+version = "0.12.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "19fe8d6cb13c4714962c072ea496f3392015f0989b1a2847bb4b2d9effd71d83"+dependencies = [+ "askama_parser",+ "basic-toml",+ "mime",+ "mime_guess",+ "proc-macro2",+ "quote",+ "serde",+ "syn",+]++[[package]]+name = "askama_escape"+version = "0.10.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "619743e34b5ba4e9703bba34deac3427c72507c7159f5fd030aea8cac0cfe341"++[[package]]+name = "askama_parser"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "acb1161c6b64d1c3d83108213c2a2533a342ac225aabd0bda218278c2ddb00c0"+dependencies = [+ "nom",+]+[[package]]name = "async-trait"version = "0.1.89"@@ -375,6 +442,39 @@ version = "0.22.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"+[[package]]+name = "basic-toml"+version = "0.1.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ba62675e8242a4c4e806d12f11d136e626e6c8361d6b829310732241652a178a"+dependencies = [+ "serde",+]++[[package]]+name = "bincode"+version = "1.3.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b1f45e9417d87227c7a56d22e471c6206462cba514c7590c09aff4cf6d1ddcad"+dependencies = [+ "serde",+]++[[package]]+name = "bit-set"+version = "0.8.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3"+dependencies = [+ "bit-vec",+]++[[package]]+name = "bit-vec"+version = "0.8.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7"+[[package]]name = "bitflags"version = "2.11.1"@@ -703,6 +803,17 @@ version = "0.1.9"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a"+[[package]]+name = "fancy-regex"+version = "0.16.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "998b056554fbe42e03ae0e152895cd1a7e1002aec800fdc6635d20270260c46f"+dependencies = [+ "bit-set",+ "regex-automata",+ "regex-syntax",+]+[[package]]name = "fastrand"version = "2.4.1"@@ -758,6 +869,12 @@ dependencies = ["miniz_oxide",]+[[package]]+name = "fnv"+version = "1.0.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"+[[package]]name = "foldhash"version = "0.1.5"@@ -1018,6 +1135,15 @@ version = "1.0.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"+[[package]]+name = "humansize"+version = "2.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6cb51c9a029ddc91b07a787f1d86b53ccfa49b0e86688c946ebe8d3555685dd7"+dependencies = [+ "libm",+]+[[package]]name = "hyper"version = "1.9.0"@@ -1386,6 +1512,12 @@ dependencies = ["pkg-config",]+[[package]]+name = "libm"+version = "0.2.16"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"+[[package]]name = "libredox"version = "0.1.16"@@ -1418,6 +1550,12 @@ dependencies = ["vcpkg",]+[[package]]+name = "linked-hash-map"+version = "0.5.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0717cef1bc8b636c6e1c1bbdefc09e6322da8a9321966e8928ef80d20f7f770f"+[[package]]name = "linux-raw-sys"version = "0.12.1"@@ -1478,6 +1616,22 @@ version = "0.3.17"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"+[[package]]+name = "mime_guess"+version = "2.0.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e"+dependencies = [+ "mime",+ "unicase",+]++[[package]]+name = "minimal-lexical"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"+[[package]]name = "miniz_oxide"version = "0.8.9"@@ -1500,6 +1654,16 @@ dependencies = ["windows-sys 0.61.2",]+[[package]]+name = "nom"+version = "7.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a"+dependencies = [+ "memchr",+ "minimal-lexical",+]+[[package]]name = "notify"version = "8.2.0"@@ -1661,6 +1825,19 @@ version = "0.3.33"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e"+[[package]]+name = "plist"+version = "1.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "092791278e026273c1b65bbdcfbba3a300f2994c896bd01ab01da613c29c46f1"+dependencies = [+ "base64",+ "indexmap",+ "quick-xml",+ "serde",+ "time",+]+[[package]]name = "portable-atomic"version = "1.13.1"@@ -1732,6 +1909,33 @@ dependencies = ["yansi",]+[[package]]+name = "pulldown-cmark"+version = "0.12.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f86ba2052aebccc42cbbb3ed234b8b13ce76f75c3551a303cb2bcffcff12bb14"+dependencies = [+ "bitflags",+ "memchr",+ "pulldown-cmark-escape",+ "unicase",+]++[[package]]+name = "pulldown-cmark-escape"+version = "0.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "007d8adb5ddab6f8e3f491ac63566a7d5002cc7ed73901f72057943fa71ae1ae"++[[package]]+name = "quick-xml"+version = "0.39.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cdcc8dd4e2f670d309a5f0e83fe36dfdc05af317008fea29144da1a2ac858e5e"+dependencies = [+ "memchr",+]+[[package]]name = "quinn"version = "0.11.9"@@ -2464,6 +2668,27 @@ dependencies = ["syn",]+[[package]]+name = "syntect"+version = "5.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "656b45c05d95a5704399aeef6bd0ddec7b2b3531b7c9e900abbf7c4d2190c925"+dependencies = [+ "bincode",+ "fancy-regex",+ "flate2",+ "fnv",+ "once_cell",+ "plist",+ "regex-syntax",+ "serde",+ "serde_derive",+ "serde_json",+ "thiserror 2.0.18",+ "walkdir",+ "yaml-rust",+]+[[package]]name = "sysinfo"version = "0.32.1"@@ -2866,6 +3091,12 @@ dependencies = ["version_check",]+[[package]]+name = "unicase"+version = "2.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dbc4bc3a9f746d862c45cb89d705aa10f187bb96c76001afab07a0d35ce60142"+[[package]]name = "unicode-ident"version = "1.0.24"@@ -3537,6 +3768,15 @@ dependencies = ["rustix",]+[[package]]+name = "yaml-rust"+version = "0.4.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "56c1936c4cc7a1c9ab21a1ebb602eb942ba868cbd44a99cb7cdc5892335e1c85"+dependencies = [+ "linked-hash-map",+]+[[package]]name = "yansi"version = "1.0.1"diff --git a/Cargo.toml b/Cargo.tomlindex cc12e413..f68768f8 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -8,6 +8,7 @@ members = ["crates/ai-memory-hooks","crates/ai-memory-llm","crates/ai-memory-consolidate",+ "crates/ai-memory-web","crates/ai-memory-cli",# Live A/B harness — not part of the shipped binary, but in# the workspace so it shares deps + builds with the rest.@@ -31,6 +32,7 @@ ai-memory-mcp = { path = "crates/ai-memory-mcp", version = "0.1.0" }ai-memory-hooks = { path = "crates/ai-memory-hooks", version = "0.1.0" }ai-memory-llm = { path = "crates/ai-memory-llm", version = "0.1.0" }ai-memory-consolidate = { path = "crates/ai-memory-consolidate", version = "0.1.0" }+ai-memory-web = { path = "crates/ai-memory-web", version = "0.1.0" }# (Workspace shared deps follow below)diff --git a/README.md b/README.mdindex 47a102da..5f261c02 100644--- a/README.md+++ b/README.md@@ -201,6 +201,28 @@ docker cp ai-memory:/data/wiki ./my-ai-memory-wikidocker exec ai-memory git -C /data/wiki log --oneline```+### Browse the wiki in a browser++For a more navigable view, start the server with `--enable-web` and+open `http://<host>:49374/web` in any browser. Project-list homepage,+per-project page tree with breadcrumbs, rendered markdown with syntax+highlighting and metadata (tier, kind, pinned, supersedes chain),+plus FTS5 search — all read-only, no editing. Light/dark theme+follows your OS setting via `prefers-color-scheme`.++```bash+ai-memory serve --transport http --bind 127.0.0.1:49374 --enable-web+# or, if you run via docker compose, add it to the command line in+# docker-compose.yml: ["serve", "--transport", "http", "--bind",+# "0.0.0.0:49374", "--enable-web"]+```++The web routes are mounted at `/web` on the same axum server as the+MCP endpoint, so the bearer-auth posture is identical (set+`AI_MEMORY_AUTH_TOKEN` and pass `Authorization: Bearer …` from the+browser, or front the server with a reverse proxy that handles its+own auth, or keep the bind loopback-only).+### Rules vs facts — ai-memory tells you when something belongs in CLAUDE.mdWhen you type something like "don't forget to never add a functiondiff --git a/crates/ai-memory-cli/Cargo.toml b/crates/ai-memory-cli/Cargo.tomlindex 127cbb06..175dff2a 100644--- a/crates/ai-memory-cli/Cargo.toml+++ b/crates/ai-memory-cli/Cargo.toml@@ -19,6 +19,7 @@ ai-memory-hooks.workspace = trueai-memory-llm.workspace = trueai-memory-mcp.workspace = trueai-memory-store.workspace = true+ai-memory-web.workspace = trueai-memory-wiki.workspace = truesecrecy.workspace = truesubtle.workspace = truediff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rsindex 787038f1..27365c9a 100644--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@ -490,6 +490,12 @@ pub struct ServeArgs {/// Project name within the workspace (auto-created).#[arg(long, default_value = "scratch")]pub project: String,+ /// Mount the read-only wiki browser at /web. Off by default. When+ /// enabled, anyone who can reach the MCP endpoint can also browse+ /// the wiki — keep the bind loopback-only or front with a reverse+ /// proxy that handles its own auth if you expose it.+ #[arg(long)]+ pub enable_web: bool,}/// Arguments for `write-page`.diff --git a/crates/ai-memory-cli/src/commands/serve.rs b/crates/ai-memory-cli/src/commands/serve.rsindex f1dc9197..176978ba 100644--- a/crates/ai-memory-cli/src/commands/serve.rs+++ b/crates/ai-memory-cli/src/commands/serve.rs@@ -8,6 +8,7 @@ use ai_memory_hooks::{HookState, hook_router};use ai_memory_llm::{build_embedder, embedder_from_env, provider_from_env};use ai_memory_mcp::AiMemoryServer;use ai_memory_store::Store;+use ai_memory_web;use ai_memory_wiki::{WatcherHandle, Wiki};use anyhow::{Context, Result};use axum::extract::DefaultBodyLimit;@@ -181,9 +182,33 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {.or_else(|| config.auth.bearer_token.clone());let auth_state = Arc::new(AuthState::new(token));let auth_enabled = auth_state.enabled();- let router = axum::Router::new()+ let mut router = axum::Router::new().nest_service("/mcp", mcp_service)- .merge(hooks)+ .merge(hooks);++ // Register the web router BEFORE applying the bearer+ // middleware. In axum 0.8, `.layer()` only attaches to+ // routes registered before the call — nesting after the+ // layer would silently bypass auth for /web/*.+ if args.enable_web {+ let web_router = ai_memory_web::router(store.reader.clone(), wiki.clone());+ // Also accept the trailing-slash form. axum 0.8's+ // `nest("/web", ..)` matches `/web` (no slash) → inner+ // `route("/")` but doesn't match `/web/` (a browser's+ // default when the user types the bare prefix), so we+ // redirect that explicitly to keep both URLs working.+ router = router+ .route(+ "/web/",+ axum::routing::get(|| async {+ axum::response::Redirect::permanent("/web")+ }),+ )+ .nest("/web", web_router);+ info!("read-only wiki browser mounted at /web");+ }++ let router = router.layer(axum::middleware::from_fn_with_state(auth_state,require_bearer,diff --git a/crates/ai-memory-store/src/lib.rs b/crates/ai-memory-store/src/lib.rsindex 1df3c9ca..319deabe 100644--- a/crates/ai-memory-store/src/lib.rs+++ b/crates/ai-memory-store/src/lib.rs@@ -22,8 +22,8 @@ mod writer;pub use decay::{DecayParams, retention_score};pub use error::{StoreError, StoreResult};pub use reader::{- ActivityWindow, BriefingPage, BriefingSnapshot, DecayCandidate, PageHit, ReaderPool,- StatusCounts, StoredEmbedding, f32_vec_to_bytes,+ ActivityWindow, BriefingPage, BriefingSnapshot, DecayCandidate, PageHit, PageMeta, PageSummary,+ ProjectSummary, ReaderPool, StatusCounts, StoredEmbedding, f32_vec_to_bytes,};pub use writer::WriterHandle;@@ -303,4 +303,124 @@ mod tests {hits[0].snippet);}++ #[tokio::test]+ async fn list_projects_with_stats_returns_aggregates() {+ let tmp = TempDir::new().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let ws = store+ .writer+ .get_or_create_workspace("default")+ .await+ .unwrap();+ let proj = store+ .writer+ .get_or_create_project(ws, "my-project", None)+ .await+ .unwrap();+ store+ .writer+ .upsert_page(sample_page(ws, proj, "a.md", "alpha"))+ .await+ .unwrap();+ store+ .writer+ .upsert_page(sample_page(ws, proj, "b.md", "beta"))+ .await+ .unwrap();++ let summaries = store.reader.list_projects_with_stats().await.unwrap();+ assert_eq!(summaries.len(), 1);+ let s = &summaries[0];+ assert_eq!(s.workspace_name, "default");+ assert_eq!(s.project_name, "my-project");+ assert_eq!(s.page_count, 2);+ assert!(s.last_updated.is_some());+ }++ #[tokio::test]+ async fn list_pages_returns_latest_pages_for_project() {+ let tmp = TempDir::new().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ 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(sample_page(ws, proj, "x.md", "body x"))+ .await+ .unwrap();+ store+ .writer+ .upsert_page(sample_page(ws, proj, "y.md", "body y"))+ .await+ .unwrap();+ // Supersede x.md — should still appear once (latest version).+ store+ .writer+ .upsert_page(sample_page(ws, proj, "x.md", "body x updated"))+ .await+ .unwrap();++ let pages = store.reader.list_pages("default", "scratch").await.unwrap();+ assert_eq!(pages.len(), 2, "only is_latest=1 pages");+ let paths: Vec<&str> = pages.iter().map(|p| p.path.as_str()).collect();+ assert!(paths.contains(&"x.md"));+ assert!(paths.contains(&"y.md"));+ }++ #[tokio::test]+ async fn page_meta_returns_metadata_for_existing_page() {+ let tmp = TempDir::new().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let ws = store+ .writer+ .get_or_create_workspace("default")+ .await+ .unwrap();+ let proj = store+ .writer+ .get_or_create_project(ws, "meta-test", None)+ .await+ .unwrap();+ let page = NewPage {+ workspace_id: ws,+ project_id: proj,+ path: PagePath::new("decisions/d1.md").unwrap(),+ title: "Decision One".into(),+ body: "content here".into(),+ tier: Tier::Semantic,+ frontmatter_json: serde_json::json!({"kind": "decision"}),+ pinned: true,+ };+ store.writer.upsert_page(page).await.unwrap();++ let meta = store+ .reader+ .page_meta("default", "meta-test", "decisions/d1.md")+ .await+ .unwrap();+ let meta = meta.expect("page_meta should return Some for existing page");+ assert_eq!(meta.workspace_name, "default");+ assert_eq!(meta.project_name, "meta-test");+ assert_eq!(meta.path, "decisions/d1.md");+ assert_eq!(meta.title, "Decision One");+ assert_eq!(meta.kind, "decision");+ assert!(meta.pinned);++ // Non-existent page returns None.+ let none = store+ .reader+ .page_meta("default", "meta-test", "no-such.md")+ .await+ .unwrap();+ assert!(none.is_none());+ }}diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rsindex 8996b31e..e0a0b96b 100644--- a/crates/ai-memory-store/src/reader.rs+++ b/crates/ai-memory-store/src/reader.rs@@ -108,6 +108,63 @@ pub struct BriefingPage {pub updated_at: String,}+/// One row per (workspace, project) with aggregate stats.+/// Returned by [`ReaderPool::list_projects_with_stats`].+#[derive(Debug, Clone, Serialize)]+pub struct ProjectSummary {+ /// Name of the workspace.+ pub workspace_name: String,+ /// Name of the project within the workspace.+ pub project_name: String,+ /// Number of `is_latest = 1` pages.+ pub page_count: u64,+ /// ISO-8601 timestamp of the newest `updated_at`, or `None` when+ /// the project has no pages yet.+ pub last_updated: Option<String>,+}++/// Page summary for tree-view rendering (no body).+/// Returned by [`ReaderPool::list_pages`].+#[derive(Debug, Clone, Serialize)]+pub struct PageSummary {+ /// Relative path within the wiki tree.+ pub path: String,+ /// Page title.+ pub title: String,+ /// Semantic kind: `fact` | `rule` | `decision` | `gotcha` | …+ pub kind: String,+ /// Memory tier: `working` | `episodic` | `semantic` | `procedural`.+ pub tier: String,+ /// ISO-8601 timestamp of last update.+ pub updated_at: String,+}++/// Full page metadata for the page-view template.+/// Returned by [`ReaderPool::page_meta`].+#[derive(Debug, Clone, Serialize)]+pub struct PageMeta {+ /// Name of the workspace.+ pub workspace_name: String,+ /// Name of the project.+ pub project_name: String,+ /// Relative wiki path.+ pub path: String,+ /// Page title.+ pub title: String,+ /// Semantic kind.+ pub kind: String,+ /// Memory tier.+ pub tier: String,+ /// Whether the page is pinned (decay-immune).+ pub pinned: bool,+ /// ISO-8601 creation timestamp.+ pub created_at: String,+ /// ISO-8601 last-update timestamp.+ pub updated_at: String,+ /// Path of the page this one supersedes, if any.+ pub supersedes: Option<String>,+}+/// Cheap, cloneable read-only connection pool handle.#[derive(Clone)]pub struct ReaderPool {@@ -670,6 +727,286 @@ impl ReaderPool {.await}+ /// Look up a page's workspace and project names by its path (across all+ /// workspaces and projects). Returns the first `is_latest = 1` match.+ ///+ /// Used by the web search handler to resolve workspace/project for a hit+ /// without a per-hit SQL join.+ ///+ /// # Errors+ /// Propagates any SQL or pool error.+ pub async fn page_meta_by_path(&self, path: &str) -> StoreResult<Option<PageMeta>> {+ let path = path.to_owned();+ self.with_conn(move |conn| {+ let row_opt = conn+ .query_row(+ "SELECT w.name, p.name, pg.path, pg.title, \+ COALESCE(json_extract(pg.frontmatter_json, '$.kind'), 'fact'), \+ pg.tier, pg.pinned, pg.created_at, pg.updated_at, \+ sp.path AS supersedes_path \+ FROM pages pg \+ JOIN projects p ON p.id = pg.project_id \+ JOIN workspaces w ON w.id = pg.workspace_id \+ LEFT JOIN pages sp ON sp.id = pg.supersedes \+ WHERE pg.path = ?1 AND pg.is_latest = 1 \+ LIMIT 1",+ params![path],+ |row| {+ let workspace_name: String = row.get(0)?;+ let project_name: String = row.get(1)?;+ let path: String = row.get(2)?;+ let title: String = row.get(3)?;+ let kind: String = row.get(4)?;+ let tier: String = row.get(5)?;+ let pinned: i64 = row.get(6)?;+ let created_us: i64 = row.get(7)?;+ let updated_us: i64 = row.get(8)?;+ let supersedes_path: Option<String> = row.get(9)?;+ Ok((+ workspace_name,+ project_name,+ path,+ title,+ kind,+ tier,+ pinned,+ created_us,+ updated_us,+ supersedes_path,+ ))+ },+ )+ .optional()?;++ let Some((+ workspace_name,+ project_name,+ path,+ title,+ kind,+ tier,+ pinned,+ created_us,+ updated_us,+ supersedes,+ )) = row_opt+ else {+ return Ok(None);+ };++ let created_at = jiff::Timestamp::from_microsecond(created_us)+ .map(|ts| ts.to_string())+ .unwrap_or_default();+ let updated_at = jiff::Timestamp::from_microsecond(updated_us)+ .map(|ts| ts.to_string())+ .unwrap_or_default();++ Ok(Some(PageMeta {+ workspace_name,+ project_name,+ path,+ title,+ kind,+ tier,+ pinned: pinned != 0,+ created_at,+ updated_at,+ supersedes,+ }))+ })+ .await+ }++ /// Return one row per (workspace, project) with page-count and+ /// last-updated aggregates. Used by the web UI project-list view.+ ///+ /// Only `is_latest = 1` pages are counted.+ ///+ /// # Errors+ /// Propagates any SQL or pool error.+ pub async fn list_projects_with_stats(&self) -> StoreResult<Vec<ProjectSummary>> {+ self.with_conn(|conn| {+ let mut stmt = conn.prepare(+ "SELECT w.name AS workspace_name, \+ p.name AS project_name, \+ COUNT(pg.id) AS page_count, \+ MAX(pg.updated_at) AS last_updated_us \+ FROM workspaces w \+ JOIN projects p ON p.workspace_id = w.id \+ LEFT JOIN pages pg ON pg.project_id = p.id AND pg.is_latest = 1 \+ GROUP BY w.id, p.id \+ ORDER BY last_updated_us DESC NULLS LAST",+ )?;+ let rows = stmt.query_map([], |row| {+ let workspace_name: String = row.get(0)?;+ let project_name: String = row.get(1)?;+ let page_count: i64 = row.get(2)?;+ let last_updated_us: Option<i64> = row.get(3)?;+ Ok((workspace_name, project_name, page_count, last_updated_us))+ })?;+ let mut out = Vec::new();+ for r in rows {+ let (workspace_name, project_name, page_count, last_updated_us) = r?;+ let last_updated = last_updated_us+ .and_then(|us| jiff::Timestamp::from_microsecond(us).ok())+ .map(|ts| ts.to_string());+ #[allow(clippy::cast_sign_loss)]+ out.push(ProjectSummary {+ workspace_name,+ project_name,+ page_count: page_count.max(0) as u64,+ last_updated,+ });+ }+ Ok(out)+ })+ .await+ }++ /// All `is_latest = 1` pages under a given (workspace, project),+ /// ordered by path ascending. Used by the web UI tree view.+ ///+ /// # Errors+ /// Propagates any SQL or pool error.+ pub async fn list_pages(+ &self,+ workspace: &str,+ project: &str,+ ) -> StoreResult<Vec<PageSummary>> {+ let workspace = workspace.to_owned();+ let project = project.to_owned();+ self.with_conn(move |conn| {+ let mut stmt = conn.prepare(+ "SELECT pg.path, pg.title, \+ COALESCE(json_extract(pg.frontmatter_json, '$.kind'), 'fact') AS kind, \+ pg.tier, pg.updated_at \+ FROM pages pg \+ JOIN projects p ON p.id = pg.project_id \+ JOIN workspaces w ON w.id = pg.workspace_id \+ WHERE w.name = ?1 AND p.name = ?2 AND pg.is_latest = 1 \+ ORDER BY pg.path ASC",+ )?;+ let rows = stmt.query_map(params![workspace, project], |row| {+ let path: String = row.get(0)?;+ let title: String = row.get(1)?;+ let kind: String = row.get(2)?;+ let tier: String = row.get(3)?;+ let updated_us: i64 = row.get(4)?;+ Ok((path, title, kind, tier, updated_us))+ })?;+ let mut out = Vec::new();+ for r in rows {+ let (path, title, kind, tier, updated_us) = r?;+ let updated_at = jiff::Timestamp::from_microsecond(updated_us)+ .map(|ts| ts.to_string())+ .unwrap_or_default();+ out.push(PageSummary {+ path,+ title,+ kind,+ tier,+ updated_at,+ });+ }+ Ok(out)+ })+ .await+ }++ /// Full page metadata for the page-view template (body comes from+ /// `Wiki::read_page`). Returns `None` when no `is_latest = 1` row+ /// matches the given path.+ ///+ /// # Errors+ /// Propagates any SQL or pool error.+ pub async fn page_meta(+ &self,+ workspace: &str,+ project: &str,+ page_path: &str,+ ) -> StoreResult<Option<PageMeta>> {+ let workspace = workspace.to_owned();+ let project = project.to_owned();+ let page_path = page_path.to_owned();+ self.with_conn(move |conn| {+ let row_opt = conn+ .query_row(+ "SELECT w.name, p.name, pg.path, pg.title, \+ COALESCE(json_extract(pg.frontmatter_json, '$.kind'), 'fact'), \+ pg.tier, pg.pinned, pg.created_at, pg.updated_at, \+ sp.path AS supersedes_path \+ FROM pages pg \+ JOIN projects p ON p.id = pg.project_id \+ JOIN workspaces w ON w.id = pg.workspace_id \+ LEFT JOIN pages sp ON sp.id = pg.supersedes \+ WHERE w.name = ?1 AND p.name = ?2 AND pg.path = ?3 AND pg.is_latest = 1",+ params![workspace, project, page_path],+ |row| {+ let workspace_name: String = row.get(0)?;+ let project_name: String = row.get(1)?;+ let path: String = row.get(2)?;+ let title: String = row.get(3)?;+ let kind: String = row.get(4)?;+ let tier: String = row.get(5)?;+ let pinned: i64 = row.get(6)?;+ let created_us: i64 = row.get(7)?;+ let updated_us: i64 = row.get(8)?;+ let supersedes_path: Option<String> = row.get(9)?;+ Ok((+ workspace_name,+ project_name,+ path,+ title,+ kind,+ tier,+ pinned,+ created_us,+ updated_us,+ supersedes_path,+ ))+ },+ )+ .optional()?;++ let Some((+ workspace_name,+ project_name,+ path,+ title,+ kind,+ tier,+ pinned,+ created_us,+ updated_us,+ supersedes,+ )) = row_opt+ else {+ return Ok(None);+ };++ let created_at = jiff::Timestamp::from_microsecond(created_us)+ .map(|ts| ts.to_string())+ .unwrap_or_default();+ let updated_at = jiff::Timestamp::from_microsecond(updated_us)+ .map(|ts| ts.to_string())+ .unwrap_or_default();++ Ok(Some(PageMeta {+ workspace_name,+ project_name,+ path,+ title,+ kind,+ tier,+ pinned: pinned != 0,+ created_at,+ updated_at,+ supersedes,+ }))+ })+ .await+ }+/// Return aggregate counts for the `status` view.////// # Errorsdiff --git a/crates/ai-memory-web/Cargo.toml b/crates/ai-memory-web/Cargo.tomlnew file mode 100644index 00000000..58a444f9--- /dev/null+++ b/crates/ai-memory-web/Cargo.toml@@ -0,0 +1,39 @@+[package]+name = "ai-memory-web"+version.workspace = true+edition.workspace = true+rust-version.workspace = true+license.workspace = true+repository.workspace = true+authors.workspace = true+description = "Read-only HTTP browser for the ai-memory wiki (project list, tree navigation, markdown rendering, FTS5 search)."++[dependencies]+ai-memory-core.workspace = true+ai-memory-store.workspace = true+ai-memory-wiki.workspace = true+anyhow.workspace = true+thiserror.workspace = true+serde.workspace = true+serde_json.workspace = true+tokio.workspace = true+tracing.workspace = true+axum.workspace = true+jiff.workspace = true++# Templating + markdown.+askama = "0.12"+pulldown-cmark = { version = "0.12", default-features = false, features = ["html"] }+# Syntax highlighting for fenced code blocks. Default features pull+# in onig (regex via C); the pure-Rust regex feature avoids that.+syntect = { version = "5", default-features = false, features = ["default-fancy"] }++[build-dependencies]+anyhow.workspace = true++[dev-dependencies]+tempfile.workspace = true+tower.workspace = true++[lints]+workspace = truediff --git a/crates/ai-memory-web/build.rs b/crates/ai-memory-web/build.rsnew file mode 100644index 00000000..ea8d1476--- /dev/null+++ b/crates/ai-memory-web/build.rs@@ -0,0 +1,213 @@+//! Build script for ai-memory-web.+//!+//! Downloads the standalone Tailwind CSS CLI (pinned version) and+//! compiles `static/input.css` → `OUT_DIR/tailwind.css`.+//!+//! # Escape hatch+//! Set `TAILWIND_SKIP=1` to skip the download entirely and use the+//! vendored `static/tailwind.css` instead.+//!+//! # Incremental builds+//! Also skips the download when `static/tailwind.css` is newer than+//! every template file and `static/input.css`.++use std::path::{Path, PathBuf};+use std::process::Command;+use std::time::SystemTime;++const TAILWIND_VERSION: &str = "3.4.17";++fn main() {+ // Re-run triggers.+ println!("cargo:rerun-if-changed=build.rs");+ println!("cargo:rerun-if-changed=static/input.css");+ println!("cargo:rerun-if-changed=templates/");+ println!("cargo:rerun-if-env-changed=TAILWIND_SKIP");++ let out_dir = PathBuf::from(std::env::var("OUT_DIR").unwrap());+ let out_css = out_dir.join("tailwind.css");+ let crate_dir = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap());++ // Escape hatch: TAILWIND_SKIP=1 → use the vendored file.+ if std::env::var("TAILWIND_SKIP").as_deref() == Ok("1") {+ let src = crate_dir.join("static/tailwind.css");+ std::fs::copy(&src, &out_css)+ .unwrap_or_else(|e| panic!("TAILWIND_SKIP=1 but static/tailwind.css missing: {e}"));+ emit_env(&out_css);+ return;+ }++ // Incremental: skip if static/tailwind.css is newer than all sources.+ let vendored = crate_dir.join("static/tailwind.css");+ if is_vendored_fresh(&vendored, &crate_dir) {+ std::fs::copy(&vendored, &out_css)+ .expect("failed to copy vendored tailwind.css to OUT_DIR");+ emit_env(&out_css);+ return;+ }++ // Download the tailwind binary (cached by version in OUT_DIR's parent).+ let binary = download_tailwind(&out_dir);++ // Run tailwind.+ compile_tailwind(&binary, &crate_dir, &out_css);+ // Also update the vendored copy so the next build is incremental.+ let _ = std::fs::copy(&out_css, &vendored);++ emit_env(&out_css);+}++fn emit_env(css_path: &Path) {+ println!(+ "cargo:rustc-env=AI_MEMORY_WEB_TAILWIND_CSS={}",+ css_path.display()+ );+}++/// True when `static/tailwind.css` is newer than all template files+/// and `static/input.css`.+fn is_vendored_fresh(vendored: &Path, crate_dir: &Path) -> bool {+ let Ok(vmt) = mtime(vendored) else {+ return false;+ };+ // Check input.css.+ let input = crate_dir.join("static/input.css");+ if mtime(&input).map(|t| t > vmt).unwrap_or(false) {+ return false;+ }+ // Walk templates/.+ let tmpl_dir = crate_dir.join("templates");+ is_dir_older_than(&tmpl_dir, vmt)+}++fn is_dir_older_than(dir: &Path, threshold: SystemTime) -> bool {+ let Ok(entries) = std::fs::read_dir(dir) else {+ return true; // no templates → consider fresh+ };+ for entry in entries.flatten() {+ let path = entry.path();+ if path.is_dir() {+ if !is_dir_older_than(&path, threshold) {+ return false;+ }+ } else if mtime(&path).map(|t| t > threshold).unwrap_or(false) {+ return false;+ }+ }+ true+}++fn mtime(p: &Path) -> std::io::Result<SystemTime> {+ std::fs::metadata(p)?.modified()+}++/// Platform-specific download URL for the Tailwind CLI binary.+fn tailwind_url() -> String {+ let os = std::env::consts::OS;+ let arch = std::env::consts::ARCH;+ let slug = match (os, arch) {+ ("linux", "x86_64") => "tailwindcss-linux-x64",+ ("linux", "aarch64") => "tailwindcss-linux-arm64",+ ("macos", "x86_64") => "tailwindcss-macos-x64",+ ("macos", "aarch64") => "tailwindcss-macos-arm64",+ ("windows", "x86_64") => "tailwindcss-windows-x64.exe",+ _ => panic!(+ "Unsupported platform {os}/{arch} — set TAILWIND_SKIP=1 and provide static/tailwind.css manually"+ ),+ };+ format!(+ "https://github.com/tailwindlabs/tailwindcss/releases/download/v{TAILWIND_VERSION}/{slug}"+ )+}++/// Download the Tailwind CLI and return the path to the executable.+/// The file is cached in `OUT_DIR/tailwindcss-{version}` across rebuilds.+fn download_tailwind(out_dir: &Path) -> PathBuf {+ let bin_name = if cfg!(windows) {+ format!("tailwindcss-{TAILWIND_VERSION}.exe")+ } else {+ format!("tailwindcss-{TAILWIND_VERSION}")+ };+ // Cache in the grandparent of OUT_DIR so it survives incremental rebuilds+ // across profile changes. Fall back to OUT_DIR itself if that fails.+ let cache_dir = out_dir+ .parent()+ .and_then(|p| p.parent())+ .and_then(|p| p.parent())+ .unwrap_or(out_dir);+ let dest = cache_dir.join(&bin_name);++ if dest.exists() {+ // Already cached.+ return dest;+ }++ let url = tailwind_url();+ eprintln!("cargo:warning=Downloading Tailwind CSS CLI v{TAILWIND_VERSION} from {url}");++ // Try curl first, then wget.+ let success = try_download_curl(&url, &dest) || try_download_wget(&url, &dest);++ if !success {+ panic!(+ "Could not download Tailwind CSS CLI — curl and wget both failed.\n\+ Either install curl or wget, OR set TAILWIND_SKIP=1 and place a compiled \+ tailwind.css in crates/ai-memory-web/static/tailwind.css."+ );+ }++ // Make executable on Unix.+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ let mut perms = std::fs::metadata(&dest).unwrap().permissions();+ perms.set_mode(0o755);+ std::fs::set_permissions(&dest, perms).unwrap();+ }++ dest+}++fn try_download_curl(url: &str, dest: &Path) -> bool {+ Command::new("curl")+ .args(["--fail", "--silent", "--location", "--output"])+ .arg(dest)+ .arg(url)+ .status()+ .map(|s| s.success())+ .unwrap_or(false)+}++fn try_download_wget(url: &str, dest: &Path) -> bool {+ Command::new("wget")+ .args(["--quiet", "--output-document"])+ .arg(dest)+ .arg(url)+ .status()+ .map(|s| s.success())+ .unwrap_or(false)+}++/// Invoke the Tailwind CLI to produce `out_css`.+fn compile_tailwind(binary: &Path, crate_dir: &Path, out_css: &Path) {+ let input_css = crate_dir.join("static/input.css");+ let config_js = crate_dir.join("tailwind.config.js");++ let status = Command::new(binary)+ .current_dir(crate_dir)+ .args([+ "--input",+ input_css.to_str().unwrap(),+ "--output",+ out_css.to_str().unwrap(),+ "--config",+ config_js.to_str().unwrap(),+ "--minify",+ ])+ .status()+ .unwrap_or_else(|e| panic!("Failed to run tailwind CLI: {e}"));++ if !status.success() {+ panic!("tailwind CSS compilation failed (exit status {status:?})");+ }+}diff --git a/crates/ai-memory-web/src/lib.rs b/crates/ai-memory-web/src/lib.rsnew file mode 100644index 00000000..dbc22639--- /dev/null+++ b/crates/ai-memory-web/src/lib.rs@@ -0,0 +1,39 @@+//! `ai-memory-web` — read-only HTTP browser for the wiki.+//!+//! Mounted under `/web` on the same axum server that hosts the MCP+//! endpoint, so a single port + single auth posture covers both. The+//! crate is deliberately read-only in v1: no editing, no POST routes,+//! no agent-write APIs. The wiki is already markdown-on-disk; this+//! surface just makes it browsable from a phone, a tablet, or a+//! teammate's machine without `docker exec cat …`.+//!+//! Routes (all under whatever prefix the host nests this router at):+//! - `GET /` → project list (cards)+//! - `GET /w/:workspace/:project` → page tree + recent activity+//! - `GET /w/:workspace/:project/p/*path` → rendered markdown + metadata+//! - `GET /search?q=…` → FTS5 hit list+//! - `GET /static/*` → embedded CSS + logos+//!+//! Theme follows `prefers-color-scheme` via the included Tailwind+//! stylesheet; no JS toggle, no cookie.++use std::sync::Arc;++use ai_memory_store::ReaderPool;+use ai_memory_wiki::Wiki;+use axum::Router;++mod markdown;+mod routes;+mod state;+mod templates;++pub use state::WebState;++/// Build the read-only web router. Call once at server startup and+/// `nest("/web", router)` it onto the existing axum app, OR mount at+/// `/` if the web UI is the only HTTP surface.+pub fn router(reader: ReaderPool, wiki: Wiki) -> Router {+ let state = Arc::new(WebState::new(reader, wiki));+ routes::build(state)+}diff --git a/crates/ai-memory-web/src/markdown.rs b/crates/ai-memory-web/src/markdown.rsnew file mode 100644index 00000000..cbabe41c--- /dev/null+++ b/crates/ai-memory-web/src/markdown.rs@@ -0,0 +1,44 @@+//! Markdown → HTML rendering with `syntect` syntax highlighting.+//!+//! Stub at scaffold time; full implementation in the next step.++use pulldown_cmark::{Options, Parser, html};++/// Render a markdown body to HTML using GFM-ish defaults.+///+/// v1: trust the wiki source (the wiki is on-disk markdown the+/// project owner writes/consolidates; not user-uploaded content from+/// arbitrary callers). Syntax highlighting is deferred.+#[must_use]+pub fn render(body: &str) -> String {+ let mut opts = Options::empty();+ opts.insert(Options::ENABLE_TABLES);+ opts.insert(Options::ENABLE_FOOTNOTES);+ opts.insert(Options::ENABLE_STRIKETHROUGH);+ opts.insert(Options::ENABLE_TASKLISTS);+ opts.insert(Options::ENABLE_SMART_PUNCTUATION);+ let parser = Parser::new_ext(body, opts);+ let mut out = String::with_capacity(body.len() + body.len() / 4);+ html::push_html(&mut out, parser);+ out+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn renders_basic_markdown() {+ let html = render("# Hello\n\nworld");+ assert!(html.contains("<h1>Hello</h1>"));+ assert!(html.contains("<p>world</p>"));+ }++ #[test]+ fn renders_tables() {+ let md = "| a | b |\n|---|---|\n| 1 | 2 |";+ let html = render(md);+ assert!(html.contains("<table>"));+ assert!(html.contains("<td>1</td>"));+ }+}diff --git a/crates/ai-memory-web/src/routes/index.rs b/crates/ai-memory-web/src/routes/index.rsnew file mode 100644index 00000000..b3b48eeb--- /dev/null+++ b/crates/ai-memory-web/src/routes/index.rs@@ -0,0 +1,42 @@+//! `GET /` — project list cards.++use std::sync::Arc;++use askama::Template;+use axum::extract::State;+use axum::http::StatusCode;+use axum::response::Html;++use crate::state::WebState;+use crate::templates::{ProjectCard, ProjectsView, humanize};++/// Handler for `GET /`.+pub(crate) async fn handler(+ State(state): State<Arc<WebState>>,+) -> Result<Html<String>, StatusCode> {+ let summaries = state+ .reader+ .list_projects_with_stats()+ .await+ .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;++ let projects = summaries+ .into_iter()+ .map(|s| {+ let last_updated_relative = s.last_updated.as_deref().map(humanize).unwrap_or_default();+ let href = format!("/web/w/{}/{}", s.workspace_name, s.project_name);+ ProjectCard {+ workspace: s.workspace_name,+ project: s.project_name,+ page_count: s.page_count,+ last_updated_relative,+ href,+ }+ })+ .collect();++ let html = ProjectsView { projects }+ .render()+ .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;+ Ok(Html(html))+}diff --git a/crates/ai-memory-web/src/routes/mod.rs b/crates/ai-memory-web/src/routes/mod.rsnew file mode 100644index 00000000..19c1da2d--- /dev/null+++ b/crates/ai-memory-web/src/routes/mod.rs@@ -0,0 +1,27 @@+//! Route module — assembles the public axum router.++use std::sync::Arc;++use axum::Router;+use axum::routing::get;++use crate::state::WebState;++mod index;+mod page;+mod project;+mod search;+mod statics;++/// Build the read-only web router from a shared [`WebState`].+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("/search", get(search::handler))+ .route("/static/tailwind.css", get(statics::tailwind_css))+ .route("/static/logo.png", get(statics::logo_light))+ .route("/static/logo-dark.png", get(statics::logo_dark))+ .with_state(state)+}diff --git a/crates/ai-memory-web/src/routes/page.rs b/crates/ai-memory-web/src/routes/page.rsnew file mode 100644index 00000000..e6d292f1--- /dev/null+++ b/crates/ai-memory-web/src/routes/page.rs@@ -0,0 +1,64 @@+//! `GET /w/:workspace/:project/p/*path` — rendered markdown page.++use std::sync::Arc;++use ai_memory_core::PagePath;+use askama::Template;+use axum::extract::{Path, State};+use axum::http::StatusCode;+use axum::response::{Html, IntoResponse, Response};++use crate::markdown;+use crate::state::WebState;+use crate::templates::{NotFoundView, PageView, humanize};++/// Handler for `GET /w/:workspace/:project/p/*path`.+pub(crate) async fn handler(+ State(state): State<Arc<WebState>>,+ Path((workspace, project, path)): Path<(String, String, String)>,+) -> Response {+ let meta = match state.reader.page_meta(&workspace, &project, &path).await {+ Ok(Some(m)) => m,+ Ok(None) => return not_found_response(),+ Err(_) => return StatusCode::INTERNAL_SERVER_ERROR.into_response(),+ };++ let page_path = match PagePath::new(&path) {+ Ok(p) => p,+ Err(_) => return StatusCode::BAD_REQUEST.into_response(),+ };++ let markdown_doc = match state.wiki.read_page(&page_path) {+ Ok(doc) => doc,+ Err(_) => return not_found_response(),+ };++ let body_html = markdown::render(&markdown_doc.body);++ match (PageView {+ workspace,+ project,+ path: meta.path,+ title: meta.title,+ kind: meta.kind,+ tier: meta.tier,+ pinned: meta.pinned,+ updated_relative: humanize(&meta.updated_at),+ created_relative: humanize(&meta.created_at),+ supersedes_path: meta.supersedes.unwrap_or_default(),+ body_html,+ }+ .render())+ {+ Ok(html) => Html(html).into_response(),+ Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),+ }+}++/// Render a 404 response with the not-found template body.+fn not_found_response() -> Response {+ let html = NotFoundView {}+ .render()+ .unwrap_or_else(|_| "<h1>Not found</h1>".to_owned());+ (StatusCode::NOT_FOUND, Html(html)).into_response()+}diff --git a/crates/ai-memory-web/src/routes/project.rs b/crates/ai-memory-web/src/routes/project.rsnew file mode 100644index 00000000..32fc35bb--- /dev/null+++ b/crates/ai-memory-web/src/routes/project.rs@@ -0,0 +1,76 @@+//! `GET /w/:workspace/:project` — page tree + recent activity.++use std::collections::BTreeMap;+use std::sync::Arc;++use askama::Template;+use axum::extract::{Path, State};+use axum::http::StatusCode;+use axum::response::Html;++use crate::state::WebState;+use crate::templates::{Folder, PageRow, ProjectView, humanize};++/// Handler for `GET /w/:workspace/:project`.+pub(crate) async fn handler(+ State(state): State<Arc<WebState>>,+ Path((workspace, project)): Path<(String, String)>,+) -> Result<Html<String>, StatusCode> {+ let pages = state+ .reader+ .list_pages(&workspace, &project)+ .await+ .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;++ // Build sidebar folder tree (group by first path segment).+ let mut folder_map: BTreeMap<String, Vec<PageRow>> = BTreeMap::new();+ for p in &pages {+ let folder = p+ .path+ .split('/')+ .next()+ .and_then(|seg| {+ // Only treat it as a folder prefix if there's a slash in the path.+ if p.path.contains('/') {+ Some(seg.to_owned())+ } else {+ None+ }+ })+ .unwrap_or_else(|| "(root)".to_owned());+ folder_map.entry(folder).or_default().push(PageRow {+ path: p.path.clone(),+ title: p.title.clone(),+ kind: p.kind.clone(),+ updated_relative: humanize(&p.updated_at),+ });+ }+ let folders: Vec<Folder> = folder_map+ .into_iter()+ .map(|(name, pages)| Folder { name, pages })+ .collect();++ // Recent pages: sort by updated_at desc, take 20.+ let mut sorted = pages.clone();+ sorted.sort_by(|a, b| b.updated_at.cmp(&a.updated_at));+ sorted.truncate(20);+ let recent: Vec<PageRow> = sorted+ .into_iter()+ .map(|p| PageRow {+ path: p.path.clone(),+ title: p.title.clone(),+ kind: p.kind.clone(),+ updated_relative: humanize(&p.updated_at),+ })+ .collect();++ let html = ProjectView {+ workspace,+ project,+ folders,+ recent,+ }+ .render()+ .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;+ Ok(Html(html))+}diff --git a/crates/ai-memory-web/src/routes/search.rs b/crates/ai-memory-web/src/routes/search.rsnew file mode 100644index 00000000..f2878143--- /dev/null+++ b/crates/ai-memory-web/src/routes/search.rs@@ -0,0 +1,73 @@+//! `GET /search?q=…` — FTS5 search results.++use std::sync::Arc;++use askama::Template;+use axum::extract::{Query, State};+use axum::http::StatusCode;+use axum::response::Html;+use serde::Deserialize;++use crate::state::WebState;+use crate::templates::{SearchHit, SearchView};++/// Query-string parameters for the search endpoint.+#[derive(Debug, Deserialize)]+pub(crate) struct SearchParams {+ /// The free-text search query.+ #[serde(default)]+ pub q: String,+}++/// Handler for `GET /search?q=…`.+pub(crate) async fn handler(+ State(state): State<Arc<WebState>>,+ Query(params): Query<SearchParams>,+) -> Result<Html<String>, StatusCode> {+ let query = params.q.trim().to_owned();++ let hits = if query.is_empty() {+ Vec::new()+ } else {+ let raw = state+ .reader+ .search_pages(query.clone(), 50)+ .await+ .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;++ // For each hit we need (workspace, project) — look up via a second+ // query per hit is too expensive; instead query the page_meta inline.+ // Since search_pages returns PageHit with workspace/project not yet+ // separated, we query page_meta by path using the "default" workspace+ // for now. The proper approach joins workspaces/projects in the FTS+ // query; for v1 we accept the extra lookup.+ let mut results = Vec::with_capacity(raw.len());+ for h in raw {+ // Get workspace + project by looking up full meta.+ // We try across all project/workspace combos by using the raw+ // search hit's path and calling a lightweight query.+ if let Ok(Some(m)) = state.reader.page_meta_by_path(h.path.as_str()).await {+ results.push(SearchHit {+ workspace: m.workspace_name,+ project: m.project_name,+ path: h.path.as_str().to_owned(),+ title: h.title,+ snippet: h.snippet,+ });+ } else {+ // Fallback: no workspace/project known; skip for now.+ }+ }+ results+ };++ let hit_count = hits.len();+ let html = SearchView {+ query,+ hits,+ hit_count,+ }+ .render()+ .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;+ Ok(Html(html))+}diff --git a/crates/ai-memory-web/src/routes/statics.rs b/crates/ai-memory-web/src/routes/statics.rsnew file mode 100644index 00000000..6b3161b7--- /dev/null+++ b/crates/ai-memory-web/src/routes/statics.rs@@ -0,0 +1,41 @@+//! Static asset handlers: Tailwind CSS and logo images.+//!+//! Assets are embedded at compile time so the binary is fully+//! self-contained — no runtime file access needed.++use axum::http::{HeaderMap, HeaderValue, StatusCode, header};+use axum::response::IntoResponse;++/// Compiled Tailwind CSS. The path is emitted by `build.rs` via the+/// `AI_MEMORY_WEB_TAILWIND_CSS` cargo env var.+static TAILWIND_CSS: &str = include_str!(env!("AI_MEMORY_WEB_TAILWIND_CSS"));++/// Light-mode logo (PNG).+static LOGO_LIGHT: &[u8] = include_bytes!("../../../../docs/logo.png");++/// Dark-mode logo (PNG).+static LOGO_DARK: &[u8] = include_bytes!("../../../../docs/logo-dark.png");++/// `GET /static/tailwind.css`+pub(crate) async fn tailwind_css() -> impl IntoResponse {+ let mut headers = HeaderMap::new();+ headers.insert(+ header::CONTENT_TYPE,+ HeaderValue::from_static("text/css; charset=utf-8"),+ );+ (StatusCode::OK, headers, TAILWIND_CSS)+}++/// `GET /static/logo.png`+pub(crate) async fn logo_light() -> impl IntoResponse {+ let mut headers = HeaderMap::new();+ headers.insert(header::CONTENT_TYPE, HeaderValue::from_static("image/png"));+ (StatusCode::OK, headers, LOGO_LIGHT)+}++/// `GET /static/logo-dark.png`+pub(crate) async fn logo_dark() -> impl IntoResponse {+ let mut headers = HeaderMap::new();+ headers.insert(header::CONTENT_TYPE, HeaderValue::from_static("image/png"));+ (StatusCode::OK, headers, LOGO_DARK)+}diff --git a/crates/ai-memory-web/src/state.rs b/crates/ai-memory-web/src/state.rsnew file mode 100644index 00000000..7ef11c39--- /dev/null+++ b/crates/ai-memory-web/src/state.rs@@ -0,0 +1,27 @@+//! Web router state — the handle a request handler receives.+//!+//! Holds the read-only store pool + the wiki handle. Cheap to clone+//! (everything inside is `Arc`-shaped already), so axum's+//! `State<Arc<WebState>>` extractor stays free of clone-heavy code.++use ai_memory_store::ReaderPool;+use ai_memory_wiki::Wiki;++/// Shared state for every web route. Construct once via+/// [`crate::router`].+#[derive(Clone)]+pub struct WebState {+ /// Read-only SQLite pool — drives FTS5 search, page metadata,+ /// project list aggregates.+ pub reader: ReaderPool,+ /// Wiki handle — reads page bodies from disk.+ pub wiki: Wiki,+}++impl WebState {+ /// Build a new shared state.+ #[must_use]+ pub fn new(reader: ReaderPool, wiki: Wiki) -> Self {+ Self { reader, wiki }+ }+}diff --git a/crates/ai-memory-web/src/templates.rs b/crates/ai-memory-web/src/templates.rsnew file mode 100644index 00000000..7d04016f--- /dev/null+++ b/crates/ai-memory-web/src/templates.rs@@ -0,0 +1,177 @@+//! `askama` template definitions and per-route view-models.++use askama::Template;++// ---------------------------------------------------------------------------+// Humanise helper+// ---------------------------------------------------------------------------++/// Format an ISO-8601 timestamp string as a relative human-readable string+/// (e.g. "3 hours ago", "2 days ago"). Falls back to the raw string on any+/// parse error.+#[must_use]+pub(crate) fn humanize(iso: &str) -> String {+ let Ok(then) = iso.parse::<jiff::Timestamp>() else {+ return iso.to_owned();+ };+ let now = jiff::Timestamp::now();+ // Compute elapsed seconds using microsecond arithmetic to avoid Span API.+ let diff_us = now.as_microsecond() - then.as_microsecond();+ let secs = diff_us.abs() / 1_000_000;+ if secs < 60 {+ return "just now".to_owned();+ }+ let mins = secs / 60;+ if mins < 60 {+ return format!("{mins} minute{} ago", if mins == 1 { "" } else { "s" });+ }+ let hours = mins / 60;+ if hours < 24 {+ return format!("{hours} hour{} ago", if hours == 1 { "" } else { "s" });+ }+ let days = hours / 24;+ if days < 30 {+ return format!("{days} day{} ago", if days == 1 { "" } else { "s" });+ }+ let months = days / 30;+ if months < 12 {+ return format!("{months} month{} ago", if months == 1 { "" } else { "s" });+ }+ let years = months / 12;+ format!("{years} year{} ago", if years == 1 { "" } else { "s" })+}++// ---------------------------------------------------------------------------+// projects.html+// ---------------------------------------------------------------------------++/// One card on the project-list page.+pub(crate) struct ProjectCard {+ /// Workspace name.+ pub workspace: String,+ /// Project name.+ pub project: String,+ /// Number of latest pages.+ pub page_count: u64,+ /// Humanised timestamp (e.g. "3 hours ago"), or empty string.+ pub last_updated_relative: String,+ /// Link target (`/web/w/{ws}/{proj}`).+ pub href: String,+}++/// View-model for `GET /`.+#[derive(Template)]+#[template(path = "projects.html")]+pub(crate) struct ProjectsView {+ /// All project cards, sorted by most recently active first.+ pub projects: Vec<ProjectCard>,+}++// ---------------------------------------------------------------------------+// project.html+// ---------------------------------------------------------------------------++/// One entry in the sidebar or recent-list.+pub(crate) struct PageRow {+ /// Relative wiki path.+ pub path: String,+ /// Page title.+ pub title: String,+ /// Semantic kind badge text.+ pub kind: String,+ /// Humanised updated timestamp.+ pub updated_relative: String,+}++/// A folder in the sidebar tree (groups pages by first path segment).+pub(crate) struct Folder {+ /// Folder name (first path segment, without trailing slash).+ pub name: String,+ /// Pages inside this folder.+ pub pages: Vec<PageRow>,+}++/// View-model for `GET /w/:workspace/:project`.+#[derive(Template)]+#[template(path = "project.html")]+pub(crate) struct ProjectView {+ /// Workspace name.+ pub workspace: String,+ /// Project name.+ pub project: String,+ /// Sidebar folder tree.+ pub folders: Vec<Folder>,+ /// N most-recent pages for the right column.+ pub recent: Vec<PageRow>,+}++// ---------------------------------------------------------------------------+// page.html+// ---------------------------------------------------------------------------++/// View-model for `GET /w/:workspace/:project/p/*path`.+#[derive(Template)]+#[template(path = "page.html")]+pub(crate) struct PageView {+ /// Workspace name.+ pub workspace: String,+ /// Project name.+ pub project: String,+ /// Relative wiki path.+ pub path: String,+ /// Page title.+ pub title: String,+ /// Semantic kind.+ pub kind: String,+ /// Memory tier.+ pub tier: String,+ /// Whether the page is pinned.+ pub pinned: bool,+ /// Humanised updated timestamp.+ pub updated_relative: String,+ /// Humanised created timestamp.+ pub created_relative: String,+ /// Path of the page this supersedes, or empty string.+ pub supersedes_path: String,+ /// Rendered markdown body (HTML, trusted).+ pub body_html: String,+}++// ---------------------------------------------------------------------------+// search.html+// ---------------------------------------------------------------------------++/// One FTS5 search hit.+pub(crate) struct SearchHit {+ /// Workspace name.+ pub workspace: String,+ /// Project name.+ pub project: String,+ /// Relative wiki path.+ pub path: String,+ /// Page title.+ pub title: String,+ /// FTS5 snippet (HTML-marked with `<mark>` tags).+ pub snippet: String,+}++/// View-model for `GET /search?q=…`.+#[derive(Template)]+#[template(path = "search.html")]+pub(crate) struct SearchView {+ /// The raw query string.+ pub query: String,+ /// FTS5 search hits.+ pub hits: Vec<SearchHit>,+ /// Pre-computed hit count for display (avoids needing `|length` filter).+ pub hit_count: usize,+}++// ---------------------------------------------------------------------------+// not_found.html+// ---------------------------------------------------------------------------++/// View-model for 404 responses.+#[derive(Template)]+#[template(path = "not_found.html")]+pub(crate) struct NotFoundView {}diff --git a/crates/ai-memory-web/static/input.css b/crates/ai-memory-web/static/input.cssnew file mode 100644index 00000000..b5c61c95--- /dev/null+++ b/crates/ai-memory-web/static/input.css@@ -0,0 +1,3 @@+@tailwind base;+@tailwind components;+@tailwind utilities;diff --git a/crates/ai-memory-web/static/tailwind.css b/crates/ai-memory-web/static/tailwind.cssnew file mode 100644index 00000000..cf825336--- /dev/null+++ b/crates/ai-memory-web/static/tailwind.css@@ -0,0 +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}.sticky{position:sticky}.top-0{top:0}.z-10{z-index:10}.mx-auto{margin-left:auto;margin-right:auto}.mb-1{margin-bottom:.25rem}.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-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-7{height:1.75rem}.h-full{height:100%}.min-h-full{min-height:100%}.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-xs{max-width:20rem}.flex-1{flex:1 1 0%}.shrink-0{flex-shrink:0}.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-center{align-items:center}.justify-between{justify-content:space-between}.gap-1{gap:.25rem}.gap-2{gap:.5rem}.gap-4{gap:1rem}.gap-8{gap:2rem}.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)))}.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))}.truncate{overflow:hidden;text-overflow:ellipsis}.truncate,.whitespace-nowrap{white-space:nowrap}.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-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-slate-100{--tw-bg-opacity:1;background-color:rgb(241 245 249/var(--tw-bg-opacity,1))}.bg-white{--tw-bg-opacity:1;background-color:rgb(255 255 255/var(--tw-bg-opacity,1))}.p-12{padding:3rem}.p-5{padding:1.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}.text-center{text-align:center}.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-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}.tracking-wide{letter-spacing:.025em}.text-amber-700{--tw-text-opacity:1;color:rgb(180 83 9/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-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))}.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-blue-700:hover{--tw-bg-opacity:1;background-color:rgb(29 78 216/var(--tw-bg-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))}@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-blue-800{--tw-border-opacity:1;border-color:rgb(30 64 175/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-950{--tw-bg-opacity:1;background-color:rgb(69 26 3/var(--tw-bg-opacity,1))}.dark\:bg-blue-950{--tw-bg-opacity:1;background-color:rgb(23 37 84/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-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-300{--tw-text-opacity:1;color:rgb(252 211 77/var(--tw-text-opacity,1))}.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\:hover\:border-blue-600:hover{--tw-border-opacity:1;border-color:rgb(37 99 235/var(--tw-border-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/tailwind.config.js b/crates/ai-memory-web/tailwind.config.jsnew file mode 100644index 00000000..54212fbe--- /dev/null+++ b/crates/ai-memory-web/tailwind.config.js@@ -0,0 +1,6 @@+module.exports = {+ content: ["./templates/**/*.html"],+ darkMode: 'media',+ theme: { extend: {} },+ plugins: [],+};diff --git a/crates/ai-memory-web/templates/base.html b/crates/ai-memory-web/templates/base.htmlnew file mode 100644index 00000000..231b29bf--- /dev/null+++ b/crates/ai-memory-web/templates/base.html@@ -0,0 +1,41 @@+<!doctype html>+<html lang="en" class="h-full">+<head>+ <meta charset="utf-8">+ <meta name="viewport" content="width=device-width, initial-scale=1">+ <title>{% block title %}ai-memory{% endblock %}</title>+ <link rel="stylesheet" href="/web/static/tailwind.css">+</head>+<body class="min-h-full bg-white text-slate-900 dark:bg-slate-950 dark:text-slate-100">+ <header class="border-b border-slate-200 dark:border-slate-800 bg-white dark:bg-slate-950 sticky top-0 z-10">+ <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 flex items-center gap-4 h-14">+ <a href="/web/" class="flex items-center gap-2 shrink-0">+ <picture>+ <source media="(prefers-color-scheme: dark)" srcset="/web/static/logo-dark.png">+ <img src="/web/static/logo.png" alt="ai-memory logo" class="h-7 w-auto">+ </picture>+ <span class="font-semibold text-slate-800 dark:text-slate-100 text-sm hidden sm:inline">ai-memory</span>+ </a>+ <div class="flex-1"></div>+ <form action="/web/search" method="get" class="flex items-center">+ <input+ name="q"+ type="search"+ placeholder="Search…"+ class="w-40 sm:w-64 rounded-md border border-slate-300 dark:border-slate-700 bg-white dark:bg-slate-900 px-3 py-1.5 text-sm placeholder-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500"+ >+ </form>+ </div>+ </header>++ <main class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">+ {% block content %}{% endblock %}+ </main>++ <footer class="border-t border-slate-200 dark:border-slate-800 mt-16 py-4">+ <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 text-xs text-slate-400 dark:text-slate-600">+ ai-memory · read-only+ </div>+ </footer>+</body>+</html>diff --git a/crates/ai-memory-web/templates/not_found.html b/crates/ai-memory-web/templates/not_found.htmlnew file mode 100644index 00000000..9829769e--- /dev/null+++ b/crates/ai-memory-web/templates/not_found.html@@ -0,0 +1,14 @@+{% extends "base.html" %}++{% block title %}Not Found — ai-memory{% endblock %}++{% block content %}+<div class="text-center py-20">+ <p class="text-6xl font-bold text-slate-200 dark:text-slate-800">404</p>+ <h1 class="mt-4 text-2xl font-semibold text-slate-700 dark:text-slate-300">Page not found</h1>+ <p class="mt-2 text-sm text-slate-500 dark:text-slate-400">The page you're looking for doesn't exist or has been superseded.</p>+ <a href="/web/" class="mt-6 inline-block rounded-md bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700">+ Back to home+ </a>+</div>+{% endblock %}diff --git a/crates/ai-memory-web/templates/page.html b/crates/ai-memory-web/templates/page.htmlnew file mode 100644index 00000000..3a06dbda--- /dev/null+++ b/crates/ai-memory-web/templates/page.html@@ -0,0 +1,64 @@+{% extends "base.html" %}++{% block title %}{{ title }} — 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="/web/" class="hover:text-blue-600 dark:hover:text-blue-400">home</a>+ <span>/</span>+ <a href="/web/w/{{ workspace }}/{{ project }}" class="hover:text-blue-600 dark:hover:text-blue-400">{{ workspace }}/{{ project }}</a>+ <span>/</span>+ <span class="text-slate-700 dark:text-slate-200 truncate max-w-xs">{{ path }}</span>+</nav>++<article class="max-w-3xl">+ <h1 class="text-3xl font-bold text-slate-900 dark:text-slate-100 mb-3">{{ title }}</h1>++ <!-- Metadata row -->+ <div class="flex flex-wrap items-center gap-2 mb-6 text-xs text-slate-500 dark:text-slate-400">+ <span class="inline-flex items-center rounded px-2 py-0.5 font-medium bg-blue-50 dark:bg-blue-950 text-blue-700 dark:text-blue-300 border border-blue-200 dark:border-blue-800">+ {{ tier }}+ </span>+ <span class="inline-flex items-center rounded px-2 py-0.5 font-medium bg-slate-100 dark:bg-slate-800 text-slate-600 dark:text-slate-400">+ {{ kind }}+ </span>+ {% if pinned %}+ <span class="inline-flex items-center rounded px-2 py-0.5 font-medium bg-amber-50 dark:bg-amber-950 text-amber-700 dark:text-amber-300 border border-amber-200 dark:border-amber-800">+ pinned+ </span>+ {% endif %}+ <span class="ml-1">Updated {{ updated_relative }}</span>+ <span>·</span>+ <span>Created {{ created_relative }}</span>+ {% if supersedes_path != "" %}+ <span>·</span>+ <span>Supersedes <a href="/web/w/{{ workspace }}/{{ project }}/p/{{ supersedes_path }}" class="text-blue-600 dark:text-blue-400 underline">{{ supersedes_path }}</a></span>+ {% endif %}+ </div>++ <!-- Rendered markdown body -->+ <div class="+ [&_h1]:text-3xl [&_h1]:font-bold [&_h1]:mt-6 [&_h1]:mb-3+ [&_h2]:text-2xl [&_h2]:font-semibold [&_h2]:mt-5 [&_h2]:mb-2+ [&_h3]:text-xl [&_h3]:font-semibold [&_h3]:mt-4 [&_h3]:mb-2+ [&_h4]:text-lg [&_h4]:font-semibold [&_h4]:mt-3 [&_h4]:mb-1+ [&_p]:my-3 [&_p]:leading-relaxed+ [&_ul]:list-disc [&_ul]:pl-5 [&_ul]:my-3+ [&_ol]:list-decimal [&_ol]:pl-5 [&_ol]:my-3+ [&_li]:my-1+ [&_blockquote]:border-l-4 [&_blockquote]:border-slate-300 [&_blockquote]:dark:border-slate-700 [&_blockquote]:pl-4 [&_blockquote]:italic [&_blockquote]:text-slate-600 [&_blockquote]:dark:text-slate-400 [&_blockquote]:my-3+ [&_code]:bg-slate-100 [&_code]:dark:bg-slate-800 [&_code]:rounded [&_code]:px-1 [&_code]:py-0.5 [&_code]:text-sm [&_code]:font-mono+ [&_pre]:p-3 [&_pre]:rounded [&_pre]:bg-slate-100 [&_pre]:dark:bg-slate-800 [&_pre]:overflow-x-auto [&_pre]:my-3+ [&_pre_code]:bg-transparent [&_pre_code]:p-0+ [&_a]:text-blue-600 [&_a]:dark:text-blue-400 [&_a]:underline+ [&_table]:w-full [&_table]:my-3 [&_table]:border-collapse+ [&_th]:border [&_th]:border-slate-300 [&_th]:dark:border-slate-700 [&_th]:px-3 [&_th]:py-2 [&_th]:text-left [&_th]:bg-slate-50 [&_th]:dark:bg-slate-800+ [&_td]:border [&_td]:border-slate-300 [&_td]:dark:border-slate-700 [&_td]:px-3 [&_td]:py-2+ [&_hr]:border-slate-200 [&_hr]:dark:border-slate-800 [&_hr]:my-6+ [&_mark]:bg-yellow-200 [&_mark]:dark:bg-yellow-800 [&_mark]:px-0.5+ text-slate-800 dark:text-slate-200+ ">+ {{ body_html|safe }}+ </div>+</article>+{% endblock %}diff --git a/crates/ai-memory-web/templates/project.html b/crates/ai-memory-web/templates/project.htmlnew file mode 100644index 00000000..f91f1150--- /dev/null+++ b/crates/ai-memory-web/templates/project.html@@ -0,0 +1,71 @@+{% extends "base.html" %}++{% block title %}{{ project }} — 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="/web/" class="hover:text-blue-600 dark:hover:text-blue-400">home</a>+ <span>/</span>+ <span class="text-slate-400 dark:text-slate-500">{{ workspace }}</span>+ <span>/</span>+ <span class="text-slate-700 dark:text-slate-200 font-medium">{{ project }}</span>+</nav>++<h1 class="text-2xl font-bold text-slate-900 dark:text-slate-100 mb-6">{{ workspace }}/{{ project }}</h1>++<div class="flex flex-col md:flex-row gap-8">+ <!-- Sidebar: folder tree -->+ <aside class="w-full md:w-56 shrink-0">+ <h2 class="text-xs font-semibold uppercase tracking-wide text-slate-400 dark:text-slate-500 mb-3">Pages</h2>+ {% if folders.is_empty() %}+ <p class="text-sm text-slate-400 dark:text-slate-600">No pages yet.</p>+ {% else %}+ <ul class="space-y-1">+ {% for folder in folders %}+ <li>+ <div class="text-xs font-medium text-slate-500 dark:text-slate-400 py-1 border-b border-slate-100 dark:border-slate-800 mb-1">{{ folder.name }}/</div>+ <ul class="space-y-0.5 pl-2">+ {% for page in folder.pages %}+ <li>+ <a href="/web/w/{{ workspace }}/{{ project }}/p/{{ page.path }}"+ class="block truncate text-sm text-slate-700 dark:text-slate-300 hover:text-blue-600 dark:hover:text-blue-400 py-0.5">+ {{ page.title }}+ </a>+ </li>+ {% endfor %}+ </ul>+ </li>+ {% endfor %}+ </ul>+ {% endif %}+ </aside>++ <!-- Main: recent pages -->+ <div class="flex-1 min-w-0">+ <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>+ {% else %}+ <ul class="divide-y divide-slate-100 dark:divide-slate-800">+ {% for page in recent %}+ <li class="py-3 flex items-start justify-between gap-4">+ <div class="min-w-0">+ <a href="/web/w/{{ workspace }}/{{ project }}/p/{{ page.path }}"+ class="text-sm font-medium text-slate-800 dark:text-slate-100 hover:text-blue-600 dark:hover:text-blue-400 truncate block">+ {{ page.title }}+ </a>+ <div class="flex items-center gap-2 mt-1">+ <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">+ {{ page.kind }}+ </span>+ <span class="text-xs text-slate-400 dark:text-slate-500 truncate">{{ page.path }}</span>+ </div>+ </div>+ <span class="text-xs text-slate-400 dark:text-slate-500 whitespace-nowrap shrink-0">{{ page.updated_relative }}</span>+ </li>+ {% endfor %}+ </ul>+ {% endif %}+ </div>+</div>+{% endblock %}diff --git a/crates/ai-memory-web/templates/projects.html b/crates/ai-memory-web/templates/projects.htmlnew file mode 100644index 00000000..9977e252--- /dev/null+++ b/crates/ai-memory-web/templates/projects.html@@ -0,0 +1,33 @@+{% extends "base.html" %}++{% block title %}Projects — ai-memory{% endblock %}++{% block content %}+<div class="mb-6">+ <h1 class="text-2xl font-bold text-slate-900 dark:text-slate-100">Projects</h1>+ <p class="mt-1 text-sm text-slate-500 dark:text-slate-400">All workspaces and projects in your wiki.</p>+</div>++{% if projects.is_empty() %}+<div class="rounded-lg border border-dashed border-slate-300 dark:border-slate-700 p-12 text-center">+ <p class="text-slate-500 dark:text-slate-400 text-sm">+ No projects yet — wire up a hook and start a session.+ </p>+</div>+{% else %}+<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">+ {% for card in projects %}+ <a href="{{ card.href }}" class="block rounded-lg border border-slate-200 dark:border-slate-800 bg-white dark:bg-slate-900 p-5 hover:border-blue-400 dark:hover:border-blue-600 hover:shadow-sm transition-all">+ <div class="text-xs font-medium text-slate-400 dark:text-slate-500 mb-1">{{ card.workspace }}</div>+ <div class="text-base font-semibold text-slate-800 dark:text-slate-100 truncate">{{ card.project }}</div>+ <div class="mt-3 flex items-center justify-between text-xs text-slate-500 dark:text-slate-400">+ <span>{{ card.page_count }} page{% if card.page_count != 1 %}s{% endif %}</span>+ {% if card.last_updated_relative != "" %}+ <span>{{ card.last_updated_relative }}</span>+ {% endif %}+ </div>+ </a>+ {% endfor %}+</div>+{% endif %}+{% endblock %}diff --git a/crates/ai-memory-web/templates/search.html b/crates/ai-memory-web/templates/search.htmlnew file mode 100644index 00000000..64ac4745--- /dev/null+++ b/crates/ai-memory-web/templates/search.html@@ -0,0 +1,48 @@+{% extends "base.html" %}++{% block title %}Search: {{ query }} — ai-memory{% endblock %}++{% block content %}+<div class="mb-6">+ <h1 class="text-2xl font-bold text-slate-900 dark:text-slate-100">+ {% if query != "" %}+ Search: <span class="text-blue-600 dark:text-blue-400">{{ query }}</span>+ {% else %}+ Search+ {% endif %}+ </h1>+</div>++<form action="/web/search" method="get" class="mb-8 flex gap-2">+ <input+ name="q"+ type="search"+ value="{{ query }}"+ placeholder="Search pages…"+ class="flex-1 max-w-md rounded-md border border-slate-300 dark:border-slate-700 bg-white dark:bg-slate-900 px-3 py-2 text-sm placeholder-slate-400 focus:outline-none focus:ring-2 focus:ring-blue-500"+ >+ <button type="submit" class="rounded-md bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700">+ Search+ </button>+</form>++{% if query == "" %}+<p class="text-sm text-slate-500 dark:text-slate-400">Enter a search term above.</p>+{% else if hits.is_empty() %}+<p class="text-sm text-slate-500 dark:text-slate-400">No results for <strong>{{ query }}</strong>.</p>+{% else %}+<p class="text-sm text-slate-500 dark:text-slate-400 mb-4">{{ hit_count }} result{% if hit_count != 1 %}s{% endif %}</p>+<ul class="divide-y divide-slate-100 dark:divide-slate-800">+ {% for hit in hits %}+ <li class="py-4">+ <a href="/web/w/{{ hit.workspace }}/{{ hit.project }}/p/{{ hit.path }}"+ class="text-base font-medium text-blue-700 dark:text-blue-400 hover:underline block mb-1">+ {{ hit.title }}+ </a>+ <div class="text-sm text-slate-600 dark:text-slate-400 mb-1">{{ hit.snippet|safe }}</div>+ <div class="text-xs text-slate-400 dark:text-slate-500">{{ hit.workspace }}/{{ hit.project }} · {{ hit.path }}</div>+ </li>+ {% endfor %}+</ul>+{% endif %}+{% endblock %}diff --git a/crates/ai-memory-web/tests/routes.rs b/crates/ai-memory-web/tests/routes.rsnew file mode 100644index 00000000..f364cf3f--- /dev/null+++ b/crates/ai-memory-web/tests/routes.rs@@ -0,0 +1,230 @@+//! Smoke integration tests for the read-only web UI.+//!+//! Spins up a `Store` + `Wiki` in a tempdir, seeds two pages, builds+//! the router, and exercises each route via `tower::ServiceExt::oneshot`.++use ai_memory_core::{NewPage, PagePath, Tier};+use ai_memory_store::Store;+use ai_memory_web::router;+use ai_memory_wiki::{Wiki, WritePageRequest};+use axum::body::Body;+use axum::http::{Request, StatusCode};+use tempfile::TempDir;+use tower::ServiceExt;++async fn setup() -> (TempDir, Store, Wiki) {+ let tmp = TempDir::new().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();+ (tmp, store, wiki)+}++fn new_page(+ ws: ai_memory_core::WorkspaceId,+ proj: ai_memory_core::ProjectId,+ path: &str,+ title: &str,+ body: &str,+) -> NewPage {+ NewPage {+ workspace_id: ws,+ project_id: proj,+ path: PagePath::new(path).unwrap(),+ title: title.to_owned(),+ body: body.to_owned(),+ tier: Tier::Semantic,+ frontmatter_json: serde_json::json!({"kind": "fact"}),+ pinned: false,+ }+}++fn wiki_req(+ ws: ai_memory_core::WorkspaceId,+ proj: ai_memory_core::ProjectId,+ path: &str,+ body: &str,+) -> WritePageRequest {+ WritePageRequest {+ workspace_id: ws,+ project_id: proj,+ path: PagePath::new(path).unwrap(),+ frontmatter: serde_json::json!({"kind": "fact"}),+ body: body.to_owned(),+ tier: Tier::Semantic,+ pinned: false,+ title: None,+ }+}++#[tokio::test]+async fn smoke_index_returns_200() {+ let (_tmp, store, wiki) = setup().await;+ let ws = store+ .writer+ .get_or_create_workspace("default")+ .await+ .unwrap();+ let proj = store+ .writer+ .get_or_create_project(ws, "scratch", None)+ .await+ .unwrap();+ store+ .writer+ .upsert_page(new_page(ws, proj, "foo.md", "Foo Page", "Hello world"))+ .await+ .unwrap();++ let app = router(store.reader.clone(), wiki.clone());+ let req = Request::builder().uri("/").body(Body::empty()).unwrap();+ let resp = app.oneshot(req).await.unwrap();+ assert_eq!(resp.status(), StatusCode::OK);++ let body = axum::body::to_bytes(resp.into_body(), usize::MAX)+ .await+ .unwrap();+ let text = std::str::from_utf8(&body).unwrap();+ assert!(+ text.contains("scratch"),+ "expected project name in index response"+ );+}++#[tokio::test]+async fn smoke_project_page_returns_200() {+ let (_tmp, store, wiki) = setup().await;+ let ws = store+ .writer+ .get_or_create_workspace("default")+ .await+ .unwrap();+ let proj = store+ .writer+ .get_or_create_project(ws, "scratch", None)+ .await+ .unwrap();+ store+ .writer+ .upsert_page(new_page(+ ws,+ proj,+ "notes/bar.md",+ "Bar Note",+ "A note about bar",+ ))+ .await+ .unwrap();++ let app = router(store.reader.clone(), wiki.clone());+ let req = Request::builder()+ .uri("/w/default/scratch")+ .body(Body::empty())+ .unwrap();+ let resp = app.oneshot(req).await.unwrap();+ assert_eq!(resp.status(), StatusCode::OK);++ let body = axum::body::to_bytes(resp.into_body(), usize::MAX)+ .await+ .unwrap();+ let text = std::str::from_utf8(&body).unwrap();+ assert!(+ text.contains("Bar Note"),+ "expected page title in project response"+ );+}++#[tokio::test]+async fn smoke_page_view_returns_200() {+ let (_tmp, store, wiki) = setup().await;+ let ws = store+ .writer+ .get_or_create_workspace("default")+ .await+ .unwrap();+ let proj = store+ .writer+ .get_or_create_project(ws, "scratch", None)+ .await+ .unwrap();+ // Use wiki.write_page so the file is written to disk (needed for read_page).+ wiki.write_page(wiki_req(ws, proj, "foo.md", "# Foo\n\nHello world"))+ .await+ .unwrap();++ let app = router(store.reader.clone(), wiki.clone());+ let req = Request::builder()+ .uri("/w/default/scratch/p/foo.md")+ .body(Body::empty())+ .unwrap();+ let resp = app.oneshot(req).await.unwrap();+ assert_eq!(resp.status(), StatusCode::OK);++ let body = axum::body::to_bytes(resp.into_body(), usize::MAX)+ .await+ .unwrap();+ let text = std::str::from_utf8(&body).unwrap();+ // The title is derived from the H1 heading.+ assert!(text.contains("Foo"), "expected page title");+ assert!(text.contains("Hello world"), "expected rendered body");+}++#[tokio::test]+async fn smoke_search_returns_200() {+ let (_tmp, store, wiki) = setup().await;+ let ws = store+ .writer+ .get_or_create_workspace("default")+ .await+ .unwrap();+ let proj = store+ .writer+ .get_or_create_project(ws, "scratch", None)+ .await+ .unwrap();+ store+ .writer+ .upsert_page(new_page(+ ws,+ proj,+ "foo.md",+ "Searchable Page",+ "unique_term_xyz_abc",+ ))+ .await+ .unwrap();++ let app = router(store.reader.clone(), wiki.clone());+ let req = Request::builder()+ .uri("/search?q=unique_term_xyz_abc")+ .body(Body::empty())+ .unwrap();+ let resp = app.oneshot(req).await.unwrap();+ assert_eq!(resp.status(), StatusCode::OK);++ let body = axum::body::to_bytes(resp.into_body(), usize::MAX)+ .await+ .unwrap();+ let text = std::str::from_utf8(&body).unwrap();+ assert!(+ text.contains("unique_term_xyz_abc"),+ "expected search term in results"+ );+}++#[tokio::test]+async fn smoke_page_not_found_returns_404() {+ let (_tmp, store, wiki) = setup().await;+ let _ws = store+ .writer+ .get_or_create_workspace("default")+ .await+ .unwrap();++ let app = router(store.reader.clone(), wiki.clone());+ let req = Request::builder()+ .uri("/w/default/scratch/p/does-not-exist.md")+ .body(Body::empty())+ .unwrap();+ let resp = app.oneshot(req).await.unwrap();+ assert_eq!(resp.status(), StatusCode::NOT_FOUND);+}