Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(wikisync): accept ordinary Windows destination prefixes
Jun5164f1db907a946
diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.ymlindex f8a59605..1f651fbb 100644--- a/.github/workflows/windows.yml+++ b/.github/workflows/windows.yml@@ -79,14 +79,15 @@ jobs:# Windows jobs auto-run on those PRs without a human remembering the label.# It runs on every event (a cheap Linux job) so the `needs:` edge below is# always satisfied; the filter step only fires on `pull_request`, where its- # `platform` output drives the gate. On schedule / manual dispatch the output- # is empty and unused, because those jobs' `if:` short-circuits on+ # path outputs drive the gates. On schedule / manual dispatch the outputs+ # are empty and unused, because those jobs' `if:` short-circuits on# `github.event_name != 'pull_request'`.changes:name: detect platform-sensitive changesruns-on: ubuntu-latestoutputs:platform: ${{ steps.filter.outputs.platform }}+ wikisync: ${{ steps.filter.outputs.wikisync }}steps:# For `pull_request` events this action reads the changed-file list from# the GitHub API, so no checkout is needed. Pinned to a full commit SHA@@ -110,6 +111,32 @@ jobs:- 'install.ps1'- 'tests/install_ps1.ps1'- '.github/workflows/windows.yml'+ wikisync:+ - 'companions/ai-memory-wikisync/**'+ - '.github/workflows/windows.yml'++ # This companion has its own Cargo workspace. Its path changes run native+ # Windows checks without also starting the root workspace or hook suite.+ wikisync:+ name: wiki sync companion (windows-latest)+ needs: changes+ if: >-+ github.event_name != 'pull_request' ||+ contains(github.event.pull_request.labels.*.name, 'windows') ||+ contains(github.event.pull_request.labels.*.name, 'full-ci') ||+ needs.changes.outputs.wikisync == 'true'+ runs-on: windows-latest+ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ - uses: dtolnay/rust-toolchain@4cda84d5c5c54efe2404f9d843567869ab1699d4 # stable+ with:+ components: rustfmt, clippy+ - uses: Swatinem/rust-cache@f0d9c3887740aee45f6153b24b3a6b815192ec16 # v2+ with:+ workspaces: companions/ai-memory-wikisync+ - run: cargo fmt --check --manifest-path companions/ai-memory-wikisync/Cargo.toml+ - run: cargo clippy --locked --manifest-path companions/ai-memory-wikisync/Cargo.toml --all-targets -- -D warnings+ - run: cargo test --locked --manifest-path companions/ai-memory-wikisync/Cargo.tomltest:name: test (windows-latest)diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e3539787..00bd48af 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -12,6 +12,9 @@ version in [`docs/changelog/`](docs/changelog/):## [Unreleased]### Fixed+- Accepted ordinary absolute and relative Windows destination paths in the+ wiki sync companion while still refusing directory junctions and symlinks.+ ([#1476](https://github.com/akitaonrails/ai-memory/issues/1476))- Routed OpenCode's `claude-haiku-5-5` through the Anthropic Messages API forboth Go and Zen instead of the unsupported Chat Completions protocol.([#1470](https://github.com/akitaonrails/ai-memory/issues/1470))diff --git a/companions/ai-memory-wikisync/README.md b/companions/ai-memory-wikisync/README.mdindex 242182b0..fcfdcbc8 100644--- a/companions/ai-memory-wikisync/README.md+++ b/companions/ai-memory-wikisync/README.md@@ -26,6 +26,10 @@ cargo fmt --check --manifest-path companions/ai-memory-wikisync/Cargo.tomlcargo clippy --manifest-path companions/ai-memory-wikisync/Cargo.toml --all-targets -- -D warnings```+The [Windows workflow](../../.github/workflows/windows.yml) checks this+companion separately when its files or that workflow change, when a PR has+the `windows` or `full-ci` label, and on nightly or manual runs.+## Usage```bash@@ -110,6 +114,8 @@ This section describes `plan` and `export`; `sync` adds the rules under`--dest`; case-fold collisions are refused; symlinked destinations,symlinked components and symlinked state directories are refused; filesare replaced atomically (tmp + rename + fsync).+ On Windows, ordinary absolute and relative destinations are accepted;+ directory junctions and paths through them are still refused.- **Local edits win until forced.** Each page is compared three ways:destination file, last exported state, server body. A file thatdiverged from both is reported with a diff summary and refused; thediff --git a/companions/ai-memory-wikisync/src/hook.rs b/companions/ai-memory-wikisync/src/hook.rsindex 2b2e995d..d4dd33ab 100644--- a/companions/ai-memory-wikisync/src/hook.rs+++ b/companions/ai-memory-wikisync/src/hook.rs@@ -467,11 +467,12 @@ mod tests {"{text}");assert!(- text.contains(+ text.contains(&format!("( command -v ai-memory-wikisync >/dev/null && ai-memory-wikisync sync \- --workspace 'demo' --project 'app' --dest 'docs/wiki' --include 'decisions' ) \- || true"- ),+ --workspace 'demo' --project 'app' --dest '{}' --include 'decisions' ) \+ || true",+ Path::new("docs").join("wiki").display()+ )),"{text}");for flag in [@@ -616,7 +617,13 @@ mod tests {install(&install_args(&worktree.join("docs/wiki"))).unwrap();let text = fs::read_to_string(hook_of(&root)).unwrap();- assert!(text.contains("--dest 'docs/wiki'"), "{text}");+ assert!(+ text.contains(&format!(+ "--dest '{}'",+ Path::new("docs").join("wiki").display()+ )),+ "{text}"+ );// A worktree config can set hooksPath too.fs::write(wt_gitdir.join("config.worktree"), "[core]\nhooksPath = x\n").unwrap();diff --git a/companions/ai-memory-wikisync/src/paths.rs b/companions/ai-memory-wikisync/src/paths.rsindex 5bad7db8..1422e11f 100644--- a/companions/ai-memory-wikisync/src/paths.rs+++ b/companions/ai-memory-wikisync/src/paths.rs@@ -180,6 +180,41 @@ pub fn lexical_absolute(path: &Path) -> PathBuf {normalized}+#[cfg(not(windows))]+fn destination_paths_match(canonical: &Path, lexical: &Path) -> bool {+ canonical == lexical+}++#[cfg(windows)]+fn destination_paths_match(canonical: &Path, lexical: &Path) -> bool {+ use std::path::Prefix;++ // Windows canonicalization adds a verbatim prefix even when no link was+ // followed. Compare the remaining components without resolving lexical:+ // resolving both paths would hide junctions and ancestor symlinks.+ let mut canonical = canonical.components();+ let mut lexical = lexical.components();+ let same_prefix = match (canonical.next(), lexical.next()) {+ (Some(Component::Prefix(left)), Some(Component::Prefix(right))) => {+ match (left.kind(), right.kind()) {+ (+ Prefix::Disk(left) | Prefix::VerbatimDisk(left),+ Prefix::Disk(right) | Prefix::VerbatimDisk(right),+ ) => left.eq_ignore_ascii_case(&right),+ (+ Prefix::UNC(left_server, left_share)+ | Prefix::VerbatimUNC(left_server, left_share),+ Prefix::UNC(right_server, right_share)+ | Prefix::VerbatimUNC(right_server, right_share),+ ) => left_server == right_server && left_share == right_share,+ (left, right) => left == right,+ }+ }+ (left, right) => left == right,+ };+ same_prefix && canonical.eq(lexical)+}+/// Prepare the destination directory: create it when missing, then refuse/// symlinked destinations (including any symlinked component on the way —/// on Windows this also catches junction/reparse targets via the@@ -207,7 +242,7 @@ pub fn prepare_dest(dest: &Path) -> Result<PathBuf> {let lexical = lexical_absolute(dest);let canonical = fs::canonicalize(dest).with_context(|| format!("cannot canonicalize --dest {}", dest.display()))?;- if canonical != lexical {+ if !destination_paths_match(&canonical, &lexical) {bail!("--dest reaches through a symlink ({} -> {}); pass the resolved path instead",lexical.display(),@@ -341,6 +376,102 @@ mod tests {assert!(made.is_dir());}+ #[cfg(windows)]+ #[test]+ fn prepare_dest_accepts_plain_windows_absolute_paths() {+ // Windows TEMP may use an 8.3 alias, which exercises a different+ // canonicalization change from the verbatim prefix under test.+ let tmp = tempfile::tempdir_in(std::env::current_dir().unwrap()).unwrap();+ let dest = tmp.path().join("wiki").join("nested");+ assert_eq!(prepare_dest(&dest).unwrap(), dest.canonicalize().unwrap());+ assert_eq!(+ prepare_dest(tmp.path()).unwrap(),+ tmp.path().canonicalize().unwrap()+ );+ }++ #[cfg(windows)]+ #[test]+ fn prepare_dest_accepts_windows_relative_paths() {+ let cwd = std::env::current_dir().unwrap();+ let tmp = tempfile::tempdir_in(&cwd).unwrap();+ let relative = tmp.path().strip_prefix(&cwd).unwrap().join("wiki");+ assert!(!relative.is_absolute());+ assert_eq!(+ prepare_dest(&relative).unwrap(),+ tmp.path().join("wiki").canonicalize().unwrap()+ );+ }++ #[cfg(windows)]+ #[test]+ fn windows_destination_prefixes_do_not_hide_different_paths() {+ for (canonical, lexical) in [+ (r"\\?\C:\wiki", r"C:\wiki"),+ (r"\\?\C:\wiki", r"c:\wiki"),+ (r"\\?\UNC\server\share\wiki", r"\\server\share\wiki"),+ (r"\\?\C:\wiki", r"\\?\C:\wiki"),+ ] {+ assert!(destination_paths_match(+ Path::new(canonical),+ Path::new(lexical)+ ));+ }+ for (canonical, lexical) in [+ (r"\\?\C:\outside", r"C:\wiki"),+ (r"\\?\C:\wiki", r"D:\wiki"),+ (r"\\?\UNC\server\share\wiki", r"\\server\other\wiki"),+ (r"\\?\UNC\server\share\wiki", r"\\other\share\wiki"),+ (r"\\?\Volume{one}\wiki", r"\\?\Volume{two}\wiki"),+ ] {+ assert!(!destination_paths_match(+ Path::new(canonical),+ Path::new(lexical)+ ));+ }+ }++ #[cfg(windows)]+ #[test]+ fn prepare_dest_refuses_windows_junctions_without_touching_the_target() {+ let tmp = tempfile::tempdir_in(std::env::current_dir().unwrap()).unwrap();+ let outside = tmp.path().join("outside");+ let child = outside.join("child");+ fs::create_dir_all(&child).unwrap();+ let canary = child.join("canary.md");+ fs::write(&canary, b"untouched").unwrap();+ assert_eq!(prepare_dest(&child).unwrap(), child.canonicalize().unwrap());++ let junction = tmp.path().join("junction");+ // A junction needs no symlink privilege. Paths stay data in the+ // child environment, including shell metacharacters in a temp root.+ let output = std::process::Command::new("powershell.exe")+ .args([+ "-NoProfile",+ "-NonInteractive",+ "-Command",+ "$ErrorActionPreference = 'Stop'; New-Item -ItemType Junction -Path $env:WIKISYNC_TEST_LINK -Target $env:WIKISYNC_TEST_TARGET | Out-Null",+ ])+ .env("WIKISYNC_TEST_LINK", &junction)+ .env("WIKISYNC_TEST_TARGET", &outside)+ .output()+ .unwrap();+ assert!(+ output.status.success(),+ "{}",+ String::from_utf8_lossy(&output.stderr)+ );++ for dest in [&junction, &junction.join("child")] {+ let err = prepare_dest(dest).unwrap_err().to_string();+ assert!(err.contains("symlink"), "{err}");+ }+ assert_eq!(fs::read(&canary).unwrap(), b"untouched");+ assert_eq!(fs::read_dir(&child).unwrap().count(), 1);+ fs::remove_dir(&junction).unwrap();+ assert!(canary.is_file());+ }+#[test]fn secure_join_stays_under_root_and_refuses_symlink_components() {let tmp = tempfile::tempdir().unwrap();diff --git a/docs/security-boundaries.md b/docs/security-boundaries.mdindex c007ed58..e6a60960 100644--- a/docs/security-boundaries.md+++ b/docs/security-boundaries.md@@ -57,6 +57,7 @@ means the boundary is not built yet.| 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 || 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 | `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) | STRONG |+| 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 || 6 | Active-project pointer (PerActor, no clobber) | `ai-memory-core/src/active_project.rs` `set_for`/`lookup_for` (fail-closed on `Mismatch`); `ai-memory-cli/src/commands/mcp_bridge.rs` `bridge_session_id`: the session-less bridge (`--no-session-id`, every non-Claude stdio client on a token-file install) never forwards an inherited `CLAUDE_CODE_SESSION_ID`, so a client launched from a Claude Code terminal cannot steer that session's per-session pointer; the session-aware bridge reads only the variable its `--agent` names (`CLAUDE_CODE_SESSION_ID`, or `MUSE_SESSION_ID` for Meta Muse Code), so neither harness's id stands in for the other's | `active_project.rs` `parallel_harnesses_of_one_user_keep_separate_pointers`, `two_operators_never_read_each_others_pointer`, `a_session_mismatch_fails_closed_once_anything_has_been_keyed`; `mcp_bridge.rs` `only_the_session_aware_mode_forwards_and_requires_a_session_id` (an inherited id is dropped in session-less mode; the session-aware control forwards it and still fails closed without one), `each_harness_forwards_only_its_own_session_id` (a Muse bridge never forwards an inherited Claude id and fails closed without its own, a Claude bridge never forwards an inherited Muse id; controls forward each harness's own id) and `a_session_less_upstream_config_carries_no_session_header`; `auth_default_e2e.rs` `a_session_less_bridge_serves_any_client_without_holding_the_token` (the built `mcp-bridge --agent muse` refuses to start with only `CLAUDE_CODE_SESSION_ID` set) | STRONG || 6b | Native `_meta` routing coordinate is routing-only (never grants identity) | `ai-memory-mcp/src/server.rs` `attach_native_session` reads only `_meta["ai.opencode/sessionID"]` into `ActorKey.session_id` (trimmed, non-empty-string-validated); `user` still comes from the authenticated `ActorContext`, so a forged `_meta` cannot cross a user/scope boundary — it only selects a session slot behind the existing `active_project` guard | `server.rs` `native_session_metadata_is_routing_only_and_preserves_precedence`, `native_session_metadata_validates_strings_without_granting_identity`; `autoscope_multiuser.rs` `native_metadata_routes_concurrent_reads_and_writes_to_hook_workspaces` (#864) | STRONG || 6c | Per-user slot namespaces stay per operator (`[slots] per_user`) | `ai-memory-mcp/src/server.rs` `place_slot_mutation`, shared by `place_slot_write` (`memory_write_page`) and `place_slot_delete` (`memory_delete_page`): a non-admin's generic `_slots/<name>.md` is redirected to their own `_slots/u-<operator>/` namespace, a path inside another operator's namespace is refused, admins bypass, and nothing changes with the flag off (#1083) | `slot_identity.rs` `oidc_operator_cannot_delete_another_operators_personal_slot`, `oidc_operator_deleting_shared_slot_path_deletes_their_personal_slot` (shared slot survives), legitimate controls `oidc_operator_can_delete_their_own_personal_slot_explicitly`, `admin_can_delete_shared_and_personal_slots` | STRONG |