Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(web): sort recent pages by timestamp
Samir Hanna Verzae397e62cb93c
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e65cba04..177bc5f0 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -13,6 +13,11 @@ version in [`docs/changelog/`](docs/changelog/):### Fixed+- Sorted recent page lists by timestamp rather than RFC3339 text, so updates+ with different fractional-second precision appear in chronological order+ in the legacy recent API, project activity, folder previews and namespace+ listings. Kept title-sort and equal-timestamp path tie-breaks (#1247).+- Refused empty and whitespace-only `--workspace` and `--project` flags at theshared CLI scope-resolution choke point (`resolve_scope`,`resolve_scope_noting_marker_project`, `resolve_scope_with_marker`, anddiff --git a/crates/ai-memory-web/src/routes/api.rs b/crates/ai-memory-web/src/routes/api.rsindex ac8eeedd..346e93d5 100644--- a/crates/ai-memory-web/src/routes/api.rs+++ b/crates/ai-memory-web/src/routes/api.rs@@ -1,5 +1,6 @@//! JSON routes for third-party read-only frontends.+use std::cmp::Reverse;use std::sync::Arc;use ai_memory_core::{ObservationKind, PagePath, ProjectId, SessionId, WorkspaceId};@@ -642,7 +643,14 @@ async fn recent_handler(.list_unexpired_pages(&workspace, &project).await.map_err(internal_error)?;- pages.sort_by(|a, b| b.updated_at.cmp(&a.updated_at));+ // RFC3339's variable fractional precision is not lexically ordered.+ // The reader's empty fallback for an invalid timestamp stays last.+ pages.sort_by_cached_key(|page| {+ (+ Reverse(page.updated_at.parse::<jiff::Timestamp>().ok()),+ page.path.clone(),+ )+ });pages.truncate(limit);return Ok(with_cache(Json(pages).into_response(), LIST_CACHE_MAX_AGE));}diff --git a/crates/ai-memory-web/src/routes/page.rs b/crates/ai-memory-web/src/routes/page.rsindex b3fb098f..a30826ad 100644--- a/crates/ai-memory-web/src/routes/page.rs+++ b/crates/ai-memory-web/src/routes/page.rs@@ -1,5 +1,6 @@//! `GET /w/:workspace/:project/p/*path` — rendered markdown page.+use std::cmp::Reverse;use std::sync::Arc;use ai_memory_core::PagePath;@@ -219,20 +220,16 @@ async fn namespace_or_not_found(}let sort_title = query.sort.as_deref() == Some("title");// Titles repeat (session pages), so ties fall back to recency, then path.- let newest_first = |a: &PageSummary, b: &PageSummary| {- b.updated_at- .cmp(&a.updated_at)- .then_with(|| a.path.cmp(&b.path))+ let newest_first = |page: &PageSummary| {+ (+ Reverse(page.updated_at.parse::<jiff::Timestamp>().ok()),+ page.path.clone(),+ )};if sort_title {- under.sort_by(|a, b| {- a.title- .to_lowercase()- .cmp(&b.title.to_lowercase())- .then_with(|| newest_first(a, b))- });+ under.sort_by_cached_key(|page| (page.title.to_lowercase(), newest_first(page)));} else {- under.sort_by(newest_first);+ under.sort_by_cached_key(newest_first);}let total = under.len();let last_page = total.div_ceil(NAMESPACE_PAGE_SIZE);diff --git a/crates/ai-memory-web/src/routes/project.rs b/crates/ai-memory-web/src/routes/project.rsindex a85f3b36..e92c5264 100644--- a/crates/ai-memory-web/src/routes/project.rs+++ b/crates/ai-memory-web/src/routes/project.rs@@ -1,5 +1,6 @@//! `GET /w/:workspace/:project` — page tree + recent activity.+use std::cmp::Reverse;use std::collections::BTreeMap;use std::sync::Arc;@@ -7,6 +8,7 @@ use askama::Template;use axum::extract::{Path, State};use axum::http::StatusCode;use axum::response::{Html, IntoResponse, Response};+use jiff::Timestamp;use ai_memory_store::ResolvedScope;@@ -75,8 +77,8 @@ async fn render(// bundle indexes) than curated knowledge; listing them as peers// buried the concepts/decisions/rules a human actually opens this// UI for.- let mut knowledge_map: BTreeMap<String, Vec<(String, PageRow)>> = BTreeMap::new();- let mut system_map: BTreeMap<String, Vec<(String, PageRow)>> = BTreeMap::new();+ let mut knowledge_map: BTreeMap<String, Vec<(Option<Timestamp>, PageRow)>> = BTreeMap::new();+ let mut system_map: BTreeMap<String, Vec<(Option<Timestamp>, PageRow)>> = BTreeMap::new();for p in &pages {let folder = p.path@@ -97,7 +99,7 @@ async fn render(&mut knowledge_map};map.entry(folder).or_default().push((- p.updated_at.clone(),+ p.updated_at.parse::<Timestamp>().ok(),PageRow {path: p.path.clone(),href: page_href(&workspace, &project, &p.path),@@ -119,7 +121,12 @@ async fn render(.filter(|p| !is_system_page(&p.path)).cloned().collect();- sorted.sort_by(|a, b| b.updated_at.cmp(&a.updated_at));+ sorted.sort_by_cached_key(|page| {+ (+ Reverse(page.updated_at.parse::<Timestamp>().ok()),+ page.path.clone(),+ )+ });sorted.truncate(20);let recent: Vec<PageRow> = sorted.into_iter()@@ -154,7 +161,7 @@ async fn render(/// Turn grouped pages into sidebar folders: newest first, capped at/// `FOLDER_PREVIEW`, each linked to its namespace listing.fn to_folders(- map: BTreeMap<String, Vec<(String, PageRow)>>,+ map: BTreeMap<String, Vec<(Option<Timestamp>, PageRow)>>,workspace: &str,project: &str,) -> Vec<Folder> {diff --git a/crates/ai-memory-web/tests/suite/routes.rs b/crates/ai-memory-web/tests/suite/routes.rsindex c5fbe9ee..e64a2b1a 100644--- a/crates/ai-memory-web/tests/suite/routes.rs+++ b/crates/ai-memory-web/tests/suite/routes.rs@@ -1499,6 +1499,135 @@ async fn api_project_routes_return_404_for_missing_project() {assert_eq!(resp.status(), StatusCode::NOT_FOUND);}+#[tokio::test]+async fn recent_page_lists_order_timestamps_chronologically() {+ let (tmp, store, wiki) = setup().await;+ let ws = store+ .writer+ .get_or_create_workspace("default")+ .await+ .unwrap();+ let proj = store+ .writer+ .get_or_create_project(ws, "scratch", None)+ .await+ .unwrap();+ let second = "2026-01-01T12:00:00Z"+ .parse::<jiff::Timestamp>()+ .unwrap()+ .as_microsecond();+ let conn = rusqlite::Connection::open(tmp.path().join("db/memory.sqlite")).unwrap();+ for (path, delta) in [+ ("notes/oldest.md", -2_000_000),+ ("notes/prior.md", -1_000_000),+ ("notes/whole.md", 0),+ ("notes/tenth.md", 100_000),+ ("notes/z-newest.md", 100_001),+ ("notes/a-newest.md", 100_001),+ ] {+ let id = store+ .writer+ .upsert_page(new_page(ws, proj, path, "Repeated title", "body"))+ .await+ .unwrap();+ conn.execute(+ "UPDATE pages SET updated_at = ?1 WHERE id = ?2",+ rusqlite::params![second + delta, id.as_bytes()],+ )+ .unwrap();+ }+ let expected = [+ "notes/a-newest.md",+ "notes/z-newest.md",+ "notes/tenth.md",+ "notes/whole.md",+ "notes/prior.md",+ "notes/oldest.md",+ ];+ let api = api_router(store.reader.clone(), wiki.clone());+ let (status, body) =+ get_body(&api, "/workspaces/default/projects/scratch/recent?limit=1").await;+ assert_eq!(status, StatusCode::OK);+ let rows: Value = serde_json::from_str(&body).unwrap();+ assert_eq!(+ rows[0]["path"], expected[0],+ "limit must retain the newest instant, not the lexically largest timestamp"+ );+ let (_, body) = get_body(+ &api,+ "/workspaces/default/projects/scratch/recent?limit=100",+ )+ .await;+ let rows: Value = serde_json::from_str(&body).unwrap();+ let paths: Vec<_> = rows+ .as_array()+ .unwrap()+ .iter()+ .map(|row| row["path"].as_str().unwrap())+ .collect();+ assert_eq!(paths, expected);+ assert_eq!(rows[2]["updated_at"], "2026-01-01T12:00:00.1Z");+ assert_eq!(rows[3]["updated_at"], "2026-01-01T12:00:00Z");++ // Incremental reads keep their SQL-backed ascending order.+ let (status, body) = get_body(+ &api,+ "/workspaces/default/projects/scratch/recent?updated_since=2026-01-01T00:00:00Z&limit=100",+ )+ .await;+ assert_eq!(status, StatusCode::OK);+ let incremental: Value = serde_json::from_str(&body).unwrap();+ let ascending: Vec<_> = incremental["pages"]+ .as_array()+ .unwrap()+ .iter()+ .map(|page| page["path"].as_str().unwrap())+ .collect();+ assert_eq!(+ ascending,+ [+ expected[5],+ expected[4],+ expected[3],+ expected[2],+ expected[0],+ expected[1]+ ]+ );++ let web = router(store.reader.clone(), wiki);+ let assert_order = |html: &str, paths: &[&str]| {+ let positions: Vec<_> = paths+ .iter()+ .map(|path| {+ html.find(&format!("href=\"w/default/scratch/p/{path}\""))+ .unwrap_or_else(|| panic!("missing {path}"))+ })+ .collect();+ assert!(+ positions.windows(2).all(|pair| pair[0] < pair[1]),+ "wrong chronological order: {positions:?}"+ );+ };+ let (_, project) = get_body(&web, "/w/default/scratch").await;+ let sidebar = &project[..project.find("</aside>").unwrap()];+ assert_order(sidebar, &expected[..5]);+ assert!(+ !sidebar.contains("p/notes/oldest.md\""),+ "folder preview must omit the oldest page"+ );+ let recent = &project[project.find("Recent Activity").unwrap()..];+ assert_order(recent, &expected);+ for uri in [+ "/w/default/scratch/p/notes/",+ "/w/default/scratch/p/notes/?sort=title",+ ] {+ let (status, body) = get_body(&web, uri).await;+ assert_eq!(status, StatusCode::OK);+ assert_order(&body, &expected);+ }+}+#[tokio::test]async fn api_recent_and_briefing_return_project_data() {let (_tmp, store, wiki) = setup().await;diff --git a/docs/frontend-api.md b/docs/frontend-api.mdindex 2a621665..96af6680 100644--- a/docs/frontend-api.md+++ b/docs/frontend-api.md@@ -314,7 +314,9 @@ GET /api/v1/workspaces/{workspace}/projects/{project}/recent?limit=20````is_latest = 1` pages whose `expires_at` TTL has not passed, ordered by-`updated_at` DESC. `limit` clamped `1..=100`, default `10`.+`updated_at` DESC by instant, with path ascending for equal timestamps.+Fractional-second precision in the serialized timestamps does not change this+order. `limit` clamped `1..=100`, default `10`.Every reader surface uses the same `kind` contract. An explicit frontmatter`kind` wins; otherwise the path families `_rules/`, `_slots/`, `sessions/`,