Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(audit): harden wiki reindex rebuild
AkitaOnRails066f1f087d8f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4dfa3f24..42ce38ec 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,6 +6,23 @@ 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+- New `ai-memory reindex` lifecycle command rebuilds the derived SQLite page+ index from the on-disk wiki. It recreates workspace/project rows from+ per-scope `_meta.md` manifests while preserving the UUIDs encoded in the+ wiki tree, then reindexes page markdown into pages, links, and FTS. The+ command refuses to run unless the SQLite store is clean; operators should+ stop the server, back up data, move/remove `db/memory.sqlite`, run+ `reindex`, and recompute embeddings separately with `embed` when needed.+- Wiki startup now backfills per-workspace and per-project `_meta.md` manifests+ containing the human workspace/project names (and `repo_path` for projects)+ so the markdown tree is self-describing enough to rebuild the derived DB.++### Fixed+- Wiki reindexing now treats `log.md` / `log-YYYY-MM.md` as raw hook ledgers+ only when their content opens with the hook log prefix, so ordinary markdown+ pages with reserved-looking names are no longer silently dropped. `_meta.md`+ manifests and direct watcher events also reject symlinks before reading.## [0.12.3] - 2026-06-07diff --git a/README.md b/README.mdindex e76b0d33..b81e23fb 100644--- a/README.md+++ b/README.md@@ -500,7 +500,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.** 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". |+| [`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/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/commands/reindex.rs b/crates/ai-memory-cli/src/commands/reindex.rsindex 493529cb..d6b0b9e6 100644--- a/crates/ai-memory-cli/src/commands/reindex.rs+++ b/crates/ai-memory-cli/src/commands/reindex.rs@@ -39,6 +39,23 @@ pub async fn run(config: &Config, _args: ReindexArgs) -> Result<()> {}let store = Store::open(&config.data_dir).context("opening store for reindex")?;+ let target = store+ .reader+ .reindex_target_status()+ .await+ .context("checking whether the SQLite store is clean for reindex")?;+ if !target.is_clean() {+ bail!(+ "refusing to reindex into a non-empty SQLite store ({counts}). \+ `ai-memory reindex` rebuilds a clean derived DB from wiki files; \+ it is not an in-place dirty-index repair. Stop the server, take a \+ backup, move or remove {db_path}, then re-run reindex. DB-only \+ state (sessions, observations, handoffs, users, audit rows, \+ embeddings, decay counters) is not reconstructed from markdown.",+ counts = target.nonzero_summary(),+ db_path = store.db_path().display(),+ );+ }let wiki = Wiki::new(&config.data_dir, store.writer.clone()).context("opening wiki")?// Reindex is index-rebuild only; embeddings are recomputed separately@@ -64,3 +81,55 @@ pub async fn run(config: &Config, _args: ReindexArgs) -> Result<()> {);Ok(())}++#[cfg(test)]+mod tests {+ use super::*;+ use ai_memory_core::{NewPage, PagePath, Tier};+ use tempfile::TempDir;++ #[tokio::test]+ async fn reindex_refuses_dirty_store() {+ let tmp = TempDir::new().unwrap();+ let config = Config {+ data_dir: tmp.path().to_path_buf(),+ ..Default::default()+ };++ 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();+ store+ .writer+ .upsert_page(NewPage {+ workspace_id: ws,+ project_id: proj,+ path: PagePath::new("notes/stale.md").unwrap(),+ title: "stale".into(),+ body: "stale body".into(),+ tier: Tier::Semantic,+ frontmatter_json: serde_json::json!({}),+ pinned: false,+ links: Vec::new(),+ author_id: None,+ })+ .await+ .unwrap();+ drop(store);++ let err = run(&config, ReindexArgs {}).await.unwrap_err();+ assert!(+ err.to_string()+ .contains("refusing to reindex into a non-empty SQLite store"),+ "dirty DB must be rejected, got {err:#}"+ );+ }+}diff --git a/crates/ai-memory-cli/src/commands/serve.rs b/crates/ai-memory-cli/src/commands/serve.rsindex ae7c3de0..5587fb5f 100644--- a/crates/ai-memory-cli/src/commands/serve.rs+++ b/crates/ai-memory-cli/src/commands/serve.rs@@ -117,7 +117,6 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {"admission webhook chain attached");wiki.with_admission_chain(chain)- .with_store_reader(store.reader.clone())};let provider_health = ProviderHealth::default();let (wiki, embedder) = configure_embedder(config, &store, wiki, &provider_health).await?;diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rsindex 5096fb35..1f9e4880 100644--- a/crates/ai-memory-mcp/src/admin.rs+++ b/crates/ai-memory-mcp/src/admin.rs@@ -1513,7 +1513,7 @@ async fn handle_purge_project(.to_string();let mut files_deleted: Vec<String> = Vec::new();let mut files_failed: Vec<String> = Vec::new();- match state.wiki.remove_project_dir(ws_id, proj_id) {+ match state.wiki.remove_project_dir(ws_id, proj_id).await {Ok(()) => {files_deleted.push(proj_root_str);}@@ -2393,7 +2393,7 @@ async fn copy_purge_merge(.to_string();let mut files_deleted: Vec<String> = Vec::new();let mut files_failed: Vec<String> = Vec::new();- match state.wiki.remove_project_dir(src_ws, src_proj) {+ match state.wiki.remove_project_dir(src_ws, src_proj).await {Ok(()) => files_deleted.push(proj_root_str),Err(e) => {warn!(path = %proj_root_str, error = %e, "move-project: failed to remove source dir");diff --git a/crates/ai-memory-store/src/lib.rs b/crates/ai-memory-store/src/lib.rsindex 22dbc733..b2c16b7f 100644--- a/crates/ai-memory-store/src/lib.rs+++ b/crates/ai-memory-store/src/lib.rs@@ -29,8 +29,9 @@ pub use ops::{EmbeddingWrite, MoveSummary, PurgeSummary, ReorgSummary};pub use reader::{ActivityWindow, BriefingPage, BriefingSnapshot, DecayCandidate, DerivedIndexStatus,EmbeddingTripleCount, HealthDetail, HealthPage, ObservationHit, PageAuthor, PageHit,- PageHitWithMeta, PageLinks, PageMeta, PageSummary, ProjectSummary, ReaderPool, RelatedPage,- ScopeRow, StatusCounts, StoredEmbedding, StoredPageBody, WorkspaceSummary, f32_vec_to_bytes,+ PageHitWithMeta, PageLinks, PageMeta, PageSummary, ProjectSummary, ReaderPool,+ ReindexTargetStatus, RelatedPage, ScopeRow, StatusCounts, StoredEmbedding, StoredPageBody,+ WorkspaceScopeRow, WorkspaceSummary, f32_vec_to_bytes,};pub use users::{TOKEN_HASH_LEN, TOKEN_RAW_LEN, TokenPepper, generate_token, hash_token};pub use writer::WriterHandle;@@ -392,6 +393,38 @@ mod tests {assert_eq!(counts.observations, 0);}+ #[tokio::test]+ async fn reindex_target_status_tracks_clean_and_dirty_store() {+ let tmp = TempDir::new().unwrap();+ let store = Store::open(tmp.path()).unwrap();++ let clean = store.reader.reindex_target_status().await.unwrap();+ assert!(clean.is_clean(), "fresh migrated DB must be reindex-clean");++ let ws = store+ .writer+ .get_or_create_workspace("default")+ .await+ .unwrap();+ let proj = store+ .writer+ .get_or_create_project(ws, "ai-memory", None)+ .await+ .unwrap();+ store+ .writer+ .upsert_page(sample_page(ws, proj, "alpha.md", "body"))+ .await+ .unwrap();++ let dirty = store.reader.reindex_target_status().await.unwrap();+ assert!(+ !dirty.is_clean(),+ "existing rows must block lifecycle reindex"+ );+ assert!(dirty.nonzero_summary().contains("pages=1"));+ }+#[tokio::test]async fn search_finds_inserted_page_and_counts_reflect_supersession() {let tmp = TempDir::new().unwrap();diff --git a/crates/ai-memory-store/src/ops.rs b/crates/ai-memory-store/src/ops.rsindex 13b8196d..7c7250d0 100644--- a/crates/ai-memory-store/src/ops.rs+++ b/crates/ai-memory-store/src/ops.rs@@ -158,6 +158,22 @@ pub fn ensure_workspace_with_id(ON CONFLICT(id) DO NOTHING",params![id.as_bytes(), name, Timestamp::now().as_microsecond()],)?;+ let existing: Option<String> = conn+ .query_row(+ "SELECT name FROM workspaces WHERE id = ?1",+ params![id.as_bytes()],+ |row| row.get(0),+ )+ .optional()?;+ match existing {+ Some(existing) if existing == name => Ok(()),+ Some(existing) => Err(StoreError::Duplicate(format!(+ "workspace id {id} already exists as name '{existing}', not manifest name '{name}'"+ ))),+ None => Err(StoreError::NotFound(format!(+ "workspace id {id} was not inserted"+ ))),+ }?;Ok(())}@@ -181,6 +197,32 @@ pub fn ensure_project_with_id(Timestamp::now().as_microsecond()],)?;+ type ProjectRow = (Vec<u8>, String, Option<String>);+ let existing: Option<ProjectRow> = conn+ .query_row(+ "SELECT workspace_id, name, repo_path FROM projects WHERE id = ?1",+ params![id.as_bytes()],+ |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),+ )+ .optional()?;+ match existing {+ Some((existing_ws, existing_name, existing_repo_path))+ if existing_ws.as_slice() == workspace_id.as_bytes()+ && existing_name == name+ && existing_repo_path.as_deref() == repo_path =>+ {+ Ok(())+ }+ Some((existing_ws, existing_name, existing_repo_path)) => {+ Err(StoreError::Duplicate(format!(+ "project id {id} already exists with workspace_id bytes length {}, name='{existing_name}', repo_path={existing_repo_path:?}; manifest has workspace={workspace_id}, name='{name}', repo_path={repo_path:?}",+ existing_ws.len(),+ )))+ }+ None => Err(StoreError::NotFound(format!(+ "project id {id} was not inserted"+ ))),+ }?;Ok(())}@@ -1245,7 +1287,7 @@ mod tests {//! one-line diff instead of a cascading e2e failure.use super::*;use ai_memory_core::{- LinkTarget, NewHandoff, NewPage, NewSession, PagePath, Tier, WorkspaceId,+ LinkTarget, NewHandoff, NewPage, NewSession, PagePath, ProjectId, Tier, WorkspaceId,};use rusqlite::Connection;use tempfile::TempDir;@@ -2150,6 +2192,35 @@ mod tests {);}+ #[test]+ fn ensure_workspace_with_id_rejects_id_name_mismatch() {+ let (_tmp, mut conn, _ws, _proj) = fresh_db();+ let id = WorkspaceId::new();++ ensure_workspace_with_id(&mut conn, id, "from-manifest").unwrap();+ let err = ensure_workspace_with_id(&mut conn, id, "other-name").unwrap_err();++ assert!(+ matches!(err, StoreError::Duplicate(_)),+ "same workspace id with different name must fail loudly; got {err:?}"+ );+ }++ #[test]+ fn ensure_project_with_id_rejects_existing_id_mismatch() {+ let (_tmp, mut conn, ws, _proj) = fresh_db();+ let id = ProjectId::new();++ ensure_project_with_id(&mut conn, id, ws, "from-manifest", Some("/repo/a")).unwrap();+ let err =+ ensure_project_with_id(&mut conn, id, ws, "renamed", Some("/repo/a")).unwrap_err();++ assert!(+ matches!(err, StoreError::Duplicate(_)),+ "same project id with different manifest data must fail loudly; got {err:?}"+ );+ }+/// V19 data-repair migration: observations whose `project_id`/// disagrees with their session's `project_id` are re-attributed/// to the session's project. Handoffs that carry a session id arediff --git a/crates/ai-memory-store/src/reader.rs b/crates/ai-memory-store/src/reader.rsindex 026a049f..f43aa5d7 100644--- a/crates/ai-memory-store/src/reader.rs+++ b/crates/ai-memory-store/src/reader.rs@@ -110,6 +110,73 @@ pub struct StatusCounts {pub observations: u64,}+/// Counts that must all be zero before `ai-memory reindex` rebuilds the+/// derived SQLite store from wiki files.+#[derive(Debug, Clone, Default, Serialize)]+pub struct ReindexTargetStatus {+ /// Workspace rows already present in SQLite.+ pub workspaces: u64,+ /// Project rows already present in SQLite.+ pub projects: u64,+ /// Page rows, including superseded versions.+ pub pages: u64,+ /// Link rows derived from latest page bodies.+ pub links: u64,+ /// Stored embedding rows derived from latest pages.+ pub page_embeddings: u64,+ /// Session rows. These are DB-only episodic state and are not rebuilt.+ pub sessions: u64,+ /// Observation rows. These are DB-only episodic state and are not rebuilt.+ pub observations: u64,+ /// Handoff rows. These are DB-only episodic state and are not rebuilt.+ pub handoffs: u64,+ /// User rows and token hashes. These are DB-only state and are not rebuilt.+ pub users: u64,+ /// Audit rows. These are DB-only state and are not rebuilt.+ pub audit_log: u64,+}++impl ReindexTargetStatus {+ /// True when the store has no user data or derived rows.+ #[must_use]+ pub fn is_clean(&self) -> bool {+ self.workspaces == 0+ && self.projects == 0+ && self.pages == 0+ && self.links == 0+ && self.page_embeddings == 0+ && self.sessions == 0+ && self.observations == 0+ && self.handoffs == 0+ && self.users == 0+ && self.audit_log == 0+ }++ /// Render a compact list of non-zero counters for operator errors.+ #[must_use]+ pub fn nonzero_summary(&self) -> String {+ let mut parts = Vec::new();+ macro_rules! push_nonzero {+ ($field:ident) => {+ if self.$field != 0 {+ parts.push(format!("{}={}", stringify!($field), self.$field));+ }+ };+ }+ push_nonzero!(workspaces);+ push_nonzero!(projects);+ push_nonzero!(pages);+ push_nonzero!(links);+ push_nonzero!(page_embeddings);+ push_nonzero!(sessions);+ push_nonzero!(observations);+ push_nonzero!(handoffs);+ push_nonzero!(users);+ push_nonzero!(audit_log);+ parts.join(", ")+ }+}+/// Derived-index health counters surfaced by admin status.#[derive(Debug, Clone, Default, Serialize)]pub struct DerivedIndexStatus {@@ -230,6 +297,17 @@ pub struct ProjectSummary {pub last_updated: Option<String>,}+/// One workspace scope with the id + name needed to write its+/// self-describing `_meta.md` manifest. Returned by+/// [`ReaderPool::list_all_workspace_scopes`].+#[derive(Debug, Clone)]+pub struct WorkspaceScopeRow {+ /// Workspace id — matches the level-1 wiki directory name.+ pub workspace_id: WorkspaceId,+ /// Human-readable workspace name.+ pub workspace_name: String,+}+/// One `(workspace, project)` scope with the ids + repo_path needed to write/// its self-describing `_meta.md` manifest. Returned by/// [`ReaderPool::list_all_scopes`]; consumed by `Wiki::backfill_scope_manifests`.@@ -2524,6 +2602,72 @@ impl ReaderPool {.collect()}+ /// Return every workspace with its id and name so manifest backfill can+ /// describe even empty workspaces that have no project rows yet.+ ///+ /// # Errors+ /// Propagates any SQL or pool error.+ pub async fn list_all_workspace_scopes(&self) -> StoreResult<Vec<WorkspaceScopeRow>> {+ let raw: Vec<(Vec<u8>, String)> = self+ .with_conn(|conn| {+ let mut stmt = conn.prepare("SELECT id, name FROM workspaces")?;+ let rows = stmt.query_map([], |row| Ok((row.get(0)?, row.get(1)?)))?;+ let out: rusqlite::Result<Vec<_>> = rows.collect();+ Ok(out?)+ })+ .await?;+ raw.into_iter()+ .map(|(wi, wn)| {+ Ok(WorkspaceScopeRow {+ workspace_id: WorkspaceId::from_slice(&wi)?,+ workspace_name: wn,+ })+ })+ .collect()+ }++ /// Return counts that must be zero before `ai-memory reindex` runs.+ ///+ /// `reindex` is a rebuild-from-files operation, not an in-place repair of a+ /// dirty DB. If rows already exist, stale derived rows or DB-only episodic+ /// state could survive and contradict the "rebuilt from wiki" contract.+ ///+ /// # Errors+ /// Propagates any SQL or pool error.+ pub async fn reindex_target_status(&self) -> StoreResult<ReindexTargetStatus> {+ self.with_conn(|conn| {+ Ok(conn.query_row(+ "SELECT \+ (SELECT COUNT(*) FROM workspaces), \+ (SELECT COUNT(*) FROM projects), \+ (SELECT COUNT(*) FROM pages), \+ (SELECT COUNT(*) FROM links), \+ (SELECT COUNT(*) FROM page_embeddings), \+ (SELECT COUNT(*) FROM sessions), \+ (SELECT COUNT(*) FROM observations), \+ (SELECT COUNT(*) FROM handoffs), \+ (SELECT COUNT(*) FROM users), \+ (SELECT COUNT(*) FROM audit_log)",+ [],+ |row| {+ Ok(ReindexTargetStatus {+ workspaces: row.get(0)?,+ projects: row.get(1)?,+ pages: row.get(2)?,+ links: row.get(3)?,+ page_embeddings: row.get(4)?,+ sessions: row.get(5)?,+ observations: row.get(6)?,+ handoffs: row.get(7)?,+ users: row.get(8)?,+ audit_log: row.get(9)?,+ })+ },+ )?)+ })+ .await+ }+/// Return one row per workspace with project/page-count and/// last-updated aggregates. Used by custom frontends that need a/// workspace chooser before narrowing into projects.diff --git a/crates/ai-memory-wiki/src/watcher.rs b/crates/ai-memory-wiki/src/watcher.rsindex 4c151065..40c60bf1 100644--- a/crates/ai-memory-wiki/src/watcher.rs+++ b/crates/ai-memory-wiki/src/watcher.rs@@ -8,7 +8,8 @@//! Own-writes are absorbed by the store's sha256 short-circuit, so//! the loop terminates after one no-op reindex.//! 2. **Reconciliation tick** every 30s walks the entire wiki tree and-//! reindexes every markdown file. Catches any events the OS dropped+//! reindexes page markdown files (excluding `_meta.md`, bootstrap files,+//! raw event ledgers, and symlinks). Catches any events the OS dropped//! (basic-memory #580 — file watchers go stale under FSEvents buffer//! overflow, hidden-dir globs, etc.). Hidden-directory paths are//! explicitly NOT skipped (#798 lesson).@@ -203,13 +204,24 @@ async fn handle_event(wiki: &Wiki, event: notify_debouncer_full::DebouncedEvent)return;}for raw_path in &event.paths {- if raw_path.is_dir() {+ let Ok(metadata) = std::fs::symlink_metadata(raw_path) else {+ // Likely a transient state (mv, atomic rename in flight).+ continue;+ };+ let ft = metadata.file_type();+ if ft.is_symlink() {+ continue;+ }+ if ft.is_dir() {let Some((ws, proj, proj_root)) = extract_project_dir_ids(wiki.root(), raw_path) else {continue;};reindex_project_dir(wiki, ws, proj, proj_root).await;continue;}+ if !ft.is_file() {+ continue;+ }if !is_markdown(raw_path) {continue;}@@ -222,10 +234,6 @@ async fn handle_event(wiki: &Wiki, event: notify_debouncer_full::DebouncedEvent)if is_reserved_page_file(raw_path, &page_path) {continue;}- if !raw_path.is_file() {- // Likely a transient state (mv, atomic rename in flight).- continue;- }match wiki.reindex_page(ws, proj, page_path.clone()).await {Ok(_) => debug!(path = %page_path, "reindexed via watcher"),Err(e) => warn!(path = %page_path, error = %e, "watcher reindex failed"),@@ -439,9 +447,18 @@ fn is_manifest_filename(page_path: &PagePath) -> bool {/// entries, never YAML frontmatter.fn is_log_ledger_filename(page_path: &PagePath) -> bool {let s = page_path.as_str();- s == "log.md"- // log-YYYY-MM.md — 7 chars between the dash and the dot.- || (s.starts_with("log-") && s.ends_with(".md") && s.len() == "log-YYYY-MM.md".len())+ s == "log.md" || is_rotated_log_filename(s)+}++fn is_rotated_log_filename(s: &str) -> bool {+ let Some(stem) = s.strip_prefix("log-").and_then(|v| v.strip_suffix(".md")) else {+ return false;+ };+ let bytes = stem.as_bytes();+ bytes.len() == "YYYY-MM".len()+ && bytes[4] == b'-'+ && bytes[..4].iter().all(|b| b.is_ascii_digit())+ && bytes[5..].iter().all(|b| b.is_ascii_digit())}/// Cheap peek: does the file open with a `---` YAML frontmatter fence?@@ -455,21 +472,34 @@ fn opens_with_frontmatter(abs: &Path) -> bool {BufReader::new(file).read_line(&mut line).is_ok() && line.trim_end() == "---"}+/// Cheap check for the raw hook event ledger shape. Real page markdown can be+/// frontmatter-free; a reserved-looking filename is only a ledger when the+/// content starts with the hook log prefix.+fn opens_with_log_ledger(abs: &Path) -> bool {+ use std::io::{BufRead, BufReader};+ let Ok(file) = std::fs::File::open(abs) else {+ return false;+ };+ let mut line = String::new();+ BufReader::new(file)+ .read_line(&mut line)+ .is_ok_and(|_| line.starts_with("## ["))+}+/// Returns `true` for markdown files that are NOT wiki pages and must be/// skipped by the indexer:/// - `_meta.md` (the self-describing scope manifest) and `bootstrap.md` —/// always; and-/// - the raw event ledger (`log.md` / `log-YYYY-MM.md`) — skipping which+/// - the raw event ledger (`log.md` / exact `log-YYYY-MM.md`) — skipping which/// avoids supersession loops, since every `append_event` write triggers a-/// watcher event. **Unless** a file that merely collides with a ledger name-/// actually carries YAML frontmatter: then it is a genuine page (e.g. a page-/// that happens to live at `log.md`) and IS indexed, so it is never silently-/// dropped on a reindex.+/// watcher event. A reserved-looking filename is skipped only when its+/// content opens with the raw hook log prefix; ordinary markdown pages with+/// those names are indexed.fn is_reserved_page_file(abs: &Path, page_path: &PagePath) -> bool {if is_manifest_filename(page_path) || page_path.as_str() == "bootstrap.md" {return true;}- is_log_ledger_filename(page_path) && !opens_with_frontmatter(abs)+ is_log_ledger_filename(page_path) && !opens_with_frontmatter(abs) && opens_with_log_ledger(abs)}fn page_path_relative_to(root: &Path, abs: &Path) -> Option<PagePath> {@@ -703,10 +733,19 @@ mod tests {// Single-word unique tokens so FTS5 (which parses hyphens as// operators) can match them.std::fs::write(proj_dir.join("real.md"), "real content\n").unwrap();- std::fs::write(proj_dir.join("log.md"), "sessionstarted logtoken unique\n").unwrap();+ std::fs::write(+ proj_dir.join("log.md"),+ "## [2026-06-08T12:34:56Z] session-start | logtoken unique\n",+ )+ .unwrap();std::fs::write(proj_dir.join("log-2026-05.md"),- "sessionstarted rotatedlogtoken unique\n",+ "## [2026-05-01T00:00:00Z] user-prompt | rotatedlogtoken unique\n",+ )+ .unwrap();+ std::fs::write(+ proj_dir.join("log-summary.md"),+ "ordinary markdown summaries regularlogtoken unique\n",).unwrap();std::fs::write(@@ -746,6 +785,18 @@ mod tests {"log-YYYY-MM.md (rotated) must not be indexed");+ let regular_hits = store+ .reader+ .search_pages("regularlogtoken".into(), 5)+ .await+ .unwrap();+ assert_eq!(+ regular_hits.len(),+ 1,+ "ordinary log-looking markdown must still be indexed"+ );+ assert_eq!(regular_hits[0].path.as_str(), "log-summary.md");+let boot_hits = store.reader.search_pages("boottoken".into(), 5)@@ -860,4 +911,42 @@ mod tests {"symlink to outside file must be skipped; got: {names:?}");}++ /// Direct notify events must use the same symlink guard as full-tree walks;+ /// otherwise a symlinked markdown file can be opened before reconciliation+ /// gets a chance to skip it.+ #[cfg(any(unix, windows))]+ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]+ async fn direct_file_event_skips_symlink() {+ let (tmp, store, wiki, ws, proj) = setup().await;+ let proj_dir = tmp+ .path()+ .join("wiki")+ .join(ws.to_string())+ .join(proj.to_string());+ std::fs::create_dir_all(&proj_dir).unwrap();++ let secret = tmp.path().join("outside-secret.md");+ std::fs::write(&secret, "directsymlinksecret should not index\n").unwrap();++ let symlink = proj_dir.join("symlinked.md");+ #[cfg(unix)]+ std::os::unix::fs::symlink(&secret, &symlink).unwrap();+ #[cfg(windows)]+ std::os::windows::fs::symlink_file(&secret, &symlink).unwrap();++ let event = notify_debouncer_full::DebouncedEvent::new(+ notify::Event::new(EventKind::Create(notify::event::CreateKind::File))+ .add_path(symlink),+ std::time::Instant::now(),+ );+ handle_event(&wiki, event).await;++ let hits = store+ .reader+ .search_pages("directsymlinksecret".into(), 5)+ .await+ .unwrap();+ assert!(hits.is_empty(), "direct symlink event must not be indexed");+ }}diff --git a/crates/ai-memory-wiki/src/watcher.rs.bak b/crates/ai-memory-wiki/src/watcher.rs.bakdeleted file mode 100644index cc3cb958..00000000--- a/crates/ai-memory-wiki/src/watcher.rs.bak+++ /dev/null@@ -1,837 +0,0 @@-//! Filesystem watcher with debouncing and a periodic reconciliation pass.-//!-//! Two parts work together:-//!-//! 1. **Debounced events** via [`notify_debouncer_full`]. When a markdown-//! file under the wiki root is created or modified, we read it from-//! disk, parse the frontmatter, and `reindex_page` against the store.-//! Own-writes are absorbed by the store's sha256 short-circuit, so-//! the loop terminates after one no-op reindex.-//! 2. **Reconciliation tick** every 30s walks the entire wiki tree and-//! reindexes every markdown file. Catches any events the OS dropped-//! (basic-memory #580 — file watchers go stale under FSEvents buffer-//! overflow, hidden-dir globs, etc.). Hidden-directory paths are-//! explicitly NOT skipped (#798 lesson).-//!-//! The watcher never *writes* to disk — that loop would be unbounded.-//! External writes drive store updates; internal writes drive disk +-//! store updates via [`Wiki::write_page`].--use std::path::Path;-use std::str::FromStr;-use std::time::Duration;--use ai_memory_core::{PagePath, ProjectId, WorkspaceId};-use notify::{EventKind, RecursiveMode};-use notify_debouncer_full::{DebounceEventResult, Debouncer, RecommendedCache, new_debouncer_opt};-use tokio::sync::mpsc;-use tracing::{debug, info, warn};--use crate::error::{WikiError, WikiResult};-use crate::wiki::Wiki;--/// Reconciliation tick interval.-pub const RECONCILE_INTERVAL: Duration = Duration::from_secs(30);--/// Debounce window for filesystem events.-pub const DEBOUNCE_WINDOW: Duration = Duration::from_millis(300);--#[cfg(all(test, target_os = "macos"))]-type PlatformWatcher = notify::PollWatcher;-#[cfg(not(all(test, target_os = "macos")))]-type PlatformWatcher = notify::RecommendedWatcher;--/// Handle representing an active watcher; drop to stop.-pub struct WatcherHandle {- _debouncer: Debouncer<PlatformWatcher, RecommendedCache>,- shutdown: Option<tokio::sync::oneshot::Sender<()>>,- task: Option<tokio::task::JoinHandle<()>>,-}--impl WatcherHandle {- /// Start watching `wiki.root()` recursively. Spawns one tokio task- /// that consumes debounced events and runs the reconciliation timer.- ///- /// Events are attributed to their `(workspace_id, project_id)` by- /// parsing the first two path segments as UUIDs. Events outside the- /// `<ws_uuid>/<proj_uuid>/...` layout are silently ignored.- ///- /// # Errors- /// Propagates any notify error encountered when installing the OS- /// watcher.- pub fn start(wiki: Wiki) -> WikiResult<Self> {- let (event_tx, event_rx) = mpsc::unbounded_channel();-- let mut debouncer = new_debouncer_opt::<_, PlatformWatcher, RecommendedCache>(- DEBOUNCE_WINDOW,- None,- move |result: DebounceEventResult| match result {- Ok(events) => {- for event in events {- let _ = event_tx.send(event);- }- }- Err(errors) => {- for e in errors {- warn!(error = %e, "notify error");- }- }- },- RecommendedCache::new(),- watcher_config(),- )- .map_err(|e| WikiError::Io(std::io::Error::other(e.to_string())))?;-- debouncer- .watch(wiki.root(), RecursiveMode::Recursive)- .map_err(|e| WikiError::Io(std::io::Error::other(e.to_string())))?;-- let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel::<()>();- let task = tokio::spawn(run_loop(wiki, event_rx, shutdown_rx));-- Ok(Self {- _debouncer: debouncer,- shutdown: Some(shutdown_tx),- task: Some(task),- })- }-- /// Stop the watcher and wait for the event loop to drain.- pub async fn shutdown(mut self) {- if let Some(tx) = self.shutdown.take() {- let _ = tx.send(());- }- if let Some(handle) = self.task.take() {- let _ = handle.await;- }- }-}--impl Drop for WatcherHandle {- fn drop(&mut self) {- if let Some(tx) = self.shutdown.take() {- let _ = tx.send(());- }- }-}--fn watcher_config() -> notify::Config {- let config = notify::Config::default();- #[cfg(all(test, target_os = "macos"))]- {- // GitHub macOS runners have flaky FSEvents delivery for tempdir unit- // tests. Use the polling backend there so the test covers our watcher- // loop without depending on runner-specific FSEvents behavior.- config.with_poll_interval(DEBOUNCE_WINDOW)- }- #[cfg(not(all(test, target_os = "macos")))]- {- config- }-}--async fn run_loop(- wiki: Wiki,- mut rx: mpsc::UnboundedReceiver<notify_debouncer_full::DebouncedEvent>,- mut shutdown: tokio::sync::oneshot::Receiver<()>,-) {- let mut tick = tokio::time::interval(RECONCILE_INTERVAL);- tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);- // First tick fires immediately; consume it so we don't reconcile at boot.- tick.tick().await;-- // Track consecutive failures of the reconciliation pass so we can- // surface a clear "watcher is degraded" event after a streak, in- // addition to the per-failure error log. Without this, a broken- // disk → store bridge can stay broken indefinitely with only a- // line per 30s in the warn stream — easy to miss in busy logs.- let mut consecutive_failures: u32 = 0;- const DEGRADED_AFTER: u32 = 5;-- loop {- tokio::select! {- biased;- _ = &mut shutdown => {- debug!("watcher shutting down");- return;- }- Some(event) = rx.recv() => {- handle_event(&wiki, event).await;- }- _ = tick.tick() => {- match reconcile(&wiki).await {- Ok(()) => {- if consecutive_failures > 0 {- tracing::info!(- prior_failures = consecutive_failures,- "reconciliation recovered after consecutive failures",- );- consecutive_failures = 0;- }- }- Err(e) => {- consecutive_failures += 1;- tracing::error!(- error = %e,- consecutive_failures,- "reconciliation failed",- );- if consecutive_failures == DEGRADED_AFTER {- tracing::error!(- consecutive_failures,- event = "watcher_degraded",- "wiki↔store reconciliation has failed {DEGRADED_AFTER} \- times in a row; the disk and SQLite index may now be \- out of sync. Investigate disk permissions, DB lock \- contention, or filesystem health. The watcher will \- keep retrying every {RECONCILE_INTERVAL:?}.",- );- }- }- }- }- else => return,- }- }-}--async fn handle_event(wiki: &Wiki, event: notify_debouncer_full::DebouncedEvent) {- if !matches!(- event.kind,- EventKind::Create(_) | EventKind::Modify(_) | EventKind::Other- ) {- return;- }- for raw_path in &event.paths {- if raw_path.is_dir() {- let Some((ws, proj, proj_root)) = extract_project_dir_ids(wiki.root(), raw_path) else {- continue;- };- reindex_project_dir(wiki, ws, proj, proj_root).await;- continue;- }- if !is_markdown(raw_path) {- continue;- }- if is_tempfile(raw_path) {- continue;- }- let Some((ws, proj, page_path)) = extract_project_ids(wiki.root(), raw_path) else {- continue;- };- if is_reserved_page_file(raw_path, &page_path) {- continue;- }- if !raw_path.is_file() {- // Likely a transient state (mv, atomic rename in flight).- continue;- }- match wiki.reindex_page(ws, proj, page_path.clone()).await {- Ok(_) => debug!(path = %page_path, "reindexed via watcher"),- Err(e) => warn!(path = %page_path, error = %e, "watcher reindex failed"),- }- }-}--async fn reindex_project_dir(- wiki: &Wiki,- ws: WorkspaceId,- proj: ProjectId,- proj_root: std::path::PathBuf,-) {- let pages = match tokio::task::spawn_blocking(move || walk_markdown(&proj_root)).await {- Ok(Ok(pages)) => pages,- Ok(Err(e)) => {- warn!(error = %e, "watcher directory walk failed");- return;- }- Err(e) => {- warn!(error = %e, "watcher directory walk task failed");- return;- }- };-- for path in pages {- match wiki.reindex_page(ws, proj, path.clone()).await {- Ok(_) => debug!(path = %path, "reindexed via watcher directory event"),- Err(e) => warn!(path = %path, error = %e, "watcher directory reindex failed"),- }- }-}--async fn reconcile(wiki: &Wiki) -> WikiResult<()> {- let root = wiki.root().to_path_buf();- // Walk all per-project subdirectories: <ws_uuid>/<proj_uuid>/- let project_dirs = tokio::task::spawn_blocking(move || walk_project_dirs(&root))- .await- .map_err(|e| WikiError::Io(std::io::Error::other(e.to_string())))??;-- let mut total = 0_usize;- for (ws, proj, proj_root) in project_dirs {- let pages = tokio::task::spawn_blocking(move || walk_markdown(&proj_root))- .await- .map_err(|e| WikiError::Io(std::io::Error::other(e.to_string())))??;- total += pages.len();- for path in pages {- if let Err(e) = wiki.reindex_page(ws, proj, path.clone()).await {- warn!(path = %path, error = %e, "reconcile reindex failed");- }- }- }- info!(count = total, "reconciliation pass complete");- Ok(())-}--/// Walk `<wiki_root>` and return all `(WorkspaceId, ProjectId, proj_root)` tuples-/// whose first two path segments parse as valid UUIDs.-fn walk_project_dirs(- wiki_root: &Path,-) -> WikiResult<Vec<(WorkspaceId, ProjectId, std::path::PathBuf)>> {- let mut out = Vec::new();- let ws_read = match std::fs::read_dir(wiki_root) {- Ok(r) => r,- Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(out),- Err(e) => return Err(WikiError::Io(e)),- };- for ws_entry in ws_read {- let ws_entry = ws_entry?;- if !ws_entry.file_type()?.is_dir() {- continue;- }- let ws_name = ws_entry.file_name();- let Some(ws_str) = ws_name.to_str() else {- continue;- };- let Ok(ws_id) = WorkspaceId::from_str(ws_str) else {- continue;- };- let proj_read = match std::fs::read_dir(ws_entry.path()) {- Ok(r) => r,- Err(_) => continue,- };- for proj_entry in proj_read {- let proj_entry = proj_entry?;- if !proj_entry.file_type()?.is_dir() {- continue;- }- let proj_name = proj_entry.file_name();- let Some(proj_str) = proj_name.to_str() else {- continue;- };- let Ok(proj_id) = ProjectId::from_str(proj_str) else {- continue;- };- out.push((ws_id, proj_id, proj_entry.path()));- }- }- Ok(out)-}--/// Parse `(WorkspaceId, ProjectId, PagePath)` from a filesystem event path.-///-/// Expects the path to have the structure:-/// `<wiki_root>/<ws_uuid>/<proj_uuid>/<page-path...>`-///-/// Returns `None` when:-/// - The path does not start with `wiki_root`.-/// - The first segment is not a valid UUID (`WorkspaceId`).-/// - The second segment is not a valid UUID (`ProjectId`).-/// - There are no remaining segments (the page path would be empty).-pub(crate) fn extract_project_ids(- wiki_root: &Path,- event_path: &Path,-) -> Option<(WorkspaceId, ProjectId, PagePath)> {- let rel = event_path.strip_prefix(wiki_root).ok()?;- let mut components = rel.components();-- let ws_seg = components.next()?.as_os_str().to_str()?;- let ws_id = WorkspaceId::from_str(ws_seg).ok()?;-- let proj_seg = components.next()?.as_os_str().to_str()?;- let proj_id = ProjectId::from_str(proj_seg).ok()?;-- // Rejoin remaining segments as the page path.- let page_rel: std::path::PathBuf = components.collect();- let page_str = page_rel.to_string_lossy().replace('\\', "/");- if page_str.is_empty() {- return None;- }- let page_path = PagePath::new(page_str).ok()?;- Some((ws_id, proj_id, page_path))-}--fn extract_project_dir_ids(- wiki_root: &Path,- event_path: &Path,-) -> Option<(WorkspaceId, ProjectId, std::path::PathBuf)> {- let rel = event_path.strip_prefix(wiki_root).ok()?;- let mut components = rel.components();-- let ws_seg = components.next()?.as_os_str().to_str()?;- let ws_id = WorkspaceId::from_str(ws_seg).ok()?;-- let proj_seg = components.next()?.as_os_str().to_str()?;- let proj_id = ProjectId::from_str(proj_seg).ok()?;-- Some((ws_id, proj_id, wiki_root.join(ws_seg).join(proj_seg)))-}--fn walk_markdown(root: &Path) -> WikiResult<Vec<PagePath>> {- let mut out = Vec::new();- let mut stack = vec![root.to_path_buf()];- while let Some(dir) = stack.pop() {- let read = match std::fs::read_dir(&dir) {- Ok(r) => r,- Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,- Err(e) => return Err(WikiError::Io(e)),- };- for entry in read {- let entry = entry?;- let path = entry.path();- let ft = entry.file_type()?;- // Skip symlinks entirely. An attacker with write access to- // the wiki/ dir could otherwise plant a symlink to /etc/hosts,- // /home/user/.ssh/id_ed25519 etc. and have the watcher- // index the target's content. The sanitiser would still- // scrub credentials, but we'd be reading files we- // shouldn't be reading. (Audit critical #3.)- if ft.is_symlink() {- continue;- }- if ft.is_dir() {- stack.push(path);- } else if ft.is_file()- && is_markdown(&path)- && !is_tempfile(&path)- && let Some(pp) = page_path_relative_to(root, &path)- && !is_reserved_page_file(&path, &pp)- {- out.push(pp);- }- }- }- Ok(out)-}--fn is_markdown(path: &Path) -> bool {- path.extension().is_some_and(|e| e == "md")-}--fn is_tempfile(path: &Path) -> bool {- path.file_name()- .and_then(|n| n.to_str())- .is_some_and(|n| n.starts_with(".ai-memory-tmp."))-}--/// `_meta.md` is the per-scope manifest the engine writes (workspace/project-/// name + repo_path) so the wiki tree is self-describing. It describes the-/// scope, it is never a wiki page.-fn is_manifest_filename(page_path: &PagePath) -> bool {- page_path- .as_str()- .rsplit('/')- .next()- .is_some_and(|name| name == "_meta.md")-}--/// `log.md` / `log-YYYY-MM.md` are the raw per-project event ledger the hooks-/// append to (see `ai-memory-hooks::log::log_filename_for`): `## [ts] ...`-/// entries, never YAML frontmatter.-fn is_log_ledger_filename(page_path: &PagePath) -> bool {- let s = page_path.as_str();- s == "log.md"- // log-YYYY-MM.md — 7 chars between the dash and the dot.- || (s.starts_with("log-") && s.ends_with(".md") && s.len() == "log-YYYY-MM.md".len())-}--/// Cheap peek: does the file open with a `---` YAML frontmatter fence?-/// Used to tell a real page apart from the raw event ledger.-fn opens_with_frontmatter(abs: &Path) -> bool {- use std::io::{BufRead, BufReader};- let Ok(file) = std::fs::File::open(abs) else {- return false;- };- let mut line = String::new();- BufReader::new(file).read_line(&mut line).is_ok() && line.trim_end() == "---"-}--/// Returns `true` for markdown files that are NOT wiki pages and must be-/// skipped by the indexer:-/// - `_meta.md` (the self-describing scope manifest) and `bootstrap.md` —-/// always; and-/// - the raw event ledger (`log.md` / `log-YYYY-MM.md`) — skipping which-/// avoids supersession loops, since every `append_event` write triggers a-/// watcher event. **Unless** a file that merely collides with a ledger name-/// actually carries YAML frontmatter: then it is a genuine page (e.g. a page-/// that happens to live at `log.md`) and IS indexed, so it is never silently-/// dropped on a reindex.-fn is_reserved_page_file(abs: &Path, page_path: &PagePath) -> bool {- if is_manifest_filename(page_path) || page_path.as_str() == "bootstrap.md" {- return true;- }- is_log_ledger_filename(page_path) && !opens_with_frontmatter(abs)-}--fn page_path_relative_to(root: &Path, abs: &Path) -> Option<PagePath> {- let rel: &Path = abs.strip_prefix(root).ok()?;- let s = rel.to_string_lossy().replace('\\', "/");- PagePath::new(s).ok()-}--#[cfg(test)]-mod tests {- use super::*;- use ai_memory_store::Store;- use tempfile::TempDir;-- async fn setup() -> (TempDir, Store, Wiki, WorkspaceId, ProjectId) {- 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();- (tmp, store, wiki, ws, proj)- }-- /// `extract_project_ids` must parse a valid `<ws>/<proj>/<path>` triplet.- #[test]- fn extract_project_ids_valid_path() {- let wiki_root = Path::new("/data/wiki");- let ws_id = WorkspaceId::new();- let proj_id = ProjectId::new();- let event_path =- std::path::PathBuf::from(format!("/data/wiki/{}/{}/decisions/foo.md", ws_id, proj_id));- let result = extract_project_ids(wiki_root, &event_path);- assert!(- result.is_some(),- "must extract IDs from valid namespaced path"- );- let (ws, proj, pp) = result.unwrap();- assert_eq!(ws, ws_id);- assert_eq!(proj, proj_id);- assert_eq!(pp.as_str(), "decisions/foo.md");- }-- /// `extract_project_ids` must return `None` when the first segment is not a UUID.- #[test]- fn extract_project_ids_garbage_first_segment() {- let wiki_root = Path::new("/data/wiki");- let event_path = Path::new("/data/wiki/not-a-uuid/some-proj/foo.md");- assert!(- extract_project_ids(wiki_root, event_path).is_none(),- "garbage first segment must return None"- );- }-- /// `extract_project_ids` must return `None` for flat (non-namespaced) paths.- #[test]- fn extract_project_ids_flat_path_returns_none() {- let wiki_root = Path::new("/data/wiki");- let event_path = Path::new("/data/wiki/foo.md");- assert!(- extract_project_ids(wiki_root, event_path).is_none(),- "flat path with no namespace must return None"- );- }-- /// `extract_project_ids` must return `None` when the second segment is not a valid UUID.- #[test]- fn extract_rejects_garbage_in_project_segment() {- let wiki_root = Path::new("/tmp/wiki");- let ws = WorkspaceId::new().to_string();- let event_path =- std::path::PathBuf::from(format!("/tmp/wiki/{ws}/not-a-uuid/decisions/foo.md"));- assert!(- extract_project_ids(wiki_root, &event_path).is_none(),- "garbage project segment must return None"- );- }-- /// `extract_project_ids` must return `None` when there is no page path- /// after the two UUID segments (would produce an empty `PagePath`).- #[test]- fn extract_rejects_empty_page_path() {- let wiki_root = Path::new("/tmp/wiki");- let ws = WorkspaceId::new().to_string();- let proj = ProjectId::new().to_string();- // Just the project dir itself with no page path beneath.- let event_path = std::path::PathBuf::from(format!("/tmp/wiki/{ws}/{proj}"));- assert!(- extract_project_ids(wiki_root, &event_path).is_none(),- "missing page path must return None"- );- }-- #[tokio::test(flavor = "multi_thread", worker_threads = 2)]- async fn picks_up_externally_created_file() {- let (tmp, store, wiki, ws, proj) = setup().await;-- // Create the project directory BEFORE starting the watcher so- // the inotify backend adds a watch for it immediately. If we- // created it after, there is a race between the new-dir event- // and the file-write event that can cause the watcher to miss- // the file on slower Linux inotify instances.- let proj_dir = tmp- .path()- .join("wiki")- .join(ws.to_string())- .join(proj.to_string());- std::fs::create_dir_all(&proj_dir).unwrap();-- let handle = WatcherHandle::start(wiki.clone()).unwrap();- // FSEvents can report readiness before the recursive watch is fully- // settled. Give the backend one debounce window before creating the- // file so this test checks event delivery, not watcher-start races.- tokio::time::sleep(DEBOUNCE_WINDOW + Duration::from_millis(200)).await;-- // Drop a file inside the per-project directory, bypassing the wiki write API- // (simulating an external editor).- let target = proj_dir.join("external.md");- std::fs::write(&target, "Hello from outside the wiki API.\n").unwrap();-- // Poll for the row to land. Watcher debounces at 300ms; extra- // margin for slow CI environments.- let deadline = std::time::Instant::now() + Duration::from_secs(15);- let mut hits = Vec::new();- while std::time::Instant::now() < deadline {- hits = store- .reader- .search_pages("outside".into(), 5)- .await- .unwrap();- if !hits.is_empty() {- break;- }- tokio::time::sleep(Duration::from_millis(100)).await;- }- assert!(!hits.is_empty(), "watcher did not pick up external write");- assert_eq!(hits[0].path.as_str(), "external.md");- handle.shutdown().await;- }-- #[tokio::test(flavor = "multi_thread", worker_threads = 2)]- async fn directory_event_reindexes_project_markdown() {- let (tmp, store, wiki, ws, proj) = setup().await;- let proj_dir = tmp- .path()- .join("wiki")- .join(ws.to_string())- .join(proj.to_string());- std::fs::create_dir_all(&proj_dir).unwrap();- std::fs::write(- proj_dir.join("external.md"),- "Directory event should reindex this page.\n",- )- .unwrap();-- let event = notify_debouncer_full::DebouncedEvent::new(- notify::Event::new(EventKind::Modify(notify::event::ModifyKind::Any))- .add_path(proj_dir),- std::time::Instant::now(),- );- handle_event(&wiki, event).await;-- let hits = store- .reader- .search_pages("reindex".into(), 5)- .await- .unwrap();- assert_eq!(hits.len(), 1);- assert_eq!(hits[0].path.as_str(), "external.md");- }-- #[tokio::test(flavor = "multi_thread", worker_threads = 2)]- async fn reconcile_picks_up_file_added_while_watcher_offline() {- let (tmp, store, wiki, ws, proj) = setup().await;-- // Write a file BEFORE starting the watcher — directly in the project dir.- let proj_dir = tmp- .path()- .join("wiki")- .join(ws.to_string())- .join(proj.to_string());- std::fs::create_dir_all(&proj_dir).unwrap();- let target = proj_dir.join("preexisting.md");- std::fs::write(&target, "I existed first.\n").unwrap();-- let handle = WatcherHandle::start(wiki.clone()).unwrap();- // Hit reconcile manually instead of waiting 30s.- reconcile(&wiki).await.unwrap();-- let hits = store- .reader- .search_pages("existed".into(), 5)- .await- .unwrap();- assert_eq!(hits.len(), 1);- assert_eq!(hits[0].path.as_str(), "preexisting.md");- handle.shutdown().await;- }-- #[tokio::test(flavor = "multi_thread", worker_threads = 2)]- async fn ignores_own_atomic_tempfiles() {- // Quick unit test: tempfile prefix detection.- let p = Path::new("/some/dir/.ai-memory-tmp.abc.md");- assert!(is_tempfile(p));- let q = Path::new("/some/dir/normal.md");- assert!(!is_tempfile(q));- }-- /// `walk_markdown` must not return `log.md` or `bootstrap.md`- /// (reserved per-project files that must not become wiki pages).- #[tokio::test(flavor = "multi_thread", worker_threads = 2)]- async fn walk_markdown_skips_reserved_filenames() {- let (tmp, store, wiki, ws, proj) = setup().await;-- let proj_dir = tmp- .path()- .join("wiki")- .join(ws.to_string())- .join(proj.to_string());- std::fs::create_dir_all(&proj_dir).unwrap();-- // Write a legitimate page plus the reserved files (legacy- // `log.md`, the rotated `log-YYYY-MM.md`, and `bootstrap.md`).- // Single-word unique tokens so FTS5 (which parses hyphens as- // operators) can match them.- std::fs::write(proj_dir.join("real.md"), "real content\n").unwrap();- std::fs::write(proj_dir.join("log.md"), "sessionstarted logtoken unique\n").unwrap();- std::fs::write(- proj_dir.join("log-2026-05.md"),- "sessionstarted rotatedlogtoken unique\n",- )- .unwrap();- std::fs::write(- proj_dir.join("bootstrap.md"),- "bootstrapmanifest boottoken unique\n",- )- .unwrap();-- let handle = WatcherHandle::start(wiki.clone()).unwrap();- // Trigger the reconciliation pass directly.- reconcile(&wiki).await.unwrap();-- // Only `real.md` should land in the index.- let hits = store- .reader- .search_pages("real content".into(), 5)- .await- .unwrap();- assert_eq!(hits.len(), 1, "only the real page should be indexed");- assert_eq!(hits[0].path.as_str(), "real.md");-- // Neither reserved file should be searchable.- let log_hits = store- .reader- .search_pages("logtoken".into(), 5)- .await- .unwrap();- assert!(log_hits.is_empty(), "log.md must not be indexed");-- let rotated_hits = store- .reader- .search_pages("rotatedlogtoken".into(), 5)- .await- .unwrap();- assert!(- rotated_hits.is_empty(),- "log-YYYY-MM.md (rotated) must not be indexed"- );-- let boot_hits = store- .reader- .search_pages("boottoken".into(), 5)- .await- .unwrap();- assert!(boot_hits.is_empty(), "bootstrap.md must not be indexed");-- handle.shutdown().await;- drop(store);- }-- /// A page that *collides* with a reserved ledger name (`log.md`) but- /// carries YAML frontmatter is a real page and MUST be indexed — not- /// silently dropped. Regression for a prod data anomaly (a page lived at- /// `log.md`) that a filename-only skip would lose on every reindex. The- /// `_meta.md` manifest, by contrast, must NEVER be indexed even though it- /// also has frontmatter.- #[tokio::test(flavor = "multi_thread", worker_threads = 2)]- async fn reindex_page_by_content_not_filename() {- let (tmp, store, wiki, ws, proj) = setup().await;- let proj_dir = tmp- .path()- .join("wiki")- .join(ws.to_string())- .join(proj.to_string());- std::fs::create_dir_all(&proj_dir).unwrap();-- // A genuine page that happens to live at `log.md` (has frontmatter).- std::fs::write(- proj_dir.join("log.md"),- "---\ntitle: Collides With Ledger\n---\nframmaticpage uniquetoken\n",- )- .unwrap();- // The self-describing manifest — never a page, even with frontmatter.- std::fs::write(- proj_dir.join("_meta.md"),- "---\nworkspace: default\nproject: scratch\n---\nmanifesttoken here\n",- )- .unwrap();- // A raw ledger (no frontmatter) — still skipped.- std::fs::write(proj_dir.join("log-2026-06.md"), "## [t] evt | x\nrawledgertoken\n").unwrap();-- let handle = WatcherHandle::start(wiki.clone()).unwrap();- reconcile(&wiki).await.unwrap();-- let page_hits = store.reader.search_pages("uniquetoken".into(), 5).await.unwrap();- assert_eq!(page_hits.len(), 1, "frontmatter page named log.md must be indexed");- assert_eq!(page_hits[0].path.as_str(), "log.md");-- let meta_hits = store.reader.search_pages("manifesttoken".into(), 5).await.unwrap();- assert!(meta_hits.is_empty(), "_meta.md manifest must not be indexed");-- let ledger_hits = store.reader.search_pages("rawledgertoken".into(), 5).await.unwrap();- assert!(ledger_hits.is_empty(), "raw ledger (no frontmatter) must not be indexed");-- handle.shutdown().await;- drop(store);- }-- /// Defence: an attacker who can write to wiki/ shouldn't be able- /// to make the watcher index arbitrary files via symlinks.- #[tokio::test(flavor = "multi_thread", worker_threads = 2)]- async fn walk_markdown_skips_symlinks() {- let tmp = TempDir::new().unwrap();- let proj_root = tmp.path().join("proj");- std::fs::create_dir_all(&proj_root).unwrap();-- // A real file (should be picked up).- std::fs::write(proj_root.join("real.md"), "real content\n").unwrap();-- // A "secret" file outside the project root.- let secret = tmp.path().join("secret.md");- std::fs::write(&secret, "this is sensitive\n").unwrap();-- // Plant a symlink inside proj/ pointing at the outside file.- #[cfg(unix)]- std::os::unix::fs::symlink(&secret, proj_root.join("symlinked.md")).unwrap();- #[cfg(windows)]- std::os::windows::fs::symlink_file(&secret, proj_root.join("symlinked.md")).unwrap();-- let found = walk_markdown(&proj_root).unwrap();- let names: Vec<_> = found.iter().map(|p| p.as_str().to_string()).collect();- assert!(names.contains(&"real.md".to_string()), "real file present");- assert!(- !names.contains(&"symlinked.md".to_string()),- "symlink to outside file must be skipped; got: {names:?}"- );- }-}diff --git a/crates/ai-memory-wiki/src/wiki.rs b/crates/ai-memory-wiki/src/wiki.rsindex 4f6285a7..cdca7694 100644--- a/crates/ai-memory-wiki/src/wiki.rs+++ b/crates/ai-memory-wiki/src/wiki.rs@@ -421,7 +421,7 @@ impl Wiki {let ctx = self.admit_purge_project(workspace_id, project_id, admission_ctx).await?;- self.remove_project_dir(workspace_id, project_id)?;+ self.remove_project_dir(workspace_id, project_id).await?;self.dispatch_purge_project(ctx.as_ref());Ok(())}@@ -454,11 +454,12 @@ impl Wiki {////// # Errors/// Returns [`WikiError::Io`] on filesystem errors other than NotFound.- pub fn remove_project_dir(+ pub async fn remove_project_dir(&self,workspace_id: WorkspaceId,project_id: ProjectId,) -> WikiResult<()> {+ let _guard = self.mutation_lock.write().await;let root = self.project_root(workspace_id, project_id);match std::fs::remove_dir_all(&root) {Ok(()) => Ok(()),@@ -526,7 +527,15 @@ impl Wiki {/// Read a `_meta.md` scope-manifest's frontmatter from `dir`.fn read_scope_meta(dir: &Path) -> WikiResult<serde_json::Value> {- let raw = std::fs::read_to_string(dir.join("_meta.md"))?;+ let path = dir.join("_meta.md");+ let meta = std::fs::symlink_metadata(&path)?;+ if meta.file_type().is_symlink() {+ return Err(WikiError::Io(std::io::Error::other(format!(+ "refusing to read symlinked scope manifest {}",+ path.display()+ ))));+ }+ let raw = std::fs::read_to_string(path)?;Ok(parse(&raw)?.frontmatter)}@@ -619,8 +628,19 @@ impl Wiki {body: String::new(),})?;let path = dir.join("_meta.md");- if std::fs::read_to_string(&path).is_ok_and(|existing| existing == content) {- return Ok(false);+ match std::fs::symlink_metadata(&path) {+ Ok(meta) if meta.file_type().is_symlink() => {+ return Err(WikiError::Io(std::io::Error::other(format!(+ "refusing to update symlinked scope manifest {}",+ path.display()+ ))));+ }+ Ok(meta) if meta.is_file() => {+ if std::fs::read_to_string(&path).is_ok_and(|existing| existing == content) {+ return Ok(false);+ }+ }+ Ok(_) | Err(_) => {}}std::fs::create_dir_all(dir)?;crate::atomic::write_atomic(&path, content.as_bytes())?;@@ -639,19 +659,21 @@ impl Wiki {let Some(reader) = &self.store_reader else {return Ok(0);};+ let _guard = self.mutation_lock.write().await;+ let workspaces = reader.list_all_workspace_scopes().await?;let scopes = reader.list_all_scopes().await?;let mut written = 0;- let mut seen_ws = std::collections::HashSet::new();- for s in scopes {- let ws_dir = self.root().join(s.workspace_id.to_string());- if seen_ws.insert(s.workspace_id)- && Self::write_scope_manifest(- &ws_dir,- serde_json::json!({ "workspace": s.workspace_name }),- )?- {+ for ws in workspaces {+ let ws_dir = self.root().join(ws.workspace_id.to_string());+ if Self::write_scope_manifest(+ &ws_dir,+ serde_json::json!({ "workspace": ws.workspace_name }),+ )? {written += 1;}+ }+ for s in scopes {+ let ws_dir = self.root().join(s.workspace_id.to_string());let mut fm = serde_json::json!({ "project": s.project_name });if let Some(rp) = s.repo_path {fm["repo_path"] = serde_json::Value::String(rp);@@ -1890,4 +1912,58 @@ mod tests {);drop(s2);}++ #[tokio::test]+ async fn backfill_writes_manifest_for_empty_workspace() {+ let tmp = TempDir::new().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let ws = store+ .writer+ .get_or_create_workspace("empty-ws")+ .await+ .unwrap();+ let wiki = Wiki::new(tmp.path(), store.writer.clone())+ .unwrap()+ .with_store_reader(store.reader.clone());++ let written = wiki.backfill_scope_manifests().await.unwrap();++ assert_eq!(written, 1);+ let meta = std::fs::read_to_string(+ tmp.path()+ .join("wiki")+ .join(ws.to_string())+ .join("_meta.md"),+ )+ .unwrap();+ assert!(meta.contains("workspace: empty-ws"));+ }++ #[cfg(any(unix, windows))]+ #[tokio::test]+ async fn reindex_rejects_symlinked_scope_manifest() {+ let tmp = TempDir::new().unwrap();+ let store = Store::open(tmp.path()).unwrap();+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();+ let ws = WorkspaceId::new();+ let proj = ProjectId::new();+ let ws_dir = tmp.path().join("wiki").join(ws.to_string());+ let proj_dir = ws_dir.join(proj.to_string());+ std::fs::create_dir_all(&proj_dir).unwrap();+ std::fs::write(ws_dir.join("_meta.md"), "---\nworkspace: acme\n---\n").unwrap();++ let outside = tmp.path().join("outside-meta.md");+ std::fs::write(&outside, "---\nproject: webapp\n---\n").unwrap();+ let link = proj_dir.join("_meta.md");+ #[cfg(unix)]+ std::os::unix::fs::symlink(&outside, &link).unwrap();+ #[cfg(windows)]+ std::os::windows::fs::symlink_file(&outside, &link).unwrap();++ let err = wiki.reindex_all().await.unwrap_err();+ assert!(+ err.to_string().contains("symlinked scope manifest"),+ "reindex must reject symlinked manifests, got {err:#}"+ );+ }}diff --git a/docs/lifecycle-ops.md b/docs/lifecycle-ops.mdindex 7f31a3f0..d67d689e 100644--- a/docs/lifecycle-ops.md+++ b/docs/lifecycle-ops.md@@ -14,11 +14,12 @@ on a homelab box where mistakes are harder to undo.| `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. || `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. |-All five commands route through the HTTP admin API except `reset` and-`restore`, which are direct-disk operations that fundamentally cannot-run while another process holds the SQLite WAL writer. See [CLAUDE.md-§16](../CLAUDE.md) for the invariant.+State-touching commands route through the HTTP admin API except `reset`,+`restore`, and `reindex`, which are direct-disk lifecycle operations that+fundamentally cannot run while another process holds the SQLite WAL writer. See+[CLAUDE.md §16](../CLAUDE.md) for the invariant.## What "project isolation" means here@@ -28,12 +29,14 @@ Every project's data lives under an isolated, UUID-keyed root on disk:<wiki_root>/├── .git/├── <workspace_id>/+│ ├── _meta.md # workspace name for rebuilds│ └── <project_id>/│ ├── concepts/│ ├── decisions/│ ├── gotchas/│ ├── sessions/│ ├── _rules/+│ ├── _meta.md # project name + repo_path for rebuilds│ ├── log-YYYY-MM.md # rolling event log, one file per month│ └── bootstrap.md└── <other_workspace_id>/@@ -53,6 +56,11 @@ as subtrees). A `git log` from inside the wiki dir shows changesacross every project; per-project diffs are also possible via`git log -- <workspace_id>/<project_id>/`.+Each workspace directory also carries `<workspace_id>/_meta.md`, and each+project directory carries `<workspace_id>/<project_id>/_meta.md`. Those small+frontmatter-only manifests store human names (plus `repo_path` for projects),+so a clean SQLite DB can be rebuilt from the UUID-keyed wiki tree alone.+## Command-by-command### `purge-project`@@ -325,6 +333,36 @@ container - but `ai-memory reset` is the cross-platform path thatworks whether the data dir is local, bind-mounted, or in a namedvolume.+### `reindex`++```bash+ai-memory reindex --data-dir <path>+```++Direct-disk lifecycle operation. Refuses if any sibling `ai-memory` process is+alive, and also refuses if SQLite already contains rows. `reindex` is a+rebuild-from-files path, not an in-place dirty-index repair.++Use it when the markdown wiki is intact but you intentionally want a fresh+SQLite migration lineage:++1. Stop the server or container.+2. Take a backup of the current data directory.+3. Move or remove `<data-dir>/db/memory.sqlite` and its WAL/SHM siblings.+4. Run `ai-memory reindex --data-dir <data-dir>`.+5. Run `ai-memory embed` after restart if you need embeddings rebuilt.++What is rebuilt:++- Workspaces and projects from `_meta.md`, preserving the UUIDs encoded in the+ wiki directory names.+- Latest page rows, page links, and FTS from markdown files.++What is not rebuilt:++- Sessions, observations, handoffs, users/tokens, audit rows, access counters,+ and embeddings. Those are DB-only state; keep a backup if you need them.+## Operator workflows### "Fresh start" (wipe everything)