Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(okf): repair date-only stale_after on existing pages at startup (#917)
Felipe Neves Ricardo66b5a1a3214c
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1a0baf49..2bfc6b4a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -53,7 +53,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0(`2026-10-01T23:59:59.999999Z`) instead of the date copied verbatim. OKFv0.2 requires every timestamp to carry an explicit UTC offset, and read abare date as the start of that day, a day earlier than ai-memory's- end-of-day TTL. An RFC 3339 `expires_at` is still carried unchanged. (#917)+ end-of-day TTL. An RFC 3339 `expires_at` is still carried unchanged.+ Pages already written that way are repaired in place when `serve`+ starts: index row and file, with the same version row, `updated_at`,+ `generated.at` and body, in one wiki commit, and nothing to do on later+ starts. (#917)- The default log filter's `rmcp=warn` cap (#894) no longer raises rmcpabove a quieter `log_level`. A target directive beats the global leveleither way, so with `log_level = "error"` or `"off"` the cap re-enabled thediff --git a/crates/ai-memory-cli/src/commands/serve.rs b/crates/ai-memory-cli/src/commands/serve.rsindex be489d74..73755924 100644--- a/crates/ai-memory-cli/src/commands/serve.rs+++ b/crates/ai-memory-cli/src/commands/serve.rs@@ -1084,6 +1084,17 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {Ok(n) => tracing::info!(count = n, "wrote _meta.md scope manifests"),Err(e) => tracing::warn!(error = %e, "scope-manifest backfill failed (non-fatal)"),}+ // Pages conformed by an older build carry a date-only OKF `stale_after`+ // copied from `expires_at`; repair them in place. Idempotent; non-fatal.+ match wiki.repair_date_only_stale_after().await {+ Ok((0, 0)) => {}+ Ok((rows, files)) => tracing::info!(+ rows,+ files,+ "repaired date-only OKF stale_after on existing pages"+ ),+ Err(e) => tracing::warn!(error = %e, "OKF stale_after repair failed (non-fatal)"),+ }let baseline_checkpoint = wiki.ensure_upgrade_baseline_checkpoint();match classify_baseline_checkpoint(&baseline_checkpoint) {BaselineCheckpointLog::Created => {diff --git a/crates/ai-memory-core/src/okf.rs b/crates/ai-memory-core/src/okf.rsindex 42bef86e..2d551a55 100644--- a/crates/ai-memory-core/src/okf.rs+++ b/crates/ai-memory-core/src/okf.rs@@ -101,8 +101,7 @@ pub fn conform_frontmatter(path: &str, frontmatter: &mut Value) {// stale_after ← existing TTL. OKF timestamps must carry an explicit// UTC offset, but `expires_at` also accepts a bare `YYYY-MM-DD`// (end of that day, UTC): render that as the instant it names. An- // RFC 3339 value already conforms and is carried verbatim, so pages- // written before this rule keep byte-identical frontmatter.+ // RFC 3339 value already conforms and is carried verbatim.if !map.contains_key("stale_after")&& let Some(expires) = map.get("expires_at").and_then(Value::as_str)&& let Some(instant) = crate::page::parse_expires_at_instant(expires)@@ -114,6 +113,9 @@ pub fn conform_frontmatter(path: &str, frontmatter: &mut Value) {};map.insert("stale_after".into(), Value::String(stale_after));}+ // A page an older build conformed carries the bare date it copied;+ // any rewrite of it (a restore, a hand edit, a reindex) repairs it.+ repair_date_only_stale_after_in(map);// sources ← session provenance already stamped by the consolidator.if !map.contains_key("sources")@@ -150,6 +152,34 @@ pub fn conform_frontmatter(path: &str, frontmatter: &mut Value) {}}+/// Repair a `stale_after` that a build before this rule copied verbatim from+/// a date-only `expires_at`. The signature is exact: `stale_after` equals+/// `expires_at` and is not an RFC 3339 instant. It becomes the instant the+/// TTL expires the page, which is what [`conform_frontmatter`] derives today,+/// so a repaired page matches one written fresh. Returns whether it changed+/// anything; a `stale_after` that differs from `expires_at` is left alone.+pub fn repair_date_only_stale_after(frontmatter: &mut Value) -> bool {+ frontmatter+ .as_object_mut()+ .is_some_and(repair_date_only_stale_after_in)+}++fn repair_date_only_stale_after_in(map: &mut Map<String, Value>) -> bool {+ let (Some(Value::String(stale)), Some(Value::String(expires))) =+ (map.get("stale_after"), map.get("expires_at"))+ else {+ return false;+ };+ if stale != expires || stale.trim().parse::<jiff::Timestamp>().is_ok() {+ return false;+ }+ let Some(instant) = crate::page::parse_expires_at_instant(expires) else {+ return false;+ };+ map.insert("stale_after".into(), Value::String(instant.to_string()));+ true+}+/// Clone `frontmatter` with `generated.at` removed — the store compares/// idempotency on this projection so an unchanged page never supersedes/// itself over a timestamp.@@ -283,6 +313,35 @@ mod tests {assert!(fm.get("stale_after").is_none());}+ #[test]+ fn a_stale_after_copied_from_a_date_only_ttl_is_repaired() {+ let mut fm = json!({"expires_at": "2026-10-01", "stale_after": "2026-10-01"});+ assert!(repair_date_only_stale_after(&mut fm));+ assert_eq!(fm["stale_after"], "2026-10-01T23:59:59.999999Z");+ assert!(+ !repair_date_only_stale_after(&mut fm),+ "repair is idempotent"+ );++ // conform_frontmatter repairs it too, so any rewrite heals the page.+ let mut old = json!({"expires_at": "2026-10-01", "stale_after": "2026-10-01"});+ conform_frontmatter("notes/x.md", &mut old);+ assert_eq!(old["stale_after"], "2026-10-01T23:59:59.999999Z");+ }++ #[test]+ fn a_stale_after_that_is_not_the_verbatim_copy_is_left_alone() {+ for mut fm in [+ json!({"expires_at": "2026-10-01", "stale_after": "2026-09-01"}),+ json!({"expires_at": "2026-10-01T12:00:00Z", "stale_after": "2026-10-01T12:00:00Z"}),+ json!({"stale_after": "2026-10-01"}),+ ] {+ let before = fm.clone();+ assert!(!repair_date_only_stale_after(&mut fm));+ assert_eq!(fm, before);+ }+ }+#[test]fn an_explicit_type_is_never_overwritten() {let mut fm = json!({"type": "Custom Thing"});diff --git a/crates/ai-memory-store/src/lib.rs b/crates/ai-memory-store/src/lib.rsindex 58365e34..c99fa5f7 100644--- a/crates/ai-memory-store/src/lib.rs+++ b/crates/ai-memory-store/src/lib.rs@@ -54,13 +54,13 @@ pub use decay::{pub use error::{StoreError, StoreResult};pub use maintenance::MaintenanceJob;pub use ops::{- AdmittedSession, BootstrapChunkRecord, CompactSummary, Compaction, DeleteWorkspaceSummary,- EmbedOutcome, EmbeddingWrite, EntityBackfillSummary, HookSessionAdmission,- IngestObservationOutcome, LifecycleOnlyEndOutcome, MAX_PENDING_INBOX_MESSAGES,- MoveSessionSummary, MoveSummary, ObservationPruneOutcome, OkfMigratedPage,- PAGE_WINDOW_BACKFILL_BATCH, PageWindowBackfillSummary, PagesMode, PurgeSessionSummary,- PurgeSummary, ReorgSummary, backfill_entity_index, backfill_page_windows,- backfill_page_windows_in_batches, purge_session, record_embed_failure,+ AdmittedSession, BootstrapChunkRecord, CompactSummary, Compaction, DateOnlyTtlPage,+ DeleteWorkspaceSummary, EmbedOutcome, EmbeddingWrite, EntityBackfillSummary,+ HookSessionAdmission, IngestObservationOutcome, LifecycleOnlyEndOutcome,+ MAX_PENDING_INBOX_MESSAGES, MoveSessionSummary, MoveSummary, ObservationPruneOutcome,+ OkfMigratedPage, PAGE_WINDOW_BACKFILL_BATCH, PageWindowBackfillSummary, PagesMode,+ PurgeSessionSummary, PurgeSummary, ReorgSummary, StaleAfterRepair, backfill_entity_index,+ backfill_page_windows, backfill_page_windows_in_batches, purge_session, record_embed_failure,};pub use reader::{ActivityWindow, AgentSessionCount, AuditEvent, AuditLogFilter, AutoImproveCandidateSession,diff --git a/crates/ai-memory-store/src/ops.rs b/crates/ai-memory-store/src/ops.rsindex a8383662..3d86a715 100644--- a/crates/ai-memory-store/src/ops.rs+++ b/crates/ai-memory-store/src/ops.rs@@ -711,6 +711,92 @@ pub fn okf_migrate_latest_pages(conn: &mut Connection) -> StoreResult<Vec<OkfMigOk(migrated)}+/// A latest page whose `expires_at` is a bare `YYYY-MM-DD`, returned by+/// [`repair_date_only_stale_after`] so the wiki layer can check its file.+#[derive(Debug, Clone)]+pub struct DateOnlyTtlPage {+ /// Owning workspace.+ pub workspace_id: ai_memory_core::WorkspaceId,+ /// Owning project.+ pub project_id: ai_memory_core::ProjectId,+ /// Wiki-relative page path.+ pub path: String,+}++/// What a [`repair_date_only_stale_after`] pass did.+#[derive(Debug, Default, Clone)]+pub struct StaleAfterRepair {+ /// Latest rows whose `stale_after` was rewritten in place.+ pub rows_repaired: u64,+ /// Every latest page with a date-only `expires_at`, repaired or not.+ pub date_only_pages: Vec<DateOnlyTtlPage>,+}++/// Idempotent startup repair of the OKF `stale_after` that builds before+/// [`ai_memory_core::okf::repair_date_only_stale_after`] copied verbatim+/// from a date-only `expires_at`. Same in-place rules as+/// [`okf_migrate_latest_pages`]: same id, same version row, `updated_at`+/// and `generated.at` untouched, historical versions left as they were.+/// A repaired store rewrites nothing on the next run.+///+/// Every date-only page is returned, not only the rows rewritten here, so+/// the wiki's file pass still finds a file whose row an earlier, interrupted+/// run already repaired. The set is small: pages with a date-only TTL.+pub fn repair_date_only_stale_after(conn: &mut Connection) -> StoreResult<StaleAfterRepair> {+ type LatestPageRow = (Vec<u8>, Vec<u8>, Vec<u8>, String, String);+ let tx = conn.transaction()?;+ let mut repair = StaleAfterRepair::default();+ {+ // The LIKE only narrows the scan; the TTL is checked on the parsed+ // frontmatter below.+ let mut stmt = tx.prepare(+ "SELECT id, workspace_id, project_id, path, frontmatter_json FROM pages \+ WHERE is_latest = 1 AND frontmatter_json LIKE '%\"expires_at\"%'",+ )?;+ let rows: Vec<LatestPageRow> = stmt+ .query_map([], |row| {+ Ok((+ row.get(0)?,+ row.get(1)?,+ row.get(2)?,+ row.get(3)?,+ row.get(4)?,+ ))+ })?+ .collect::<Result<_, _>>()?;+ drop(stmt);+ for (id, ws, proj, path, fm_str) in rows {+ let Ok(mut fm) = serde_json::from_str::<serde_json::Value>(&fm_str) else {+ continue;+ };+ let date_only = fm+ .get("expires_at")+ .and_then(serde_json::Value::as_str)+ .is_some_and(|raw| {+ raw.trim().parse::<jiff::Timestamp>().is_err()+ && ai_memory_core::parse_expires_at_instant(raw).is_some()+ });+ if !date_only {+ continue;+ }+ if ai_memory_core::okf::repair_date_only_stale_after(&mut fm) {+ tx.execute(+ "UPDATE pages SET frontmatter_json = ?1 WHERE id = ?2",+ params![serde_json::to_string(&fm)?, id],+ )?;+ repair.rows_repaired += 1;+ }+ repair.date_only_pages.push(DateOnlyTtlPage {+ workspace_id: ai_memory_core::WorkspaceId::from_slice(&ws)?,+ project_id: ai_memory_core::ProjectId::from_slice(&proj)?,+ path,+ });+ }+ }+ tx.commit()?;+ Ok(repair)+}+/// Stamp the per-version `generated.at` (write time, UTC) onto conformed/// frontmatter and serialize it. Runs only on the paths that create a new/// version row — the idempotent short-circuit above never reaches it, sodiff --git a/crates/ai-memory-store/src/writer.rs b/crates/ai-memory-store/src/writer.rsindex 50f793e1..4082195c 100644--- a/crates/ai-memory-store/src/writer.rs+++ b/crates/ai-memory-store/src/writer.rs@@ -446,6 +446,10 @@ pub(crate) enum WriteCmd {OkfMigrateLatestPages {reply: oneshot::Sender<StoreResult<Vec<ops::OkfMigratedPage>>>,},+ /// Idempotent in-place repair of date-only OKF `stale_after` values.+ RepairDateOnlyStaleAfter {+ reply: oneshot::Sender<StoreResult<ops::StaleAfterRepair>>,+ },/// Read-only count of latest rows still lacking OKF conformance.OkfNonconformantCount {reply: oneshot::Sender<StoreResult<u64>>,@@ -1935,6 +1939,20 @@ impl WriterHandle {rx.await.map_err(|_| StoreError::WriterClosed)?}+ /// Repair, in place, the OKF `stale_after` that older builds copied+ /// verbatim from a date-only `expires_at`; returns every date-only page+ /// so the wiki layer can align the files.+ ///+ /// # Errors+ /// Returns [`StoreError::WriterClosed`] if the actor has shut down, or+ /// propagates the SQL error.+ pub async fn repair_date_only_stale_after(&self) -> StoreResult<ops::StaleAfterRepair> {+ let (tx, rx) = oneshot::channel();+ self.send(WriteCmd::RepairDateOnlyStaleAfter { reply: tx })+ .await?;+ rx.await.map_err(|_| StoreError::WriterClosed)?+ }+/// Count latest page rows still lacking OKF conformance (read-only).////// # Errors@@ -3318,6 +3336,10 @@ fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {let result = ops::okf_migrate_latest_pages(&mut conn);send_or_warn(reply, result, "okf_migrate_latest_pages");}+ WriteCmd::RepairDateOnlyStaleAfter { reply } => {+ let result = ops::repair_date_only_stale_after(&mut conn);+ send_or_warn(reply, result, "repair_date_only_stale_after");+ }WriteCmd::OkfNonconformantCount { reply } => {let result = ops::okf_nonconformant_latest_pages(&conn);send_or_warn(reply, result, "okf_nonconformant_count");diff --git a/crates/ai-memory-wiki/src/wiki.rs b/crates/ai-memory-wiki/src/wiki.rsindex 1fedcd16..ee2a3e01 100644--- a/crates/ai-memory-wiki/src/wiki.rs+++ b/crates/ai-memory-wiki/src/wiki.rs@@ -1818,6 +1818,43 @@ impl Wiki {Ok(written)}+ /// Repair the OKF `stale_after` that builds before this one copied+ /// verbatim from a date-only `expires_at` (docs/okf.md): the index rows+ /// in place through the writer, then each page's file, body and+ /// `generated.at` untouched, in one git commit. Idempotent and cheap on+ /// a repaired store (only pages with a date-only TTL are read); safe to+ /// run on every startup. Returns `(rows, files)` repaired.+ ///+ /// # Errors+ /// Returns [`WikiError`] for store, filesystem or git errors.+ pub async fn repair_date_only_stale_after(&self) -> WikiResult<(u64, usize)> {+ let _guard = self.mutation_lock.write().await;+ let repair = self.writer.repair_date_only_stale_after().await?;+ let mut files = 0;+ for page in &repair.date_only_pages {+ let abs = self+ .project_root(page.workspace_id, page.project_id)+ .join(&page.path);+ let raw = match std::fs::read_to_string(&abs) {+ Ok(raw) => raw,+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,+ Err(e) => return Err(e.into()),+ };+ let Ok(mut markdown) = parse(&raw) else {+ continue;+ };+ if ai_memory_core::okf::repair_date_only_stale_after(&mut markdown.frontmatter) {+ self.git.write_atomic(&abs, emit(&markdown)?.as_bytes())?;+ files += 1;+ }+ }+ if files > 0 {+ self.git+ .commit_all("okf: repair date-only stale_after on existing pages")?;+ }+ Ok((repair.rows_repaired, files))+ }+/// Atomically apply a batch of page writes. Either all pages land/// (one SQL transaction) and their files are renamed into place./// Files are installed before the SQL batch so markdown remains the source@@ -2917,6 +2954,152 @@ mod tests {);}+ /// Put `notes/<name>.md` back in the state a pre-fix build left it:+ /// `stale_after` copied verbatim from the date-only `expires_at`, in both+ /// the index row and the file. Returns the row's `(id, updated_at)`.+ fn regress_to_date_only_stale_after(+ tmp: &TempDir,+ wiki: &Wiki,+ ws: WorkspaceId,+ proj: ProjectId,+ rel: &str,+ row: bool,+ file: bool,+ ) -> (Vec<u8>, i64) {+ let db = rusqlite::Connection::open(tmp.path().join("db").join("memory.sqlite")).unwrap();+ let (id, updated_at, fm_str): (Vec<u8>, i64, String) = db+ .query_row(+ "SELECT id, updated_at, frontmatter_json FROM pages \+ WHERE path = ?1 AND is_latest = 1",+ [rel],+ |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),+ )+ .unwrap();+ let regress = |fm: &mut serde_json::Value| {+ let expires = fm["expires_at"].clone();+ fm["stale_after"] = expires;+ };+ if row {+ let mut fm: serde_json::Value = serde_json::from_str(&fm_str).unwrap();+ regress(&mut fm);+ db.execute(+ "UPDATE pages SET frontmatter_json = ?1 WHERE id = ?2",+ rusqlite::params![serde_json::to_string(&fm).unwrap(), id],+ )+ .unwrap();+ }+ if file {+ let abs = wiki.project_root(ws, proj).join(rel);+ let mut md = crate::markdown::parse(&std::fs::read_to_string(&abs).unwrap()).unwrap();+ regress(&mut md.frontmatter);+ std::fs::write(&abs, crate::markdown::emit(&md).unwrap()).unwrap();+ }+ (id, updated_at)+ }++ fn latest_row(tmp: &TempDir, rel: &str) -> (Vec<u8>, i64, serde_json::Value) {+ let db = rusqlite::Connection::open(tmp.path().join("db").join("memory.sqlite")).unwrap();+ let (id, updated_at, fm_str): (Vec<u8>, i64, String) = db+ .query_row(+ "SELECT id, updated_at, frontmatter_json FROM pages \+ WHERE path = ?1 AND is_latest = 1",+ [rel],+ |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),+ )+ .unwrap();+ (id, updated_at, serde_json::from_str(&fm_str).unwrap())+ }++ /// Stores written before the `stale_after` fix hold the bare date the old+ /// derivation copied. The startup repair rewrites row and file in place+ /// (same version row, same `updated_at`, same `generated.at`, same body),+ /// leaves a `stale_after` that is not that copy alone, finishes a file+ /// whose row an interrupted run already repaired, and then does nothing.+ #[tokio::test]+ async fn startup_repair_fixes_a_date_only_stale_after_in_place() {+ let tmp = TempDir::new().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let ws = store.writer.get_or_create_workspace("w").await.unwrap();+ let proj = store+ .writer+ .get_or_create_project(ws, "p", None)+ .await+ .unwrap();+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();+ for (rel, fm) in [+ (+ "notes/freeze.md",+ serde_json::json!({"title": "Freeze", "expires_at": "2099-08-01"}),+ ),+ (+ "notes/interrupted.md",+ serde_json::json!({"title": "Interrupted", "expires_at": "2099-09-01"}),+ ),+ (+ "notes/authored.md",+ serde_json::json!({+ "title": "Authored",+ "expires_at": "2099-10-01",+ "stale_after": "2099-07-01",+ }),+ ),+ ] {+ wiki.write_page(req(ws, proj, rel, "body stays", fm))+ .await+ .unwrap();+ }+ let (freeze_id, freeze_updated) =+ regress_to_date_only_stale_after(&tmp, &wiki, ws, proj, "notes/freeze.md", true, true);+ regress_to_date_only_stale_after(+ &tmp,+ &wiki,+ ws,+ proj,+ "notes/interrupted.md",+ false,+ true,+ );+ let freeze_path = wiki.project_root(ws, proj).join("notes/freeze.md");+ let before =+ crate::markdown::parse(&std::fs::read_to_string(&freeze_path).unwrap()).unwrap();+ assert_eq!(before.frontmatter["stale_after"], "2099-08-01");+ let commits = wiki.git.commit_count();++ assert_eq!(wiki.repair_date_only_stale_after().await.unwrap(), (1, 2));++ let after =+ crate::markdown::parse(&std::fs::read_to_string(&freeze_path).unwrap()).unwrap();+ assert_eq!(+ after.frontmatter["stale_after"],+ "2099-08-01T23:59:59.999999Z"+ );+ assert_eq!(+ after.frontmatter["generated"],+ before.frontmatter["generated"]+ );+ assert_eq!(after.body, before.body);+ let (id, updated_at, row_fm) = latest_row(&tmp, "notes/freeze.md");+ assert_eq!(id, freeze_id, "the repair must not mint a new version");+ assert_eq!(updated_at, freeze_updated);+ assert_eq!(row_fm["stale_after"], "2099-08-01T23:59:59.999999Z");++ let interrupted = crate::markdown::parse(+ &std::fs::read_to_string(wiki.project_root(ws, proj).join("notes/interrupted.md"))+ .unwrap(),+ )+ .unwrap();+ assert_eq!(+ interrupted.frontmatter["stale_after"],+ "2099-09-01T23:59:59.999999Z"+ );+ let (_, _, authored) = latest_row(&tmp, "notes/authored.md");+ assert_eq!(authored["stale_after"], "2099-07-01");+ assert_eq!(wiki.git.commit_count(), commits + 1);++ assert_eq!(wiki.repair_date_only_stale_after().await.unwrap(), (0, 0));+ assert_eq!(wiki.git.commit_count(), commits + 1);+ }+/// Refused on every platform, not only the case-insensitive ones: the/// wiki is synced between them, so what it accepts cannot depend on the/// filesystem underneath.diff --git a/docs/okf.md b/docs/okf.mdindex 8344e74f..33e7f925 100644--- a/docs/okf.md+++ b/docs/okf.md@@ -123,6 +123,26 @@ Order is fixed; each step gates the next:Rollback: restore the archive (blunt, no git knowledge needed), or thepre-migration git checkpoint + `reindex` (surgical).+### Repairs to already-migrated stores++A conformance bug found after a store migrated is repaired by an+idempotent startup pass, not by a new `WikiMigration`: a registered+migration name makes every older binary refuse the wiki+(`NewerWikiFormat`), a format-generation step a patch fix should not+force. The pass follows the+migration's no-churn rules (row in place, same version, `updated_at` and+`generated.at` untouched, body untouched, one git commit) and is a no-op+once the store is clean. `conform_frontmatter` applies the same repair,+so any later rewrite of an affected page (a restore, a hand edit, a+`reindex`) heals it too.++- **Date-only `stale_after`.** Builds before the fix copied a bare+ `expires_at` date into `stale_after` verbatim. `serve` rewrites a+ `stale_after` that equals its date-only `expires_at` to the instant the+ TTL names (`2026-10-01` → `2026-10-01T23:59:59.999999Z`); a+ `stale_after` that differs from `expires_at` was not derived by+ ai-memory and is left alone.+## Tests (each with a control that must fail on a broken build)- Round-trip: page → OKF file on disk → parsed back identical.