Skip to content

Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors

Rust

fix(web): derive Created from PageMeta and index the first-version lookup

Peterson Salme0de5ad62ea0a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9b720404..bd92ece8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -17,9 +17,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
hand-written forms differently: a numeric-looking `title` or tag such as
`007` is no longer used, a `!!timestamp`-tagged title fails that page's
import, and a custom-tagged title (`!foo x`) imports as its plain text.
-- Fixed the web page header showing the date of the latest version as
- "Created", so a page rewritten many times looked new. It now shows when the
- first version was written. "Updated" is unchanged. (#1238)
+- Fixed the web page header and the `/api/v1` page response reporting the
+ date of the latest version as "Created", so a page rewritten many times
+ looked new. They now report when the oldest retained version was written.
+ "Updated" is unchanged. (#1238)
## [2.6.5] - 2026-10-12
diff --git a/crates/ai-memory-store/migrations/V77__pages_path_created_index.sql b/crates/ai-memory-store/migrations/V77__pages_path_created_index.sql
new file mode 100644
index 00000000..20f80edb
--- /dev/null
+++ b/crates/ai-memory-store/migrations/V77__pages_path_created_index.sql
@@ -0,0 +1,6 @@
+-- V77: serve the page header's "Created" (the oldest retained version of a
+-- path). idx_pages_latest_path is partial on is_latest = 1, so it cannot answer
+-- MIN(created_at) over a page's superseded versions; without this index every
+-- page view scanned all versions in the project.
+CREATE INDEX idx_pages_path_created
+ ON pages(workspace_id, project_id, path, created_at);
diff --git a/crates/ai-memory-store/src/api_credentials.rs b/crates/ai-memory-store/src/api_credentials.rs
index 471cdc6c..9fa0ba20 100644
--- a/crates/ai-memory-store/src/api_credentials.rs
+++ b/crates/ai-memory-store/src/api_credentials.rs
@@ -411,7 +411,7 @@ mod tests {
|row| row.get(0),
)
.unwrap();
- assert_eq!(version, 76, "update the pin when adding a migration");
+ assert_eq!(version, 77, "update the pin when adding a migration");
let cols: i64 = conn
.query_row(
"SELECT COUNT(*) FROM pragma_table_info('users') WHERE name = 'token_hash'",
diff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rs
index c2a056e8..54f83052 100644
--- a/crates/ai-memory-store/src/reader.rs
+++ b/crates/ai-memory-store/src/reader.rs
@@ -1660,7 +1660,7 @@ pub struct PageMeta {
pub tier: String,
/// Whether the page is pinned (decay-immune).
pub pinned: bool,
- /// ISO-8601 creation timestamp.
+ /// ISO-8601 instant the oldest retained version of the page was written.
pub created_at: String,
/// ISO-8601 last-update timestamp.
pub updated_at: String,
@@ -7475,10 +7475,11 @@ impl ReaderPool {
pub async fn page_meta_by_id(&self, page_id: PageId) -> StoreResult<Option<PageMeta>> {
self.with_conn(move |conn| {
let kind_expr = page_kind_expr("pg.path", "pg.frontmatter_json");
+ let created_expr = PAGE_FIRST_CREATED_EXPR;
let sql = format!(
"SELECT w.name, p.name, w.id, p.id, pg.path, pg.title, \
{kind_expr}, \
- pg.tier, pg.pinned, pg.created_at, pg.updated_at, \
+ pg.tier, pg.pinned, {created_expr}, pg.updated_at, \
sp.path AS supersedes_path, \
au.username, au.name, au.email, pg.expires_at \
FROM pages pg \
@@ -7508,10 +7509,11 @@ impl ReaderPool {
let path = path.to_owned();
self.with_conn(move |conn| {
let kind_expr = page_kind_expr("pg.path", "pg.frontmatter_json");
+ let created_expr = PAGE_FIRST_CREATED_EXPR;
let sql = format!(
"SELECT w.name, p.name, w.id, p.id, pg.path, pg.title, \
{kind_expr}, \
- pg.tier, pg.pinned, pg.created_at, pg.updated_at, \
+ pg.tier, pg.pinned, {created_expr}, pg.updated_at, \
sp.path AS supersedes_path, \
au.username, au.name, au.email, pg.expires_at \
FROM pages pg \
@@ -8407,10 +8409,11 @@ impl ReaderPool {
let page_path = page_path.to_owned();
self.with_conn(move |conn| {
let kind_expr = page_kind_expr("pg.path", "pg.frontmatter_json");
+ let created_expr = PAGE_FIRST_CREATED_EXPR;
let sql = format!(
"SELECT w.name, p.name, w.id, p.id, pg.path, pg.title, \
{kind_expr}, \
- pg.tier, pg.pinned, pg.created_at, pg.updated_at, \
+ pg.tier, pg.pinned, {created_expr}, pg.updated_at, \
sp.path AS supersedes_path, \
au.username, au.name, au.email, pg.expires_at \
FROM pages pg \
@@ -8432,41 +8435,6 @@ impl ReaderPool {
.await
}
- /// Creation instant of the oldest version of a page, as ISO-8601.
- ///
- /// `pages.created_at` is per version, so [`PageMeta::created_at`] is when
- /// the *latest* version was written. Every version of a page shares
- /// `(workspace_id, project_id, path)`; this returns the earliest of them,
- /// which is when the page itself first appeared. Keyed by ids, so a
- /// same-path page in another project never contributes.
- ///
- /// # Errors
- /// Propagates any SQL or pool error.
- pub async fn page_first_created_at(
- &self,
- workspace_id: WorkspaceId,
- project_id: ProjectId,
- page_path: &str,
- ) -> StoreResult<Option<String>> {
- let page_path = page_path.to_owned();
- self.with_conn(move |conn| {
- let first_us: Option<i64> = conn.query_row(
- "SELECT MIN(created_at) FROM pages \
- WHERE workspace_id = ?1 AND project_id = ?2 AND path = ?3",
- params![
- workspace_id.as_bytes().to_vec(),
- project_id.as_bytes().to_vec(),
- page_path
- ],
- |row| row.get(0),
- )?;
- Ok(first_us
- .and_then(|us| jiff::Timestamp::from_microsecond(us).ok())
- .map(|ts| ts.to_string()))
- })
- .await
- }
-
/// Fetch the latest version's stored body/title/frontmatter for a page by
/// `(workspace_id, project_id, path)`. Used as a DB-backed fallback for
/// `memory_read_page` when the on-disk markdown read fails (index/disk
@@ -10489,6 +10457,21 @@ fn health_page_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<HealthPage>
})
}
+/// SQL for [`PageMeta::created_at`]: when the page itself first appeared.
+///
+/// `pages.created_at` is per version, so the latest row alone would report the
+/// last rewrite. Every version shares `(workspace_id, project_id, path)`;
+/// the earliest retained one is the page's creation instant, which also
+/// follows a tombstone-resurrected page onto its old chain (#929). Versions
+/// removed by retention or ledger reclaim no longer count. Served by
+/// `idx_pages_path_created`.
+const PAGE_FIRST_CREATED_EXPR: &str = "COALESCE(\
+ (SELECT MIN(v.created_at) FROM pages v \
+ WHERE v.workspace_id = pg.workspace_id \
+ AND v.project_id = pg.project_id \
+ AND v.path = pg.path), \
+ pg.created_at)";
+
fn page_meta_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<StoreResult<PageMeta>> {
let workspace_name: String = row.get(0)?;
let project_name: String = row.get(1)?;
diff --git a/crates/ai-memory-store/tests/suite/page_first_created.rs b/crates/ai-memory-store/tests/suite/page_first_created.rs
index cb048256..905ccfc0 100644
--- a/crates/ai-memory-store/tests/suite/page_first_created.rs
+++ b/crates/ai-memory-store/tests/suite/page_first_created.rs
@@ -1,5 +1,5 @@
-//! `ReaderPool::page_first_created_at`: the page-level creation instant behind
-//! the web header's "Created".
+//! `PageMeta::created_at`: the page-level creation instant behind the web
+//! header's "Created" and the API's `created_at`.
//!
//! Invariants under test:
//! - **Oldest version wins.** `pages.created_at` is per version, so a page
@@ -91,31 +91,28 @@ async fn first_created_is_the_oldest_version_and_stays_in_its_project() {
let iso = |us: i64| jiff::Timestamp::from_microsecond(us).unwrap().to_string();
- let first = store
- .reader
- .page_first_created_at(ws, app, "notes/a.md")
- .await
- .unwrap();
- assert_eq!(first, Some(iso(now - 30 * DAY_US)));
-
- let single = store
- .reader
- .page_first_created_at(ws, app, "notes/single.md")
- .await
- .unwrap();
- assert_eq!(single, Some(iso(now - 5 * DAY_US)));
+ let created = |project: &'static str, path: &'static str| {
+ let reader = store.reader.clone();
+ async move {
+ reader
+ .page_meta("default", project, path)
+ .await
+ .unwrap()
+ .map(|m| m.created_at)
+ }
+ };
- let foreign = store
- .reader
- .page_first_created_at(ws, other, "notes/a.md")
- .await
- .unwrap();
- assert_eq!(foreign, Some(iso(now - 90 * DAY_US)));
-
- let missing = store
- .reader
- .page_first_created_at(ws, app, "notes/none.md")
- .await
- .unwrap();
- assert_eq!(missing, None);
+ assert_eq!(
+ created("app", "notes/a.md").await,
+ Some(iso(now - 30 * DAY_US))
+ );
+ assert_eq!(
+ created("app", "notes/single.md").await,
+ Some(iso(now - 5 * DAY_US))
+ );
+ assert_eq!(
+ created("other", "notes/a.md").await,
+ Some(iso(now - 90 * DAY_US))
+ );
+ assert_eq!(created("app", "notes/none.md").await, None);
}
diff --git a/crates/ai-memory-web/src/routes/page.rs b/crates/ai-memory-web/src/routes/page.rs
index 3d94494e..be3ea857 100644
--- a/crates/ai-memory-web/src/routes/page.rs
+++ b/crates/ai-memory-web/src/routes/page.rs
@@ -32,16 +32,6 @@ pub(crate) async fn handler(
Err(_) => return StatusCode::INTERNAL_SERVER_ERROR.into_response(),
};
- // `created_at` is per version; the header's "Created" is the first one.
- let created_at = match state
- .reader
- .page_first_created_at(meta.workspace_id, meta.project_id, &meta.path)
- .await
- {
- Ok(first) => first.unwrap_or_else(|| meta.created_at.clone()),
- 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(),
@@ -93,7 +83,7 @@ pub(crate) async fn handler(
tier: meta.tier,
pinned: meta.pinned,
updated_relative: humanize(&meta.updated_at),
- created_relative: humanize(&created_at),
+ created_relative: humanize(&meta.created_at),
supersedes_path,
supersedes_href,
body_html,
diff --git a/crates/ai-memory-web/tests/suite/routes.rs b/crates/ai-memory-web/tests/suite/routes.rs
index a1c4eb57..cdfce22c 100644
--- a/crates/ai-memory-web/tests/suite/routes.rs
+++ b/crates/ai-memory-web/tests/suite/routes.rs
@@ -4209,4 +4209,29 @@ async fn web_page_view_created_is_the_first_versions_date() {
text.contains("Created just now"),
"a single-version page keeps its own date: {text}"
);
+
+ // The JSON API reads the same page-level date, so SPA clients agree.
+ let api = api_router(store.reader.clone(), wiki.clone());
+ let resp = api
+ .oneshot(
+ Request::builder()
+ .uri("/workspaces/default/projects/scratch/pages/notes/versions.md")
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(resp.status(), StatusCode::OK);
+ let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
+ let created = json["created_at"].as_str().unwrap();
+ let updated = json["updated_at"].as_str().unwrap();
+ assert_ne!(
+ created, updated,
+ "API created_at is the first version's: {json}"
+ );
+ let created_us = created.parse::<jiff::Timestamp>().unwrap().as_microsecond();
+ assert_eq!(created_us, aged, "{json}");
}