Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(wiki): roll back failed checkpoint restores
Samir Hanna Verza34e55cf0352f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e65cba04..5de8a2be 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -13,6 +13,11 @@ version in [`docs/changelog/`](docs/changelog/):### Fixed+- Restored the previous wiki file when `restore-page` could not commit its+ SQLite update, including a rejected case-colliding historical path. Restores+ now share the page writer's lock through conformance, file replacement and+ indexing so a concurrent write to that same path cannot leave disk and+ SQLite disagreeing (#PR).- Refused empty and whitespace-only `--workspace` and `--project` flags at theshared CLI scope-resolution choke point (`resolve_scope`,`resolve_scope_noting_marker_project`, `resolve_scope_with_marker`, anddiff --git a/crates/ai-memory-wiki/src/wiki.rs b/crates/ai-memory-wiki/src/wiki.rsindex ffef04b9..8c0682d6 100644--- a/crates/ai-memory-wiki/src/wiki.rs+++ b/crates/ai-memory-wiki/src/wiki.rs@@ -975,41 +975,41 @@ impl Wiki {)))})?;let mut md = parse(&raw)?;- // Conform like the three sibling write paths (`write_page_inner`,- // `apply_batch`, `approve_auto_improve_proposal`) do: the row this- // upserts is conformed at the store's write choke point either way,- // so writing the historical bytes verbatim left the file behind the- // row. Restoring the pre-OKF checkpoint every migrated install- // carries then failed `export-okf` for the whole project with "run- // the server once to migrate" — which the one-shot wiki migration- // never does again — and made each `serve` boot re-archive the data- // dir once the migration archive was deleted. Conformance is- // idempotent modulo `generated.at`. When the file on disk already- // holds the same content, its timestamp still wins, so the file keeps- // matching the row the store's idempotent upsert reuses. Otherwise- // the disk holds a newer version and would leave only `now()`; an- // already-conformant checkpoint keeps its own `generated.at` instead,- // so it restores byte-exact whatever the clock.- conform_frontmatter_for_disk_keeping(- &self.abs_path(workspace_id, project_id, &path),- path.as_str(),- &mut md,- true,- );- let raw = emit(&md)?;- let title = derive_title(&md.frontmatter, &md.body, &path);- let links = crate::markdown::extract_all_links(&md.frontmatter, &md.body, &path);- let meta = derive_index_metadata(&path, &md.frontmatter)?;- let body = md.body.clone();- let abstract_text = frontmatter_abstract(&md.frontmatter).map(str::to_owned);-- let id = {+ let (id, body, abstract_text) = {let _guard = self.mutation_lock.read().await;+ // Restore shares the writer/reindex lock, including the disk read+ // that chooses generated.at and any rollback after a refused upsert.+ let _page_guard = self.lock_page(workspace_id, project_id, &path).await;+ let abs = self.confined_page_path(workspace_id, project_id, &path, Prepare::Inspect)?;+ // Conform like the three sibling write paths (`write_page_inner`,+ // `apply_batch`, `approve_auto_improve_proposal`) do: the row this+ // upserts is conformed at the store's write choke point either way,+ // so writing the historical bytes verbatim left the file behind the+ // row. Restoring the pre-OKF checkpoint every migrated install+ // carries then failed `export-okf` for the whole project with "run+ // the server once to migrate" — which the one-shot wiki migration+ // never does again — and made each `serve` boot re-archive the data+ // dir once the migration archive was deleted. Conformance is+ // idempotent modulo `generated.at`. When the file on disk already+ // holds the same content, its timestamp still wins, so the file keeps+ // matching the row the store's idempotent upsert reuses. Otherwise+ // the disk holds a newer version and would leave only `now()`; an+ // already-conformant checkpoint keeps its own `generated.at` instead,+ // so it restores byte-exact whatever the clock.+ conform_frontmatter_for_disk_keeping(&abs, path.as_str(), &mut md, true);+ let raw = emit(&md)?;+ let title = derive_title(&md.frontmatter, &md.body, &path);+ let links = crate::markdown::extract_all_links(&md.frontmatter, &md.body, &path);+ let meta = derive_index_metadata(&path, &md.frontmatter)?;+ let body = md.body.clone();+ let abstract_text = frontmatter_abstract(&md.frontmatter).map(str::to_owned);+self.ensure_project_workspace(workspace_id, project_id).await?;let abs = self.confined_page_path(workspace_id, project_id, &path, Prepare::Parents)?;- self.git.write_atomic(&abs, raw.as_bytes())?;- self.writer+ let installed = replace_file_with_rollback_snapshot(&self.git, &abs, raw.as_bytes())?;+ let id = match self+ .writer.upsert_page(NewPage {workspace_id,project_id,@@ -1025,7 +1025,15 @@ impl Wiki {entities: meta.entities,evidence: Vec::new(),})- .await?+ .await+ {+ Ok(id) => id,+ Err(e) => {+ rollback_or_inconsistent(&self.git, std::slice::from_ref(&installed), &e)?;+ return Err(e.into());+ }+ };+ (id, body, abstract_text)};// Embed the restored version like `write_page` does; without this it// ranked FTS-only until a backfill. The watcher's reindex of the file@@ -5328,6 +5336,249 @@ mod tests {assert_eq!(md.body.trim(), "old");}+ #[tokio::test]+ async fn restore_page_collision_keeps_disk_and_store_unchanged() {+ let tmp = TempDir::new().unwrap();+ let (store, wiki, ws, proj) = scoped(&tmp).await;+ let historical = PagePath::new("notes/A.md").unwrap();+ let current = PagePath::new("notes/a.md").unwrap();+ wiki.write_page(req(+ ws,+ proj,+ historical.as_str(),+ "historical",+ serde_json::json!({}),+ ))+ .await+ .unwrap();+ let rev = wiki.commit_all("checkpoint").unwrap().unwrap().to_string();+ wiki.delete_page(ws, proj, &historical, None, None)+ .await+ .unwrap();+ let current_id = wiki+ .write_page(req(+ ws,+ proj,+ current.as_str(),+ "current",+ serde_json::json!({}),+ ))+ .await+ .unwrap();+ let current_abs = wiki.abs_path(ws, proj, ¤t);+ let historical_abs = wiki.abs_path(ws, proj, &historical);+ let before = std::fs::read(¤t_abs).unwrap();+ // On case-folding filesystems these paths already address one file;+ // on case-sensitive filesystems the rejected restore must not create A.md.+ let historical_existed = historical_abs.exists();++ let err = wiki+ .restore_page_from_checkpoint(ws, proj, historical.clone(), &rev)+ .await+ .unwrap_err();++ assert!(+ err.to_string().contains("collides with existing page"),+ "{err}"+ );+ assert_eq!(std::fs::read(¤t_abs).unwrap(), before);+ assert_eq!(historical_abs.exists(), historical_existed);+ assert_eq!(+ store+ .reader+ .latest_page_id_by_ids(ws, proj, current.as_str().into())+ .await+ .unwrap(),+ Some(current_id)+ );+ assert_eq!(+ store+ .reader+ .latest_page_id_by_ids(ws, proj, historical.as_str().into())+ .await+ .unwrap(),+ None+ );+ assert_eq!(+ store+ .reader+ .page_body_by_ids(ws, proj, current.as_str())+ .await+ .unwrap()+ .unwrap()+ .body,+ "current"+ );+ }++ #[tokio::test]+ async fn restore_page_store_failure_rolls_back_replacement_and_new_file() {+ for existing in [true, false] {+ let tmp = TempDir::new().unwrap();+ let (store, wiki, ws, proj) = scoped(&tmp).await;+ let path = PagePath::new("notes/restore.md").unwrap();+ wiki.write_page(req(+ ws,+ proj,+ path.as_str(),+ "historical",+ serde_json::json!({}),+ ))+ .await+ .unwrap();+ let rev = wiki.commit_all("checkpoint").unwrap().unwrap().to_string();+ let expected_id = if existing {+ Some(+ wiki.write_page(req(+ ws,+ proj,+ path.as_str(),+ "current",+ serde_json::json!({}),+ ))+ .await+ .unwrap(),+ )+ } else {+ wiki.delete_page(ws, proj, &path, None, None).await.unwrap();+ None+ };+ let abs = wiki.abs_path(ws, proj, &path);+ let before = snapshot_existing_file(&abs).unwrap();+ // Reject the real store transaction after restore installs the file.+ // Both rollback branches must work regardless of filesystem casing.+ let db = rusqlite::Connection::open(tmp.path().join("db/memory.sqlite")).unwrap();+ db.execute_batch(+ "CREATE TRIGGER reject_restore BEFORE INSERT ON pages \+ WHEN NEW.path = 'notes/restore.md' BEGIN \+ SELECT RAISE(ABORT, 'injected restore failure'); END;",+ )+ .unwrap();++ let err = wiki+ .restore_page_from_checkpoint(ws, proj, path.clone(), &rev)+ .await+ .unwrap_err();++ assert!(+ err.to_string().contains("injected restore failure"),+ "{err}"+ );+ assert_eq!(snapshot_existing_file(&abs).unwrap(), before);+ assert_eq!(+ store+ .reader+ .latest_page_id_by_ids(ws, proj, path.as_str().into())+ .await+ .unwrap(),+ expected_id+ );+ if existing {+ assert_eq!(+ store+ .reader+ .page_body_by_ids(ws, proj, path.as_str())+ .await+ .unwrap()+ .unwrap()+ .body,+ "current"+ );+ }++ db.execute_batch("DROP TRIGGER reject_restore;").unwrap();+ wiki.restore_page_from_checkpoint(ws, proj, path.clone(), &rev)+ .await+ .unwrap();+ assert_eq!(wiki.read_page(ws, proj, &path).unwrap().body, "historical");+ assert_eq!(+ store+ .reader+ .page_body_by_ids(ws, proj, path.as_str())+ .await+ .unwrap()+ .unwrap()+ .body,+ "historical"+ );+ }+ }++ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]+ async fn restore_page_lock_waits_before_conformance_and_allows_another_path() {+ let tmp = TempDir::new().unwrap();+ let (_store, wiki, ws, proj) = scoped(&tmp).await;+ let path = PagePath::new("notes/held-restore.md").unwrap();+ let abs = wiki.abs_path(ws, proj, &path);+ wiki.write_page(req(+ ws,+ proj,+ path.as_str(),+ "historical",+ serde_json::json!({}),+ ))+ .await+ .unwrap();+ let mut checkpoint_md = wiki.read_page(ws, proj, &path).unwrap();+ ai_memory_core::okf::stamp_generated_at(+ &mut checkpoint_md.frontmatter,+ "2020-01-01T00:00:00Z",+ );+ std::fs::write(&abs, emit(&checkpoint_md).unwrap()).unwrap();+ let rev = wiki.commit_all("checkpoint").unwrap().unwrap().to_string();+ wiki.write_page(req(ws, proj, path.as_str(), "newer", serde_json::json!({})))+ .await+ .unwrap();++ let global = wiki.mutation_lock.read().await;+ let page = wiki.lock_page(ws, proj, &path).await;+ // Queue an ordinary writer first, then the restore. The restore must+ // conform against the bytes that writer commits, not the old disk view.+ let write = wiki.write_page(req(+ ws,+ proj,+ path.as_str(),+ "historical",+ serde_json::json!({}),+ ));+ tokio::pin!(write);+ wait_for_page_waiter(&wiki, &(ws, proj, path.clone()), write.as_mut()).await;+ let restore = wiki.restore_page_from_checkpoint(ws, proj, path.clone(), &rev);+ tokio::pin!(restore);+ wait_for_page_waiter(&wiki, &(ws, proj, path.clone()), restore.as_mut()).await;+ finish_lock_test(wiki.write_page(req(+ ws,+ proj,+ "notes/independent.md",+ "control",+ serde_json::json!({}),+ )))+ .await+ .unwrap();+ assert_eq!(wiki.read_page(ws, proj, &path).unwrap().body, "newer");++ drop(page);+ drop(global);+ let written = finish_lock_test(write).await.unwrap();+ let committed = std::fs::read(&abs).unwrap();+ let restored = finish_lock_test(restore).await.unwrap();+ assert_eq!(+ restored, written,+ "restoring the same content reuses the current row"+ );+ assert_eq!(std::fs::read(&abs).unwrap(), committed);+ let disk = wiki.read_page(ws, proj, &path).unwrap();+ let row = latest_row(&tmp, path.as_str()).2;+ assert_eq!(+ ai_memory_core::okf::generated_at(&disk.frontmatter),+ ai_memory_core::okf::generated_at(&row)+ );+ assert_ne!(+ ai_memory_core::okf::generated_at(&disk.frontmatter),+ Some("2020-01-01T00:00:00Z")+ );+ }+// The newer file on disk has another body, so the disk-inheritance rule// cannot supply `generated.at`; a past timestamp makes the restore fail// on every run without the checkpoint's own value, not only when thediff --git a/docs/lifecycle-ops.md b/docs/lifecycle-ops.mdindex afb26dfa..a3fc0530 100644--- a/docs/lifecycle-ops.md+++ b/docs/lifecycle-ops.md@@ -1031,6 +1031,8 @@ What happens: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 newlatest page row in SQLite so search, links, and `/web` agree with disk.+ It shares the same-path lock with writes and watcher reindexing, including+ the read of current frontmatter used to preserve `generated.at`.5. Server writes a post-restore checkpoint (`restore-page ...`) when the livetree changed.@@ -1042,6 +1044,10 @@ Failure modes:pre-restore checkpoint remains as an audit breadcrumb.- **Historical markdown is malformed or non-UTF-8** → 500, live file is notreplaced.+- **SQLite rejects the restored version** (for example, the historical path+ collides with a current page under case folding) → 500, the previous file is+ restored or a newly created file is removed. If that rollback also fails,+ the error explicitly reports an inconsistent state requiring repair.What it does not recover:diff --git a/docs/security-boundaries.md b/docs/security-boundaries.mdindex 23b2d5a6..13cccdfd 100644--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@ -68,7 +68,7 @@ the legitimate restricted-project control and the failed-query cases.| 4o | An OMP subagent session never claims a handoff or leaves one behind | `ai-memory-hooks/src/router.rs` SessionEnd `child_session`: an OpenCode or OMP end whose body carries a subagent marker (`payload.rs` `body_is_subagent`) closes and summarizes the session without a baton. The generated OMP extension (`ai-memory-cli/src/commands/install_hooks.rs` `build_omp_extension`) records a subagent session from `ctx.agent.kind` on the session's own `session_start`, `before_agent_start` and `session_shutdown`, never on a tool event (an advisor's tool calls reach the session they advise as `kind: "sub"` under that session's id), skips `fetchHandoff` for it and posts its events with `agent_id`. Pi reports no `ctx.agent`, so every Pi session stays top-level | router `omp_subagent_session_end_closes_and_summarizes_without_baton` (a marked OMP end leaves no baton; control: a top-level OMP session in the same project still leaves one), beside `opencode_child_session_end_closes_and_summarizes_without_baton`, and `drop_subagent_captures_drops_an_omp_subagent_session` (an opted-in project drops the marked session through its end; control: the top-level session is stored); `install_hooks.rs` `omp_extension_marks_subagent_sessions_and_skips_their_handoff` and, running the generated OMP extension in Node, `slow_generated_handoff_runtime::omp_extension_keeps_subagent_sessions_off_the_baton` (a task subagent, a `/tan` clone and a revived subagent never request `/handoff` and carry `agent_id` on every event, their ends included; controls: the top-level session and a session without `ctx.agent` claim, and the advisor's tool calls leave the top-level session unmarked). Each fails with its guard removed | STRONG || 5a | Pages shared: `author_id` is never a read filter (invariant #16) | `ai-memory-store/src/reader.rs` `search_pages`/`page_body_by_ids` — `author_id` is an attribution JOIN only, never a WHERE term; `observation_stream_votes` lets every session vote whatever its owner (the owner filter only withholds the observation excerpt and ids, never the vote or the page) | `multi_session.rs` — a page with a **non-null** `author_id` (operator A) is readable by operator B in the same project; `multi_session.rs` `another_operators_observations_lift_their_session_page_in_a_shared_project` (operator B's owned session, authored page and observations lift that page for operator A's query); `ai-memory-mcp` `server.rs` `observation_stream_evidence_stays_inside_a_restricted_project` (a second operator with only a read grant gets the session page lifted by the first operator's observation); `multi_session.rs` `observation_excerpts_follow_the_session_owner_while_the_vote_stays_shared` (B still gets A's session page ranked by A's observation, with the page's own snippet) | STRONG || 5b | Page supersession (loser stays reachable) | `ai-memory-store/src/ops.rs` `upsert_page_in_tx` — demote `is_latest=0` (never delete) + `supersedes` chain; read side: `reader.rs` `page_versions` lists every row at the path, with no `is_latest` filter, for `/web/w/…/h/*path` and `/api/v1/…/history/*path`. It does apply TTL expiry (`reader.rs` `history_visible`): a version whose own `expires_at` passed is neither listed nor readable by id, a path whose live version expired shows no history at all (the forget sweep hard-deletes every row there), and a `supersedes` link to a hidden version reads as `null`. Expiry is the only thing that hides a superseded version; a concurrent write never does | `multi_session.rs` `concurrent_writes_to_one_path_supersede_rather_than_destroy`; `retrieval_superseded.rs`; `multi_session.rs` `page_history_keeps_the_overwritten_version_and_stays_in_scope`; `ai-memory-web` `history_replay.rs` `history_keeps_both_sides_of_a_concurrent_divergent_write` (two attributed writers on one base: all three versions and both authors listed, one `is_latest`, the two writers' versions diff by id) and `history_lists_k_plus_one_versions_newest_first_and_diffs_the_latest`; bite: an `is_latest = 1` filter in `page_versions` fails both; `history_hides_expired_versions_and_expired_pages` (an expired superseded version and every version of a page whose live version expired answer 404 by path and by id on HTML and JSON, and the live successor's `supersedes` is `null`; control: a TTL in the future is listed and diffable; bites with the per-row predicate removed, with the live-version clause disabled, and with the `supersedes` hiding removed) | STRONG |-| 5c | Watcher reindex and Wiki writes share per-page serialization (invariant #16) | `ai-memory-wiki/src/wiki.rs` `reindex_page` takes `mutation_lock.read` before `reindex_page_locked` takes `lock_page`, covering disk read through the single-writer upsert; callers already holding the exclusive global guard do not reacquire it. `write_page` uses the same page mutex and `apply_batch` retains sorted, deduplicated locks; embedding runs after both guards are released | `wiki.rs` `reindex_page_lock_waits_before_reading_and_allows_another_path` (transient snapshot refused while locked, another path progresses, release indexes the committed bytes without rewriting disk), `reindex_page_lock_serializes_write_through_the_upsert` and `reindex_page_lock_and_reversed_duplicate_batches_do_not_deadlock` (real concurrent operations, final disk/SQL winner and supersession ancestry preserved); all three fail with the reindex page guard removed. `reindex_page_lock_releases_both_guards_before_embedding` checks both body and abstract embedding; `decay_cleanup_reindex_does_not_embed_under_the_exclusive_lock` covers the exclusive caller | STRONG for a shared Wiki handle and its clones. External editors and independently constructed Wiki handles do not participate in these locks |+| 5c | Watcher reindex and Wiki writes share per-page serialization (invariant #16) | `ai-memory-wiki/src/wiki.rs` `reindex_page` takes `mutation_lock.read` before `reindex_page_locked` takes `lock_page`, covering disk read through the single-writer upsert; callers already holding the exclusive global guard do not reacquire it. `write_page` and `restore_page_from_checkpoint` use the same page mutex and `apply_batch` retains sorted, deduplicated locks; restore reads current frontmatter under the guard and rolls back its installed file if the store refuses the version; embedding runs after both guards are released | `wiki.rs` `reindex_page_lock_waits_before_reading_and_allows_another_path` (transient snapshot refused while locked, another path progresses, release indexes the committed bytes without rewriting disk), `reindex_page_lock_serializes_write_through_the_upsert` and `reindex_page_lock_and_reversed_duplicate_batches_do_not_deadlock` (real concurrent operations, final disk/SQL winner and supersession ancestry preserved); all three fail with the reindex page guard removed. `restore_page_lock_waits_before_conformance_and_allows_another_path` (a queued writer wins first, its timestamp is preserved, another path progresses; fails without the restore page guard or with conformance before it), `restore_page_collision_keeps_disk_and_store_unchanged` and `restore_page_store_failure_rolls_back_replacement_and_new_file` (rejected historical alias and injected upsert failures preserve disk and SQL, ordinary restore succeeds after removing the fault; fail without restore rollback). `reindex_page_lock_releases_both_guards_before_embedding` checks both body and abstract embedding; `decay_cleanup_reindex_does_not_embed_under_the_exclusive_lock` covers the exclusive caller | STRONG for a shared Wiki handle and its clones. External editors and independently constructed Wiki handles do not participate in these locks || 5d | Wiki project-tree filesystem confinement | `ai-memory-wiki/src/confinement.rs` checks the wiki root, workspace/project roots, every existing ancestor, the final component, and the in-root ordinary `.git` directory with link-aware metadata; repository workdir/gitdir/commondir are containment-checked after opening, and write parents are created one component at a time and rechecked. `Wiki` checks before admission and again under mutation/page locks, while `GitAdapter` rechecks immediately before writes, appends, renames, and removals. Direct reindex, checkpoint restore, manifests, auto-improvement artifacts, ledger append, startup repair, purge/session moves, rollback, migrations, and git tree staging use the same boundary. Confinement is a distinct `WikiError` and therefore cannot trigger missing-file DB fallback | `wiki.rs` `page_reads_refuse_leaf_and_ancestor_symlinks_without_fallback_classification`, `ai-memory-mcp` `admin_read_page.rs` `read_page_does_not_db_fallback_through_a_symlink`, `page_mutations_refuse_ancestor_symlink_and_leave_outside_and_store_unchanged`, `confinement_refusal_happens_before_blocking_and_observer_admission`, `restore_and_reindex_refuse_ancestor_symlink_without_touching_canary_or_db`; `git.rs` `git_metadata_link_is_refused_without_touching_external_repository`, `gitfile_redirect_outside_is_refused_without_touching_target`, `git_metadata_redirect_files_are_refused_before_repository_open`, `configured_worktree_outside_the_wiki_root_is_refused`, `linked_git_metadata_never_reaches_commit_fallback`, `gitfile_metadata_never_reaches_commit_fallback`, `out_of_root_worktree_never_reaches_commit_fallback`, `fallback_preflight_refuses_invalid_git_metadata`, `windows_commit_fallback_accepts_established_eligible_errors`, `eligible_windows_open_error_dispatches_the_fallback_after_validation`, `windows_init_error_dispatches_fallback_after_root_preflight`, `invalid_root_never_reaches_init_fallback`, `checkpoint_and_revision_reads_refuse_a_replaced_git_directory`, and ordinary-repository/API controls `init_is_idempotent_and_creates_dotgit`; `linked_wiki_root_is_refused_during_construction`, `linked_or_dangling_scope_roots_are_refused_but_real_roots_work`, existing `decay_cleanup_refuses_to_reindex_a_symlinked_recreation` and `reindex_rejects_symlinked_scope_manifest`; `ai-memory-mcp` `admin_move.rs` `true_move_refuses_an_invalid_destination_namespace_without_db_changes` and `delete_workspace_refuses_invalid_namespace_before_db_or_notification`; `admin_backup.rs` `backup_refuses_redirected_git_metadata_before_returning_an_archive`, `backup_refuses_wiki_leaf_links_before_returning_an_archive`, `backup_refuses_linked_wiki_directories_before_returning_an_archive`, and ordinary archive controls; `watcher.rs` `direct_file_event_skips_symlink`, `walk_markdown_skips_linked_directories_and_their_ledgers`, and `shared_link_like_helper_accepts_regular_files_and_directories` (Windows directory-link coverage exercises reparse metadata when privilege is available); `backup.rs` `a_pre_migration_backup_refuses_a_linked_wiki_tree_without_an_archive`; `confinement.rs` metadata-helper controls run on every platform | STRONG for imported/static links and same-process mutations. Component checks do not claim descriptor-relative protection against a concurrently malicious same-user process; Windows reparse behavior requires the `windows` PR label/full CI || 5e | Conditional page mutation (#986, invariant #16) | `ai-memory-store/src/ops.rs` `upsert_page_if` reads the latest version and writes in one transaction, the authority; `ai-memory-wiki/src/wiki.rs` `write_page_if` pre-checks under the per-page lock before touching disk and restores the file when the store check fails; conditional deletes reuse `delete_page_if_latest` (exclusive mutation lock plus an in-transaction check). `ai-memory-mcp/src/server.rs` checks the precondition only after scope resolution and the write grant, against the resolved scope's own latest row, and returns `precondition_failed` with no write, checkpoint or webhook dispatch. The agentmemory importer (`agentmemory/mod.rs` `apply_page`) resumes from a conflicting destination only when its complete body equals a planned version; a retained attribution key alone cannot supply the next write's expected version. `companions/ai-memory-wikisync/src/bidi.rs` `build_plan` reads the full page for an edited repository file, keeping classification and `expected_page_id` on the same server version | `multi_session.rs` `conditional_writers_on_one_base_exactly_one_wins_and_nothing_is_destroyed` (two writers from one version: one wins, the base stays reachable, no loser row; fails with the store check removed); `server.rs` `conditional_page_writes::*` (stale id, `create_only` on an existing page, a version id from another project, and conditional deletes are refused and change nothing, with and without the wiki pre-check; the store check proven to bite with the reader pre-check off); `a_reader_may_read_everything_and_change_nothing` (a read-only user's conditional write or delete, with the right id or a wrong one, gets the authorization error and no version data; the page is unchanged); importer `resume_refuses_an_edited_body_even_with_the_original_ingest_key` and `e2e_export_import_rebuilds_chains_and_honours_ttl` (an edited destination body keeps its attribution key but cannot be superseded by a resumed import; both fail with marker-only matching); `resume_after_an_injected_failure_writes_no_duplicates` and `a_foreign_page_at_the_destination_is_never_replaced` are the legitimate-resume and foreign-page controls; wikisync `tests/api_server.rs` `sync_does_not_rebase_an_import_onto_a_concurrent_server_edit` (an edit after the read snapshot is refused by the original version precondition, preserving server, repository and baseline; fails without the conditional-read guard), `sync_imports_a_repo_edit_with_its_metadata` and `sync_exports_metadata_and_round_trips_without_writes` (ordinary import and unchanged-file ETag controls) | STRONG. Importer resumption compares bodies, not frontmatter-only edits; custom server sanitation that changes the planned body fails closed || 5f | Wiki-sync companion destination confinement | `companions/ai-memory-wikisync/src/paths.rs` `prepare_dest` compares canonical and lexical destination components without resolving the lexical path; Windows disk and UNC verbatim prefixes compare as equivalent spellings, while changed directory components are refused. `secure_join` keeps validated page paths below that root and refuses existing symlink components | `paths.rs` `prepare_dest_refuses_windows_junctions_without_touching_the_target` refuses a junction and a destination reached through it, leaves an outside canary unchanged, and accepts the real directory; `windows_destination_prefixes_do_not_hide_different_paths` refuses different drives, shares and directory components with ordinary/verbatim controls; `prepare_dest_refuses_symlinks_and_files` and `secure_join_stays_under_root_and_refuses_symlink_components` retain the Unix link controls | Static path checks; no descriptor-relative protection against a concurrently malicious same-user process. The dedicated `windows.yml` wiki sync companion job runs the prefix and junction tests on companion/workflow changes, `windows` or `full-ci` labels, nightly runs and dispatch |