Skip to content

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

Rust

feat(wiki): add checkpoint page recovery

AkitaOnRailsaa6bd62444c5
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6f0013a6..22cc8d39 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,14 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased]
+### Added
+- Wiki recovery checkpoints now have first-class operator commands:
+ `ai-memory checkpoints` lists recent wiki git commits and
+ `ai-memory restore-page --path <page.md> --from <rev>` restores one page
+ from a checkpoint, writes a new post-restore checkpoint, and reindexes the
+ restored page into SQLite. Startup also creates a one-time upgrade baseline
+ checkpoint for existing wiki trees that had no git commits yet.
+
### Fixed
- Release publication now limits the GitHub Release asset download step to
`ai-memory-*` artifacts, avoiding Docker Buildx side artifacts that can make
diff --git a/README.md b/README.md
index ce7ce4f5..c251f0f0 100644
--- a/README.md
+++ b/README.md
@@ -72,7 +72,7 @@ priors are at the [bottom](#influences-and-prior-art).
- **Karpathy-style LLM wiki.** Pages are compiled from observations
at session-end (or PreCompact), not retrieved over raw logs.
Supersession chain + git-versioned markdown means you can
- time-travel with `git log`.
+ time-travel with `ai-memory checkpoints`, `restore-page`, or raw `git log`.
- **Built-in `/web` browser.** Read-only HTML UI for the wiki -
project list, folder tree, FTS5 search, markdown rendering, dark
mode. Mounted on the same axum server as MCP.
@@ -84,8 +84,9 @@ priors are at the [bottom](#influences-and-prior-art).
with bearer-token auth. Shared servers can opt into
[`[auto_scope]` modes](docs/auto-scope.md) for per-user or
session-aware current-project routing.
-- **Thin-client CLI.** `ai-memory status`, `bootstrap`, `purge-project`,
- `rename-project`, `move-project`, `lint`, `embed`, `forget-sweep`, `backup` are
+- **Thin-client CLI.** `ai-memory status`, `bootstrap`, `checkpoints`,
+ `restore-page`, `purge-project`, `rename-project`, `move-project`, `lint`,
+ `embed`, `forget-sweep`, `backup` are
all HTTP clients of the running server - never touch SQLite or
wiki files directly. `status` also reports passive LLM/embedding
provider health from the last real provider call. Server is the
@@ -132,6 +133,12 @@ priors are at the [bottom](#influences-and-prior-art).
the wiki at `http://<server>:49374/web` - HTTP Basic dialog if
auth is on, paste the token as password. Per-project tree view,
rendered markdown, supersession chain visible per page.
+- **"Undo one bad page edit without rolling back the whole server."**
+ `ai-memory checkpoints` shows recent wiki commits, then
+ `ai-memory restore-page --path notes/foo.md --from <rev>` restores that one
+ markdown file and reindexes it into SQLite. Full `backup` / `restore` is
+ still the answer for DB-only state such as sessions, observations, handoffs,
+ users, audit rows, and embeddings.
- **"Drop an experiment, keep the rest."**
`ai-memory purge-project --project experimental --confirm`.
Atomic: that project's DB rows cascade away, its wiki subdir gets
@@ -317,8 +324,9 @@ created via `ai-memory user add` get their own tokens that resolve to
their identity in audit logs (and, in subsequent milestones, page
frontmatter + the web UI). Data stays single-tenant — there is no
per-page RBAC — but once `[auth].token_pepper` enables multi-user
-mode, operational `/admin/*` endpoints such as backup, purge, move,
-embed, and commit require the root token. Existing single-user installs
+mode, operational `/admin/*` endpoints such as backup, checkpoints,
+restore-page, purge, move, embed, and commit require the root token.
+Existing single-user installs
are not affected unless you opt in by setting `[auth].token_pepper`
(auto-generated for new installs by `ai-memory init`). See
[`docs/users.md`](docs/users.md) for the full walkthrough and the
@@ -500,7 +508,7 @@ diagram, crate breakdown, schema notes, and invariants.
| [`docs/deploy.md`](docs/deploy.md) | Homelab deploy: bin/deploy, bearer-token auth, pointers to the TLS guide. |
| [`docs/users.md`](docs/users.md) | **Multi-user attribution (v0.8).** Four-rung auth ladder, `ai-memory user add/list/expire/revive/rotate-token` walkthrough, backward-compat migration for pre-v0.8 installs, token storage rationale. |
| [`docs/https-via-proxy.md`](docs/https-via-proxy.md) | **HTTPS via a reverse proxy.** When you need TLS (multi-user, non-loopback) and when you don't (loopback / stdio). Copy-paste docker compose templates for Caddy + Let's Encrypt, Caddy + internal CA (LAN-only), Cloudflare Tunnel (no open ports), and external cert files; plus native-Caddy + nginx recipes. The "thinking you're secure when you're not" failure modes explicitly called out. |
-| [`docs/lifecycle-ops.md`](docs/lifecycle-ops.md) | **Read before running purge / rename / backup / restore / reset / reindex.** Safety matrix for the state-touching commands, per-project disk layout (how isolation actually works), and operator workflows for "fresh start", "snapshot before risky op", "drop one project", and rebuilding SQLite from wiki files. |
+| [`docs/lifecycle-ops.md`](docs/lifecycle-ops.md) | **Read before running purge / rename / backup / restore / reset / reindex / restore-page.** Safety matrix for state-touching commands, per-project disk layout (how isolation actually works), checkpoint-based page recovery, and operator workflows for "fresh start", "snapshot before risky op", "drop one project", and rebuilding SQLite from wiki files. |
| [`docs/llm-provider-comparison.md`](docs/llm-provider-comparison.md) | Empirical notes behind the recommended LLM defaults. |
| [`docs/ARCHITECTURE.md`](docs/ARCHITECTURE.md) | Operational summary: data flow, crate layout, cross-cutting invariants, schema. |
| [`docs/design-decisions.md`](docs/design-decisions.md) | The full v1 spec. |
diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rs
index d9a11d10..b82cec05 100644
--- a/crates/ai-memory-cli/src/cli.rs
+++ b/crates/ai-memory-cli/src/cli.rs
@@ -69,6 +69,10 @@ pub enum Command {
InstallMcp(InstallMcpArgs),
/// Stage + commit the wiki tree under git.
Commit(CommitArgs),
+ /// List recent wiki git checkpoints for recovery.
+ Checkpoints(CheckpointsArgs),
+ /// Restore a single wiki page from a git checkpoint and reindex it.
+ RestorePage(RestorePageArgs),
/// Smoke-test an LLM provider by sending one prompt.
LlmTest(LlmTestArgs),
/// Run the M8 retention sweep over episodic pages.
@@ -630,6 +634,37 @@ pub struct RestoreArgs {
pub force: bool,
}
+/// Arguments for `checkpoints`.
+#[derive(Debug, Args)]
+pub struct CheckpointsArgs {
+ /// Maximum number of checkpoints to list.
+ #[arg(short = 'n', long, default_value_t = 20)]
+ pub limit: usize,
+ /// Emit checkpoints as JSON instead of human-readable rows.
+ #[arg(long)]
+ pub json: bool,
+}
+
+/// Arguments for `restore-page`.
+#[derive(Debug, Args)]
+pub struct RestorePageArgs {
+ /// Exact wiki path to restore (e.g. `notes/foo.md`).
+ #[arg(long)]
+ pub path: String,
+ /// Git checkpoint/revision to restore from.
+ #[arg(long)]
+ pub from: String,
+ /// Workspace name. Defaults to `default`.
+ #[arg(long, default_value_t = crate::config::DEFAULT_WORKSPACE.to_string())]
+ pub workspace: String,
+ /// Project name. When omitted, auto-derived from the current project.
+ #[arg(long)]
+ pub project: Option<String>,
+ /// Emit the server response as JSON.
+ #[arg(long)]
+ pub json: bool,
+}
+
/// Arguments for `reindex`.
#[derive(Debug, Args)]
pub struct ReindexArgs {}
diff --git a/crates/ai-memory-cli/src/commands/checkpoints.rs b/crates/ai-memory-cli/src/commands/checkpoints.rs
new file mode 100644
index 00000000..177f244c
--- /dev/null
+++ b/crates/ai-memory-cli/src/commands/checkpoints.rs
@@ -0,0 +1,47 @@
+//! `ai-memory checkpoints` — list recent wiki git checkpoints.
+
+use anyhow::Result;
+use serde::{Deserialize, Serialize};
+
+use crate::cli::CheckpointsArgs;
+use crate::config::Config;
+use crate::http_client::{ServerEndpoint, get_json};
+
+#[derive(Debug, Deserialize, Serialize)]
+struct CheckpointResponse {
+ oid: String,
+ short_oid: String,
+ time: i64,
+ summary: String,
+}
+
+/// Run the `checkpoints` subcommand.
+///
+/// # Errors
+/// Returns an error if the server is unreachable or returns a non-2xx
+/// response.
+pub async fn run(config: &Config, args: CheckpointsArgs) -> Result<()> {
+ let endpoint = ServerEndpoint::from_config(config);
+ let limit = args.limit.to_string();
+ let checkpoints: Vec<CheckpointResponse> = get_json(
+ &endpoint,
+ "/admin/checkpoints",
+ &[("limit", limit.as_str())],
+ )
+ .await?;
+
+ if args.json {
+ println!("{}", serde_json::to_string_pretty(&checkpoints)?);
+ return Ok(());
+ }
+
+ if checkpoints.is_empty() {
+ println!("no wiki checkpoints found");
+ return Ok(());
+ }
+
+ for cp in checkpoints {
+ println!("{} {} {}", cp.short_oid, cp.time, cp.summary);
+ }
+ Ok(())
+}
diff --git a/crates/ai-memory-cli/src/commands/mod.rs b/crates/ai-memory-cli/src/commands/mod.rs
index 9b13ca4c..6161d807 100644
--- a/crates/ai-memory-cli/src/commands/mod.rs
+++ b/crates/ai-memory-cli/src/commands/mod.rs
@@ -8,6 +8,7 @@ pub mod apply_shared;
pub mod auth;
pub mod backup;
pub mod bootstrap;
+pub mod checkpoints;
pub mod commit;
pub mod data_purge;
pub mod delete_page;
@@ -32,6 +33,7 @@ pub mod render_shared;
pub mod reorg;
pub mod reset;
pub mod restore;
+pub mod restore_page;
pub mod search;
pub mod serve;
pub mod setup_agent;
diff --git a/crates/ai-memory-cli/src/commands/restore_page.rs b/crates/ai-memory-cli/src/commands/restore_page.rs
new file mode 100644
index 00000000..d26dc969
--- /dev/null
+++ b/crates/ai-memory-cli/src/commands/restore_page.rs
@@ -0,0 +1,70 @@
+//! `ai-memory restore-page` — restore one wiki page from a git checkpoint.
+
+use anyhow::{Context, Result};
+use serde::{Deserialize, Serialize};
+
+use crate::cli::RestorePageArgs;
+use crate::config::Config;
+use crate::http_client::{ServerEndpoint, post_json};
+
+#[derive(Serialize)]
+struct RestorePageRequest {
+ workspace: String,
+ project: String,
+ path: String,
+ rev: String,
+}
+
+#[derive(Deserialize, Serialize)]
+struct RestorePageResponse {
+ page_id: String,
+ path: String,
+ restored_from: String,
+ #[serde(default)]
+ pre_checkpoint: Option<String>,
+ #[serde(default)]
+ checkpoint: Option<String>,
+}
+
+/// Run the `restore-page` subcommand.
+///
+/// # Errors
+/// Returns an error if the server is unreachable, the checkpoint/path cannot be
+/// restored, or the restored page cannot be reindexed.
+pub async fn run(config: &Config, args: RestorePageArgs) -> Result<()> {
+ let project = super::resolve_project_name(config, args.project.as_deref())?;
+ let endpoint = ServerEndpoint::from_config(config);
+ let resp: RestorePageResponse = post_json(
+ &endpoint,
+ "/admin/restore-page",
+ &RestorePageRequest {
+ workspace: args.workspace.clone(),
+ project: project.clone(),
+ path: args.path.clone(),
+ rev: args.from.clone(),
+ },
+ )
+ .await
+ .context("restoring page via server")?;
+
+ if args.json {
+ println!("{}", serde_json::to_string_pretty(&resp)?);
+ return Ok(());
+ }
+
+ println!(
+ "restored {} under {}/{} from {} (page_id={})",
+ resp.path,
+ args.workspace,
+ project,
+ resp.restored_from,
+ &resp.page_id[..resp.page_id.len().min(8)]
+ );
+ if let Some(pre) = resp.pre_checkpoint {
+ println!("pre-restore checkpoint: {pre}");
+ }
+ if let Some(cp) = resp.checkpoint {
+ println!("restore checkpoint: {cp}");
+ }
+ Ok(())
+}
diff --git a/crates/ai-memory-cli/src/commands/serve.rs b/crates/ai-memory-cli/src/commands/serve.rs
index 5587fb5f..e67be0a7 100644
--- a/crates/ai-memory-cli/src/commands/serve.rs
+++ b/crates/ai-memory-cli/src/commands/serve.rs
@@ -129,6 +129,13 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {
Ok(n) => tracing::info!(count = n, "wrote _meta.md scope manifests"),
Err(e) => tracing::warn!(error = %e, "scope-manifest backfill failed (non-fatal)"),
}
+ match wiki.ensure_upgrade_baseline_checkpoint() {
+ Ok(Some(oid)) => {
+ tracing::info!(checkpoint = %oid, "created wiki upgrade baseline checkpoint")
+ }
+ Ok(None) => {}
+ Err(e) => tracing::warn!(error = %e, "wiki upgrade baseline checkpoint failed (non-fatal)"),
+ }
// Keep the guard alive for the lifetime of `serve`.
let _watcher = start_watcher(&args, &wiki)?;
diff --git a/crates/ai-memory-cli/src/main.rs b/crates/ai-memory-cli/src/main.rs
index b2092465..83543266 100644
--- a/crates/ai-memory-cli/src/main.rs
+++ b/crates/ai-memory-cli/src/main.rs
@@ -68,6 +68,8 @@ async fn main() -> Result<()> {
Command::Hook(_) => unreachable!("hook handled before config load"),
Command::InstallMcp(args) => commands::install_mcp::run(&config, args),
Command::Commit(args) => commands::commit::run(&config, args).await,
+ Command::Checkpoints(args) => commands::checkpoints::run(&config, args).await,
+ Command::RestorePage(args) => commands::restore_page::run(&config, args).await,
Command::LlmTest(args) => commands::llm_test::run(&config, args).await,
Command::ForgetSweep(args) => commands::forget_sweep::run(&config, args).await,
Command::Lint(args) => commands::lint::run(&config, args).await,
diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rs
index 1f9e4880..caa68d29 100644
--- a/crates/ai-memory-mcp/src/admin.rs
+++ b/crates/ai-memory-mcp/src/admin.rs
@@ -11,6 +11,8 @@
//! - `POST /admin/forget-sweep` — run the M8 retention sweep.
//! - `POST /admin/embed` — backfill embeddings for latest pages.
//! - `POST /admin/commit` — stage + commit the wiki tree via git.
+//! - `GET /admin/checkpoints` — list recent wiki git checkpoints.
+//! - `POST /admin/restore-page` — restore one page from a checkpoint.
//! - `POST /admin/purge-project` — delete a project and all its data.
//! - `POST /admin/rename-project` — rename a project (column-only; no files move).
//! - `POST /admin/move-project` — move a project into another workspace
@@ -156,6 +158,8 @@ fn default_chunk_input_tokens() -> usize {
/// - `POST /admin/forget-sweep`
/// - `POST /admin/embed`
/// - `POST /admin/commit`
+/// - `GET /admin/checkpoints`
+/// - `POST /admin/restore-page`
/// - `POST /admin/purge-project`
/// - `POST /admin/rename-project`
/// - `POST /admin/move-project`
@@ -173,6 +177,8 @@ pub fn admin_router(state: AdminState) -> Router {
.route("/admin/forget-sweep", post(handle_forget_sweep))
.route("/admin/embed", post(handle_embed))
.route("/admin/commit", post(handle_commit))
+ .route("/admin/checkpoints", get(handle_checkpoints))
+ .route("/admin/restore-page", post(handle_restore_page))
.route("/admin/purge-project", post(handle_purge_project))
.route("/admin/rename-project", post(handle_rename_project))
.route("/admin/move-project", post(handle_move_project))
@@ -1394,6 +1400,53 @@ struct CommitRequest {
message: String,
}
+#[derive(Debug, Serialize)]
+struct CheckpointResponse {
+ /// Full git commit OID.
+ oid: String,
+ /// First 12 hex characters, useful for CLI display.
+ short_oid: String,
+ /// Commit author timestamp in seconds since Unix epoch.
+ time: i64,
+ /// First line of the commit message.
+ summary: String,
+}
+
+#[derive(Debug, Deserialize)]
+struct CheckpointListQuery {
+ /// Maximum number of checkpoints to return.
+ #[serde(default = "default_checkpoint_limit")]
+ limit: usize,
+}
+
+fn default_checkpoint_limit() -> usize {
+ 20
+}
+
+fn short_oid(oid: &str) -> String {
+ oid.chars().take(12).collect()
+}
+
+fn checkpoint_or_500(
+ wiki: &Wiki,
+ message: impl AsRef<str>,
+) -> Result<Option<String>, (StatusCode, Json<serde_json::Value>)> {
+ wiki.commit_all(message.as_ref())
+ .map(|oid| oid.map(|oid| oid.to_string()))
+ .map_err(|e| internal_err(e.to_string()))
+}
+
+fn checkpoint_or_warn(wiki: &Wiki, message: impl AsRef<str>) -> Option<String> {
+ match wiki.commit_all(message.as_ref()) {
+ Ok(Some(oid)) => Some(oid.to_string()),
+ Ok(None) => None,
+ Err(e) => {
+ warn!(error = %e, "wiki checkpoint failed after mutation");
+ None
+ }
+ }
+}
+
async fn handle_commit(
State(state): State<Arc<AdminState>>,
Json(req): Json<CommitRequest>,
@@ -1420,6 +1473,116 @@ async fn handle_commit(
}
}
+async fn handle_checkpoints(
+ State(state): State<Arc<AdminState>>,
+ Query(query): Query<CheckpointListQuery>,
+) -> impl IntoResponse {
+ let limit = query.limit.clamp(1, 100);
+ match state.wiki.recent_checkpoints(limit) {
+ Ok(checkpoints) => {
+ let checkpoints: Vec<CheckpointResponse> = checkpoints
+ .into_iter()
+ .map(|cp| CheckpointResponse {
+ short_oid: short_oid(&cp.oid),
+ oid: cp.oid,
+ time: cp.time,
+ summary: cp.summary,
+ })
+ .collect();
+ (
+ StatusCode::OK,
+ Json(serde_json::to_value(checkpoints).unwrap_or_else(|_| serde_json::json!([]))),
+ )
+ }
+ Err(e) => internal_err(e.to_string()),
+ }
+}
+
+// ---------------------------------------------------------------------
+// restore-page
+// ---------------------------------------------------------------------
+
+#[derive(Deserialize)]
+struct RestorePageRequest {
+ /// Workspace name. Must exist.
+ workspace: String,
+ /// Project name. Must exist within `workspace`.
+ project: String,
+ /// Relative wiki path to restore.
+ path: String,
+ /// Git revision/commit to restore from.
+ rev: String,
+}
+
+#[derive(Serialize)]
+struct RestorePageResponse {
+ /// UUID of the restored page version.
+ page_id: String,
+ /// Canonical wiki path restored.
+ path: String,
+ /// Revision requested by the caller.
+ restored_from: String,
+ /// Pre-restore checkpoint, if the current tree had changes to save.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pre_checkpoint: Option<String>,
+ /// Post-restore checkpoint, if the restore changed the tree.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ checkpoint: Option<String>,
+}
+
+async fn handle_restore_page(
+ State(state): State<Arc<AdminState>>,
+ Json(req): Json<RestorePageRequest>,
+) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {
+ let path = PagePath::new(req.path.clone()).map_err(|e| {
+ (
+ StatusCode::UNPROCESSABLE_ENTITY,
+ Json(serde_json::json!({ "error": format!("invalid path: {e}") })),
+ )
+ })?;
+ let (ws, proj) = lookup_ws_proj_no_create(&state, &req.workspace, &req.project).await?;
+
+ let pre_checkpoint = checkpoint_or_500(
+ &state.wiki,
+ format!(
+ "pre-restore-page {}/{}: {}",
+ req.workspace,
+ req.project,
+ path.as_str()
+ ),
+ )?;
+
+ let page_id = state
+ .wiki
+ .restore_page_from_checkpoint(ws, proj, path.clone(), &req.rev)
+ .await
+ .map_err(|e| internal_err(e.to_string()))?;
+ let checkpoint = checkpoint_or_warn(
+ &state.wiki,
+ format!(
+ "restore-page {}/{}: {} from {}",
+ req.workspace,
+ req.project,
+ path.as_str(),
+ req.rev
+ ),
+ );
+
+ Ok((
+ StatusCode::OK,
+ Json(
+ serde_json::to_value(RestorePageResponse {
+ page_id: page_id.to_string(),
+ path: path.to_string(),
+ restored_from: req.rev,
+ pre_checkpoint,
+ checkpoint,
+ })
+ .unwrap_or_else(|_| serde_json::json!({})),
+ ),
+ ))
+}
+
// ---------------------------------------------------------------------
// purge-project
// ---------------------------------------------------------------------
@@ -1455,6 +1618,12 @@ pub struct PurgeProjectReport {
pub files_deleted: Vec<String>,
/// Paths that could not be removed from disk (non-fatal; DB rows are gone).
pub files_failed: Vec<String>,
+ /// Pre-purge checkpoint, if the tree had uncommitted changes.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub pre_checkpoint: Option<String>,
+ /// Post-purge checkpoint, if the purge changed the tree.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub checkpoint: Option<String>,
}
async fn handle_purge_project(
@@ -1498,6 +1667,12 @@ async fn handle_purge_project(
Err(e) => return internal_err(e.to_string()),
};
+ let pre_checkpoint = match checkpoint_or_500(&state.wiki, format!("pre-purge-project {label}"))
+ {
+ Ok(oid) => oid,
+ Err(e) => return e,
+ };
+
let summary = match state.writer.purge_project(ws_id, proj_id, &label).await {
Ok(s) => s,
Err(e) => return internal_err(e.to_string()),
@@ -1536,6 +1711,8 @@ async fn handle_purge_project(
}
state.wiki.dispatch_purge_project(dispatch_ctx.as_ref());
+ let checkpoint = checkpoint_or_warn(&state.wiki, format!("purge-project {label}"));
+
let report = PurgeProjectReport {
label: summary.label,
pages_deleted: summary.pages_deleted,
@@ -1545,6 +1722,8 @@ async fn handle_purge_project(
embeddings_deleted: summary.embeddings_deleted,
files_deleted,
files_failed,
+ pre_checkpoint,
+ checkpoint,
};
(
@@ -1580,6 +1759,9 @@ pub struct RenameProjectSummary {
/// Number of `is_latest=1` pages now under the renamed project.
/// No files move — this is purely an informational count.
pub pages: u64,
+ /// Post-rename checkpoint, if `_meta.md` changed.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub checkpoint: Option<String>,
}
async fn handle_rename_project(
@@ -1640,10 +1822,22 @@ async fn handle_rename_project(
};
let summary = RenameProjectSummary {
- workspace: req.workspace,
- from: req.from,
- to: req.to,
+ workspace: req.workspace.clone(),
+ from: req.from.clone(),
+ to: req.to.clone(),
pages,
+ checkpoint: {
+ if let Err(e) = state.wiki.backfill_scope_manifests().await {
+ warn!(error = %e, "rename-project: scope-manifest backfill failed after rename");
+ }
+ checkpoint_or_warn(
+ &state.wiki,
+ format!(
+ "rename-project {}/{} -> {}",
+ req.workspace, req.from, req.to
+ ),
+ )
+ },
};
(
StatusCode::OK,
@@ -1745,6 +1939,12 @@ pub struct MoveProjectReport {
/// under a de-duplicated path so BOTH survive. Each entry is the original
/// source path and the de-duplicated destination path it was written to.
pub conflicts: Vec<PathConflict>,
+ /// Pre-move checkpoint, if the tree had uncommitted changes.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub pre_checkpoint: Option<String>,
+ /// Post-move checkpoint, if the move changed the tree.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub checkpoint: Option<String>,
}
/// One same-path collision resolved by de-duplicating the source page's path.
@@ -1766,6 +1966,7 @@ async fn true_move_project(
req: &MoveProjectRequest,
src_ws: WorkspaceId,
src_proj: ProjectId,
+ pre_checkpoint: Option<String>,
) -> (StatusCode, Json<serde_json::Value>) {
// Ensure the destination workspace ROW exists (FK target for the
// re-stamp) without creating a new project — the existing project_id is
@@ -1843,6 +2044,17 @@ async fn true_move_project(
evict(src_proj);
}
+ if let Err(e) = state.wiki.backfill_scope_manifests().await {
+ warn!(error = %e, "true-move: scope-manifest backfill failed after move");
+ }
+ let checkpoint = checkpoint_or_warn(
+ &state.wiki,
+ format!(
+ "move-project {}/{} -> {}/{}",
+ req.from_workspace, req.project, req.to_workspace, req.project
+ ),
+ );
+
let report = MoveProjectReport {
from: format!("{}/{}", req.from_workspace, req.project),
to: format!("{}/{}", req.to_workspace, req.project),
@@ -1862,6 +2074,8 @@ async fn true_move_project(
files_failed: Vec::new(),
// A true move never copies pages, so it never has a path conflict.
conflicts: Vec::new(),
+ pre_checkpoint,
+ checkpoint,
};
(
StatusCode::OK,
@@ -2006,6 +2220,17 @@ async fn handle_move_project(
Err(e) => return internal_err(e.to_string()),
};
+ let pre_checkpoint = match checkpoint_or_500(
+ &state.wiki,
+ format!(
+ "pre-move-project {}/{} -> {}/{}",
+ req.from_workspace, req.project, req.to_workspace, req.project
+ ),
+ ) {
+ Ok(oid) => oid,
+ Err(e) => return e,
+ };
+
// FRESH destination (no same-named project there) → lossless TRUE MOVE.
// Re-stamp the source project's workspace_id across every domain table in
// one transaction (same project_id), then rename its on-disk dir. This
@@ -2015,7 +2240,7 @@ async fn handle_move_project(
// case, where two project_ids can't be re-stamped into one
// (UNIQUE(workspace_id, name) collision).
if !merged_into_existing {
- return true_move_project(&state, &req, src_ws, src_proj).await;
+ return true_move_project(&state, &req, src_ws, src_proj, pre_checkpoint).await;
}
// MERGE: the destination already holds a same-named project. Get-or-create
@@ -2026,7 +2251,16 @@ async fn handle_move_project(
Err(e) => return e,
};
- copy_purge_merge(&state, &req, src_ws, src_proj, dst_ws, dst_proj).await
+ copy_purge_merge(
+ &state,
+ &req,
+ src_ws,
+ src_proj,
+ dst_ws,
+ dst_proj,
+ pre_checkpoint,
+ )
+ .await
}
/// One source page, with everything the copy loop and the block
@@ -2131,6 +2365,7 @@ async fn copy_purge_merge(
src_proj: ProjectId,
dst_ws: WorkspaceId,
dst_proj: ProjectId,
+ pre_checkpoint: Option<String>,
) -> (StatusCode, Json<serde_json::Value>) {
// Enumerate the source's latest pages (authoritative on is_latest).
let summaries = match state
@@ -2330,6 +2565,13 @@ async fn copy_purge_merge(
// now would destroy data we failed to copy. Report and let the operator
// fix + re-run (re-running is idempotent: copied pages just supersede).
if !pages_skipped.is_empty() {
+ let checkpoint = checkpoint_or_warn(
+ &state.wiki,
+ format!(
+ "move-project-partial {}/{} -> {}/{}",
+ req.from_workspace, req.project, req.to_workspace, req.project
+ ),
+ );
let report = MoveProjectReport {
from: format!("{}/{}", req.from_workspace, req.project),
to: format!("{}/{}", req.to_workspace, req.project),
@@ -2348,6 +2590,8 @@ async fn copy_purge_merge(
files_deleted: Vec::new(),
files_failed: Vec::new(),
conflicts,
+ pre_checkpoint,
+ checkpoint,
};
return (
StatusCode::OK,
@@ -2421,6 +2665,17 @@ async fn copy_purge_merge(
evict(src_proj);
}
+ if let Err(e) = state.wiki.backfill_scope_manifests().await {
+ warn!(error = %e, "copy-purge move: scope-manifest backfill failed after move");
+ }
+ let checkpoint = checkpoint_or_warn(
+ &state.wiki,
+ format!(
+ "move-project {}/{} -> {}/{}",
+ req.from_workspace, req.project, req.to_workspace, req.project
+ ),
+ );
+
let report = MoveProjectReport {
from: label,
to: format!("{}/{}", req.to_workspace, req.project),
@@ -2438,6 +2693,8 @@ async fn copy_purge_merge(
files_deleted,
files_failed,
conflicts,
+ pre_checkpoint,
+ checkpoint,
};
(
StatusCode::OK,
@@ -2490,6 +2747,9 @@ struct WritePageResponse {
page_id: String,
/// Canonical wiki path.
path: String,
+ /// Post-write checkpoint, if the write changed the tree.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ checkpoint: Option<String>,
}
async fn handle_write_page(
@@ -2585,6 +2845,15 @@ async fn handle_write_page(
})
.await
.map_err(|e| internal_err(e.to_string()))?;
+ let checkpoint = checkpoint_or_warn(
+ &state.wiki,
+ format!(
+ "write-page {}/{}: {}",
+ req.workspace,
+ req.project,
+ path.as_str()
+ ),
+ );
Ok((
StatusCode::OK,
@@ -2592,6 +2861,7 @@ async fn handle_write_page(
serde_json::to_value(WritePageResponse {
page_id: page_id.to_string(),
path: path.to_string(),
+ checkpoint,
})
.unwrap_or_else(|_| serde_json::json!({})),
),
@@ -2629,6 +2899,12 @@ struct DeletePageResponse {
/// fails to resolve (so a stale or wrong-scope call never returns a misleading
/// `deleted: true`).
deleted: bool,
+ /// Pre-delete checkpoint, if the tree had uncommitted changes.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pre_checkpoint: Option<String>,
+ /// Post-delete checkpoint, if the delete changed the tree.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ checkpoint: Option<String>,
}
async fn handle_delete_page(
@@ -2650,6 +2926,16 @@ async fn handle_delete_page(
// empty containers and then return `deleted: true` for nothing.
let (ws, proj) = lookup_ws_proj_no_create(&state, &req.workspace, &req.project).await?;
+ let pre_checkpoint = checkpoint_or_500(
+ &state.wiki,
+ format!(
+ "pre-delete-page {}/{}: {}",
+ req.workspace,
+ req.project,
+ path.as_str()
+ ),
+ )?;
+
let actor = actor_ext
.map(|axum::Extension(actor)| actor)
.unwrap_or_else(ai_memory_core::ActorContext::anonymous);
@@ -2675,6 +2961,15 @@ async fn handle_delete_page(
.delete_page(ws, proj, &path, admission_ctx)
.await
.map_err(|e| internal_err(e.to_string()))?;
+ let checkpoint = checkpoint_or_warn(
+ &state.wiki,
+ format!(
+ "delete-page {}/{}: {}",
+ req.workspace,
+ req.project,
+ path.as_str()
+ ),
+ );
Ok((
StatusCode::OK,
@@ -2682,6 +2977,8 @@ async fn handle_delete_page(
serde_json::to_value(DeletePageResponse {
path: path.to_string(),
deleted: true,
+ pre_checkpoint,
+ checkpoint,
})
.unwrap_or_else(|_| serde_json::json!({})),
),
@@ -3365,6 +3662,17 @@ mod tests {
"/admin/commit",
serde_json::json!({"message": "test"}),
),
+ ("GET", "/admin/checkpoints?limit=1", serde_json::Value::Null),
+ (
+ "POST",
+ "/admin/restore-page",
+ serde_json::json!({
+ "workspace": "default",
+ "project": "scratch",
+ "path": "notes/x.md",
+ "rev": "HEAD"
+ }),
+ ),
(
"POST",
"/admin/purge-project",
diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rs
index ebbbe361..603a6aed 100644
--- a/crates/ai-memory-mcp/src/server.rs
+++ b/crates/ai-memory-mcp/src/server.rs
@@ -1225,10 +1225,12 @@ impl AiMemoryServer {
})
.await
.map_err(|e| McpError::internal_error(e.to_string(), None))?;
+ let checkpoint = checkpoint_or_warn(wiki, format!("memory_write_page: {}", path.as_str()));
ok_json(&serde_json::json!({
"page_id": page_id.to_string(),
- "path": path.to_string()
+ "path": path.to_string(),
+ "checkpoint": checkpoint
}))
}
@@ -1390,11 +1392,20 @@ impl AiMemoryServer {
None
};
+ let pre_checkpoint =
+ checkpoint_or_mcp(wiki, format!("pre-memory_delete_page: {}", path.as_str()))?;
+
wiki.delete_page(ws, proj, &path, admission_ctx)
.await
.map_err(|e| McpError::internal_error(e.to_string(), None))?;
+ let checkpoint = checkpoint_or_warn(wiki, format!("memory_delete_page: {}", path.as_str()));
- ok_json(&serde_json::json!({ "path": path.to_string(), "deleted": true }))
+ ok_json(&serde_json::json!({
+ "path": path.to_string(),
+ "deleted": true,
+ "pre_checkpoint": pre_checkpoint,
+ "checkpoint": checkpoint,
+ }))
}
/// Create a handoff snapshot for the next agent CLI.
@@ -1757,6 +1768,23 @@ fn ok_json<T: Serialize>(value: &T) -> Result<CallToolResult, McpError> {
Ok(CallToolResult::success(vec![Content::text(s)]))
}
+fn checkpoint_or_mcp(wiki: &Wiki, message: impl AsRef<str>) -> Result<Option<String>, McpError> {
+ wiki.commit_all(message.as_ref())
+ .map(|oid| oid.map(|oid| oid.to_string()))
+ .map_err(|e| McpError::internal_error(e.to_string(), None))
+}
+
+fn checkpoint_or_warn(wiki: &Wiki, message: impl AsRef<str>) -> Option<String> {
+ match wiki.commit_all(message.as_ref()) {
+ Ok(Some(oid)) => Some(oid.to_string()),
+ Ok(None) => None,
+ Err(e) => {
+ tracing::warn!(error = %e, "wiki checkpoint failed after MCP mutation");
+ None
+ }
+ }
+}
+
fn is_missing_wiki_file(err: &WikiError) -> bool {
matches!(err, WikiError::Io(e) if e.kind() == std::io::ErrorKind::NotFound)
}
diff --git a/crates/ai-memory-mcp/tests/admin_phase3.rs b/crates/ai-memory-mcp/tests/admin_phase3.rs
index 9bf2bc1e..d164bd25 100644
--- a/crates/ai-memory-mcp/tests/admin_phase3.rs
+++ b/crates/ai-memory-mcp/tests/admin_phase3.rs
@@ -68,6 +68,16 @@ async fn post(state: AdminState, uri: &str, body: serde_json::Value) -> axum::re
router.oneshot(req).await.unwrap()
}
+async fn get(state: AdminState, uri: &str) -> axum::response::Response {
+ let router = admin_router(state);
+ let req = Request::builder()
+ .method("GET")
+ .uri(uri)
+ .body(Body::empty())
+ .unwrap();
+ router.oneshot(req).await.unwrap()
+}
+
// ---------------------------------------------------------------------------
// reorg
// ---------------------------------------------------------------------------
@@ -495,3 +505,94 @@ async fn commit_with_new_page_returns_committed_true_and_40char_oid() {
"oid must be all hex digits: {oid}"
);
}
+
+#[tokio::test]
+async fn checkpoints_list_and_restore_page_round_trip() {
+ let tmp = TempDir::new().unwrap();
+ let (state, store) = make_state(&tmp).await;
+ let ws = store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ let proj = store
+ .writer
+ .get_or_create_project(ws, "scratch", None)
+ .await
+ .unwrap();
+ let path = PagePath::new("notes/recover.md").unwrap();
+
+ state
+ .wiki
+ .write_page(WritePageRequest {
+ workspace_id: ws,
+ project_id: proj,
+ path: path.clone(),
+ frontmatter: serde_json::json!({"title": "Recover", "tier": "semantic"}),
+ body: "old body".into(),
+ tier: Tier::Semantic,
+ pinned: false,
+ title: Some("Recover".into()),
+ admission_ctx: None,
+ author_id: None,
+ actor: ai_memory_core::ActorContext::anonymous(),
+ })
+ .await
+ .unwrap();
+ let old_oid = state.wiki.commit_all("old checkpoint").unwrap().unwrap();
+
+ state
+ .wiki
+ .write_page(WritePageRequest {
+ workspace_id: ws,
+ project_id: proj,
+ path: path.clone(),
+ frontmatter: serde_json::json!({"title": "Recover", "tier": "semantic"}),
+ body: "new body".into(),
+ tier: Tier::Semantic,
+ pinned: false,
+ title: Some("Recover".into()),
+ admission_ctx: None,
+ author_id: None,
+ actor: ai_memory_core::ActorContext::anonymous(),
+ })
+ .await
+ .unwrap();
+ state.wiki.commit_all("new checkpoint").unwrap().unwrap();
+
+ let resp = get(state.clone(), "/admin/checkpoints?limit=5").await;
+ assert_eq!(resp.status(), StatusCode::OK);
+ let checkpoints = body_json(resp).await;
+ assert!(
+ checkpoints
+ .as_array()
+ .is_some_and(|rows| rows.iter().any(|row| row["summary"] == "old checkpoint")),
+ "expected old checkpoint in list: {checkpoints}"
+ );
+
+ let resp = post(
+ state.clone(),
+ "/admin/restore-page",
+ json!({
+ "workspace": "default",
+ "project": "scratch",
+ "path": "notes/recover.md",
+ "rev": old_oid.to_string(),
+ }),
+ )
+ .await;
+ assert_eq!(resp.status(), StatusCode::OK);
+ let body = body_json(resp).await;
+ assert_eq!(body["path"], "notes/recover.md");
+ assert_eq!(body["restored_from"], old_oid.to_string());
+
+ let md = state.wiki.read_page(ws, proj, &path).unwrap();
+ assert_eq!(md.body, "old body");
+ let stored = store
+ .reader
+ .page_body_by_ids(ws, proj, "notes/recover.md")
+ .await
+ .unwrap()
+ .expect("restored page should be indexed");
+ assert_eq!(stored.body, "old body");
+}
diff --git a/crates/ai-memory-wiki/src/git.rs b/crates/ai-memory-wiki/src/git.rs
index 9a0f9689..f16d319a 100644
--- a/crates/ai-memory-wiki/src/git.rs
+++ b/crates/ai-memory-wiki/src/git.rs
@@ -7,7 +7,7 @@
use std::path::{Path, PathBuf};
-use git2::{IndexAddOption, Repository, Signature};
+use git2::{IndexAddOption, ObjectType, Repository, Signature};
use tracing::{debug, warn};
use crate::error::{WikiError, WikiResult};
@@ -24,6 +24,17 @@ pub struct GitAdapter {
root: PathBuf,
}
+/// One git checkpoint in the wiki repository.
+#[derive(Debug, Clone)]
+pub struct Checkpoint {
+ /// Full commit OID.
+ pub oid: String,
+ /// Commit summary (first line of the commit message).
+ pub summary: String,
+ /// Author timestamp, seconds since Unix epoch.
+ pub time: i64,
+}
+
impl GitAdapter {
/// Open or initialise the repo at `root`. Idempotent: if the
/// directory is already a git repo, leaves it alone.
@@ -117,6 +128,61 @@ impl GitAdapter {
}
walk.count()
}
+
+ /// Return the most recent commits reachable from HEAD.
+ ///
+ /// Empty repositories return an empty list.
+ ///
+ /// # Errors
+ /// Propagates any underlying libgit2 error.
+ pub fn recent_checkpoints(&self, limit: usize) -> WikiResult<Vec<Checkpoint>> {
+ if limit == 0 {
+ return Ok(Vec::new());
+ }
+ let repo = Repository::open(&self.root).map_err(map_git_err)?;
+ let mut walk = repo.revwalk().map_err(map_git_err)?;
+ if walk.push_head().is_err() {
+ return Ok(Vec::new());
+ }
+ let mut out = Vec::with_capacity(limit.min(100));
+ for oid in walk.take(limit) {
+ let oid = oid.map_err(map_git_err)?;
+ let commit = repo.find_commit(oid).map_err(map_git_err)?;
+ out.push(Checkpoint {
+ oid: oid.to_string(),
+ summary: commit.summary().unwrap_or("(no summary)").to_string(),
+ time: commit.time().seconds(),
+ });
+ }
+ Ok(out)
+ }
+
+ /// Read `path` as it existed at `rev`.
+ ///
+ /// `path` is relative to the wiki repo root. The returned bytes are the
+ /// blob contents exactly as stored in git.
+ ///
+ /// # Errors
+ /// Returns [`WikiError`] when the revision, path, or blob cannot be read.
+ pub fn file_at_rev(&self, rev: &str, path: &Path) -> WikiResult<Vec<u8>> {
+ let repo = Repository::open(&self.root).map_err(map_git_err)?;
+ let object = repo.revparse_single(rev).map_err(map_git_err)?;
+ let commit = object.peel_to_commit().map_err(map_git_err)?;
+ let tree = commit.tree().map_err(map_git_err)?;
+ let entry = tree.get_path(path).map_err(map_git_err)?;
+ let blob = entry
+ .to_object(&repo)
+ .map_err(map_git_err)?
+ .peel(ObjectType::Blob)
+ .map_err(map_git_err)?;
+ let blob = blob.as_blob().ok_or_else(|| {
+ WikiError::Io(std::io::Error::other(format!(
+ "{} at {rev} is not a file",
+ path.display()
+ )))
+ })?;
+ Ok(blob.content().to_vec())
+ }
}
fn map_git_err(e: git2::Error) -> WikiError {
@@ -169,4 +235,39 @@ mod tests {
assert!(oid.is_some());
assert_eq!(adapter.commit_count(), 2);
}
+
+ #[test]
+ fn recent_checkpoints_returns_newest_first() {
+ let tmp = TempDir::new().unwrap();
+ let root = tmp.path().join("wiki");
+ let adapter = GitAdapter::open_or_init(&root).unwrap();
+
+ std::fs::write(root.join("a.md"), "one").unwrap();
+ let first = adapter.commit_all("first checkpoint").unwrap().unwrap();
+ std::fs::write(root.join("a.md"), "two").unwrap();
+ let second = adapter.commit_all("second checkpoint").unwrap().unwrap();
+
+ let checkpoints = adapter.recent_checkpoints(10).unwrap();
+ assert_eq!(checkpoints.len(), 2);
+ assert_eq!(checkpoints[0].oid, second.to_string());
+ assert_eq!(checkpoints[0].summary, "second checkpoint");
+ assert_eq!(checkpoints[1].oid, first.to_string());
+ }
+
+ #[test]
+ fn file_at_rev_reads_historical_blob() {
+ let tmp = TempDir::new().unwrap();
+ let root = tmp.path().join("wiki");
+ let adapter = GitAdapter::open_or_init(&root).unwrap();
+
+ std::fs::write(root.join("a.md"), "one").unwrap();
+ let first = adapter.commit_all("first").unwrap().unwrap();
+ std::fs::write(root.join("a.md"), "two").unwrap();
+ adapter.commit_all("second").unwrap();
+
+ let bytes = adapter
+ .file_at_rev(&first.to_string(), Path::new("a.md"))
+ .unwrap();
+ assert_eq!(String::from_utf8(bytes).unwrap(), "one");
+ }
}
diff --git a/crates/ai-memory-wiki/src/wiki.rs b/crates/ai-memory-wiki/src/wiki.rs
index cdca7694..3c86a5a4 100644
--- a/crates/ai-memory-wiki/src/wiki.rs
+++ b/crates/ai-memory-wiki/src/wiki.rs
@@ -11,7 +11,7 @@ use tokio::sync::RwLock;
use crate::admission::{AdmissionChain, AdmissionContext, AdmissionOp};
use crate::atomic;
use crate::error::{WikiError, WikiResult};
-use crate::git::GitAdapter;
+use crate::git::{Checkpoint, GitAdapter};
use crate::markdown::{Markdown, derive_title, emit, extract_links, parse};
/// Summary of a [`Wiki::reindex_all`] run.
@@ -173,6 +173,31 @@ impl Wiki {
self.git.commit_all(message)
}
+ /// Return the most recent wiki git checkpoints, newest first.
+ ///
+ /// # Errors
+ /// Propagates [`WikiError`] from the git adapter.
+ pub fn recent_checkpoints(&self, limit: usize) -> WikiResult<Vec<Checkpoint>> {
+ self.git.recent_checkpoints(limit)
+ }
+
+ /// Create the one-time baseline checkpoint for an existing wiki tree that
+ /// was created before git recovery checkpoints existed.
+ ///
+ /// Existing repos with any commit are left untouched. Fresh empty repos
+ /// return `Ok(None)` because there is nothing to commit.
+ ///
+ /// # Errors
+ /// Propagates [`WikiError`] from the git adapter.
+ pub fn ensure_upgrade_baseline_checkpoint(&self) -> WikiResult<Option<git2::Oid>> {
+ if self.git.commit_count() == 0 {
+ self.git
+ .commit_all("upgrade baseline: existing wiki tree before recovery checkpoints")
+ } else {
+ Ok(None)
+ }
+ }
+
/// Path of the wiki root on disk.
#[must_use]
pub fn root(&self) -> &Path {
@@ -311,6 +336,71 @@ impl Wiki {
parse(&raw)
}
+ /// Restore one page from a git checkpoint and reindex it into the store.
+ ///
+ /// The checkpoint path is resolved through the UUID-backed wiki layout, so
+ /// callers address pages by `(workspace_id, project_id, page_path)` while
+ /// git still stores the exact markdown file. The restored file is parsed
+ /// before it is written so a malformed checkpoint cannot replace the live
+ /// disk copy and then fail during indexing.
+ ///
+ /// # Errors
+ /// Returns [`WikiError`] when the revision/path does not exist, the stored
+ /// bytes are not UTF-8 markdown, parsing fails, or the filesystem/store
+ /// update fails.
+ pub async fn restore_page_from_checkpoint(
+ &self,
+ workspace_id: WorkspaceId,
+ project_id: ProjectId,
+ path: PagePath,
+ rev: &str,
+ ) -> WikiResult<PageId> {
+ let rel = PathBuf::from(workspace_id.to_string())
+ .join(project_id.to_string())
+ .join(path.as_str());
+ let bytes = self.git.file_at_rev(rev, &rel)?;
+ let raw = String::from_utf8(bytes).map_err(|e| {
+ WikiError::Io(std::io::Error::other(format!(
+ "{} at {rev} is not valid UTF-8 markdown: {e}",
+ path.as_str()
+ )))
+ })?;
+ let md = parse(&raw)?;
+ let title = derive_title(&md.frontmatter, &md.body, &path);
+ let links = extract_links(&md.body, &path);
+ let pinned = is_slot_path(&path)
+ || md
+ .frontmatter
+ .get("pinned")
+ .and_then(|v| v.as_bool())
+ .unwrap_or(false);
+
+ let _guard = self.mutation_lock.read().await;
+ self.ensure_project_workspace(workspace_id, project_id)
+ .await?;
+ let abs = self.abs_path(workspace_id, project_id, &path);
+ if let Some(parent) = abs.parent() {
+ std::fs::create_dir_all(parent)?;
+ }
+ atomic::write_atomic(&abs, raw.as_bytes())?;
+ let id = self
+ .writer
+ .upsert_page(NewPage {
+ workspace_id,
+ project_id,
+ path,
+ title,
+ body: md.body,
+ tier: Tier::Semantic,
+ frontmatter_json: md.frontmatter,
+ pinned,
+ links,
+ author_id: None,
+ })
+ .await?;
+ Ok(id)
+ }
+
/// Delete the on-disk file for `path` within the given project.
///
/// Returns `Ok(())` when the file was removed or did not exist (idempotent).
@@ -1124,6 +1214,49 @@ mod tests {
);
}
+ #[tokio::test]
+ async fn upgrade_baseline_checkpoint_commits_existing_uncommitted_tree_once() {
+ let tmp = TempDir::new().unwrap();
+ let store = Store::open(tmp.path()).unwrap();
+ let ws = store
+ .writer
+ .get_or_create_workspace("default")
+ .await
+ .unwrap();
+ let proj = store
+ .writer
+ .get_or_create_project(ws, "scratch", None)
+ .await
+ .unwrap();
+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();
+
+ wiki.write_page(req(
+ ws,
+ proj,
+ "notes/baseline.md",
+ "existing page before recovery checkpoints",
+ serde_json::json!({ "title": "Baseline" }),
+ ))
+ .await
+ .unwrap();
+
+ assert_eq!(wiki.git().commit_count(), 0);
+ let oid = wiki
+ .ensure_upgrade_baseline_checkpoint()
+ .unwrap()
+ .expect("existing wiki content should be checkpointed");
+ assert_eq!(wiki.git().commit_count(), 1);
+ assert!(wiki.ensure_upgrade_baseline_checkpoint().unwrap().is_none());
+ assert_eq!(wiki.git().commit_count(), 1);
+
+ let checkpoints = wiki.recent_checkpoints(1).unwrap();
+ assert_eq!(checkpoints[0].oid, oid.to_string());
+ assert_eq!(
+ checkpoints[0].summary,
+ "upgrade baseline: existing wiki tree before recovery checkpoints"
+ );
+ }
+
fn req(
ws: WorkspaceId,
proj: ProjectId,
diff --git a/docs/install.md b/docs/install.md
index a6fedd5e..136da7a3 100644
--- a/docs/install.md
+++ b/docs/install.md
@@ -840,7 +840,7 @@ Two ways to invoke a subcommand against the docker deploy:
```bash
# A) Against the running container (stateful: status, search, backup,
-# forget-sweep, lint, embed).
+# checkpoints, restore-page, forget-sweep, lint, embed).
docker exec ai-memory ai-memory status --json
docker exec ai-memory ai-memory search "karpathy"
docker exec ai-memory ai-memory backup --to /data/snapshot.tar.gz
@@ -861,6 +861,7 @@ docker run --rm akitaonrails/ai-memory:latest --help # full subcommand tree
| `search "<query>"` | `docker exec` | Wiki search with FTS5 + graph/vector RRF |
| `write-page` | `docker exec` | Manual page write (atomic + indexed) |
| `backup --to` / `restore --from` | `docker exec` | Snapshot or restore the data dir |
+| `checkpoints` / `restore-page` | `docker exec` | List wiki git checkpoints or restore one markdown page and reindex it |
| `forget-sweep` / `lint` / `embed` | `docker exec` | Manual maintenance; sweep + lint also run on the server schedule by default |
| `commit -m "…"` | `docker exec` | Stage + commit the wiki tree |
| `reset --confirm` | `docker exec` | Wipe data (refuses while siblings alive) |
diff --git a/docs/lifecycle-ops.md b/docs/lifecycle-ops.md
index d67d689e..054ab409 100644
--- a/docs/lifecycle-ops.md
+++ b/docs/lifecycle-ops.md
@@ -12,6 +12,8 @@ on a homelab box where mistakes are harder to undo.
| `rename-project --from --to` | ✅ yes | no | yes (rename back) | Column-only update on `projects.name`. The on-disk dir is keyed by `project_id` (UUID), so the rename never moves a file. |
| `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. |
| `backup --output-path` | ✅ 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. |
| `restore --from <tarball>` | ❌ **stop the server first** | overwrites the data dir | no (without prior backup) | Refuses if any sibling `ai-memory` process is alive (sysinfo guard). |
| `reset --confirm` | ❌ **stop the server first** | yes, all data | no | Refuses if any sibling `ai-memory` process is alive (sysinfo guard). |
| `reindex` | ❌ **stop the server first** | no wiki wipe; requires a clean DB | only with prior DB backup | Rebuilds pages/links/FTS from `wiki/` using `_meta.md` manifests. Refuses if SQLite already has rows so stale DB-only state cannot survive silently. |
@@ -255,6 +257,63 @@ Failure modes:
directory moved but before SQL committed, the error includes the
exact manual repair.
+### `checkpoints`
+
+```bash
+ai-memory checkpoints
+```
+
+Lists recent wiki git commits, newest first. The short OID is enough for
+`restore-page`, but the JSON output includes the full OID:
+
+```bash
+ai-memory checkpoints --json
+```
+
+What it is for:
+
+- Finding the checkpoint just before a bad page write, delete, purge, move, or
+ restore.
+- Inspecting wiki history without shelling into the server's `wiki/.git` repo.
+
+Startup creates a one-time `upgrade baseline: existing wiki tree before recovery
+checkpoints` commit for existing data dirs whose wiki repo has zero commits.
+Fresh empty installs still have no commit until there is content to save.
+
+### `restore-page`
+
+```bash
+ai-memory restore-page --workspace default --project my-project \
+ --path notes/foo.md --from <checkpoint>
+```
+
+What happens:
+
+1. Server resolves `(workspace, project)` without auto-creating anything.
+2. Server validates the page path.
+3. Server checkpoints the current wiki tree first (`pre-restore-page ...`) when
+ there are uncommitted changes.
+4. Server reads the exact markdown blob for that project/page from git at
+ `--from`, parses it, writes it back to the live wiki tree, and upserts a new
+ latest page row in SQLite so search, links, and `/web` agree with disk.
+5. Server writes a post-restore checkpoint (`restore-page ...`) when the live
+ tree changed.
+
+Failure modes:
+
+- **Workspace or project name not found** → 404, no mutation.
+- **Invalid page path** → 422, no mutation.
+- **Checkpoint or file not found** → 500 with the git/libgit2 error; any
+ pre-restore checkpoint remains as an audit breadcrumb.
+- **Historical markdown is malformed or non-UTF-8** → 500, live file is not
+ replaced.
+
+What it does not recover:
+
+- Sessions, observations, handoffs, users, audit rows, access counters, and
+ embeddings. Those live only in SQLite and require a full `backup` / `restore`
+ if you need to roll them back.
+
### `backup`
```bash