Skip to content

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

Rust

fix(wikisync): preserve local edits during export

Samir Hanna Verza1889be7f75c4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c6a02aca..ddfe3e39 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,6 +13,11 @@ version in [`docs/changelog/`](docs/changelog/):
### Fixed
+- Preserved repository edits saved while `ai-memory-wikisync export --apply`
+ fetched server pages. Export now rechecks each file before replacing it,
+ as two-way sync already did, and refuses a changed file even with `--force`
+ without advancing its export state (#986).
+
- `ai-memory user list` and `ai-memory api-key list` now size their columns
by terminal display width rather than bytes, as `list-projects` and the
grants tables already do. An accented username, display name or key label
diff --git a/companions/ai-memory-wikisync/README.md b/companions/ai-memory-wikisync/README.md
index a216ea45..9db020d0 100644
--- a/companions/ai-memory-wikisync/README.md
+++ b/companions/ai-memory-wikisync/README.md
@@ -124,6 +124,12 @@ This section describes `plan` and `export`; `sync` adds the rules under
a missing line is shown as `<end of file>`. The
whole batch is then refused and nothing is written. `--force` overwrites the
divergent files with server content.
+- **Edits during export are preserved.** Before each replacement, `export
+ --apply` rechecks the file against the bytes the plan read. A file edited,
+ created or removed during the server requests is left alone, even with
+ `--force`, and the run exits non-zero. Earlier files may already have been
+ exported; the state stays at the previous successful batch so the next run
+ compares those files again.
- **Never deletes.** `plan` and `export` never delete local files or server
pages, including brand-new local files inside an allowlisted family.
Only `sync --propagate-deletes` deletes (see below).
diff --git a/companions/ai-memory-wikisync/src/bidi.rs b/companions/ai-memory-wikisync/src/bidi.rs
index dec52870..244e04da 100644
--- a/companions/ai-memory-wikisync/src/bidi.rs
+++ b/companions/ai-memory-wikisync/src/bidi.rs
@@ -26,7 +26,7 @@ use crate::client::{ApiClient, ApiPage};
use crate::mcp::{self, McpClient, Precondition, PreconditionFailed, Scope};
use crate::page_file::{self, PageMeta};
use crate::state::{self, PageState, SyncState};
-use crate::sync::{self, Mode, RunArgs};
+use crate::sync::{self, Mode, RunArgs, write_if_unchanged};
use crate::{MAX_BODY_BYTES, MAX_PAGES, paths};
/// Server frontmatter keys a `memory_write_page` import writes back, or
@@ -848,24 +848,6 @@ fn report_local_change(path: &str) {
);
}
-/// Write `bytes` over a repository file only while it is still the file the
-/// plan classified: `expected` is that file's hash, or `None` when there was
-/// no file. Returns `false`, writing nothing, when an edit landed after the
-/// plan (the check and the rename are as close together as `delete_file`'s).
-fn write_if_unchanged(
- dest_root: &Path,
- rel: &str,
- expected: Option<&str>,
- bytes: &[u8],
-) -> Result<bool> {
- let current = sync::read_disk(dest_root, rel)?;
- if current.as_deref().map(state::sha256_hex).as_deref() != expected {
- return Ok(false);
- }
- sync::atomic_write(dest_root, rel, bytes)?;
- Ok(true)
-}
-
fn report_race(path: &str, error: &anyhow::Error) {
println!(
" {:<9} {path} — {error}; left for the next sync",
diff --git a/companions/ai-memory-wikisync/src/sync.rs b/companions/ai-memory-wikisync/src/sync.rs
index 8b8de240..20311bb8 100644
--- a/companions/ai-memory-wikisync/src/sync.rs
+++ b/companions/ai-memory-wikisync/src/sync.rs
@@ -79,6 +79,8 @@ pub struct PlannedWrite {
pub title: String,
pub body: String,
pub etag: Option<String>,
+ /// Hash of the repository file the plan read, or `None` if it was absent.
+ pub expected_disk: Option<String>,
}
/// A destination file that diverged, with a bounded diff summary.
@@ -335,6 +337,24 @@ pub(crate) fn read_disk(dest_root: &Path, path: &str) -> Result<Option<Vec<u8>>>
}
}
+/// Write `bytes` over a repository file only while it is still the file the
+/// plan classified: `expected` is that file's hash, or `None` when there was
+/// no file. Returns `false`, writing nothing, when an edit landed after the
+/// plan. The check and atomic replacement are deliberately adjacent.
+pub(crate) fn write_if_unchanged(
+ dest_root: &Path,
+ rel: &str,
+ expected: Option<&str>,
+ bytes: &[u8],
+) -> Result<bool> {
+ let current = read_disk(dest_root, rel)?;
+ if current.as_deref().map(state::sha256_hex).as_deref() != expected {
+ return Ok(false);
+ }
+ atomic_write(dest_root, rel, bytes)?;
+ Ok(true)
+}
+
/// Fetch and classify every allowlisted page. In [`Mode::Apply`] (and only
/// when allowed past the divergence guard) also performs the write batch
/// and persists the new state atomically.
@@ -414,7 +434,18 @@ async fn run_batch(
let applied = mode == Mode::Apply && (report.divergent.is_empty() || args.force);
if applied {
for write in &report.writes {
- atomic_write(dest_root, &write.path, write.body.as_bytes())?;
+ if !write_if_unchanged(
+ dest_root,
+ &write.path,
+ write.expected_disk.as_deref(),
+ write.body.as_bytes(),
+ )? {
+ bail!(
+ "{} changed in the repository during this run; left untouched. \
+ Earlier exports may have completed; export state was not advanced",
+ write.path
+ );
+ }
}
// Only after the whole batch is on disk does the state move: a
// crash mid-batch leaves the old state, and the next run's
@@ -480,6 +511,7 @@ fn record_decision(
title: page.title,
body,
etag,
+ expected_disk: disk.map(state::sha256_hex),
});
}
Classification::Divergent(reason) => {
@@ -507,6 +539,7 @@ fn record_decision(
title: page.title.clone(),
body: body.clone(),
etag,
+ expected_disk: disk.map(state::sha256_hex),
});
}
}
diff --git a/companions/ai-memory-wikisync/tests/api_server.rs b/companions/ai-memory-wikisync/tests/api_server.rs
index 36fb4a83..bd273127 100644
--- a/companions/ai-memory-wikisync/tests/api_server.rs
+++ b/companions/ai-memory-wikisync/tests/api_server.rs
@@ -71,6 +71,8 @@ struct Fixture {
/// Rewrite this page's body on its Nth read (1-based), to simulate an
/// edit landing between a sync's classification and its write.
edit_on_read: Option<(&'static str, usize)>,
+ /// Save an editor's local change while the next page request is in flight.
+ repository_edit_on_read: Mutex<Option<(PathBuf, Vec<u8>)>>,
/// Text the fixture's write path redacts, like the server's sanitizer.
redact: Option<&'static str>,
/// Edit this page right before an MCP call on it is handled, to simulate
@@ -106,6 +108,7 @@ impl Fixture {
project_exists: true,
unreachable: None,
edit_on_read: None,
+ repository_edit_on_read: Mutex::new(None),
redact: None,
edit_before_mcp: None,
old_server: false,
@@ -242,6 +245,10 @@ async fn page_handler(
if fixture.unreachable == Some(path.as_str()) {
return error_json(StatusCode::NOT_FOUND, "page not found");
}
+ if let Some((path, bytes)) = fixture.repository_edit_on_read.lock().unwrap().take() {
+ fs::create_dir_all(path.parent().unwrap()).unwrap();
+ fs::write(path, bytes).unwrap();
+ }
let read_count = {
let mut reads = fixture.reads_by_path.lock().unwrap();
let count = reads.entry(path.clone()).or_insert(0);
@@ -634,6 +641,64 @@ async fn local_edits_are_refused_until_forced() {
);
}
+#[tokio::test]
+async fn export_preserves_edits_saved_while_fetching_pages_even_with_force() {
+ for force in [false, true] {
+ let (addr, fixture) = serve(Fixture::new(vec![(
+ "notes/a.md".to_string(),
+ "# Original\n".to_string(),
+ )]))
+ .await;
+ let (_tmp, dest) = temp_dest();
+ let mut run_args = args(addr, &dest, &["notes"]);
+ run(&run_args, Mode::Apply).await.unwrap();
+ let old_state = fs::read(state::state_path(&dest)).unwrap();
+ fixture.update("notes/a.md", |page| {
+ page.body = "# Server edit\n".to_string()
+ });
+ if force {
+ fs::write(dest.join("notes/a.md"), b"# Older local edit\n").unwrap();
+ }
+ run_args.force = force;
+ let newest = b"# Editor saved this during export\n";
+ *fixture.repository_edit_on_read.lock().unwrap() =
+ Some((dest.join("notes/a.md"), newest.to_vec()));
+
+ let result = run(&run_args, Mode::Apply).await;
+ assert_eq!(fs::read(dest.join("notes/a.md")).unwrap(), newest);
+ let message = result
+ .expect_err("must preserve an unseen edit")
+ .to_string();
+ assert!(
+ message.contains("changed in the repository during this run"),
+ "{message}"
+ );
+ assert_eq!(fs::read(state::state_path(&dest)).unwrap(), old_state);
+ }
+}
+
+#[tokio::test]
+async fn export_preserves_a_file_created_while_fetching_pages() {
+ let (addr, fixture) = serve(Fixture::new(vec![(
+ "notes/a.md".to_string(),
+ "# Server page\n".to_string(),
+ )]))
+ .await;
+ let (_tmp, dest) = temp_dest();
+ let newest = b"# New local page\n";
+ *fixture.repository_edit_on_read.lock().unwrap() =
+ Some((dest.join("notes/a.md"), newest.to_vec()));
+
+ let result = run(&args(addr, &dest, &["notes"]), Mode::Apply).await;
+ assert_eq!(fs::read(dest.join("notes/a.md")).unwrap(), newest);
+ let message = result.expect_err("must preserve a new file").to_string();
+ assert!(
+ message.contains("changed in the repository during this run"),
+ "{message}"
+ );
+ assert!(!state::state_path(&dest).exists());
+}
+
#[tokio::test]
async fn unauthorized_is_a_clear_error() {
let (addr, _fixture) = serve(Fixture::new(fixture_pages()).with_token("sekrit")).await;