Skip to content

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

Rust

feat(cli): repair-backfill-timestamps restores original start/end of backfilled sessions

Maxsuel Einstein25fabe4a1340
diff --git a/CHANGELOG.md b/CHANGELOG.md
index adae0176..ca269f5b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Added
+- `ai-memory repair-backfill-timestamps [--project] [--workspace] [--confirm]
+ [--json]` and `POST /admin/repair-session-times` correct
+ `sessions.started_at`/`ended_at` for sessions an older `backfill` imported
+ before it carried the transcript's own event time, which flattened every
+ imported session onto the import day. Only rewrites a row whose
+ `started_at` actually postdates the candidate's own transcript end (a
+ correctly hook-captured session, or a re-run, is a no-op); refuses
+ out-of-scope, unchanged, negative, inverted, or future-dated candidates;
+ never closes a still-open session; and records an `audit_log` row on
+ apply. Dry-run by default. (#921)
+
## [2.4.1] - 2026-09-25
### Changed
diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rs
index 22f3ac38..fe71e85d 100644
--- a/crates/ai-memory-cli/src/cli.rs
+++ b/crates/ai-memory-cli/src/cli.rs
@@ -42,6 +42,11 @@ pub enum Command {
/// mid-project doesn't start amnesiac. No-op once the store has any
/// sessions unless `--force`.
Backfill(BackfillArgs),
+ /// Correct `sessions.started_at`/`ended_at` for sessions that `backfill`
+ /// already imported before it carried the transcript's own event times,
+ /// by re-reading the local transcripts and matching them by session id.
+ /// Dry-run by default; `--confirm` applies.
+ RepairBackfillTimestamps(RepairBackfillTimestampsArgs),
/// Launch an agent in an opt-in, cross-harness managed workstream.
/// Native arguments are forwarded except exact wrapper flags such as
/// `--yolo` and `--fresh`.
@@ -1416,6 +1421,33 @@ pub struct BackfillArgs {
pub auto: bool,
}
+/// Arguments for `repair-backfill-timestamps`.
+///
+/// A thin client like every other lifecycle command: it reads the local
+/// transcripts (read-only, reusing `backfill`'s own discovery) to compute
+/// candidate `started_at`/`ended_at` values, then posts them to
+/// `POST /admin/repair-session-times`, which validates each one against the
+/// scope and the backfill bug's own signature, and applies (or, without
+/// `--confirm`, only reports) the change.
+#[derive(Debug, Args)]
+pub struct RepairBackfillTimestampsArgs {
+ /// Workspace name. Defaults to the current project's resolved scope.
+ #[arg(long)]
+ pub workspace: Option<String>,
+ /// Project name. Defaults to the current project's resolved scope.
+ #[arg(long)]
+ pub project: Option<String>,
+ /// Apply the computed times. Without this flag the command only reports
+ /// what would change (sessions repaired/skipped, by reason, plus the
+ /// before/after date range) — the server runs the write inside a
+ /// rolled-back transaction, so this is a real dry run, not an estimate.
+ #[arg(long)]
+ pub confirm: bool,
+ /// Emit the server's report(s) as JSON instead of the human summary.
+ #[arg(long)]
+ pub json: bool,
+}
+
/// Arguments for `doctor`.
#[derive(Debug, Args)]
pub struct DoctorArgs {
diff --git a/crates/ai-memory-cli/src/commands/backfill.rs b/crates/ai-memory-cli/src/commands/backfill.rs
index 2565f2ef..9b149722 100644
--- a/crates/ai-memory-cli/src/commands/backfill.rs
+++ b/crates/ai-memory-cli/src/commands/backfill.rs
@@ -68,9 +68,9 @@ const BACKFILL_EXTENSION: &str = "ai-memory-backfill";
/// A local native session eligible for import.
#[derive(Debug, Clone)]
pub(crate) struct SessionRef {
- harness: ManagedHarness,
- native_session_id: String,
- updated_at: SystemTime,
+ pub(crate) harness: ManagedHarness,
+ pub(crate) native_session_id: String,
+ pub(crate) updated_at: SystemTime,
}
/// The outcome of a backfill run, and the JSON output shape.
@@ -192,7 +192,8 @@ pub async fn run(config: &Config, args: crate::cli::BackfillArgs) -> Result<()>
}
// Enumerate local sessions for this cwd across every supported harness.
- let candidates = collect_local_sessions(&home, &cwd, args.session.as_deref()).await;
+ let (candidates, _limit_hit) =
+ collect_local_sessions(&home, &cwd, args.session.as_deref()).await;
let selected = select_sessions(candidates, args.max_sessions.max(1));
report.selected = selected.len();
@@ -263,11 +264,16 @@ async fn project_is_empty(
/// Enumerate local native sessions for `cwd` across every scanned harness.
/// Read-only; a harness whose store is absent/unreadable contributes nothing.
-async fn collect_local_sessions(
+///
+/// Returns, alongside the sessions, the harnesses whose scan came back at
+/// exactly [`PER_HARNESS_SCAN_LIMIT`] — a caller that cares about missing
+/// older sessions (as opposed to `backfill`'s own newest-first + cap
+/// selection, which does not) can surface that.
+pub(crate) async fn collect_local_sessions(
home: &Path,
cwd: &Path,
only_session: Option<&str>,
-) -> Vec<SessionRef> {
+) -> (Vec<SessionRef>, Vec<ManagedHarness>) {
collect_local_sessions_with(home, cwd, only_session, relocated_session_dir).await
}
@@ -275,13 +281,14 @@ async fn collect_local_sessions(
/// same reason as `doctor::scan_local_with`: tests pass `|_| None` so a
/// developer's `CLAUDE_CONFIG_DIR` cannot hide a fixture planted under a
/// temporary `$HOME`.
-async fn collect_local_sessions_with(
+pub(crate) async fn collect_local_sessions_with(
home: &Path,
cwd: &Path,
only_session: Option<&str>,
session_dir_for: impl Fn(ManagedHarness) -> Option<PathBuf>,
-) -> Vec<SessionRef> {
+) -> (Vec<SessionRef>, Vec<ManagedHarness>) {
let mut out = Vec::new();
+ let mut limit_hit = Vec::new();
for &harness in SCANNED_HARNESSES {
let session_dir = session_dir_for(harness);
let Ok(sessions) = list_native_sessions(
@@ -295,6 +302,9 @@ async fn collect_local_sessions_with(
else {
continue;
};
+ if sessions.len() >= PER_HARNESS_SCAN_LIMIT {
+ limit_hit.push(harness);
+ }
for session in sessions {
if only_session.is_some_and(|want| want != session.native_session_id) {
continue;
@@ -306,7 +316,7 @@ async fn collect_local_sessions_with(
});
}
}
- out
+ (out, limit_hit)
}
/// One item in a `POST /hook/batch` request: the full hook URL (whose query the
@@ -968,7 +978,8 @@ mod tests {
});
std::fs::write(session_dir.join("foreign.jsonl"), format!("{foreign}\n")).unwrap();
- let found = collect_local_sessions_with(home.path(), cwd.path(), None, |_| None).await;
+ let (found, _limit_hit) =
+ collect_local_sessions_with(home.path(), cwd.path(), None, |_| None).await;
let claude: Vec<_> = found
.iter()
.filter(|s| s.harness == ManagedHarness::Claude)
@@ -980,7 +991,7 @@ mod tests {
);
// `--session` narrows to one id.
- let only =
+ let (only, _limit_hit) =
collect_local_sessions_with(home.path(), cwd.path(), Some("nope"), |_| None).await;
assert!(only.is_empty(), "no session matches the filter: {only:?}");
}
diff --git a/crates/ai-memory-cli/src/commands/mod.rs b/crates/ai-memory-cli/src/commands/mod.rs
index 2ee7c88a..ce7826cf 100644
--- a/crates/ai-memory-cli/src/commands/mod.rs
+++ b/crates/ai-memory-cli/src/commands/mod.rs
@@ -68,6 +68,7 @@ pub mod rename_project;
pub mod rename_workstream;
pub mod render_shared;
pub mod reorg;
+pub mod repair_backfill_timestamps;
pub mod reset;
pub mod restore;
pub mod restore_page;
diff --git a/crates/ai-memory-cli/src/commands/repair_backfill_timestamps.rs b/crates/ai-memory-cli/src/commands/repair_backfill_timestamps.rs
new file mode 100644
index 00000000..8ba28a4f
--- /dev/null
+++ b/crates/ai-memory-cli/src/commands/repair_backfill_timestamps.rs
@@ -0,0 +1,393 @@
+//! `ai-memory repair-backfill-timestamps` — thin HTTP client that corrects
+//! `sessions.started_at`/`ended_at` for sessions an older `backfill` already
+//! imported before it carried the transcript's own event time, flattening
+//! every imported session onto the import day.
+//!
+//! Like every other lifecycle command, this is a thin client: the server
+//! (`POST /admin/repair-session-times`) owns validation (including the guard
+//! that only a genuinely flattened session is ever rewritten) and the write,
+//! one transaction per request through the single `WriterHandle`. This
+//! command's only job is the part that must run on the operator's machine —
+//! reading the local harness transcripts, which the server never has access
+//! to — and it reuses `backfill`'s own discovery (`collect_local_sessions`)
+//! and the `ai-memory-workstream` transcript reader (`export_transcript`)
+//! rather than re-parsing transcript formats.
+//!
+//! Dry-run by default: the server validates and reports without writing.
+//! `--confirm` applies. See `docs/lifecycle-ops.md` for the full validation
+//! list.
+
+use std::collections::BTreeMap;
+use std::path::Path;
+
+use anyhow::{Context, Result};
+use serde::{Deserialize, Serialize};
+
+use ai_memory_core::SessionId;
+use ai_memory_workstream::{ManagedHarness, build_launch_plan, export_transcript};
+
+use super::backfill::{SessionRef, collect_local_sessions};
+use super::run;
+use crate::cli::RepairBackfillTimestampsArgs;
+use crate::config::Config;
+use crate::http_client::{ServerEndpoint, post_json};
+
+/// One request never carries more candidates than the server's
+/// `MAX_REPAIR_SESSIONS` (`ai-memory-mcp/src/admin.rs`) accepts; a larger
+/// local batch is split into several requests, each its own transaction.
+const MAX_SESSIONS_PER_REQUEST: usize = 2_000;
+
+/// One candidate posted to `POST /admin/repair-session-times`.
+#[derive(Debug, Clone, Serialize)]
+struct SessionTimesItem {
+ session_id: String,
+ started_at_us: i64,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ ended_at_us: Option<i64>,
+}
+
+#[derive(Debug, Serialize)]
+struct RepairSessionTimesRequest {
+ workspace: String,
+ project: String,
+ sessions: Vec<SessionTimesItem>,
+ confirm: bool,
+}
+
+/// The server's response, kept in full (not just a summarized subset) so
+/// `--json` can pass it straight through and the human report can print
+/// concrete old/new values.
+#[derive(Debug, Deserialize, Serialize)]
+struct RepairSessionTimesResponse {
+ dry_run: bool,
+ repaired: Vec<RepairedItem>,
+ skipped: Vec<SkippedItem>,
+}
+
+#[derive(Debug, Deserialize, Serialize)]
+struct RepairedItem {
+ session_id: String,
+ old_started_at_us: i64,
+ #[serde(default)]
+ old_ended_at_us: Option<i64>,
+ new_started_at_us: i64,
+ #[serde(default)]
+ new_ended_at_us: Option<i64>,
+ #[serde(default)]
+ end_kept_open: bool,
+}
+
+#[derive(Debug, Deserialize, Serialize)]
+struct SkippedItem {
+ session_id: String,
+ reason: String,
+}
+
+/// First/last event timestamp of one local session's transcript, in Unix
+/// microseconds. `None` when the transcript could not be read or carried no
+/// parseable `occurred_at` on any event.
+async fn session_time_span(
+ home: &Path,
+ cwd: &Path,
+ session_dir: Option<&Path>,
+ session: &SessionRef,
+) -> Option<(i64, i64)> {
+ let transcript = export_transcript(
+ session.harness,
+ home,
+ cwd,
+ session_dir,
+ &session.native_session_id,
+ None,
+ )
+ .await
+ .ok()?;
+ let mut first_us: Option<i64> = None;
+ let mut last_us: Option<i64> = None;
+ for event in &transcript.events {
+ let Some(us) = event
+ .occurred_at
+ .as_deref()
+ .and_then(|s| s.parse::<jiff::Timestamp>().ok())
+ .map(jiff::Timestamp::as_microsecond)
+ else {
+ continue;
+ };
+ first_us = Some(first_us.map_or(us, |f: i64| f.min(us)));
+ last_us = Some(last_us.map_or(us, |l: i64| l.max(us)));
+ }
+ Some((first_us?, last_us?))
+}
+
+fn format_us(us: i64) -> String {
+ jiff::Timestamp::from_microsecond(us)
+ .map(|t| t.to_string())
+ .unwrap_or_else(|_| us.to_string())
+}
+
+/// Build one candidate per local session with a readable transcript
+/// timestamp. `session_dir` is resolved once per harness (`build_launch_plan`
+/// only depends on the harness, not the session), not once per session.
+async fn build_candidates(
+ home: &Path,
+ cwd: &Path,
+ sessions: &[SessionRef],
+) -> (Vec<SessionTimesItem>, usize) {
+ // A small, fixed set of harnesses: a linear scan avoids requiring `Hash`
+ // on `ManagedHarness` for a handful of entries.
+ let mut session_dirs: Vec<(ManagedHarness, Option<std::path::PathBuf>)> = Vec::new();
+ let mut items = Vec::with_capacity(sessions.len());
+ let mut uncaptured = 0usize;
+ for session in sessions {
+ let session_dir = match session_dirs.iter().find(|(h, _)| *h == session.harness) {
+ Some((_, dir)) => dir.clone(),
+ None => {
+ let dir = build_launch_plan(session.harness, None, Vec::new(), None)
+ .ok()
+ .and_then(|plan| plan.session_dir);
+ session_dirs.push((session.harness, dir.clone()));
+ dir
+ }
+ };
+ let Some((first_us, last_us)) =
+ session_time_span(home, cwd, session_dir.as_deref(), session).await
+ else {
+ uncaptured += 1;
+ continue;
+ };
+ let session_id = SessionId::from_native(&session.native_session_id);
+ items.push(SessionTimesItem {
+ session_id: session_id.to_string(),
+ started_at_us: first_us,
+ ended_at_us: Some(last_us),
+ });
+ }
+ (items, uncaptured)
+}
+
+/// Run the `repair-backfill-timestamps` subcommand.
+///
+/// # Errors
+/// Returns an error when the scope cannot be resolved, the local harness
+/// session stores cannot be located, or the server is unreachable or answers
+/// non-2xx.
+pub async fn run(config: &Config, args: RepairBackfillTimestampsArgs) -> Result<()> {
+ let (workspace, project) =
+ super::resolve_scope(config, args.workspace.as_deref(), args.project.as_deref())?;
+ let cwd = std::env::current_dir().context("resolving the current working directory")?;
+ let home = run::native_home(config).context("locating the local harness session stores")?;
+
+ // Same discovery `backfill` uses to select what it would import: every
+ // local native session (across every scanned harness) whose recorded cwd
+ // matches this checkout. Sharing it means this command looks at exactly
+ // the sessions `backfill` itself would have found.
+ let (sessions, limit_hit) = collect_local_sessions(&home, &cwd, None).await;
+ let (items, uncaptured) = build_candidates(&home, &cwd, &sessions).await;
+
+ if items.is_empty() {
+ println!(
+ "ai-memory: repair-backfill-timestamps for {workspace}/{project}: no local \
+ transcript carried a readable timestamp ({uncaptured} session(s) scanned locally, \
+ none captured); nothing to send."
+ );
+ print_scan_limit_note(&limit_hit);
+ return Ok(());
+ }
+
+ let endpoint = ServerEndpoint::from_config_resolving_auth(config).await;
+ let mut responses = Vec::new();
+ for chunk in items.chunks(MAX_SESSIONS_PER_REQUEST) {
+ let response: RepairSessionTimesResponse = post_json(
+ &endpoint,
+ "/admin/repair-session-times",
+ &RepairSessionTimesRequest {
+ workspace: workspace.clone(),
+ project: project.clone(),
+ sessions: chunk.to_vec(),
+ confirm: args.confirm,
+ },
+ )
+ .await?;
+ responses.push(response);
+ }
+
+ if args.json {
+ println!("{}", serde_json::to_string_pretty(&responses)?);
+ return Ok(());
+ }
+
+ let dry_run = responses.first().is_none_or(|r| r.dry_run);
+ let total_repaired: usize = responses.iter().map(|r| r.repaired.len()).sum();
+ let total_skipped: usize = responses.iter().map(|r| r.skipped.len()).sum();
+ let mut skipped_by_reason: BTreeMap<&str, usize> = BTreeMap::new();
+ for response in &responses {
+ for skip in &response.skipped {
+ *skipped_by_reason.entry(skip.reason.as_str()).or_default() += 1;
+ }
+ }
+
+ println!(
+ "ai-memory: repair-backfill-timestamps for {workspace}/{project}: {total_repaired} \
+ session(s) {}, {total_skipped} skipped, {uncaptured} local transcript(s) had no \
+ readable timestamp.",
+ if dry_run {
+ "would be repaired"
+ } else {
+ "repaired"
+ },
+ );
+ if responses.len() > 1 {
+ println!(
+ " sent {} session(s) across {} request(s) of up to {MAX_SESSIONS_PER_REQUEST} each \
+ (one transaction per request).",
+ items.len(),
+ responses.len(),
+ );
+ }
+ for (reason, count) in &skipped_by_reason {
+ println!(" skipped ({reason}): {count}");
+ }
+ print_scan_limit_note(&limit_hit);
+
+ for response in &responses {
+ for repaired in &response.repaired {
+ println!(
+ " {}: {} .. {} -> {} .. {}{}",
+ repaired.session_id,
+ format_us(repaired.old_started_at_us),
+ repaired
+ .old_ended_at_us
+ .map_or_else(|| "open".to_string(), format_us),
+ format_us(repaired.new_started_at_us),
+ repaired
+ .new_ended_at_us
+ .map_or_else(|| "open".to_string(), format_us),
+ if repaired.end_kept_open {
+ " (end left open)"
+ } else {
+ ""
+ },
+ );
+ }
+ }
+ if dry_run && total_repaired > 0 {
+ println!(
+ " dry run: nothing was written. Re-run with --confirm to apply (recorded in \
+ audit_log on apply, which is the reversibility backing)."
+ );
+ }
+ Ok(())
+}
+
+/// A harness whose local scan came back at the cap means older sessions may
+/// exist that were not even considered — surface that instead of silently
+/// under-reporting.
+fn print_scan_limit_note(limit_hit: &[ManagedHarness]) {
+ for harness in limit_hit {
+ println!(
+ " note: {} returned the maximum scanned sessions for this checkout; older \
+ sessions may exist and were not considered.",
+ harness.as_str()
+ );
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// `--json` aside, the human report reads real server-supplied old/new
+ /// values, not values this command invented — this is a compile-time
+ /// shape check on the (de)serialization, not an HTTP test (the HTTP path
+ /// is covered by `admin_repair_session_times.rs` on the server side).
+ #[test]
+ fn repair_session_times_response_round_trips_through_json() {
+ let response = RepairSessionTimesResponse {
+ dry_run: true,
+ repaired: vec![RepairedItem {
+ session_id: "11111111-2222-3333-4444-555555555555".into(),
+ old_started_at_us: 2,
+ old_ended_at_us: Some(3),
+ new_started_at_us: 0,
+ new_ended_at_us: Some(1),
+ end_kept_open: false,
+ }],
+ skipped: vec![SkippedItem {
+ session_id: "22222222-3333-4444-5555-666666666666".into(),
+ reason: "not_flattened".into(),
+ }],
+ };
+ let json = serde_json::to_string(&response).unwrap();
+ let back: RepairSessionTimesResponse = serde_json::from_str(&json).unwrap();
+ assert_eq!(back.repaired[0].new_started_at_us, 0);
+ assert_eq!(back.skipped[0].reason, "not_flattened");
+ }
+
+ /// End-to-end proof that this command's own candidate-building reads a
+ /// planted transcript's real event timestamps (not the file's mtime or
+ /// any other stand-in), mirroring
+ /// `backfill::tests::collect_local_sessions_finds_a_planted_claude_session_for_this_cwd`.
+ /// Unix-gated for the same reason that test is: the fixture uses a
+ /// POSIX-encoded `~/.claude/projects/<enc-cwd>/` layout.
+ #[cfg(unix)]
+ #[tokio::test]
+ async fn build_candidates_reads_the_planted_transcripts_own_timestamps() {
+ let home = tempfile::tempdir().unwrap();
+ let cwd = tempfile::tempdir().unwrap();
+ let session_dir = home
+ .path()
+ .join(".claude")
+ .join("projects")
+ .join(cwd.path().to_string_lossy().replace('/', "-"));
+ std::fs::create_dir_all(&session_dir).unwrap();
+ let native_id = "11111111-2222-3333-4444-555555555555";
+ let header =
+ serde_json::json!({"sessionId": native_id, "cwd": cwd.path().to_string_lossy()});
+ let first = serde_json::json!({
+ "type": "user",
+ "message": {"role": "user", "content": "hello"},
+ "timestamp": "2020-01-01T00:00:00Z",
+ });
+ let last = serde_json::json!({
+ "type": "assistant",
+ "message": {"role": "assistant", "content": "hi back"},
+ "timestamp": "2020-01-01T00:05:00Z",
+ });
+ std::fs::write(
+ session_dir.join("sess.jsonl"),
+ format!("{header}\n{first}\n{last}\n"),
+ )
+ .unwrap();
+
+ let (sessions, limit_hit) = crate::commands::backfill::collect_local_sessions_with(
+ home.path(),
+ cwd.path(),
+ None,
+ |_| None,
+ )
+ .await;
+ assert!(limit_hit.is_empty(), "{limit_hit:?}");
+ let (items, uncaptured) = build_candidates(home.path(), cwd.path(), &sessions).await;
+ assert_eq!(uncaptured, 0, "{items:?}");
+ let claude_item = items
+ .iter()
+ .find(|item| item.session_id == native_id)
+ .unwrap_or_else(|| panic!("no candidate for {native_id} in {items:?}"));
+ assert_eq!(
+ claude_item.started_at_us,
+ "2020-01-01T00:00:00Z"
+ .parse::<jiff::Timestamp>()
+ .unwrap()
+ .as_microsecond()
+ );
+ assert_eq!(
+ claude_item.ended_at_us,
+ Some(
+ "2020-01-01T00:05:00Z"
+ .parse::<jiff::Timestamp>()
+ .unwrap()
+ .as_microsecond()
+ )
+ );
+ }
+}
diff --git a/crates/ai-memory-cli/src/lib.rs b/crates/ai-memory-cli/src/lib.rs
index ab2ece38..2b5523ff 100644
--- a/crates/ai-memory-cli/src/lib.rs
+++ b/crates/ai-memory-cli/src/lib.rs
@@ -86,6 +86,9 @@ pub async fn run() -> Result<()> {
Command::Status(args) => commands::status::run(&config, args).await,
Command::Doctor(args) => commands::doctor::run(&config, args).await,
Command::Backfill(args) => commands::backfill::run(&config, args).await,
+ Command::RepairBackfillTimestamps(args) => {
+ commands::repair_backfill_timestamps::run(&config, args).await
+ }
Command::Run(args) => {
let exit_code = commands::run::run(&config, args).await?;
if exit_code != 0 {
diff --git a/crates/ai-memory-core/src/ids.rs b/crates/ai-memory-core/src/ids.rs
index d779627f..5fa744fe 100644
--- a/crates/ai-memory-core/src/ids.rs
+++ b/crates/ai-memory-core/src/ids.rs
@@ -93,6 +93,20 @@ id_newtype!(pub AutoImproveRunId, "Identifier for one auto-improvement review ru
id_newtype!(pub AutoImproveProposalId, "Identifier for one staged auto-improvement proposal.");
id_newtype!(pub PageFeedbackId, "Identifier for one page-feedback signal (`memory_feedback`).");
+impl SessionId {
+ /// Resolve a harness-native session id to the `SessionId` the store keys
+ /// on: a UUID native id is used as-is (canonicalized); any other string
+ /// (Codex, OpenCode, ...) is hashed to a deterministic UUID v5. The hook
+ /// router and any offline tool that matches transcripts by native id
+ /// (e.g. `ai-memory repair-backfill-timestamps`) must agree on this one
+ /// rule to end up with the same key.
+ #[must_use]
+ pub fn from_native(raw: &str) -> Self {
+ raw.parse::<Self>()
+ .unwrap_or_else(|_| Self(Uuid::new_v5(&Uuid::NAMESPACE_OID, raw.as_bytes())))
+ }
+}
+
/// Relative path of a page within the wiki tree.
///
/// Always uses `/` as the separator (POSIX-style), normalised on construction.
@@ -445,6 +459,28 @@ mod tests {
assert!(PagePath::new("a/../b").is_err());
}
+ /// A UUID native id round-trips as-is; a non-UUID native id (Codex,
+ /// OpenCode) hashes to a deterministic UUID v5, so hook capture and any
+ /// offline tool matching transcripts by native id agree on one key.
+ #[test]
+ fn session_id_from_native_hashes_non_uuid_ids_and_passes_uuids_through() {
+ let uuid_native = "11111111-2222-3333-4444-555555555555";
+ assert_eq!(SessionId::from_native(uuid_native).to_string(), uuid_native);
+
+ let non_uuid_native = "codex-native-id-123";
+ let expected = SessionId(Uuid::new_v5(
+ &Uuid::NAMESPACE_OID,
+ non_uuid_native.as_bytes(),
+ ));
+ assert_eq!(SessionId::from_native(non_uuid_native), expected);
+ // Deterministic: repeated calls (and hence repeated hook deliveries,
+ // or a repeated repair run) must resolve to the same id.
+ assert_eq!(
+ SessionId::from_native(non_uuid_native),
+ SessionId::from_native(non_uuid_native)
+ );
+ }
+
#[test]
fn agent_kind_grok_round_trips() {
assert_eq!(AgentKind::Grok.as_str(), "grok");
diff --git a/crates/ai-memory-hooks/src/router.rs b/crates/ai-memory-hooks/src/router.rs
index f8474527..5977f2ab 100644
--- a/crates/ai-memory-hooks/src/router.rs
+++ b/crates/ai-memory-hooks/src/router.rs
@@ -30,7 +30,6 @@ use axum::routing::{get, post};
use jiff::Timestamp;
use serde::{Deserialize, Serialize};
use tracing::{debug, info, warn};
-use uuid::Uuid;
use crate::capture_policy::{
CaptureConfig, CaptureDisposition, CapturePolicy, CaptureProtocol, CaptureSource, PolicyState,
@@ -1349,7 +1348,7 @@ async fn fetch_and_accept_handoff(
.session_id
.as_deref()
.filter(|value| !value.trim().is_empty())
- .map(resolve_native_session_id);
+ .map(SessionId::from_native);
let receiving_session = if handoff.is_some() {
match accepting_session {
Some(id) => Some(NewSession {
@@ -3069,7 +3068,7 @@ fn parse_session_owner(owner: Option<String>) -> anyhow::Result<Option<IdentityK
fn resolve_session_id(env: &HookEnvelope) -> anyhow::Result<SessionId> {
if let Some(raw) = &env.session_id {
- return Ok(resolve_native_session_id(raw));
+ return Ok(SessionId::from_native(raw));
}
if matches!(env.event, HookEvent::SessionStart) {
return Ok(SessionId::new());
@@ -3077,13 +3076,6 @@ fn resolve_session_id(env: &HookEnvelope) -> anyhow::Result<SessionId> {
anyhow::bail!("hook payload missing session_id and event is not session-start")
}
-fn resolve_native_session_id(raw: &str) -> SessionId {
- // Accept either a UUID (canonical) or any string, hashing the latter to a
- // deterministic UUID v5 so hook POSTs and startup GETs share one key.
- SessionId::from_str(raw)
- .unwrap_or_else(|_| SessionId(Uuid::new_v5(&Uuid::NAMESPACE_OID, raw.as_bytes())))
-}
-
/// A session is substantive iff it logged at least one `UserPrompt`,
/// `PreToolUse`, or `PostToolUse` observation. Everything else — including
/// `Stop` and `Notification`, which some harnesses (e.g. OpenCode) fire for
@@ -10401,7 +10393,7 @@ mod tests {
.unwrap();
assert_eq!(
accepted.lifecycle.accepted_by_session,
- Some(resolve_native_session_id(empty_sid))
+ Some(SessionId::from_native(empty_sid))
);
for event in ["session-start", "session-end"] {
@@ -13245,7 +13237,7 @@ mod tests {
.await
.unwrap();
- let session_id = resolve_native_session_id(session);
+ let session_id = SessionId::from_native(session);
let summary = state
.reader
.session_summary_scoped(
diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rs
index 2051632a..d0bf5e5f 100644
--- a/crates/ai-memory-mcp/src/admin.rs
+++ b/crates/ai-memory-mcp/src/admin.rs
@@ -24,6 +24,10 @@
//! - `POST /admin/purge-project` — delete a project's rows and wiki files
//! (logical unless `compact` is set; see `ai_memory_store::Compaction`).
//! - `POST /admin/purge-session` — delete one session and what it derived.
+//! - `POST /admin/repair-session-times` — correct `started_at`/`ended_at` of
+//! already-imported sessions from caller-supplied candidate times (the CLI
+//! computes them from local transcripts; see `ai-memory
+//! repair-backfill-timestamps`).
//! - `POST /admin/rename-project` — rename a project (column-only; no files move).
//! - `POST /admin/rename-workspace` — rename a workspace and refresh scope manifests.
//! - `POST /admin/compact` — reclaim free pages; deletes nothing.
@@ -588,6 +592,7 @@ fn hex_to_sha256(hex: &str) -> Result<[u8; 32], String> {
/// - `POST /admin/rename-project`
/// - `POST /admin/move-project`
/// - `POST /admin/move-session`
+/// - `POST /admin/repair-session-times`
/// - `POST /admin/merge-workspace`
/// - `POST /admin/write-page`
/// - `POST /admin/delete-page`
@@ -673,6 +678,10 @@ pub fn admin_router_with_sweep_tuning(
.route("/admin/rename-project", post(handle_rename_project))
.route("/admin/move-project", post(handle_move_project))
.route("/admin/move-session", post(handle_move_session))
+ .route(
+ "/admin/repair-session-times",
+ post(handle_repair_session_times),
+ )
.route("/admin/delete-workspace", post(handle_delete_workspace))
.route("/admin/compact", post(handle_compact))
.route("/admin/rename-workspace", post(handle_rename_workspace))
@@ -4040,6 +4049,233 @@ async fn handle_purge_session(
(StatusCode::OK, Json(json_or_empty(&report)))
}
+// ---------------------------------------------------------------------
+// repair-session-times
+// ---------------------------------------------------------------------
+
+/// Upper bound on how many session candidates one
+/// `POST /admin/repair-session-times` request may carry. The CLI builds this
+/// list from a local transcript scan, which is operator-controlled, but the
+/// request body is still client-supplied input to a single writer-actor
+/// transaction — bounding it keeps that transaction (and the rolled-back dry
+/// run alike) from growing unboundedly on a malformed or hostile request.
+/// Comfortably above what one project's transcript history should ever
+/// produce; the CLI chunks larger batches into requests of this size.
+const MAX_REPAIR_SESSIONS: usize = 2_000;
+
+/// One candidate session correction in `POST /admin/repair-session-times`.
+#[derive(Deserialize)]
+struct RepairSessionTimesItem {
+ /// Full `sessions.id` UUID (native id or its UUID v5, already resolved by
+ /// the caller — same rule the hook router uses).
+ session_id: String,
+ /// Replacement `started_at`, Unix microseconds, read from the caller's
+ /// transcript.
+ started_at_us: i64,
+ /// Replacement `ended_at`, or omitted/`null` to leave the column as it
+ /// is. Never applied when the session is currently open; see
+ /// [`ai_memory_store::RepairedSessionTimes::end_kept_open`].
+ #[serde(default)]
+ ended_at_us: Option<i64>,
+}
+
+/// JSON request body for `POST /admin/repair-session-times`.
+#[derive(Deserialize)]
+struct RepairSessionTimesRequest {
+ /// Workspace name. Must already exist; 404 otherwise.
+ workspace: String,
+ /// Project name. Must already exist; 404 otherwise.
+ project: String,
+ /// Candidate corrections, one per session. A candidate whose
+ /// `session_id` does not belong to this `(workspace, project)` is
+ /// reported `not_found` and left untouched — the id alone is never
+ /// authority over another scope, same as `purge-session`. A candidate
+ /// naming a session whose row is not dated after the candidate's own end
+ /// (i.e. is not actually flattened) is reported `not_flattened` and left
+ /// untouched too — this endpoint repairs the backfill bug, it does not
+ /// let a caller set an arbitrary session's times. Bounded by
+ /// [`MAX_REPAIR_SESSIONS`].
+ sessions: Vec<RepairSessionTimesItem>,
+ /// Without `confirm: true` this is a real dry run: every candidate is
+ /// validated and the exact would-be outcome is reported, but nothing is
+ /// written.
+ #[serde(default)]
+ confirm: bool,
+}
+
+/// One session actually rewritten (or, for a dry run, that would be),
+/// mirrored from [`ai_memory_store::RepairedSessionTimes`].
+#[derive(Debug, Serialize)]
+pub struct RepairedSessionTimesReport {
+ /// Session that was rewritten (or, for a dry run, that would be).
+ pub session_id: String,
+ /// `started_at` before the repair.
+ pub old_started_at_us: i64,
+ /// `ended_at` before the repair.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub old_ended_at_us: Option<i64>,
+ /// `started_at` after the repair.
+ pub new_started_at_us: i64,
+ /// `ended_at` after the repair (unchanged when `None`).
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub new_ended_at_us: Option<i64>,
+ /// `true` when the candidate carried `ended_at_us` but the session was
+ /// open, so only `started_at` was applied.
+ #[serde(skip_serializing_if = "std::ops::Not::not")]
+ pub end_kept_open: bool,
+}
+
+/// One candidate left untouched, with why.
+#[derive(Debug, Serialize)]
+pub struct SkippedSessionTimesReport {
+ /// Session the candidate named.
+ pub session_id: String,
+ /// `"not_found"`, `"not_flattened"`, `"unchanged"`, `"invalid_time"`,
+ /// `"inverted_times"`, or `"future_time"`.
+ pub reason: &'static str,
+}
+
+/// Wire-format report for `POST /admin/repair-session-times`.
+#[derive(Debug, Serialize)]
+pub struct RepairSessionTimesReport {
+ /// Human workspace name.
+ pub workspace: String,
+ /// Human project name.
+ pub project: String,
+ /// `true` when nothing was written (no `confirm`).
+ pub dry_run: bool,
+ /// Sessions rewritten (or, for a dry run, that would be).
+ pub repaired: Vec<RepairedSessionTimesReport>,
+ /// Sessions left untouched, with why — includes scope mismatches
+ /// (`"not_found"`), sessions not matching the bug's signature
+ /// (`"not_flattened"`), no-op candidates (`"unchanged"`), and refused
+ /// times.
+ pub skipped: Vec<SkippedSessionTimesReport>,
+}
+
+fn repair_skip_reason_label(reason: ai_memory_store::SessionTimesSkipReason) -> &'static str {
+ match reason {
+ ai_memory_store::SessionTimesSkipReason::NotFound => "not_found",
+ ai_memory_store::SessionTimesSkipReason::NotFlattened => "not_flattened",
+ ai_memory_store::SessionTimesSkipReason::Unchanged => "unchanged",
+ ai_memory_store::SessionTimesSkipReason::InvalidTime => "invalid_time",
+ ai_memory_store::SessionTimesSkipReason::InvertedTimes => "inverted_times",
+ ai_memory_store::SessionTimesSkipReason::FutureTime => "future_time",
+ }
+}
+
+/// `POST /admin/repair-session-times` — correct `sessions.started_at`/
+/// `ended_at` for sessions already imported by an older `backfill` that
+/// discarded the transcript's own timestamps.
+///
+/// The CLI (`ai-memory repair-backfill-timestamps`) owns transcript access —
+/// it reads the operator's local harness transcripts, matches each one to a
+/// session id, and posts the computed candidate times here; this endpoint
+/// never touches the filesystem. Every candidate is validated against the
+/// scope: a `session_id` that does not belong to `(workspace, project)` is
+/// `not_found`, exactly like `purge-session`. A candidate whose named session
+/// is not actually flattened (its `started_at` does not postdate the
+/// candidate's own end) is `not_flattened` and left untouched — this targets
+/// the backfill bug specifically, it is not a generic "set session times"
+/// primitive that would happily rewrite a correctly hook-captured session.
+/// Without `confirm` the write runs inside a rolled-back transaction, so the
+/// report is the literal would-be outcome (same pattern as `move-session`). A
+/// confirmed batch writes one `audit_log` row with the repaired sessions'
+/// before/after times, which is the reversibility an operator has after the
+/// fact.
+async fn handle_repair_session_times(
+ State(state): State<Arc<AdminState>>,
+ author_ext: Option<axum::Extension<ai_memory_core::UserId>>,
+ Json(req): Json<RepairSessionTimesRequest>,
+) -> (StatusCode, Json<serde_json::Value>) {
+ let author_id = author_ext.map(|axum::Extension(u)| u);
+ if req.sessions.len() > MAX_REPAIR_SESSIONS {
+ return (
+ StatusCode::BAD_REQUEST,
+ Json(serde_json::json!({
+ "error": format!(
+ "sessions: at most {MAX_REPAIR_SESSIONS} candidates per request, got {}",
+ req.sessions.len()
+ )
+ })),
+ );
+ }
+
+ let (ws_id, proj_id) =
+ match lookup_ws_proj_no_create(&state, &req.workspace, &req.project).await {
+ Ok(ids) => ids,
+ Err((status, body)) => return (status, body),
+ };
+
+ // Parsed locally (not via the writer) so a single malformed id fails the
+ // whole request before anything is validated against the scope, same as
+ // `purge-session`'s UUID check.
+ let mut candidates = Vec::with_capacity(req.sessions.len());
+ let mut malformed = Vec::new();
+ for item in &req.sessions {
+ match item.session_id.trim().parse::<SessionId>() {
+ Ok(session_id) => candidates.push(ai_memory_store::SessionTimesCandidate {
+ session_id,
+ started_at_us: item.started_at_us,
+ ended_at_us: item.ended_at_us,
+ }),
+ Err(_) => malformed.push(item.session_id.clone()),
+ }
+ }
+ if !malformed.is_empty() {
+ return (
+ StatusCode::BAD_REQUEST,
+ Json(serde_json::json!({
+ "error": "session_id must be a full UUID",
+ "malformed": malformed,
+ })),
+ );
+ }
+
+ let now_us = jiff::Timestamp::now().as_microsecond();
+ let outcome = match state
+ .writer
+ .repair_session_times(ws_id, proj_id, candidates, now_us, author_id, req.confirm)
+ .await
+ {
+ Ok(summary) => summary,
+ Err(e) => {
+ return (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Json(serde_json::json!({ "error": e.to_string() })),
+ );
+ }
+ };
+
+ let report = RepairSessionTimesReport {
+ workspace: req.workspace,
+ project: req.project,
+ dry_run: !req.confirm,
+ repaired: outcome
+ .repaired
+ .into_iter()
+ .map(|r| RepairedSessionTimesReport {
+ session_id: r.session_id.to_string(),
+ old_started_at_us: r.old_started_at_us,
+ old_ended_at_us: r.old_ended_at_us,
+ new_started_at_us: r.new_started_at_us,
+ new_ended_at_us: r.new_ended_at_us,
+ end_kept_open: r.end_kept_open,
+ })
+ .collect(),
+ skipped: outcome
+ .skipped
+ .into_iter()
+ .map(|s| SkippedSessionTimesReport {
+ session_id: s.session_id.to_string(),
+ reason: repair_skip_reason_label(s.reason),
+ })
+ .collect(),
+ };
+
+ (StatusCode::OK, Json(json_or_empty(&report)))
+}
+
// ---------------------------------------------------------------------
// purge-project
// ---------------------------------------------------------------------
@@ -11512,6 +11748,16 @@ mod tests {
"confirm": true
}),
),
+ (
+ "POST",
+ "/admin/repair-session-times",
+ serde_json::json!({
+ "workspace": "default",
+ "project": "scratch",
+ "sessions": [],
+ "confirm": false
+ }),
+ ),
(
"POST",
"/admin/delete-workspace",
diff --git a/crates/ai-memory-mcp/tests/suite/admin_repair_session_times.rs b/crates/ai-memory-mcp/tests/suite/admin_repair_session_times.rs
new file mode 100644
index 00000000..d7e19623
--- /dev/null
+++ b/crates/ai-memory-mcp/tests/suite/admin_repair_session_times.rs
@@ -0,0 +1,540 @@
+//! Integration tests for `POST /admin/repair-session-times`
+//! (`ai-memory repair-backfill-timestamps`).
+//!
+//! Follows the same pattern as `admin_purge.rs`: build a real [`AdminState`]
+//! over a tmpdir-backed store, drive the router with `tower::ServiceExt::oneshot`.
+
+use super::common::post;
+use ai_memory_core::{AgentKind, NewSession, SessionId};
+use ai_memory_mcp::{AdminState, admin_router};
+use ai_memory_store::{DecayParams, Store};
+use ai_memory_wiki::Wiki;
+use axum::Router;
+use axum::body::Body;
+use axum::http::{Request, StatusCode};
+use serde_json::json;
+use tempfile::TempDir;
+use tower::ServiceExt as _;
+
+// ---------------------------------------------------------------------------
+// Helpers
+// ---------------------------------------------------------------------------
+
+async fn make_state(tmp: &TempDir) -> (AdminState, Store) {
+ let store = Store::open(tmp.path()).unwrap();
+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();
+ let db_path = store.db_path().to_path_buf();
+ let state = AdminState {
+ ingest_metrics: std::sync::Arc::new(ai_memory_core::IngestMetrics::default()),
+ writer: store.writer.clone(),
+ reader: store.reader.clone(),
+ wiki,
+ llm: None,
+ auto_improve_require_approval: false,
+ auto_improve_review_config: Default::default(),
+ embedder: None,
+ provider_health: ai_memory_llm::ProviderHealth::default(),
+ decay_params: DecayParams::default(),
+ data_dir: tmp.path().to_path_buf(),
+ bind: "127.0.0.1:0".to_string(),
+ home_dir: None,
+ bootstrap_lock: std::sync::Arc::new(tokio::sync::Mutex::new(())),
+ token_pepper: None,
+ active_project: ai_memory_core::ActiveProject::new(),
+ scope_invalidator: None,
+ trusted_proxy_identity: false,
+ db_path,
+ };
+ (state, store)
+}
+
+async fn body_json(resp: axum::response::Response) -> serde_json::Value {
+ let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ serde_json::from_slice(&bytes).unwrap_or(serde_json::Value::Null)
+}
+
+async fn seed_session(store: &Store, workspace: &str, project: &str, ended: bool) -> SessionId {
+ let ws = store
+ .writer
+ .get_or_create_workspace(workspace)
+ .await
+ .unwrap();
+ let proj = store
+ .writer
+ .get_or_create_project(ws, project, None)
+ .await
+ .unwrap();
+ let sid = SessionId::new();
+ store
+ .writer
+ .begin_session(NewSession {
+ id: sid,
+ workspace_id: ws,
+ project_id: proj,
+ agent_kind: AgentKind::ClaudeCode,
+ cwd: None,
+ actor_user: None,
+ occurred_at: None,
+ })
+ .await
+ .unwrap();
+ if ended {
+ store.writer.end_session(sid, None).await.unwrap();
+ }
+ sid
+}
+
+async fn session_times(store: &Store, sid: SessionId) -> (i64, Option<i64>) {
+ store
+ .reader
+ .with_conn(move |conn| {
+ conn.query_row(
+ "SELECT started_at, ended_at FROM sessions WHERE id = ?1",
+ [&sid.as_bytes()[..]],
+ |r| Ok((r.get(0)?, r.get(1)?)),
+ )
+ .map_err(Into::into)
+ })
+ .await
+ .unwrap()
+}
+
+fn now_us() -> i64 {
+ jiff::Timestamp::now().as_microsecond()
+}
+
+// ---------------------------------------------------------------------------
+// Tests
+// ---------------------------------------------------------------------------
+
+/// Without `confirm`, the endpoint is a real dry run: it reports the
+/// would-be repair but the database keeps the original times.
+#[tokio::test]
+async fn dry_run_reports_without_writing() {
+ let tmp = TempDir::new().unwrap();
+ let (state, store) = make_state(&tmp).await;
+ let sid = seed_session(&store, "default", "scratch", true).await;
+ let (original_started, original_ended) = session_times(&store, sid).await;
+ let now = now_us();
+ let new_started = now - 1_000_000_000;
+
+ let resp = post(
+ state,
+ "/admin/repair-session-times",
+ json!({
+ "workspace": "default",
+ "project": "scratch",
+ "sessions": [{"session_id": sid.to_string(), "started_at_us": new_started}],
+ "confirm": false,
+ }),
+ )
+ .await;
+ assert_eq!(resp.status(), StatusCode::OK);
+ let body = body_json(resp).await;
+ assert_eq!(body["dry_run"], json!(true));
+ assert_eq!(body["repaired"].as_array().unwrap().len(), 1);
+
+ assert_eq!(
+ session_times(&store, sid).await,
+ (original_started, original_ended),
+ "dry run must not write anything"
+ );
+}
+
+/// With `confirm: true` the write commits.
+#[tokio::test]
+async fn confirm_applies_the_repair() {
+ let tmp = TempDir::new().unwrap();
+ let (state, store) = make_state(&tmp).await;
+ let sid = seed_session(&store, "default", "scratch", true).await;
+ let now = now_us();
+ let new_started = now - 1_000_000_000;
+ let new_ended = now - 999_000_000;
+
+ let resp = post(
+ state,
+ "/admin/repair-session-times",
+ json!({
+ "workspace": "default",
+ "project": "scratch",
+ "sessions": [{
+ "session_id": sid.to_string(),
+ "started_at_us": new_started,
+ "ended_at_us": new_ended,
+ }],
+ "confirm": true,
+ }),
+ )
+ .await;
+ assert_eq!(resp.status(), StatusCode::OK);
+ let body = body_json(resp).await;
+ assert_eq!(body["dry_run"], json!(false));
+ assert_eq!(body["repaired"][0]["new_started_at_us"], json!(new_started));
+
+ assert_eq!(
+ session_times(&store, sid).await,
+ (new_started, Some(new_ended))
+ );
+}
+
+/// Adversarial: a session belonging to a different project must be reported
+/// `not_found` and left untouched, even though it is a real session id.
+/// Control: a sibling session actually inside the requested scope is
+/// repaired in the same request.
+#[tokio::test]
+async fn cross_project_session_is_not_found_and_untouched() {
+ let tmp = TempDir::new().unwrap();
+ let (state, store) = make_state(&tmp).await;
+ let sid_in_scope = seed_session(&store, "default", "scratch", true).await;
+ let sid_other = seed_session(&store, "default", "other-project", true).await;
+ let original_other = session_times(&store, sid_other).await;
+ let now = now_us();
+ let new_started = now - 1_000_000_000;
+
+ let resp = post(
+ state,
+ "/admin/repair-session-times",
+ json!({
+ "workspace": "default",
+ "project": "scratch",
+ "sessions": [
+ {"session_id": sid_in_scope.to_string(), "started_at_us": new_started},
+ {"session_id": sid_other.to_string(), "started_at_us": new_started},
+ ],
+ "confirm": true,
+ }),
+ )
+ .await;
+ assert_eq!(resp.status(), StatusCode::OK);
+ let body = body_json(resp).await;
+ assert_eq!(body["repaired"].as_array().unwrap().len(), 1, "{body}");
+ assert_eq!(
+ body["repaired"][0]["session_id"],
+ json!(sid_in_scope.to_string())
+ );
+ assert_eq!(body["skipped"].as_array().unwrap().len(), 1);
+ assert_eq!(
+ body["skipped"][0]["session_id"],
+ json!(sid_other.to_string())
+ );
+ assert_eq!(body["skipped"][0]["reason"], json!("not_found"));
+
+ assert_eq!(
+ session_times(&store, sid_other).await,
+ original_other,
+ "a session outside the requested project must not be rewritten"
+ );
+}
+
+/// Adversarial: a session belonging to a different WORKSPACE (same project
+/// name, so same-named projects across workspaces do not collide) must also
+/// be `not_found` and untouched. Control: a sibling session in the requested
+/// workspace is repaired in the same request. Mirrors
+/// `purge_session_refuses_a_session_from_another_workspace`.
+#[tokio::test]
+async fn cross_workspace_session_is_not_found_and_untouched() {
+ let tmp = TempDir::new().unwrap();
+ let (state, store) = make_state(&tmp).await;
+ let sid_in_scope = seed_session(&store, "default", "scratch", true).await;
+ let sid_other = seed_session(&store, "other-workspace", "scratch", true).await;
+ let original_other = session_times(&store, sid_other).await;
+ let now = now_us();
+ let new_started = now - 1_000_000_000;
+
+ let resp = post(
+ state,
+ "/admin/repair-session-times",
+ json!({
+ "workspace": "default",
+ "project": "scratch",
+ "sessions": [
+ {"session_id": sid_in_scope.to_string(), "started_at_us": new_started},
+ {"session_id": sid_other.to_string(), "started_at_us": new_started},
+ ],
+ "confirm": true,
+ }),
+ )
+ .await;
+ assert_eq!(resp.status(), StatusCode::OK);
+ let body = body_json(resp).await;
+ assert_eq!(body["repaired"].as_array().unwrap().len(), 1, "{body}");
+ assert_eq!(
+ body["repaired"][0]["session_id"],
+ json!(sid_in_scope.to_string())
+ );
+ assert_eq!(body["skipped"].as_array().unwrap().len(), 1);
+ assert_eq!(
+ body["skipped"][0]["session_id"],
+ json!(sid_other.to_string())
+ );
+ assert_eq!(body["skipped"][0]["reason"], json!("not_found"));
+
+ assert_eq!(
+ session_times(&store, sid_other).await,
+ original_other,
+ "a session in another workspace must not be rewritten"
+ );
+}
+
+/// B1: a correctly hook-captured session (its stored `started_at` already
+/// sits at or before the candidate's own end) must not be rewritten, even
+/// though the candidate is otherwise well-formed — this endpoint targets the
+/// backfill bug's signature, it is not a generic "set session times"
+/// primitive. Control: a genuinely flattened sibling session is repaired in
+/// the same request.
+#[tokio::test]
+async fn correctly_dated_session_is_not_flattened_and_untouched() {
+ let tmp = TempDir::new().unwrap();
+ let (state, store) = make_state(&tmp).await;
+ let correct_sid = seed_session(&store, "default", "scratch", true).await;
+ let flattened_sid = seed_session(&store, "default", "scratch", true).await;
+ let (correct_started, correct_ended) = session_times(&store, correct_sid).await;
+ let now = now_us();
+
+ let resp = post(
+ state,
+ "/admin/repair-session-times",
+ json!({
+ "workspace": "default",
+ "project": "scratch",
+ "sessions": [
+ // Repeats the session's own start and nearly (not exactly,
+ // to keep this test distinct from a plain no-op) its own
+ // end.
+ {
+ "session_id": correct_sid.to_string(),
+ "started_at_us": correct_started,
+ "ended_at_us": correct_ended.map(|e| e - 1),
+ },
+ {
+ "session_id": flattened_sid.to_string(),
+ "started_at_us": now - 1_000_000_000,
+ "ended_at_us": now - 999_000_000,
+ },
+ ],
+ "confirm": true,
+ }),
+ )
+ .await;
+ assert_eq!(resp.status(), StatusCode::OK);
+ let body = body_json(resp).await;
+ assert_eq!(body["repaired"].as_array().unwrap().len(), 1, "{body}");
+ assert_eq!(
+ body["repaired"][0]["session_id"],
+ json!(flattened_sid.to_string()),
+ "control (flattened session) must be repaired"
+ );
+ assert_eq!(body["skipped"].as_array().unwrap().len(), 1);
+ assert_eq!(
+ body["skipped"][0]["session_id"],
+ json!(correct_sid.to_string())
+ );
+ assert_eq!(body["skipped"][0]["reason"], json!("not_flattened"));
+
+ assert_eq!(
+ session_times(&store, correct_sid).await,
+ (correct_started, correct_ended),
+ "a correctly-dated hook-captured session must not be touched"
+ );
+}
+
+/// An open session (no `ended_at`) never has an end time imposed on it, even
+/// when the candidate carries one; `started_at` is still applied.
+#[tokio::test]
+async fn open_session_keeps_null_end() {
+ let tmp = TempDir::new().unwrap();
+ let (state, store) = make_state(&tmp).await;
+ let sid = seed_session(&store, "default", "scratch", false).await;
+ let now = now_us();
+ let new_started = now - 1_000_000_000;
+
+ let resp = post(
+ state,
+ "/admin/repair-session-times",
+ json!({
+ "workspace": "default",
+ "project": "scratch",
+ "sessions": [{
+ "session_id": sid.to_string(),
+ "started_at_us": new_started,
+ "ended_at_us": now - 999_000_000,
+ }],
+ "confirm": true,
+ }),
+ )
+ .await;
+ assert_eq!(resp.status(), StatusCode::OK);
+ let body = body_json(resp).await;
+ assert_eq!(body["repaired"][0]["end_kept_open"], json!(true));
+
+ let (started, ended) = session_times(&store, sid).await;
+ assert_eq!(started, new_started);
+ assert!(ended.is_none(), "an open session must stay open");
+}
+
+/// Future, negative, and inverted times are refused outright.
+#[tokio::test]
+async fn refuses_future_negative_and_inverted_times() {
+ let tmp = TempDir::new().unwrap();
+ let (state, store) = make_state(&tmp).await;
+ let router = admin_router(state);
+ let now = now_us();
+
+ for (label, item) in [
+ (
+ "future",
+ json!({"started_at_us": now + 60 * 60 * 1_000_000}),
+ ),
+ ("negative", json!({"started_at_us": -1})),
+ (
+ "inverted",
+ json!({"started_at_us": now - 1_000, "ended_at_us": now - 2_000}),
+ ),
+ ] {
+ let sid = seed_session(&store, "default", "scratch", true).await;
+ let mut item = item;
+ item["session_id"] = json!(sid.to_string());
+ let payload = json!({
+ "workspace": "default",
+ "project": "scratch",
+ "sessions": [item],
+ "confirm": true,
+ });
+ let req = Request::builder()
+ .method("POST")
+ .uri("/admin/repair-session-times")
+ .header("content-type", "application/json")
+ .body(Body::from(serde_json::to_vec(&payload).unwrap()))
+ .unwrap();
+ let resp = router.clone().oneshot(req).await.unwrap();
+ assert_eq!(resp.status(), StatusCode::OK, "{label}");
+ let body = body_json(resp).await;
+ assert!(
+ body["repaired"].as_array().unwrap().is_empty(),
+ "{label}: {body}"
+ );
+ assert_eq!(body["skipped"].as_array().unwrap().len(), 1, "{label}");
+ }
+}
+
+/// The request body is bounded: a batch over the limit is refused before any
+/// scope lookup or write.
+#[tokio::test]
+async fn bounds_the_number_of_candidates() {
+ let tmp = TempDir::new().unwrap();
+ let (state, _store) = make_state(&tmp).await;
+ let sessions: Vec<_> = (0..2_001)
+ .map(|_| json!({"session_id": SessionId::new().to_string(), "started_at_us": 1}))
+ .collect();
+
+ let resp = post(
+ state,
+ "/admin/repair-session-times",
+ json!({
+ "workspace": "default",
+ "project": "scratch",
+ "sessions": sessions,
+ "confirm": false,
+ }),
+ )
+ .await;
+ assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
+}
+
+/// Exactly at the limit (2,000) is accepted — the bound is `> MAX`, not
+/// `>= MAX`.
+#[tokio::test]
+async fn exact_limit_of_candidates_is_accepted() {
+ let tmp = TempDir::new().unwrap();
+ let (state, store) = make_state(&tmp).await;
+ // Establish the scope so the request passes the scope lookup and reaches
+ // per-candidate validation (all `not_found`, since these ids are random).
+ store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ let sessions: Vec<_> = (0..2_000)
+ .map(|_| json!({"session_id": SessionId::new().to_string(), "started_at_us": 1}))
+ .collect();
+
+ let resp = post(
+ state,
+ "/admin/repair-session-times",
+ json!({
+ "workspace": "default",
+ "project": "scratch",
+ "sessions": sessions,
+ "confirm": false,
+ }),
+ )
+ .await;
+ // Scope itself does not exist (only the workspace does), so this is a
+ // 404 rather than 200 — the point is that it is NOT the 400 the
+ // over-the-limit test gets, i.e. the bound check itself passed.
+ assert_eq!(resp.status(), StatusCode::NOT_FOUND);
+}
+
+/// Mirrors `trusted_proxy_topology_gates_admin_without_db_users` in
+/// `admin.rs` (the same gate `move-session`/`purge-session` sit behind, via
+/// the shared `require_root_for_multiuser_admin` middleware): with
+/// `trusted_proxy_identity: true`, only `AuthLevel::Root` may call this
+/// endpoint. Control: root succeeds.
+#[tokio::test]
+async fn requires_root_once_multiuser() {
+ use ai_memory_core::ActorContext;
+
+ let tmp = TempDir::new().unwrap();
+ let (mut state, store) = make_state(&tmp).await;
+ let sid = seed_session(&store, "default", "scratch", true).await;
+ state.trusted_proxy_identity = true;
+
+ let router: Router = admin_router(state).layer(axum::middleware::from_fn(
+ |mut req: Request<Body>, next: axum::middleware::Next| async move {
+ let level = match req
+ .headers()
+ .get("x-test-auth-level")
+ .and_then(|v| v.to_str().ok())
+ {
+ Some("root") => ai_memory_core::AuthLevel::Root,
+ Some("user") => ai_memory_core::AuthLevel::User,
+ _ => ai_memory_core::AuthLevel::Anonymous,
+ };
+ req.extensions_mut().insert(level);
+ req.extensions_mut().insert(ActorContext::anonymous());
+ next.run(req).await
+ },
+ ));
+
+ let body = json!({
+ "workspace": "default",
+ "project": "scratch",
+ "sessions": [{"session_id": sid.to_string(), "started_at_us": 1_700_000_000_000_000i64}],
+ "confirm": false,
+ });
+
+ for (level, expected) in [
+ (None, StatusCode::UNAUTHORIZED),
+ (Some("user"), StatusCode::FORBIDDEN),
+ (Some("root"), StatusCode::OK),
+ ] {
+ let mut req = Request::builder()
+ .method("POST")
+ .uri("/admin/repair-session-times")
+ .header("content-type", "application/json");
+ if let Some(level) = level {
+ req = req.header("x-test-auth-level", level);
+ }
+ let resp = router
+ .clone()
+ .oneshot(
+ req.body(Body::from(serde_json::to_vec(&body).unwrap()))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(resp.status(), expected, "level={level:?}");
+ }
+}
diff --git a/crates/ai-memory-mcp/tests/suite/mod.rs b/crates/ai-memory-mcp/tests/suite/mod.rs
index 1ef69bf8..e9c487c8 100644
--- a/crates/ai-memory-mcp/tests/suite/mod.rs
+++ b/crates/ai-memory-mcp/tests/suite/mod.rs
@@ -15,6 +15,7 @@ mod admin_provider_error_logging;
mod admin_purge;
mod admin_read_page;
mod admin_rename;
+mod admin_repair_session_times;
mod admin_status_search;
mod admin_write_page;
mod agent_messages_briefing;
diff --git a/crates/ai-memory-store/src/lib.rs b/crates/ai-memory-store/src/lib.rs
index 4d9685ee..88efe698 100644
--- a/crates/ai-memory-store/src/lib.rs
+++ b/crates/ai-memory-store/src/lib.rs
@@ -59,8 +59,10 @@ pub use ops::{
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,
+ PurgeSessionSummary, PurgeSummary, ReorgSummary, RepairSessionTimesSummary,
+ RepairedSessionTimes, SessionTimesCandidate, SessionTimesSkipReason, SkippedSessionTimes,
+ 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.rs
index a8b68c0d..deebfd90 100644
--- a/crates/ai-memory-store/src/ops.rs
+++ b/crates/ai-memory-store/src/ops.rs
@@ -1683,6 +1683,301 @@ fn end_session_row(
Ok(())
}
+/// A candidate correction for one session's `started_at`/`ended_at`, as
+/// computed by the CLI from the operator's local transcripts and posted to
+/// `POST /admin/repair-session-times` (`ai-memory repair-backfill-timestamps`).
+#[derive(Debug, Clone, Copy)]
+pub struct SessionTimesCandidate {
+ /// Session to repair.
+ pub session_id: SessionId,
+ /// Replacement `started_at`, Unix microseconds.
+ pub started_at_us: i64,
+ /// Replacement `ended_at`, or `None` to leave the column as it is.
+ pub ended_at_us: Option<i64>,
+}
+
+/// Why one candidate produced no change.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum SessionTimesSkipReason {
+ /// No `sessions` row with this id belongs to the caller's
+ /// `(workspace_id, project_id)` — either the id does not exist at all,
+ /// or it belongs to a different scope. The two are never distinguished:
+ /// like `purge_session`, scope containment must not leak whether an id
+ /// exists elsewhere.
+ NotFound,
+ /// The row already sits at or before the candidate's own end (or start,
+ /// when it carries no end): it does not carry the backfill bug's
+ /// signature (`started_at` dated after the transcript actually ended),
+ /// so it is left alone rather than rewritten on the caller's say-so.
+ /// Makes a repeat run against an already-repaired or never-broken
+ /// session (e.g. one the fixed `backfill` imported) a no-op.
+ NotFlattened,
+ /// The candidate already matches the stored row: nothing to write.
+ Unchanged,
+ /// `started_at_us`, or `ended_at_us` when given, is not a positive
+ /// microsecond timestamp.
+ InvalidTime,
+ /// `ended_at_us` is given and is earlier than `started_at_us`, or
+ /// `started_at_us` is later than the end the row will have once this
+ /// candidate is applied (its own `ended_at_us`, or, when that is absent,
+ /// the row's current `ended_at`).
+ InvertedTimes,
+ /// `started_at_us` or `ended_at_us` is more than five minutes past "now"
+ /// — a repair never moves a session into the future.
+ FutureTime,
+}
+
+/// Microsecond slack allowed past "now" before a candidate time is refused as
+/// being in the future — clock-skew margin, not a real correction target.
+const REPAIR_TIMES_FUTURE_SLACK_US: i64 = 5 * 60 * 1_000_000;
+
+/// One session actually rewritten by [`repair_session_times`].
+#[derive(Debug, Clone, Copy)]
+pub struct RepairedSessionTimes {
+ /// Session that was rewritten.
+ pub session_id: SessionId,
+ /// `started_at` before the repair.
+ pub old_started_at_us: i64,
+ /// `ended_at` before the repair.
+ pub old_ended_at_us: Option<i64>,
+ /// `started_at` after the repair.
+ pub new_started_at_us: i64,
+ /// `ended_at` after the repair (unchanged when `None`).
+ pub new_ended_at_us: Option<i64>,
+ /// The candidate carried an `ended_at_us`, but the session was open
+ /// (`ended_at` was `NULL`) — `started_at` was still applied, `ended_at`
+ /// was deliberately left `NULL`.
+ pub end_kept_open: bool,
+}
+
+/// One candidate that changed nothing — whether because it never matched a
+/// session in scope ([`SessionTimesSkipReason::NotFound`]) or because it did
+/// match one but was refused or was a no-op.
+#[derive(Debug, Clone, Copy)]
+pub struct SkippedSessionTimes {
+ /// Session the candidate named.
+ pub session_id: SessionId,
+ /// Why nothing was written for it.
+ pub reason: SessionTimesSkipReason,
+}
+
+/// Outcome of one [`repair_session_times`] call.
+#[derive(Debug, Clone, Default)]
+pub struct RepairSessionTimesSummary {
+ /// Sessions whose `started_at`/`ended_at` changed (or would change).
+ pub repaired: Vec<RepairedSessionTimes>,
+ /// Sessions that were not touched, with why.
+ pub skipped: Vec<SkippedSessionTimes>,
+}
+
+/// Validate and, when `commit`, apply a batch of session-time corrections
+/// scoped to `(workspace_id, project_id)`, in ONE transaction — the store
+/// side of `POST /admin/repair-session-times`
+/// (`ai-memory repair-backfill-timestamps`).
+///
+/// Every candidate is validated against the row this same transaction reads
+/// for it, never against anything the caller already believed:
+///
+/// - A `session_id` that does not belong to this scope is
+/// [`SessionTimesSkipReason::NotFound`] and left untouched (scope
+/// containment, like `purge_session`'s).
+/// - **The bug's own signature is the gate, not the caller's say-so.** A row
+/// is only a candidate for repair when its current `started_at` sits after
+/// the candidate's own end (or its own start, when the candidate carries no
+/// end) — that is what "backfill imported this at the wrong, later, import
+/// time" looks like. A row that already sits at or before that point is
+/// [`SessionTimesSkipReason::NotFlattened`]: this endpoint is a targeted
+/// bug repair, not a generic "set session times" primitive that would
+/// happily rewrite a correctly hook-captured session's real times. This
+/// also makes a re-run against an already-repaired session, or one a fixed
+/// `backfill` imported in the first place, a true no-op.
+/// - Nonsensical, inverted (see [`SessionTimesSkipReason::InvertedTimes`]),
+/// or future-dated times are refused outright.
+/// - A session whose `ended_at` is currently `NULL` (open) never has an end
+/// time imposed on it, even when the candidate carries one — only
+/// `started_at` is applied in that case, exactly like
+/// [`RepairedSessionTimes::end_kept_open`] reports.
+/// - A candidate that would not change anything is
+/// [`SessionTimesSkipReason::Unchanged`] rather than counted as repaired.
+///
+/// `commit = false` performs the identical validation and writes, then rolls
+/// the transaction back before returning — a dry run is the literal
+/// would-be outcome, not a separate code path, same as [`move_session`]. A
+/// single `audit_log` row (`op = "repair_session_times"`) is written for the
+/// whole batch, with the repaired sessions' old/new times as `detail`; it
+/// survives only when `commit` is true, same rollback.
+///
+/// # Errors
+/// Propagates any SQL failure. Per-candidate scope/validation problems are
+/// reported in the returned summary, never as an `Err`.
+pub fn repair_session_times(
+ conn: &mut Connection,
+ workspace_id: WorkspaceId,
+ project_id: ProjectId,
+ candidates: &[SessionTimesCandidate],
+ now_us: i64,
+ author_id: Option<ai_memory_core::UserId>,
+ commit: bool,
+) -> StoreResult<RepairSessionTimesSummary> {
+ let tx = conn.transaction()?;
+ let mut summary = RepairSessionTimesSummary::default();
+
+ for candidate in candidates {
+ let sid = candidate.session_id.as_bytes();
+ let row: Option<(i64, Option<i64>)> = tx
+ .query_row(
+ "SELECT started_at, ended_at FROM sessions \
+ WHERE id = ?1 AND workspace_id = ?2 AND project_id = ?3",
+ params![&sid[..], workspace_id.as_bytes(), project_id.as_bytes()],
+ |row| Ok((row.get(0)?, row.get(1)?)),
+ )
+ .optional()?;
+ let Some((old_started_at_us, old_ended_at_us)) = row else {
+ summary.skipped.push(SkippedSessionTimes {
+ session_id: candidate.session_id,
+ reason: SessionTimesSkipReason::NotFound,
+ });
+ continue;
+ };
+
+ // Candidate sanity first — a malformed candidate is refused as such
+ // regardless of whether the row it names happens to look flattened.
+ if candidate.started_at_us <= 0 || candidate.ended_at_us.is_some_and(|e| e <= 0) {
+ summary.skipped.push(SkippedSessionTimes {
+ session_id: candidate.session_id,
+ reason: SessionTimesSkipReason::InvalidTime,
+ });
+ continue;
+ }
+ if candidate
+ .ended_at_us
+ .is_some_and(|ended| ended < candidate.started_at_us)
+ {
+ summary.skipped.push(SkippedSessionTimes {
+ session_id: candidate.session_id,
+ reason: SessionTimesSkipReason::InvertedTimes,
+ });
+ continue;
+ }
+ let future_cutoff = now_us + REPAIR_TIMES_FUTURE_SLACK_US;
+ if candidate.started_at_us > future_cutoff
+ || candidate.ended_at_us.is_some_and(|e| e > future_cutoff)
+ {
+ summary.skipped.push(SkippedSessionTimes {
+ session_id: candidate.session_id,
+ reason: SessionTimesSkipReason::FutureTime,
+ });
+ continue;
+ }
+
+ // Never impose an end time on a session the store still has open.
+ let end_kept_open = old_ended_at_us.is_none() && candidate.ended_at_us.is_some();
+ let new_ended_at_us = if old_ended_at_us.is_none() {
+ None
+ } else {
+ candidate.ended_at_us
+ };
+
+ // A candidate that already matches the stored row exactly is a no-op
+ // regardless of whether the row looks flattened — checked before that
+ // judgement call so an exact repeat never needs it.
+ if candidate.started_at_us == old_started_at_us
+ && new_ended_at_us.is_none_or(|new_end| Some(new_end) == old_ended_at_us)
+ {
+ summary.skipped.push(SkippedSessionTimes {
+ session_id: candidate.session_id,
+ reason: SessionTimesSkipReason::Unchanged,
+ });
+ continue;
+ }
+
+ // The bug's signature: backfill dated the row at import time, which
+ // is always AFTER the transcript's own last (or only) event. A row
+ // already dated at or before that point is not the bug, whatever the
+ // caller's candidate says — refuse to touch it. (Passing this check
+ // implies `candidate.started_at_us < old_started_at_us`, so it can
+ // never itself produce an `Unchanged` candidate — the check above is
+ // not redundant with this one.)
+ let candidate_end = candidate.ended_at_us.unwrap_or(candidate.started_at_us);
+ if old_started_at_us <= candidate_end {
+ summary.skipped.push(SkippedSessionTimes {
+ session_id: candidate.session_id,
+ reason: SessionTimesSkipReason::NotFlattened,
+ });
+ continue;
+ }
+
+ // The end the row will actually have once this candidate lands (its
+ // own new end, or, when that stays NULL/unwritten, whatever end it
+ // already had) must not be earlier than the new start — otherwise an
+ // omitted `ended_at_us` on an already-closed session could still
+ // invert the row.
+ if let Some(effective_end) = new_ended_at_us.or(old_ended_at_us)
+ && candidate.started_at_us > effective_end
+ {
+ summary.skipped.push(SkippedSessionTimes {
+ session_id: candidate.session_id,
+ reason: SessionTimesSkipReason::InvertedTimes,
+ });
+ continue;
+ }
+
+ tx.execute(
+ "UPDATE sessions SET started_at = ?1, ended_at = COALESCE(?2, ended_at) \
+ WHERE id = ?3 AND workspace_id = ?4 AND project_id = ?5",
+ params![
+ candidate.started_at_us,
+ new_ended_at_us,
+ &sid[..],
+ workspace_id.as_bytes(),
+ project_id.as_bytes(),
+ ],
+ )?;
+ summary.repaired.push(RepairedSessionTimes {
+ session_id: candidate.session_id,
+ old_started_at_us,
+ old_ended_at_us,
+ new_started_at_us: candidate.started_at_us,
+ new_ended_at_us,
+ end_kept_open,
+ });
+ }
+
+ if !summary.repaired.is_empty() {
+ let detail = serde_json::json!({
+ "sessions": summary
+ .repaired
+ .iter()
+ .map(|r| serde_json::json!({
+ "session_id": r.session_id.to_string(),
+ "old_started_at_us": r.old_started_at_us,
+ "old_ended_at_us": r.old_ended_at_us,
+ "new_started_at_us": r.new_started_at_us,
+ "new_ended_at_us": r.new_ended_at_us,
+ }))
+ .collect::<Vec<_>>(),
+ })
+ .to_string();
+ audit_with_detail(
+ &tx,
+ "repair_session_times",
+ Some(workspace_id.as_bytes()),
+ Some(project_id.as_bytes()),
+ None,
+ author_id.as_ref().map(ai_memory_core::UserId::as_bytes),
+ now_us,
+ &detail,
+ )?;
+ }
+
+ if commit {
+ tx.commit()?;
+ } else {
+ tx.rollback()?;
+ }
+ Ok(summary)
+}
+
/// Append a single observation. Caller is expected to have already
/// inserted the parent session via [`begin_session`].
pub fn insert_observation(
@@ -8874,6 +9169,482 @@ pub(crate) mod tests {
);
}
+ // --- repair_session_times ----------------------------------------------
+
+ fn ended_session(conn: &mut Connection, ws: WorkspaceId, proj: ProjectId) -> SessionId {
+ let sid = SessionId::new();
+ begin_session(conn, &hook_session(sid, ws, proj, None)).unwrap();
+ end_session(conn, &sid, None).unwrap();
+ sid
+ }
+
+ fn open_session(conn: &mut Connection, ws: WorkspaceId, proj: ProjectId) -> SessionId {
+ let sid = SessionId::new();
+ begin_session(conn, &hook_session(sid, ws, proj, None)).unwrap();
+ sid
+ }
+
+ fn session_times(conn: &Connection, sid: SessionId) -> (i64, Option<i64>) {
+ conn.query_row(
+ "SELECT started_at, ended_at FROM sessions WHERE id = ?1",
+ params![&sid.as_bytes()[..]],
+ |r| Ok((r.get(0)?, r.get(1)?)),
+ )
+ .unwrap()
+ }
+
+ /// A candidate scoped correctly, with sane, past times that postdate the
+ /// row's flattened `started_at`, is applied and reported as repaired.
+ #[test]
+ fn repair_session_times_applies_a_valid_candidate() {
+ let (_tmp, mut conn, ws, proj) = fresh_db();
+ let sid = ended_session(&mut conn, ws, proj);
+ let now = Timestamp::now().as_microsecond();
+ let new_started = now - 1_000_000_000;
+ let new_ended = now - 999_000_000;
+ let summary = repair_session_times(
+ &mut conn,
+ ws,
+ proj,
+ &[SessionTimesCandidate {
+ session_id: sid,
+ started_at_us: new_started,
+ ended_at_us: Some(new_ended),
+ }],
+ now,
+ None,
+ true,
+ )
+ .unwrap();
+ assert_eq!(summary.repaired.len(), 1, "{summary:?}");
+ assert!(summary.skipped.is_empty());
+ assert_eq!(session_times(&conn, sid), (new_started, Some(new_ended)));
+ }
+
+ /// `commit = false` performs the same validation and write, then rolls
+ /// back — a real dry run, not a separate code path. The audit row this
+ /// writes must roll back with it.
+ #[test]
+ fn repair_session_times_dry_run_writes_nothing() {
+ let (_tmp, mut conn, ws, proj) = fresh_db();
+ let sid = ended_session(&mut conn, ws, proj);
+ let (original_started, original_ended) = session_times(&conn, sid);
+ let now = Timestamp::now().as_microsecond();
+ let summary = repair_session_times(
+ &mut conn,
+ ws,
+ proj,
+ &[SessionTimesCandidate {
+ session_id: sid,
+ started_at_us: now - 1_000_000_000,
+ ended_at_us: Some(now - 999_000_000),
+ }],
+ now,
+ None,
+ false,
+ )
+ .unwrap();
+ assert_eq!(summary.repaired.len(), 1, "the report is still computed");
+ assert_eq!(
+ session_times(&conn, sid),
+ (original_started, original_ended),
+ "a dry run must not write anything"
+ );
+ let audit_rows: i64 = conn
+ .query_row(
+ "SELECT COUNT(*) FROM audit_log WHERE op = 'repair_session_times'",
+ [],
+ |r| r.get(0),
+ )
+ .unwrap();
+ assert_eq!(
+ audit_rows, 0,
+ "a dry run must not leave an audit row either"
+ );
+ }
+
+ /// A repaired batch writes one `audit_log` row for the whole call, with
+ /// the repaired session's old/new times recorded in `detail` — the
+ /// reversibility backing an operator relies on after `--confirm`.
+ #[test]
+ fn repair_session_times_writes_one_audit_row_with_before_after_detail() {
+ let (_tmp, mut conn, ws, proj) = fresh_db();
+ let sid = ended_session(&mut conn, ws, proj);
+ let now = Timestamp::now().as_microsecond();
+ let new_started = now - 1_000_000_000;
+ repair_session_times(
+ &mut conn,
+ ws,
+ proj,
+ &[SessionTimesCandidate {
+ session_id: sid,
+ started_at_us: new_started,
+ ended_at_us: None,
+ }],
+ now,
+ None,
+ true,
+ )
+ .unwrap();
+ let (op, detail): (String, String) = conn
+ .query_row(
+ "SELECT op, detail FROM audit_log WHERE op = 'repair_session_times'",
+ [],
+ |r| Ok((r.get(0)?, r.get(1)?)),
+ )
+ .unwrap();
+ assert_eq!(op, "repair_session_times");
+ let detail: serde_json::Value = serde_json::from_str(&detail).unwrap();
+ let sessions = detail["sessions"].as_array().unwrap();
+ assert_eq!(sessions.len(), 1, "{detail}");
+ assert_eq!(sessions[0]["session_id"], sid.to_string());
+ assert_eq!(sessions[0]["new_started_at_us"], new_started);
+ }
+
+ /// Adversarial: a session id that belongs to a different project than
+ /// the scope the caller passed must be reported `NotFound` and left
+ /// untouched — the same scope containment `purge_session` enforces.
+ /// Control: a sibling session actually inside the requested scope is
+ /// repaired in the same batch.
+ #[test]
+ fn repair_session_times_does_not_touch_a_session_of_another_project() {
+ let (_tmp, mut conn, ws, proj_a) = fresh_db();
+ let proj_b = get_or_create_project(&mut conn, &ws, "other", None).unwrap();
+ let sid_a = ended_session(&mut conn, ws, proj_a);
+ let sid_b = ended_session(&mut conn, ws, proj_b);
+ let (original_started_b, original_ended_b) = session_times(&conn, sid_b);
+ let now = Timestamp::now().as_microsecond();
+ let new_started = now - 1_000_000_000;
+
+ let summary = repair_session_times(
+ &mut conn,
+ ws,
+ proj_a,
+ &[
+ SessionTimesCandidate {
+ session_id: sid_a,
+ started_at_us: new_started,
+ ended_at_us: None,
+ },
+ SessionTimesCandidate {
+ session_id: sid_b,
+ started_at_us: new_started,
+ ended_at_us: None,
+ },
+ ],
+ now,
+ None,
+ true,
+ )
+ .unwrap();
+
+ assert_eq!(summary.repaired.len(), 1, "{summary:?}");
+ assert_eq!(summary.repaired[0].session_id, sid_a, "control must apply");
+ assert_eq!(summary.skipped.len(), 1);
+ assert_eq!(summary.skipped[0].session_id, sid_b);
+ assert_eq!(summary.skipped[0].reason, SessionTimesSkipReason::NotFound);
+ assert_eq!(
+ session_times(&conn, sid_b),
+ (original_started_b, original_ended_b),
+ "a session scoped to project B must not be rewritten by a call scoped to project A"
+ );
+ }
+
+ /// Adversarial: a session id that belongs to a different WORKSPACE (same
+ /// project name, different workspace, so same-named projects do not
+ /// collide) must also be `NotFound` and untouched. Control: a sibling
+ /// session in the requested workspace is repaired in the same batch.
+ #[test]
+ fn repair_session_times_does_not_touch_a_session_of_another_workspace() {
+ let (_tmp, mut conn, ws_a, proj_a) = fresh_db();
+ let ws_b = get_or_create_workspace(&mut conn, "other-workspace").unwrap();
+ let proj_b = get_or_create_project(&mut conn, &ws_b, "scratch", None).unwrap();
+ let sid_a = ended_session(&mut conn, ws_a, proj_a);
+ let sid_b = ended_session(&mut conn, ws_b, proj_b);
+ let (original_started_b, original_ended_b) = session_times(&conn, sid_b);
+ let now = Timestamp::now().as_microsecond();
+ let new_started = now - 1_000_000_000;
+
+ let summary = repair_session_times(
+ &mut conn,
+ ws_a,
+ proj_a,
+ &[
+ SessionTimesCandidate {
+ session_id: sid_a,
+ started_at_us: new_started,
+ ended_at_us: None,
+ },
+ SessionTimesCandidate {
+ session_id: sid_b,
+ started_at_us: new_started,
+ ended_at_us: None,
+ },
+ ],
+ now,
+ None,
+ true,
+ )
+ .unwrap();
+
+ assert_eq!(summary.repaired.len(), 1, "{summary:?}");
+ assert_eq!(summary.repaired[0].session_id, sid_a, "control must apply");
+ assert_eq!(summary.skipped.len(), 1);
+ assert_eq!(summary.skipped[0].session_id, sid_b);
+ assert_eq!(summary.skipped[0].reason, SessionTimesSkipReason::NotFound);
+ assert_eq!(
+ session_times(&conn, sid_b),
+ (original_started_b, original_ended_b),
+ "a session in another workspace must not be rewritten"
+ );
+ }
+
+ /// A session id absent from the store entirely is also `NotFound` — the
+ /// same code path as cross-project, so nonexistence never leaks a
+ /// distinguishable status.
+ #[test]
+ fn repair_session_times_reports_unknown_session_as_not_found() {
+ let (_tmp, mut conn, ws, proj) = fresh_db();
+ let now = Timestamp::now().as_microsecond();
+ let summary = repair_session_times(
+ &mut conn,
+ ws,
+ proj,
+ &[SessionTimesCandidate {
+ session_id: SessionId::new(),
+ started_at_us: now - 1_000_000,
+ ended_at_us: None,
+ }],
+ now,
+ None,
+ true,
+ )
+ .unwrap();
+ assert!(summary.repaired.is_empty());
+ assert_eq!(summary.skipped[0].reason, SessionTimesSkipReason::NotFound);
+ }
+
+ /// An open session (`ended_at` still `NULL`) never has an end imposed on
+ /// it, even when the candidate carries one — `started_at` still applies.
+ #[test]
+ fn repair_session_times_never_sets_end_of_an_open_session() {
+ let (_tmp, mut conn, ws, proj) = fresh_db();
+ let sid = open_session(&mut conn, ws, proj);
+ let now = Timestamp::now().as_microsecond();
+ let new_started = now - 1_000_000_000;
+ let summary = repair_session_times(
+ &mut conn,
+ ws,
+ proj,
+ &[SessionTimesCandidate {
+ session_id: sid,
+ started_at_us: new_started,
+ ended_at_us: Some(now - 999_000_000),
+ }],
+ now,
+ None,
+ true,
+ )
+ .unwrap();
+ assert_eq!(summary.repaired.len(), 1, "{summary:?}");
+ assert!(summary.repaired[0].end_kept_open);
+ assert_eq!(session_times(&conn, sid), (new_started, None));
+ }
+
+ /// Negative, zero, inverted, and future times are refused outright —
+ /// nothing is written for that candidate.
+ #[test]
+ fn repair_session_times_refuses_bad_times() {
+ let (_tmp, mut conn, ws, proj) = fresh_db();
+ let now = Timestamp::now().as_microsecond();
+ let cases = [
+ (
+ "negative start",
+ SessionTimesCandidate {
+ session_id: SessionId::new(),
+ started_at_us: -1,
+ ended_at_us: None,
+ },
+ SessionTimesSkipReason::InvalidTime,
+ ),
+ (
+ "inverted",
+ SessionTimesCandidate {
+ session_id: SessionId::new(),
+ started_at_us: now - 1_000,
+ ended_at_us: Some(now - 2_000),
+ },
+ SessionTimesSkipReason::InvertedTimes,
+ ),
+ (
+ "future start",
+ SessionTimesCandidate {
+ session_id: SessionId::new(),
+ started_at_us: now + 60 * 60 * 1_000_000,
+ ended_at_us: None,
+ },
+ SessionTimesSkipReason::FutureTime,
+ ),
+ ];
+ for (label, mut candidate, expected_reason) in cases {
+ let sid = ended_session(&mut conn, ws, proj);
+ candidate.session_id = sid;
+ let (original_started, original_ended) = session_times(&conn, sid);
+ let summary =
+ repair_session_times(&mut conn, ws, proj, &[candidate], now, None, true).unwrap();
+ assert!(summary.repaired.is_empty(), "{label}: {summary:?}");
+ assert_eq!(summary.skipped[0].reason, expected_reason, "{label}");
+ assert_eq!(
+ session_times(&conn, sid),
+ (original_started, original_ended),
+ "{label}: must not write anything"
+ );
+ }
+ }
+
+ /// The core bug-signature guard (B1): a session already correctly dated
+ /// by hook capture (its stored `started_at` already sits at or before
+ /// the candidate's own end) must NOT be rewritten, even though the
+ /// candidate itself is perfectly well-formed — this endpoint repairs the
+ /// backfill bug, it is not a generic "set session times" primitive.
+ /// Control: a genuinely flattened sibling session (stored `started_at`
+ /// AFTER the candidate's end, the import-time symptom) is repaired in
+ /// the same batch.
+ #[test]
+ fn repair_session_times_does_not_touch_an_already_correctly_dated_session() {
+ let (_tmp, mut conn, ws, proj) = fresh_db();
+ let correct_sid = SessionId::new();
+ let correct_started: i64 = 1_700_000_000_000_000;
+ let correct_ended: i64 = 1_700_000_100_000_000; // 100s later
+ begin_session(&mut conn, &hook_session(correct_sid, ws, proj, None)).unwrap();
+ conn.execute(
+ "UPDATE sessions SET started_at = ?1, ended_at = ?2 WHERE id = ?3",
+ params![correct_started, correct_ended, &correct_sid.as_bytes()[..]],
+ )
+ .unwrap();
+ // A flattened sibling: real transcript span ends well before its
+ // stored `started_at` (the import-time stamp).
+ let flattened_sid = ended_session(&mut conn, ws, proj);
+
+ let now = Timestamp::now().as_microsecond();
+ // The candidate for the correctly-dated session repeats its own
+ // start and nearly (not exactly, to keep this test distinct from the
+ // dedicated `Unchanged` one) its own end: if this guard did not
+ // exist, the row would still be rewritten to a value it never should
+ // have been touched for, while being counted as a "repair" of a
+ // session that was never broken.
+ let candidate_correct = SessionTimesCandidate {
+ session_id: correct_sid,
+ started_at_us: correct_started,
+ ended_at_us: Some(correct_ended - 1),
+ };
+ let candidate_flattened = SessionTimesCandidate {
+ session_id: flattened_sid,
+ started_at_us: now - 1_000_000_000,
+ ended_at_us: Some(now - 999_000_000),
+ };
+
+ let summary = repair_session_times(
+ &mut conn,
+ ws,
+ proj,
+ &[candidate_correct, candidate_flattened],
+ now,
+ None,
+ true,
+ )
+ .unwrap();
+
+ assert_eq!(summary.repaired.len(), 1, "{summary:?}");
+ assert_eq!(
+ summary.repaired[0].session_id, flattened_sid,
+ "control (flattened session) must be repaired"
+ );
+ assert_eq!(summary.skipped.len(), 1);
+ assert_eq!(summary.skipped[0].session_id, correct_sid);
+ assert_eq!(
+ summary.skipped[0].reason,
+ SessionTimesSkipReason::NotFlattened
+ );
+ assert_eq!(
+ session_times(&conn, correct_sid),
+ (correct_started, Some(correct_ended)),
+ "a correctly-dated hook-captured session must not be touched"
+ );
+ }
+
+ /// S2: a candidate that already matches the stored row exactly is
+ /// `Unchanged`, not counted as repaired, and issues no `UPDATE` — checked
+ /// before the flattened-signature judgement, so an exact repeat is a
+ /// no-op regardless of whether the row happens to look flattened.
+ #[test]
+ fn repair_session_times_skips_a_candidate_identical_to_the_stored_row() {
+ let (_tmp, mut conn, ws, proj) = fresh_db();
+ let sid = SessionId::new();
+ let started: i64 = 1_700_000_000_000_000;
+ let ended: i64 = 1_700_000_100_000_000; // a normal, sane span
+ begin_session(&mut conn, &hook_session(sid, ws, proj, None)).unwrap();
+ conn.execute(
+ "UPDATE sessions SET started_at = ?1, ended_at = ?2 WHERE id = ?3",
+ params![started, ended, &sid.as_bytes()[..]],
+ )
+ .unwrap();
+ let now = Timestamp::now().as_microsecond();
+
+ let summary = repair_session_times(
+ &mut conn,
+ ws,
+ proj,
+ &[SessionTimesCandidate {
+ session_id: sid,
+ started_at_us: started,
+ ended_at_us: Some(ended),
+ }],
+ now,
+ None,
+ true,
+ )
+ .unwrap();
+ assert!(summary.repaired.is_empty(), "{summary:?}");
+ assert_eq!(summary.skipped[0].reason, SessionTimesSkipReason::Unchanged);
+ assert_eq!(session_times(&conn, sid), (started, Some(ended)));
+ }
+
+ /// S3: a closed session whose candidate omits `ended_at_us` (leaving the
+ /// stored end alone) must still be refused when its proposed `started_at`
+ /// would land after that surviving end — an omitted end must not let a
+ /// candidate invert the row by the back door.
+ #[test]
+ fn repair_session_times_refuses_a_start_past_the_surviving_end() {
+ let (_tmp, mut conn, ws, proj) = fresh_db();
+ let sid = SessionId::new();
+ let old_started: i64 = 2_000_000_000_000_000; // far in the future of `ended`
+ let old_ended: i64 = 1_000_000_000_000_000;
+ begin_session(&mut conn, &hook_session(sid, ws, proj, None)).unwrap();
+ conn.execute(
+ "UPDATE sessions SET started_at = ?1, ended_at = ?2 WHERE id = ?3",
+ params![old_started, old_ended, &sid.as_bytes()[..]],
+ )
+ .unwrap();
+ let now = Timestamp::now().as_microsecond();
+ // No `ended_at_us`: the stored `ended_at` (1_000_000_000_000_000)
+ // survives, but this proposed start sits after it.
+ let candidate = SessionTimesCandidate {
+ session_id: sid,
+ started_at_us: 1_500_000_000_000_000,
+ ended_at_us: None,
+ };
+
+ let summary =
+ repair_session_times(&mut conn, ws, proj, &[candidate], now, None, true).unwrap();
+ assert!(summary.repaired.is_empty(), "{summary:?}");
+ assert_eq!(
+ summary.skipped[0].reason,
+ SessionTimesSkipReason::InvertedTimes
+ );
+ assert_eq!(session_times(&conn, sid), (old_started, Some(old_ended)));
+ }
+
/// Embeddings are keyed by page_id (PK). Re-storing for the same
/// page must REPLACE, not duplicate — otherwise `ai-memory embed
/// --reembed` would multiply rows on each run.
diff --git a/crates/ai-memory-store/src/writer.rs b/crates/ai-memory-store/src/writer.rs
index 94f5ea1c..fbba5cb9 100644
--- a/crates/ai-memory-store/src/writer.rs
+++ b/crates/ai-memory-store/src/writer.rs
@@ -433,6 +433,19 @@ pub(crate) enum WriteCmd {
commit: bool,
reply: oneshot::Sender<StoreResult<MoveSessionSummary>>,
},
+ /// Validate and, when `commit`, apply a batch of session-time
+ /// corrections scoped to `(workspace_id, project_id)`, in one
+ /// transaction (`ai-memory repair-backfill-timestamps`). `commit = false`
+ /// rolls back after validating, so the reply is an exact dry run.
+ RepairSessionTimes {
+ workspace_id: WorkspaceId,
+ project_id: ProjectId,
+ candidates: Vec<ops::SessionTimesCandidate>,
+ now_us: i64,
+ author_id: Option<UserId>,
+ commit: bool,
+ reply: oneshot::Sender<StoreResult<ops::RepairSessionTimesSummary>>,
+ },
/// Rename a project's `name` column without moving any files (the wiki
/// is flat on disk). Fails with [`crate::error::StoreError::ProjectNameTaken`]
/// when `new_name` is already used in the same workspace.
@@ -1889,6 +1902,39 @@ impl WriterHandle {
rx.await.map_err(|_| StoreError::WriterClosed)?
}
+ /// Validate and, when `commit`, apply a batch of session-time
+ /// corrections scoped to `(workspace_id, project_id)`, in one
+ /// transaction. `commit = false` performs the same validation and writes
+ /// then rolls back, so the reply is an exact dry run. See
+ /// [`ops::repair_session_times`].
+ ///
+ /// # Errors
+ /// Returns [`StoreError::WriterClosed`] if the actor has shut down, or
+ /// propagates the SQL error. Per-candidate scope/validation problems are
+ /// reported in the returned summary, not as an `Err`.
+ pub async fn repair_session_times(
+ &self,
+ workspace_id: WorkspaceId,
+ project_id: ProjectId,
+ candidates: Vec<ops::SessionTimesCandidate>,
+ now_us: i64,
+ author_id: Option<UserId>,
+ commit: bool,
+ ) -> StoreResult<ops::RepairSessionTimesSummary> {
+ let (tx, rx) = oneshot::channel();
+ self.send(WriteCmd::RepairSessionTimes {
+ workspace_id,
+ project_id,
+ candidates,
+ now_us,
+ author_id,
+ commit,
+ reply: tx,
+ })
+ .await?;
+ rx.await.map_err(|_| StoreError::WriterClosed)?
+ }
+
/// Rename a project within its workspace (column-only; no file moves).
///
/// # Errors
@@ -3346,6 +3392,26 @@ fn worker_loop(mut conn: Connection, mut rx: mpsc::Receiver<WriteCmd>) {
);
send_or_warn(reply, result, "move_session");
}
+ WriteCmd::RepairSessionTimes {
+ workspace_id,
+ project_id,
+ candidates,
+ now_us,
+ author_id,
+ commit,
+ reply,
+ } => {
+ let result = ops::repair_session_times(
+ &mut conn,
+ workspace_id,
+ project_id,
+ &candidates,
+ now_us,
+ author_id,
+ commit,
+ );
+ send_or_warn(reply, result, "repair_session_times");
+ }
WriteCmd::RenameProject {
workspace_id,
project_id,
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 267b117c..4a2cb294 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -555,7 +555,7 @@ move-project move-session uninstall
auth user completions
handoffs purge-session compact
api-key export-okf message
-doctor backfill
+doctor backfill repair-backfill-timestamps
```
Run `ai-memory --help` for the full tree.
diff --git a/docs/admission-webhooks.md b/docs/admission-webhooks.md
index 81f9a131..3535e687 100644
--- a/docs/admission-webhooks.md
+++ b/docs/admission-webhooks.md
@@ -189,6 +189,9 @@ terminal `purge_project` notification is unchanged.
- **`rename-workspace`** — a `workspaces.name` column update plus refreshed
`_meta.md` manifests; workspace paths are stable UUIDs, so no file move
notification is needed.
+- **`repair-backfill-timestamps`** (`/admin/repair-session-times`) — a
+ `sessions.started_at`/`ended_at` column update only; no wiki page or file
+ is touched, so there is nothing for a mirror to reconcile.
- **External / manual edits on disk** — reconciled by the watcher, not the
admission chain (the chain is for the engine's own write path).
diff --git a/docs/lifecycle-ops.md b/docs/lifecycle-ops.md
index 1848db3d..cf637330 100644
--- a/docs/lifecycle-ops.md
+++ b/docs/lifecycle-ops.md
@@ -16,6 +16,7 @@ on a homelab box where mistakes are harder to undo.
| `/admin/delete-workspace` | ✅ yes | the workspace and every child project | no | Runs `purge_workspace` admission first, deletes SQLite rows in one cascade, removes the UUID-keyed workspace directory and managed-workstream raw segments, reports filesystem partial failures, and dispatches mirror notification after durable work. Logical delete by default; `"compact": true` additionally rebuilds the FTS indexes and `VACUUM`s (see below). |
| `move-project --confirm` | ✅ yes | source only in the merge case (a `Reject`-policy `purge_project` webhook can still abort the source teardown leaving everything intact) | no | Fresh destination → lossless **true move** (re-stamp `workspace_id`, keep `project_id`, rename the dir): sessions/observations/handoffs + history all survive. Destination with a same-named project → **copy+purge merge**: only latest pages migrate. |
| `move-session <id> --to --confirm` | ✅ yes | no | yes (move it back) | Re-stamps one session (or every session touching `--from-project`) into another project: `sessions`, `observations`, its `handoffs`, consolidation jobs, auto-improve runs/claims and its `sessions/<id>.md` page, one transaction per session; the page file moves with it (`--pages move`, default) or is retired for regeneration. Without `--confirm` it is a real dry run (rolled back). Refuses with `409` an open session or a pending consolidation job unless `--force`. |
+| `repair-backfill-timestamps --project --confirm` | ✅ yes | no | yes, if the operator kept the audit row or the CLI's before/after report (nothing else) | Corrects `sessions.started_at`/`ended_at` for sessions an older `backfill` imported before it carried the transcript's own event time. The CLI reads the operator's local transcripts read-only and posts candidate `(session_id, started_at, ended_at)` tuples to `POST /admin/repair-session-times`, which validates each one against `(workspace, project)` — a candidate outside that scope is `not_found` and untouched — only rewrites a row whose `started_at` postdates the candidate's own end (`not_flattened` otherwise, so a correctly hook-captured session or a re-run is a no-op), refuses negative/inverted/future-dated times, and never assigns an end time to a session still open. Without `--confirm` the server validates and reports inside a rolled-back transaction, so it is a real dry run; a confirmed run writes one `audit_log` row per request with the before/after times. Touches only the two timestamp columns of rows already in scope; `observations` and pages (including the session's own page frontmatter) are untouched. |
| `backup --to` | ✅ yes | no | n/a | Streams a gzipped tarball from the server's online `sqlite3 .backup` plus the wiki tree. Safe alongside the live writer. |
| `checkpoints` | ✅ yes | no | n/a | Lists recent wiki git checkpoints. Read-only. |
| `restore-page --path --from` | ✅ yes | overwrites one markdown page version | yes (restore another checkpoint) | Restores one page from wiki git history, reindexes it into SQLite, and writes a post-restore checkpoint. Does not restore DB-only state. |
@@ -613,6 +614,93 @@ The dry run therefore names each scope it would drain, with counts:
`POST /admin/move-session` reports the same list as `source_scopes`. Read it
before confirming.
+### `repair-backfill-timestamps`
+
+```bash
+# Dry run: report what would change for this project
+ai-memory repair-backfill-timestamps --project my-app
+# Apply
+ai-memory repair-backfill-timestamps --project my-app --confirm
+```
+
+Corrects `sessions.started_at`/`ended_at` for sessions an older `backfill`
+already imported. `backfill` used to date every imported session at import
+time rather than from the transcript's own event times, flattening the whole
+imported history onto one day; a companion change fixes new imports, and this
+command repairs sessions a pre-fix `backfill` already wrote.
+
+The CLI is the only part that touches the filesystem: it re-reads the
+operator's local harness transcripts read-only (reusing `backfill`'s own
+session discovery, so it looks at exactly the sessions `backfill` itself
+would import for this checkout), and for each one computes the transcript's
+first and last event timestamp. It resolves each transcript's session id the
+same way the hook router does (`SessionId::from_native`: a UUID native id
+as-is, any other native id hashed to a deterministic UUID v5), then posts the
+candidate `(session_id, started_at, ended_at)` list to
+`POST /admin/repair-session-times`, chunked at up to 2,000 candidates per
+request (one transaction each) when the local batch is larger. The server is
+the only part that validates and writes.
+
+**Request.** `POST /admin/repair-session-times` takes `{"workspace",
+"project", "sessions": [{"session_id", "started_at_us", "ended_at_us"?}, ...],
+"confirm"?}`. `sessions` is capped at 2,000 entries per request so a malformed
+or oversized client request cannot grow the write-actor transaction
+unboundedly; over the cap is a 400 before any scope lookup.
+
+**Validation, per candidate, against the row this same transaction reads for
+it (never the caller's belief about it):**
+
+- **Scope containment**, exactly like `purge-session`: a `session_id` that
+ does not belong to `(workspace, project)` — wrong scope or nonexistent — is
+ reported `skipped: {reason: "not_found"}` and left untouched. The two cases
+ are never distinguished, so an id existing in a different project is not
+ leaked to the caller.
+- **A no-op candidate is `"unchanged"`, not counted as repaired.** Checked
+ before the flattened-signature judgement below, so an exact repeat is
+ always a no-op regardless of whether the row happens to look flattened.
+- **The bug's own signature is the gate, not the caller's say-so.** A row is
+ only rewritten when its current `started_at` sits AFTER the candidate's own
+ end (or start, when the candidate carries no end) — the actual shape of
+ "backfill dated this at import time". A row that already sits at or before
+ that point is `"not_flattened"` and left untouched: this endpoint repairs
+ the specific backfill bug, it is not a generic "set session times"
+ primitive that would happily rewrite a correctly hook-captured session's
+ real times. This also makes a re-run against an already-repaired session,
+ or one a fixed `backfill` imported in the first place, a true no-op.
+- **Sane times**: `started_at_us` and `ended_at_us` (when given) must be
+ positive, and `started_at_us` must not be later than the end the row will
+ actually have once the candidate lands (its own new end, or, when that
+ stays unwritten, whatever end the row already had) — otherwise
+ `"invalid_time"` or `"inverted_times"`.
+- **Never into the future**: either time more than five minutes past "now" is
+ `"future_time"`. Clock-skew margin, not a real correction target.
+- **Never closes an open session**: when the session's current `ended_at` is
+ `NULL`, the candidate's `ended_at_us` is silently withheld — `started_at` is
+ still applied, and the report marks that session `end_kept_open: true`
+ rather than skipping it outright.
+
+**Dry run by default.** Without `confirm: true` the server validates and
+computes the exact would-be write inside a transaction it then rolls back, so
+the report (`repaired`, `skipped`, before/after times) is the literal outcome,
+not an estimate — same pattern as `move-session`. `--confirm` applies through
+the single `WriterHandle`, one transaction per request (chunk).
+
+**What it touches.** Only `sessions.started_at`/`ended_at` of rows already in
+the requested scope — never `observations`, pages, or any other table, and
+never a row outside `(workspace, project)`. Session identity (`sessions.id`
+and its 3-tuple scope) is never written; this is a correction of two
+timestamp columns on rows that already exist, not a move or a delete.
+`observations.created_at` and the `sessions/<id>.md` page's own frontmatter
+timestamps still carry the old import-day times after a repair — only the
+`sessions` row's two columns are corrected; regenerating the session page
+(e.g. via a fresh consolidation) is what would bring its frontmatter in line.
+
+**Reversibility.** A confirmed batch writes one `audit_log` row (`op =
+"repair_session_times"`) per request with every repaired session's before/
+after times in `detail`, and the CLI's human report prints the same old →
+new values per session — an operator who kept either can restore the prior
+values by hand; there is no automatic undo.
+
### `checkpoints`
```bash
diff --git a/docs/security-boundaries.md b/docs/security-boundaries.md
index ac3b7024..d8ec6e44 100644
--- a/docs/security-boundaries.md
+++ b/docs/security-boundaries.md
@@ -38,6 +38,7 @@ boundary not yet built.
| 9 | Scope resolution fail-closed | `ai-memory-store/src/scope.rs` no-create `lookup_existing_*`; create only via `create_explicit_scope` | `scope.rs` no-auto-create + `unscoped_write_with_unresolvable_coordinate_errors` | STRONG |
| 10 | Destructive-op live-process refusal + confirm flags (invariant #9) | `ai-memory-cli/src/commands/process_guard.rs` `sibling_processes` + confirm flags in `reset`/`restore`/`reindex`/`uninstall --purge-data`/`purge_project` | `admin_purge.rs` confirm→400; `removal.rs` — injected live-sibling makes each destructive command bail before touching the data dir | STRONG |
| 10b | Session purge is scope+owner-bound (no cross-session/project over-delete) | `ai-memory-store/src/ops.rs` `purge_session` — selection scoped to `(workspace_id, project_id)` and keyed on this session's own `summary_page_id` **or** `path='sessions/<sid>.md'` + `json_extract(frontmatter_json,'$.session_id')=<sid>` (frontmatter owner, not the recursive latest-chain); `in_scope==0 → NotFound` fail-closed; whole op in one transaction | `ops.rs` `purge_session_leaves_a_sibling_session_in_the_same_project_intact`, `…refuses_a_session_from_another_project_and_deletes_nothing`, `…refuses_a_session_from_another_workspace`, `…does_not_delete_an_identically_pathed_page_in_another_project`, `…removes_older_summary_versions_without_deleting_prior_manual_page` (#862) | STRONG |
+| 10c | Session-time repair is scope-bound (no cross-project timestamp rewrite) | `ai-memory-store/src/ops.rs` `repair_session_times` — every candidate is read back and updated with `WHERE id=? AND workspace_id=? AND project_id=?`; a row outside that 3-tuple is reported `NotFound` and untouched, same code path as an id that does not exist at all; `ai-memory-mcp/src/admin.rs` `handle_repair_session_times` passes the caller's `(workspace, project)` straight through, never the candidate's own | `ops.rs` `repair_session_times_does_not_touch_a_session_of_another_project` (control: sibling session in-scope repaired in the same batch); `admin_repair_session_times.rs` `cross_project_session_is_not_found_and_untouched`; both bite-checked by dropping the `project_id` filter | STRONG |
| 11a | Hook backpressure (202/429) + bounded fan-out (invariant #5) | `ai-memory-hooks/src/router.rs` semaphore→429, 202 immediately, `MAX_HOOK_BATCH_ITEMS`, bounded LRU limiter | `router.rs` `handle_hook_returns_429_when_ingest_saturated`, `ingest_rate_limiter_is_bounded` | STRONG |
| 11b | Capture exclusions drop before storage | `ai-memory-hooks` `capture_policy.rs` `inspect`→`Drop` (before semaphore/spawn) | `capture_policy.rs` per-agent `…honors_exclusions` tests | STRONG |
| 11c | Capture hook ≤200ms budget (invariant #5) | `hooks/_lib.sh` capture path `curl --max-time 0.2` (context-fetch 1.0s and background drain 2.0s are separate, larger-budget paths) | none (shell-script timeout; hard to unit-test) — watch on any capture-path change | WATCH |
diff --git a/docs/usage.md b/docs/usage.md
index 2ab55183..64438af8 100644
--- a/docs/usage.md
+++ b/docs/usage.md
@@ -459,6 +459,23 @@ The session, its observations, handoffs, consolidation jobs and its
[`docs/lifecycle-ops.md`](lifecycle-ops.md#move-session) for the page modes,
guards, and what stays behind.
+## Repair backfilled session timestamps
+
+A `backfill` run from before it carried the transcript's own event time dates
+every imported session at import time, flattening the whole imported history
+onto one day. Re-reading the local transcripts corrects it:
+
+```bash
+ai-memory repair-backfill-timestamps --project my-app # dry run
+ai-memory repair-backfill-timestamps --project my-app --confirm # apply
+```
+
+It matches transcripts to sessions by id, never touches `observations` or
+pages, never assigns an end time to a still-open session, and never proposes
+a time in the future; see
+[`docs/lifecycle-ops.md`](lifecycle-ops.md#repair-backfill-timestamps) for the
+validation rules and the exact request/response shape.
+
## Project consolidation preferences
Create `_prompts/consolidation.md` in a project's wiki when its compiled pages