Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(web): resolve OKF bundle-index + relative links; add namespace listing (#603)
AkitaOnRails9ffc2c269c70
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3185b142..acbea57d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]### Fixed+- Web UI: OKF bundle-index links (and any relative in-wiki link) no+ longer 404 (#603). Relative markdown link targets are now rewritten to+ project-scoped URLs — the same convention `[[wikilinks]]` use — instead+ of resolving against the web mount's `<base href>`, and a namespace+ (directory) path such as `.../p/_lint/` now lists the pages under it+ rather than returning 404. External links, anchors, and dangerous+ schemes are untouched by the rewrite.- Pages with an empty frontmatter `title` no longer read back titlelessor trip a bogus duplicate-title lint (#599). Auto-improve could store`title: ""` while the page had a proper `# H1`; now `memory_read_page`diff --git a/crates/ai-memory-web/src/markdown.rs b/crates/ai-memory-web/src/markdown.rsindex 9993cb6a..a5cded26 100644--- a/crates/ai-memory-web/src/markdown.rs+++ b/crates/ai-memory-web/src/markdown.rs@@ -37,12 +37,59 @@ pub fn render(body: &str, workspace: &str, project: &str) -> String {// there, mirroring the engine's link extractor.let body = preprocess_wikilinks(body, workspace, project);- let parser = Parser::new_ext(&body, opts).map(sanitize_event);+ let parser =+ Parser::new_ext(&body, opts).map(|event| sanitize_event(event, workspace, project));let mut out = String::with_capacity(body.len() + body.len() / 4);html::push_html(&mut out, parser);out}+/// Rewrite a relative in-wiki link target (a page like `concepts/foo.md`+/// or a namespace directory like `_lint/`) to a project-scoped URL, so it+/// resolves under the web mount's `<base href>` instead of against it. An+/// external URL, anchor, absolute path, or anything with a scheme is left+/// for [`safe_url`] to handle. Targets are treated as project-root+/// relative — the same convention `[[wikilinks]]` use — which is what the+/// OKF bundle-index page and generated cross-references rely on (#603).+fn scope_relative_link<'a>(dest: CowStr<'a>, workspace: &str, project: &str) -> CowStr<'a> {+ let trimmed = dest.trim();+ // Leave anchors, absolute paths, network paths, and any scheme+ // (http:, mailto:, javascript:, …) to safe_url.+ if trimmed.is_empty()+ || trimmed.starts_with('#')+ || trimmed.starts_with('/')+ || trimmed.starts_with('\\')+ || trimmed.contains(':')+ {+ return dest;+ }+ // Already project-scoped (a `[[wikilink]]` the preprocessor rewrote to+ // `w/<ws>/<proj>/p/…`, including cross-project/workspace targets):+ // don't scope it again or the path doubles.+ if trimmed.starts_with("w/") && trimmed.contains("/p/") {+ return dest;+ }+ // Split off a trailing #anchor/?query so it survives the rewrite.+ let (path_part, suffix) = match trimmed.find(['#', '?']) {+ Some(i) => (&trimmed[..i], &trimmed[i..]),+ None => (trimmed, ""),+ };+ if path_part.is_empty() || path_part.contains("..") {+ return dest; // don't rewrite traversal; safe_url/router will reject+ }+ let path_part = path_part.trim_end_matches('/');+ if path_part.is_empty() {+ return dest;+ }+ CowStr::Boxed(+ format!(+ "{}{suffix}",+ crate::templates::page_href(workspace, project, path_part)+ )+ .into_boxed_str(),+ )+}+/// Convert `[[target]]` / `[[target|label]]` spans into `[label](href)`/// markdown links, skipping fenced code blocks, inline-code spans, and/// 4-space-indented code blocks. Targets that aren't internal pages@@ -237,7 +284,7 @@ fn split_scope<'a>((cur_ws, cur_proj, target)}-fn sanitize_event(event: Event<'_>) -> Event<'_> {+fn sanitize_event<'a>(event: Event<'a>, workspace: &str, project: &str) -> Event<'a> {match event {Event::Html(s) | Event::InlineHtml(s) => Event::Text(s),Event::Start(Tag::Link {@@ -247,7 +294,9 @@ fn sanitize_event(event: Event<'_>) -> Event<'_> {id,}) => Event::Start(Tag::Link {link_type,- dest_url: safe_url(dest_url),+ // Scope relative in-wiki targets first (#603), then run the+ // scheme allowlist over whatever remains.+ dest_url: safe_url(scope_relative_link(dest_url, workspace, project)),title,id,}),@@ -417,6 +466,34 @@ mod tests {assert!(html.contains(r#"href="https://example.com/docs""#));}+ #[test]+ fn scopes_relative_links_to_the_project() {+ // #603: the OKF bundle index's directory links and any relative+ // in-wiki link must resolve under the web mount, not against it.+ let html = render(+ "[lint](_lint/) and [foo](concepts/foo.md)",+ "default",+ "scratch",+ );+ assert!(+ html.contains(r#"href="w/default/scratch/p/_lint""#),+ "directory link must be project-scoped: {html}"+ );+ assert!(+ html.contains(r#"href="w/default/scratch/p/concepts/foo.md""#),+ "relative page link must be project-scoped: {html}"+ );+ // External, anchor, and dangerous schemes are untouched by the scope pass.+ let ext = render(+ "[x](https://e.com) [a](#h) [j](javascript:alert(1))",+ "d",+ "p",+ );+ assert!(ext.contains(r#"href="https://e.com""#));+ assert!(ext.contains(r##"href="#h""##));+ assert!(!ext.contains("javascript:"));+ }+#[test]fn neutralises_external_images_without_hiding_alt_text() {for target in [diff --git a/crates/ai-memory-web/src/routes/page.rs b/crates/ai-memory-web/src/routes/page.rsindex 5f6eede8..2a7fa1fe 100644--- a/crates/ai-memory-web/src/routes/page.rs+++ b/crates/ai-memory-web/src/routes/page.rs@@ -10,7 +10,9 @@ use axum::response::{Html, IntoResponse, Response};use crate::markdown;use crate::state::WebState;-use crate::templates::{NotFoundView, PageView, humanize, page_href, project_href};+use crate::templates::{+ NamespaceView, NotFoundView, PageRow, PageView, humanize, page_href, project_href,+};/// Handler for `GET /w/:workspace/:project/p/*path`.pub(crate) async fn handler(@@ -19,7 +21,10 @@ pub(crate) async fn handler() -> Response {let meta = match state.reader.page_meta(&workspace, &project, &path).await {Ok(Some(m)) => m,- Ok(None) => return not_found_response(),+ // Not a page — it may be a namespace (directory) link, e.g. the OKF+ // bundle index's `[_lint/](_lint/)`. Render a listing rather than a+ // bare 404 (#603).+ Ok(None) => return namespace_or_not_found(&state, &workspace, &project, &path).await,Err(_) => return StatusCode::INTERNAL_SERVER_ERROR.into_response(),};@@ -88,6 +93,52 @@ pub(crate) async fn handler(}}+/// When a path is not a page, list the pages under it as a namespace+/// (directory) if any exist; otherwise 404. Powers the OKF bundle index's+/// directory links and any relative `dir/` link (#603).+async fn namespace_or_not_found(+ state: &Arc<WebState>,+ workspace: &str,+ project: &str,+ path: &str,+) -> Response {+ let namespace = path.trim_end_matches('/');+ if namespace.is_empty() {+ return not_found_response();+ }+ let prefix = format!("{namespace}/");+ let all = match state.reader.list_pages(workspace, project).await {+ Ok(p) => p,+ Err(_) => return StatusCode::INTERNAL_SERVER_ERROR.into_response(),+ };+ let pages: Vec<PageRow> = all+ .into_iter()+ .filter(|p| p.path.starts_with(&prefix))+ .map(|p| PageRow {+ href: page_href(workspace, project, &p.path),+ path: p.path,+ title: p.title,+ kind: p.kind,+ updated_relative: humanize(&p.updated_at),+ })+ .collect();+ if pages.is_empty() {+ return not_found_response();+ }+ match (NamespaceView {+ workspace: workspace.to_owned(),+ project: project.to_owned(),+ project_href: project_href(workspace, project),+ namespace: namespace.to_owned(),+ pages,+ }+ .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 {}diff --git a/crates/ai-memory-web/src/templates.rs b/crates/ai-memory-web/src/templates.rsindex e44c6cac..9e20726d 100644--- a/crates/ai-memory-web/src/templates.rs+++ b/crates/ai-memory-web/src/templates.rs@@ -181,6 +181,24 @@ pub(crate) struct ProjectView {pub recent: Vec<PageRow>,}+/// View-model for a namespace (directory) listing — `GET+/// /w/:workspace/:project/p/:namespace/` when the path names a namespace+/// rather than a page (#603).+#[derive(Template)]+#[template(path = "namespace.html")]+pub(crate) struct NamespaceView {+ /// Workspace name.+ pub workspace: String,+ /// Project name.+ pub project: String,+ /// Link back to the project overview.+ pub project_href: String,+ /// The namespace path (no trailing slash), e.g. `_lint` or `concepts`.+ pub namespace: String,+ /// Pages under this namespace.+ pub pages: Vec<PageRow>,+}+// ---------------------------------------------------------------------------// page.html// ---------------------------------------------------------------------------diff --git a/crates/ai-memory-web/templates/namespace.html b/crates/ai-memory-web/templates/namespace.htmlnew file mode 100644index 00000000..9422446b--- /dev/null+++ b/crates/ai-memory-web/templates/namespace.html@@ -0,0 +1,38 @@+{% extends "base.html" %}++{% block title %}{{ namespace }}/ — {{ 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="." 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-medium">{{ namespace }}/</span>+</nav>++<h1 class="text-2xl font-bold text-slate-900 dark:text-slate-100 mb-1">{{ namespace }}/</h1>+<p class="mb-6 text-sm text-slate-500 dark:text-slate-400">{{ pages.len() }} page{% if pages.len() != 1 %}s{% endif %} in this namespace.</p>++{% if pages.is_empty() %}+<p class="text-sm text-slate-400 dark:text-slate-600">No pages in this namespace.</p>+{% else %}+<ul class="divide-y divide-slate-100 dark:divide-slate-800">+ {% for page in pages %}+ <li class="py-3 flex items-start justify-between gap-4">+ <div class="min-w-0">+ <a href="{{ page.href }}"+ 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 %}+{% endblock %}diff --git a/crates/ai-memory-web/tests/routes.rs b/crates/ai-memory-web/tests/routes.rsindex 7a849be9..6459a657 100644--- a/crates/ai-memory-web/tests/routes.rs+++ b/crates/ai-memory-web/tests/routes.rs@@ -3081,3 +3081,71 @@ async fn homepage_llm_notice_is_dismissible_and_backup_banner_is_gone() {"redundant backup banner must not render");}++// ── #603: namespace (directory) links list pages instead of 404 ──++#[tokio::test]+async fn namespace_path_lists_its_pages() {+ 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();+ for (path, title) in [+ ("_lint/report.md", "Lint report 2026-09-03"),+ ("concepts/retrieval.md", "Retrieval"),+ ] {+ store+ .writer+ .upsert_page(new_page(ws, proj, path, title, "body"))+ .await+ .unwrap();+ }+ let app = router(store.reader.clone(), wiki.clone());++ // A directory path (the OKF bundle-index link shape) lists its pages.+ let resp = app+ .clone()+ .oneshot(+ Request::builder()+ .uri("/w/default/scratch/p/_lint/")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(resp.status(), StatusCode::OK);+ let text = std::str::from_utf8(+ &axum::body::to_bytes(resp.into_body(), usize::MAX)+ .await+ .unwrap(),+ )+ .unwrap()+ .to_owned();+ assert!(+ text.contains("Lint report 2026-09-03"),+ "namespace listing must show its page"+ );+ assert!(+ !text.contains("Retrieval"),+ "must not list pages from other namespaces"+ );++ // A namespace with no pages still 404s.+ let empty = app+ .oneshot(+ Request::builder()+ .uri("/w/default/scratch/p/nope/")+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(empty.status(), StatusCode::NOT_FOUND);+}