Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(wikisync): record the baseline's scope and refuse a foreign one
AkitaOnRailsb321a835db88
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 41307bf3..572e28fe 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -11,6 +11,16 @@ version in [`docs/changelog/`](docs/changelog/):## [Unreleased]+### Fixed++- `ai-memory-wikisync` records the server, workspace and project its export+ state came from and refuses to reuse a destination for another scope before+ writing anything. Reusing one made every page of the previous project read+ as "deleted on the server", so `sync --propagate-deletes --apply` removed+ those files and emptied the state. `--adopt-scope` is the explicit way to+ take a destination over, and a baseline written before the field existed is+ adopted on its first run with a warning (#1708).+## [3.2.5] - 2026-10-25### Fixeddiff --git a/companions/ai-memory-wikisync/README.md b/companions/ai-memory-wikisync/README.mdindex 9db020d0..56e1d25c 100644--- a/companions/ai-memory-wikisync/README.md+++ b/companions/ai-memory-wikisync/README.md@@ -52,6 +52,10 @@ ai-memory-wikisync sync ... --apply --prefer repo # or --prefer serverai-memory-wikisync sync ... --apply --propagate-deletes```+- The state file records the server, workspace and project it came from. If+ you point the same `--dest` at a different scope, the run refuses before+ writing (a foreign baseline would make that project's pages look deleted);+ pass `--adopt-scope` to discard the baseline and export fresh.- `plan` never writes, not even the state file.- `export --apply` writes/updates markdown files under `--dest` and printsthe `git add` / `git commit` / `git push` commands you may run yourself.diff --git a/companions/ai-memory-wikisync/src/bidi.rs b/companions/ai-memory-wikisync/src/bidi.rsindex 244e04da..ab28924b 100644--- a/companions/ai-memory-wikisync/src/bidi.rs+++ b/companions/ai-memory-wikisync/src/bidi.rs@@ -325,7 +325,8 @@ pub async fn run(args: &SyncArgs, mode: SyncMode) -> Result<Outcome> {};let dest_root = sync::resolve_dest(&run_args.dest, fs_mode)?;let stateless_check = mode == SyncMode::Check && !state::state_path(&dest_root).exists();- let old_state = state::load(&dest_root)?;+ let scope = state::SyncScope::of(&run_args.server, &run_args.workspace, &run_args.project);+ let old_state = sync::baseline_for(state::load(&dest_root)?, &scope, run_args.adopt_scope)?;let api = ApiClient::new(&run_args.server, run_args.token.clone())?;let plan = build_plan(@@ -730,6 +731,11 @@ async fn apply_plan(plan: Plan,) -> Result<Applied> {let mut new_state = old_state.clone();+ new_state.scope = Some(state::SyncScope::of(+ &args.server,+ &args.workspace,+ &args.project,+ ));new_state.pages.extend(plan.adopted);for path in &plan.forget {new_state.pages.remove(path);diff --git a/companions/ai-memory-wikisync/src/main.rs b/companions/ai-memory-wikisync/src/main.rsindex bdd47a1a..b359399b 100644--- a/companions/ai-memory-wikisync/src/main.rs+++ b/companions/ai-memory-wikisync/src/main.rs@@ -169,6 +169,12 @@ struct CommonArgs {/// allowlist is explicit: '*' is refused.#[arg(long = "include", value_name = "FAMILY")]include: Vec<String>,+ /// Take over a destination whose baseline was recorded for another+ /// server, workspace or project. The baseline is discarded, so the run+ /// exports fresh instead of reading that project's pages as deletions+ /// (#1708).+ #[arg(long)]+ adopt_scope: bool,}impl From<ExportArgs> for RunArgs {@@ -181,6 +187,7 @@ impl From<ExportArgs> for RunArgs {dest: args.common.dest,include: args.common.include,force: args.force,+ adopt_scope: args.common.adopt_scope,}}}@@ -195,6 +202,7 @@ impl From<CommonArgs> for RunArgs {dest: args.dest,include: args.include,force: false,+ adopt_scope: args.adopt_scope,}}}diff --git a/companions/ai-memory-wikisync/src/state.rs b/companions/ai-memory-wikisync/src/state.rsindex 3b685230..7a93b3ba 100644--- a/companions/ai-memory-wikisync/src/state.rs+++ b/companions/ai-memory-wikisync/src/state.rs@@ -56,11 +56,74 @@ pub struct PageState {pub page_id: Option<String>,}+/// Which server scope a baseline was recorded from (#1708).+///+/// The page map alone cannot say that a destination belongs to one project:+/// pointing the same `--dest` at another project made every page of the first+/// one look "deleted on the server", and `--propagate-deletes --apply` then+/// removed those files.+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]+pub struct SyncScope {+ /// Server origin the baseline was exported from.+ pub server: String,+ /// Workspace the baseline was exported from.+ pub workspace: String,+ /// Project the baseline was exported from.+ pub project: String,+}++impl SyncScope {+ /// Derive the scope of a run. The server origin is normalised the way the+ /// client normalises it, so `http://host:49374/` and `http://host:49374`+ /// are one scope.+ #[must_use]+ pub fn of(server: &str, workspace: &str, project: &str) -> Self {+ Self {+ server: server.trim_end_matches('/').to_owned(),+ workspace: workspace.to_owned(),+ project: project.to_owned(),+ }+ }+}++/// What a baseline says about the run asking to use it.+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum ScopeCheck {+ /// The baseline belongs to this run's scope.+ Match,+ /// The baseline predates scope recording (or is empty) and is taken over+ /// by this run, which stamps its scope on the next save.+ Adopted,+ /// The baseline belongs to another scope. Reusing it would read that+ /// scope's pages as deletions here.+ Mismatch { recorded: SyncScope },+}++/// Compare a baseline with the run's scope.+#[must_use]+pub fn check_scope(state: &SyncState, scope: &SyncScope) -> ScopeCheck {+ match &state.scope {+ Some(recorded) if recorded != scope => ScopeCheck::Mismatch {+ recorded: recorded.clone(),+ },+ Some(_) => ScopeCheck::Match,+ // A file written before scopes existed carries no origin. With no+ // pages it is empty and cannot mislead; with pages, the origin is+ // unknown and taking it over is the behaviour every existing export+ // already had, so it is adopted with a warning rather than refused.+ None => ScopeCheck::Adopted,+ }+}+/// The whole state file. `version` guards against silently misreading a/// future format: an unknown version fails closed instead of resetting.#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]pub struct SyncState {pub version: u32,+ /// Server scope this baseline was recorded from. Absent in state written+ /// before #1708, which still loads and is adopted by the next save.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub scope: Option<SyncScope>,pub pages: BTreeMap<String, PageState>,}@@ -68,6 +131,7 @@ impl Default for SyncState {fn default() -> Self {Self {version: STATE_VERSION,+ scope: None,pages: BTreeMap::new(),}}@@ -273,13 +337,69 @@ mod tests {let future = SyncState {version: 99,- pages: BTreeMap::new(),+ ..SyncState::default()};fs::write(state_path(&root), serde_json::to_string(&future).unwrap()).unwrap();let err = load(&root).unwrap_err().to_string();assert!(err.contains("version"), "{err}");}+ #[test]+ fn a_baseline_records_its_scope_and_refuses_another_one() {+ let scope = SyncScope::of("http://host:49374", "demo", "a");+ let mut state = SyncState::default();+ assert_eq!(check_scope(&state, &scope), ScopeCheck::Adopted);++ state.scope = Some(scope.clone());+ state.pages.insert("notes/a.md".into(), page("hash", None));+ assert_eq!(check_scope(&state, &scope), ScopeCheck::Match);+ // A trailing slash is the same server.+ assert_eq!(+ check_scope(&state, &SyncScope::of("http://host:49374/", "demo", "a")),+ ScopeCheck::Match+ );++ // Another project on the same server is a different scope (#1708).+ let other = SyncScope::of("http://host:49374", "demo", "b");+ assert_eq!(+ check_scope(&state, &other),+ ScopeCheck::Mismatch {+ recorded: scope.clone()+ }+ );+ // So is another server with the same names.+ let elsewhere = SyncScope::of("http://other:49374", "demo", "a");+ assert!(matches!(+ check_scope(&state, &elsewhere),+ ScopeCheck::Mismatch { .. }+ ));+ }++ /// A state file written before scopes existed still loads, and the next+ /// save stamps the scope so the window closes after one run.+ #[test]+ fn legacy_state_loads_and_is_stamped_on_save() {+ let tmp = tempfile::tempdir().unwrap();+ let root = tmp.path().canonicalize().unwrap();+ fs::create_dir_all(root.join(STATE_DIR)).unwrap();+ fs::write(+ state_path(&root),+ r#"{"version":1,"pages":{"notes/a.md":{"hash":"h"}}}"#,+ )+ .unwrap();++ let mut state = load(&root).unwrap();+ assert!(state.scope.is_none());+ let scope = SyncScope::of("http://host:49374", "demo", "a");+ assert_eq!(check_scope(&state, &scope), ScopeCheck::Adopted);++ state.scope = Some(scope.clone());+ save(&root, &state).unwrap();+ let reloaded = load(&root).unwrap();+ assert_eq!(reloaded.scope.as_ref(), Some(&scope));+ assert_eq!(check_scope(&reloaded, &scope), ScopeCheck::Match);+ }+#[test]fn refuses_symlinked_state_dir() {let tmp = tempfile::tempdir().unwrap();diff --git a/companions/ai-memory-wikisync/src/sync.rs b/companions/ai-memory-wikisync/src/sync.rsindex 20311bb8..2b121384 100644--- a/companions/ai-memory-wikisync/src/sync.rs+++ b/companions/ai-memory-wikisync/src/sync.rs@@ -135,6 +135,60 @@ pub struct RunArgs {pub include: Vec<String>,/// Overwrite files that diverged locally since the last export.pub force: bool,+ /// Take over a destination whose baseline belongs to another server,+ /// workspace or project: the baseline is discarded, so this run treats+ /// the destination as a fresh export (#1708). Without it a scope change+ /// refuses before anything is written.+ pub adopt_scope: bool,+}++/// Refuse to reuse a baseline recorded for another scope (#1708).+///+/// Reusing it made every page of the previous project look "deleted on the+/// server", which `--propagate-deletes --apply` then removed. Returns the+/// state a run should use: cleared when `--adopt-scope` takes the+/// destination over, stamped with this run's scope so the next save records+/// it.+pub fn baseline_for(+ mut state: state::SyncState,+ scope: &state::SyncScope,+ adopt: bool,+) -> Result<state::SyncState> {+ match state::check_scope(&state, scope) {+ state::ScopeCheck::Match => {}+ state::ScopeCheck::Adopted => {+ if !state.pages.is_empty() {+ eprintln!(+ "ai-memory-wikisync: this destination's baseline predates origin tracking; adopting it for {}/{}. A baseline from another project cannot be detected, so check the plan before --apply.",+ scope.workspace, scope.project+ );+ }+ state.scope = Some(scope.clone());+ }+ state::ScopeCheck::Mismatch { recorded } => {+ if !adopt {+ bail!(+ "this destination's baseline belongs to {} ({}/{}), not {}/{}. \+ Reusing it would read that project's pages as deletions here; re-run with \+ --adopt-scope to discard the baseline and export fresh",+ recorded.server,+ recorded.workspace,+ recorded.project,+ scope.workspace,+ scope.project+ );+ }+ eprintln!(+ "ai-memory-wikisync: discarding the baseline recorded for {}/{}, adopting this destination for {}/{}",+ recorded.workspace, recorded.project, scope.workspace, scope.project+ );+ state = state::SyncState {+ scope: Some(scope.clone()),+ ..state::SyncState::default()+ };+ }+ }+ Ok(state)}/// Classify one page from its three versions. Pure: all IO happens around@@ -630,7 +684,8 @@ pub(crate) fn resolve_dest(dest: &Path, mode: Mode) -> Result<PathBuf> {pub async fn run(args: &RunArgs, mode: Mode) -> Result<()> {let families = validate_allowlist(&args.include)?;let dest_root = resolve_dest(&args.dest, mode)?;- let old_state = state::load(&dest_root)?;+ let scope = state::SyncScope::of(&args.server, &args.workspace, &args.project);+ let old_state = baseline_for(state::load(&dest_root)?, &scope, args.adopt_scope)?;let client = ApiClient::new(&args.server, args.token.clone())?;let (report, _new_state, applied) =diff --git a/companions/ai-memory-wikisync/tests/api_server.rs b/companions/ai-memory-wikisync/tests/api_server.rsindex bd273127..669a3b36 100644--- a/companions/ai-memory-wikisync/tests/api_server.rs+++ b/companions/ai-memory-wikisync/tests/api_server.rs@@ -81,6 +81,10 @@ struct Fixture {/// A server older than 3.0: no `expected_page_id` in the tool schema, no/// `id` on pages, and preconditions silently ignored.old_server: bool,+ /// Serve a listing for any project name, not only `app`. Lets a test model+ /// a second project on one server whose listing is successfully empty+ /// (#1708) instead of a 404.+ any_project: bool,/// Arguments of every MCP tool call, in order.mcp_calls: Mutex<Vec<serde_json::Value>>,reads_by_path: Mutex<BTreeMap<String, usize>>,@@ -112,6 +116,7 @@ impl Fixture {redact: None,edit_before_mcp: None,old_server: false,+ any_project: false,mcp_calls: Mutex::new(Vec::new()),reads_by_path: Mutex::new(BTreeMap::new()),recent_calls: AtomicUsize::new(0),@@ -194,7 +199,8 @@ async fn recent_handler(if let Err(response) = fixture.authorize(&headers) {return *response;}- if !fixture.project_exists || workspace != "demo" || project != "app" {+ if !fixture.project_exists || workspace != "demo" || (project != "app" && !fixture.any_project)+ {return error_json(StatusCode::NOT_FOUND, "workspace or project not found");}// Ignore updated_since; the fixture serves everything after the epoch.@@ -239,7 +245,8 @@ async fn page_handler(if let Err(response) = fixture.authorize(&headers) {return *response;}- if !fixture.project_exists || workspace != "demo" || project != "app" {+ if !fixture.project_exists || workspace != "demo" || (project != "app" && !fixture.any_project)+ {return error_json(StatusCode::NOT_FOUND, "workspace or project not found");}if fixture.unreachable == Some(path.as_str()) {@@ -486,6 +493,7 @@ fn args(addr: SocketAddr, dest: &std::path::Path, families: &[&str]) -> RunArgsdest: dest.to_path_buf(),include: families.iter().map(|f| f.to_string()).collect(),force: false,+ adopt_scope: false,}}@@ -871,6 +879,93 @@ fn decision() -> FixturePage {const DECISION_FILE: &str ="---\ntitle: \"DB\"\ntags: [\"db\"]\npinned: true\n---\n# DB\nUse Postgres.\n";+/// The reproduction from #1708: a destination exported from project `a` is+/// reused for project `b`, whose (empty) listing made every page of `a` read+/// as "deleted on the server", and `--propagate-deletes --apply` removed the+/// file and emptied the baseline. The baseline records its scope now, so the+/// reuse refuses before writing, and `--adopt-scope` is the explicit way to+/// take the destination over.+#[tokio::test]+async fn reusing_a_destination_for_another_project_refuses_and_keeps_the_files() {+ let (addr, fixture) = serve(Fixture::with_pages(vec![decision()])).await;+ let (_tmp, dest) = temp_dest();+ sync(addr, &dest).await.expect("export of project a");+ assert!(dest.join("decisions/db.md").exists());++ // Project b lists no pages at all; nothing about this destination belongs+ // to it.+ let (b_addr, _b) = serve(Fixture {+ any_project: true,+ ..Fixture::with_pages(Vec::new())+ })+ .await;+ let mut b_args = deleting_args(b_addr, &dest, None);+ b_args.run.project = "b".to_string();+ let err = bidi::run(&b_args, SyncMode::Apply)+ .await+ .expect_err("another project's baseline must not be reused");+ let message = format!("{err:#}");+ assert!(+ message.contains("belongs to") && message.contains("--adopt-scope"),+ "{message}"+ );+ assert!(+ dest.join("decisions/db.md").exists(),+ "the previous project's file must survive the refusal"+ );+ assert!(+ !state::load(&dest).unwrap().pages.is_empty(),+ "the refusal must not empty the baseline"+ );++ // The explicit takeover discards the baseline instead of reading it as+ // deletions. Project b here holds the same page, so the adopted run has+ // nothing to write and simply stamps the new scope.+ let (b_page_addr, _) = serve(Fixture {+ any_project: true,+ ..Fixture::with_pages(vec![decision()])+ })+ .await;+ let mut adopted = sync_args(b_page_addr, &dest, None);+ adopted.run.project = "b".to_string();+ adopted.run.adopt_scope = true;+ bidi::run(&adopted, SyncMode::Apply)+ .await+ .expect("adopting the destination is explicit");+ assert_eq!(+ state::load(&dest).unwrap().scope,+ Some(state::SyncScope::of(+ &format!("http://{b_page_addr}"),+ "demo",+ "b"+ ))+ );+ assert!(+ dest.join("decisions/db.md").exists(),+ "adoption writes no delete"+ );+ assert_eq!(+ fixture.page("decisions/db.md").unwrap().body,+ "# DB\nUse Postgres.\n",+ "the control: the first project's server copy is untouched"+ );+}++/// The same project on the same server keeps working, which is the control+/// for the guard above.+#[tokio::test]+async fn reusing_a_destination_for_the_same_project_still_syncs() {+ let (addr, _) = serve(Fixture::with_pages(vec![decision()])).await;+ let (_tmp, dest) = temp_dest();+ sync(addr, &dest).await.expect("first sync");+ let second = sync(addr, &dest).await.expect("same-scope sync");+ assert_eq!(+ second.status(),+ bidi::CheckStatus::InSync,+ "a same-scope rerun is in sync"+ );+}+#[tokio::test]async fn sync_exports_metadata_and_round_trips_without_writes() {let (addr, fixture) = serve(Fixture::with_pages(vec![decision()])).await;@@ -1113,6 +1208,17 @@ async fn sync_reports_a_page_changed_during_the_run_and_applies_the_rest() {])};let (race_addr, raced) = serve(racing).await;+ // The fixture binds a new ephemeral port, and the baseline records the+ // origin it was exported from (#1708). This test means "the same project,+ // served again", so restamp the scope rather than adopt a foreign one:+ // adopting would discard the baseline the race classification needs.+ let mut restamped = state::load(&dest).unwrap();+ restamped.scope = Some(state::SyncScope::of(+ &format!("http://{race_addr}"),+ "demo",+ "app",+ ));+ state::save(&dest, &restamped).unwrap();let err = sync(race_addr, &dest).await.expect_err("race reported");let message = format!("{err:#}");assert!(message.contains("changed during this run"), "{message}");diff --git a/docs/companion-crates.md b/docs/companion-crates.mdindex d3ad5e0e..3da6856c 100644--- a/docs/companion-crates.md+++ b/docs/companion-crates.md@@ -305,6 +305,13 @@ directions are family-scoped and dry-run by default.state, server body): files edited locally since the last export arereported with a diff summary and the whole batch is refused without`--force`.+- The state file records the server origin, workspace and project it was+ exported from. Reusing a destination for another scope refuses before+ anything is written — otherwise that project's pages read as "deleted on+ the server" and `--propagate-deletes --apply` removes them — and+ `--adopt-scope` is the explicit way to discard the baseline and start+ fresh (#1708). A baseline written before the field existed is adopted on+ its first run, with a warning.- `plan` and `export` never delete; `sync` deletes only with`--propagate-deletes`. It never runs git, commits, or pushes; it printsthe commands (`git add`, `git rm`) the operator may run.