Skip to content

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

Rust

feat(wikisync): read-only team-wiki export companion (#986)

AkitaOnRailsd73485de30d5
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index f3b0a53c..07994b42 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -156,7 +156,7 @@ jobs:
strategy:
fail-fast: false
matrix:
- companion: [ai-memory-client, ai-memory-importer, ai-memory-relay]
+ companion: [ai-memory-client, ai-memory-importer, ai-memory-relay, ai-memory-wikisync]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
@@ -356,6 +356,7 @@ jobs:
- run: cargo audit --file companions/ai-memory-relay/Cargo.lock
- run: cargo audit --file companions/ai-memory-importer/Cargo.lock
- run: cargo audit --file companions/ai-memory-client/Cargo.lock
+ - run: cargo audit --file companions/ai-memory-wikisync/Cargo.lock
gitleaks:
name: gitleaks (secret scan)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9378aed5..2c0e95ce 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Added
+- Added the `ai-memory-wikisync` companion (slice 1 of the accepted #986
+ team-wiki sync plan): a standalone read-only export tool that mirrors
+ explicitly allowlisted page families from a running server's `/api/v1`
+ surface into a directory inside a project repository. `plan` is always a
+ dry-run; `export` writes only with `--apply`, stores per-page hashes and
+ ETags in a single local state file, transports the server's canonical
+ page projection verbatim without forging frontmatter, refuses files
+ edited locally since the last export (with a diff summary) unless
+ `--force` is passed, never deletes anything, and never runs git — it
+ prints the commands instead. Bidirectional sync, deletes, and conflict
+ handling remain tracked in #986. (#986)
+
## [2.6.0] - 2026-10-07
### Added
diff --git a/README.md b/README.md
index 8075121e..91b4cb28 100644
--- a/README.md
+++ b/README.md
@@ -606,7 +606,7 @@ diagram, crate breakdown, schema notes, and invariants.
| [`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. |
| [`docs/managed-harness-contributions.md`](docs/managed-harness-contributions.md) | Protocol and acceptance bar for adding managed resume, transcript import, and startup context delivery to another harness. |
-| [`docs/companion-crates.md`](docs/companion-crates.md) | Optional companion projects: the [importer](companions/ai-memory-importer), [external lifecycle relay](companions/ai-memory-relay), and accepted team-wiki sync boundary. |
+| [`docs/companion-crates.md`](docs/companion-crates.md) | Optional companion projects: the [importer](companions/ai-memory-importer), [external lifecycle relay](companions/ai-memory-relay), and [team-wiki export](companions/ai-memory-wikisync). |
| [`docs/external-lifecycle.md`](docs/external-lifecycle.md) | External lifecycle producers: per-execution native capture suppression, preserved handoffs, batch ingestion and stable retry identity. |
| [`docs/auto-improvement-loop.md`](docs/auto-improvement-loop.md) | Auto-improvement design notes: scheduled review, auto-approval default, manual review opt-in, pending proposal storage, and curator work. |
diff --git a/companions/ai-memory-wikisync/Cargo.lock b/companions/ai-memory-wikisync/Cargo.lock
new file mode 100644
index 00000000..8d15e64c
--- /dev/null
+++ b/companions/ai-memory-wikisync/Cargo.lock
@@ -0,0 +1,1660 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 4
+
+[[package]]
+name = "ai-memory-wikisync"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "axum",
+ "clap",
+ "reqwest",
+ "serde",
+ "serde_json",
+ "sha2",
+ "tempfile",
+ "tokio",
+ "url",
+]
+
+[[package]]
+name = "anstream"
+version = "1.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d"
+dependencies = [
+ "anstyle",
+ "anstyle-parse",
+ "anstyle-query",
+ "anstyle-wincon",
+ "colorchoice",
+ "is_terminal_polyfill",
+ "utf8parse",
+]
+
+[[package]]
+name = "anstyle"
+version = "1.0.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"
+
+[[package]]
+name = "anstyle-parse"
+version = "1.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e"
+dependencies = [
+ "utf8parse",
+]
+
+[[package]]
+name = "anstyle-query"
+version = "1.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"
+dependencies = [
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "anstyle-wincon"
+version = "3.0.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"
+dependencies = [
+ "anstyle",
+ "once_cell_polyfill",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "anyhow"
+version = "1.0.104"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
+
+[[package]]
+name = "atomic-waker"
+version = "1.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
+
+[[package]]
+name = "axum"
+version = "0.8.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90"
+dependencies = [
+ "axum-core",
+ "bytes",
+ "form_urlencoded",
+ "futures-util",
+ "http",
+ "http-body",
+ "http-body-util",
+ "hyper",
+ "hyper-util",
+ "itoa",
+ "matchit",
+ "memchr",
+ "mime",
+ "percent-encoding",
+ "pin-project-lite",
+ "serde_core",
+ "serde_json",
+ "serde_path_to_error",
+ "serde_urlencoded",
+ "sync_wrapper",
+ "tokio",
+ "tower",
+ "tower-layer",
+ "tower-service",
+ "tracing",
+]
+
+[[package]]
+name = "axum-core"
+version = "0.5.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1"
+dependencies = [
+ "bytes",
+ "futures-core",
+ "http",
+ "http-body",
+ "http-body-util",
+ "mime",
+ "pin-project-lite",
+ "sync_wrapper",
+ "tower-layer",
+ "tower-service",
+ "tracing",
+]
+
+[[package]]
+name = "base64"
+version = "0.22.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
+
+[[package]]
+name = "base64"
+version = "0.23.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"
+
+[[package]]
+name = "bitflags"
+version = "2.13.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
+
+[[package]]
+name = "block-buffer"
+version = "0.10.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
+dependencies = [
+ "generic-array",
+]
+
+[[package]]
+name = "bumpalo"
+version = "3.20.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"
+
+[[package]]
+name = "bytes"
+version = "1.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
+
+[[package]]
+name = "cc"
+version = "1.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f74872d07caf508b30a21f6836e7d7016a2eaf7d9ff4f48deaa58cd8a0407630"
+dependencies = [
+ "find-msvc-tools",
+ "shlex",
+]
+
+[[package]]
+name = "cfg-if"
+version = "1.0.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
+
+[[package]]
+name = "cfg_aliases"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"
+
+[[package]]
+name = "chacha20"
+version = "0.10.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06"
+dependencies = [
+ "cfg-if",
+ "cpufeatures 0.3.1",
+ "rand_core",
+]
+
+[[package]]
+name = "clap"
+version = "4.6.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946"
+dependencies = [
+ "clap_builder",
+ "clap_derive",
+]
+
+[[package]]
+name = "clap_builder"
+version = "4.6.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d"
+dependencies = [
+ "anstream",
+ "anstyle",
+ "clap_lex",
+ "strsim",
+]
+
+[[package]]
+name = "clap_derive"
+version = "4.6.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0"
+dependencies = [
+ "heck",
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "clap_lex"
+version = "1.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486"
+
+[[package]]
+name = "colorchoice"
+version = "1.0.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"
+
+[[package]]
+name = "core-foundation"
+version = "0.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6"
+dependencies = [
+ "core-foundation-sys",
+ "libc",
+]
+
+[[package]]
+name = "core-foundation-sys"
+version = "0.8.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
+
+[[package]]
+name = "cpufeatures"
+version = "0.2.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "cpufeatures"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "crypto-common"
+version = "0.1.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
+dependencies = [
+ "generic-array",
+ "typenum",
+]
+
+[[package]]
+name = "digest"
+version = "0.10.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
+dependencies = [
+ "block-buffer",
+ "crypto-common",
+]
+
+[[package]]
+name = "displaydoc"
+version = "0.2.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "errno"
+version = "0.3.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
+dependencies = [
+ "libc",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "fastrand"
+version = "2.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
+
+[[package]]
+name = "find-msvc-tools"
+version = "0.1.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484"
+
+[[package]]
+name = "form_urlencoded"
+version = "1.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"
+dependencies = [
+ "percent-encoding",
+]
+
+[[package]]
+name = "futures-channel"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4"
+dependencies = [
+ "futures-core",
+]
+
+[[package]]
+name = "futures-core"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e"
+
+[[package]]
+name = "futures-task"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd"
+
+[[package]]
+name = "futures-util"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc"
+dependencies = [
+ "futures-core",
+ "futures-task",
+ "pin-project-lite",
+ "slab",
+]
+
+[[package]]
+name = "generic-array"
+version = "0.14.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
+dependencies = [
+ "typenum",
+ "version_check",
+]
+
+[[package]]
+name = "getrandom"
+version = "0.2.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
+dependencies = [
+ "cfg-if",
+ "js-sys",
+ "libc",
+ "wasi",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "getrandom"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
+dependencies = [
+ "cfg-if",
+ "js-sys",
+ "libc",
+ "r-efi",
+ "rand_core",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "heck"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
+
+[[package]]
+name = "http"
+version = "1.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0"
+dependencies = [
+ "bytes",
+ "itoa",
+]
+
+[[package]]
+name = "http-body"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c"
+dependencies = [
+ "bytes",
+ "http",
+]
+
+[[package]]
+name = "http-body-util"
+version = "0.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c"
+dependencies = [
+ "bytes",
+ "futures-core",
+ "http",
+ "http-body",
+ "pin-project-lite",
+]
+
+[[package]]
+name = "httparse"
+version = "1.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
+
+[[package]]
+name = "httpdate"
+version = "1.0.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"
+
+[[package]]
+name = "hyper"
+version = "1.12.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c"
+dependencies = [
+ "atomic-waker",
+ "bytes",
+ "futures-core",
+ "http",
+ "http-body",
+ "httparse",
+ "httpdate",
+ "itoa",
+ "pin-project-lite",
+ "smallvec",
+ "tokio",
+ "want",
+]
+
+[[package]]
+name = "hyper-rustls"
+version = "0.27.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53"
+dependencies = [
+ "http",
+ "hyper",
+ "hyper-util",
+ "rustls",
+ "rustls-native-certs",
+ "tokio",
+ "tokio-rustls",
+ "tower-service",
+]
+
+[[package]]
+name = "hyper-util"
+version = "0.1.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff"
+dependencies = [
+ "base64 0.23.1",
+ "bytes",
+ "futures-channel",
+ "futures-util",
+ "http",
+ "http-body",
+ "httparse",
+ "hyper",
+ "ipnet",
+ "libc",
+ "percent-encoding",
+ "pin-project-lite",
+ "socket2",
+ "tokio",
+ "tower-service",
+ "tracing",
+]
+
+[[package]]
+name = "icu_collections"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513"
+dependencies = [
+ "displaydoc",
+ "potential_utf",
+ "utf8_iter",
+ "yoke",
+ "zerofrom",
+ "zerovec",
+]
+
+[[package]]
+name = "icu_locale_core"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb"
+dependencies = [
+ "displaydoc",
+ "litemap",
+ "tinystr",
+ "writeable",
+ "zerovec",
+]
+
+[[package]]
+name = "icu_normalizer"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f"
+dependencies = [
+ "icu_collections",
+ "icu_normalizer_data",
+ "icu_properties",
+ "icu_provider",
+ "smallvec",
+ "zerovec",
+]
+
+[[package]]
+name = "icu_normalizer_data"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0"
+
+[[package]]
+name = "icu_properties"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148"
+dependencies = [
+ "displaydoc",
+ "icu_collections",
+ "icu_locale_core",
+ "icu_properties_data",
+ "icu_provider",
+ "zerotrie",
+ "zerovec",
+]
+
+[[package]]
+name = "icu_properties_data"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa"
+
+[[package]]
+name = "icu_provider"
+version = "2.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73"
+dependencies = [
+ "displaydoc",
+ "icu_locale_core",
+ "writeable",
+ "yoke",
+ "zerofrom",
+ "zerotrie",
+ "zerovec",
+]
+
+[[package]]
+name = "idna"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de"
+dependencies = [
+ "idna_adapter",
+ "smallvec",
+ "utf8_iter",
+]
+
+[[package]]
+name = "idna_adapter"
+version = "1.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714"
+dependencies = [
+ "icu_normalizer",
+ "icu_properties",
+]
+
+[[package]]
+name = "ipnet"
+version = "2.12.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0"
+
+[[package]]
+name = "is_terminal_polyfill"
+version = "1.70.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
+
+[[package]]
+name = "itoa"
+version = "1.0.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
+
+[[package]]
+name = "js-sys"
+version = "0.3.106"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5"
+dependencies = [
+ "cfg-if",
+ "futures-util",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "libc"
+version = "0.2.190"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78"
+
+[[package]]
+name = "linux-raw-sys"
+version = "0.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
+
+[[package]]
+name = "litemap"
+version = "0.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae"
+
+[[package]]
+name = "log"
+version = "0.4.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"
+
+[[package]]
+name = "lru-slab"
+version = "0.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f"
+
+[[package]]
+name = "matchit"
+version = "0.8.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3"
+
+[[package]]
+name = "memchr"
+version = "2.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
+
+[[package]]
+name = "mime"
+version = "0.3.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"
+
+[[package]]
+name = "mio"
+version = "1.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee"
+dependencies = [
+ "libc",
+ "wasi",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "once_cell"
+version = "1.21.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
+
+[[package]]
+name = "once_cell_polyfill"
+version = "1.70.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
+
+[[package]]
+name = "openssl-probe"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe"
+
+[[package]]
+name = "percent-encoding"
+version = "2.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
+
+[[package]]
+name = "pin-project-lite"
+version = "0.2.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
+
+[[package]]
+name = "potential_utf"
+version = "0.1.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661"
+dependencies = [
+ "zerovec",
+]
+
+[[package]]
+name = "proc-macro2"
+version = "1.0.107"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "quinn"
+version = "0.11.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11"
+dependencies = [
+ "bytes",
+ "cfg_aliases",
+ "pin-project-lite",
+ "quinn-proto",
+ "quinn-udp",
+ "rustc-hash",
+ "rustls",
+ "socket2",
+ "thiserror",
+ "tokio",
+ "tracing",
+ "web-time",
+]
+
+[[package]]
+name = "quinn-proto"
+version = "0.11.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe"
+dependencies = [
+ "bytes",
+ "getrandom 0.4.3",
+ "lru-slab",
+ "rand",
+ "rand_pcg",
+ "ring",
+ "rustc-hash",
+ "rustls",
+ "rustls-pki-types",
+ "slab",
+ "thiserror",
+ "tinyvec",
+ "tracing",
+ "web-time",
+]
+
+[[package]]
+name = "quinn-udp"
+version = "0.5.16"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016"
+dependencies = [
+ "cfg_aliases",
+ "libc",
+ "once_cell",
+ "socket2",
+ "tracing",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "quote"
+version = "1.0.47"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
+dependencies = [
+ "proc-macro2",
+]
+
+[[package]]
+name = "r-efi"
+version = "6.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
+
+[[package]]
+name = "rand"
+version = "0.10.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af"
+dependencies = [
+ "chacha20",
+ "getrandom 0.4.3",
+ "rand_core",
+]
+
+[[package]]
+name = "rand_core"
+version = "0.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"
+
+[[package]]
+name = "rand_pcg"
+version = "0.10.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a"
+dependencies = [
+ "rand_core",
+]
+
+[[package]]
+name = "reqwest"
+version = "0.12.28"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147"
+dependencies = [
+ "base64 0.22.1",
+ "bytes",
+ "futures-core",
+ "http",
+ "http-body",
+ "http-body-util",
+ "hyper",
+ "hyper-rustls",
+ "hyper-util",
+ "js-sys",
+ "log",
+ "percent-encoding",
+ "pin-project-lite",
+ "quinn",
+ "rustls",
+ "rustls-native-certs",
+ "rustls-pki-types",
+ "serde",
+ "serde_json",
+ "serde_urlencoded",
+ "sync_wrapper",
+ "tokio",
+ "tokio-rustls",
+ "tower",
+ "tower-http",
+ "tower-service",
+ "url",
+ "wasm-bindgen",
+ "wasm-bindgen-futures",
+ "web-sys",
+]
+
+[[package]]
+name = "ring"
+version = "0.17.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"
+dependencies = [
+ "cc",
+ "cfg-if",
+ "getrandom 0.2.17",
+ "libc",
+ "untrusted",
+ "windows-sys 0.52.0",
+]
+
+[[package]]
+name = "rustc-hash"
+version = "2.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"
+
+[[package]]
+name = "rustix"
+version = "1.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d"
+dependencies = [
+ "bitflags",
+ "errno",
+ "libc",
+ "linux-raw-sys",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "rustls"
+version = "0.23.45"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634"
+dependencies = [
+ "once_cell",
+ "ring",
+ "rustls-pki-types",
+ "rustls-webpki",
+ "subtle",
+ "zeroize",
+]
+
+[[package]]
+name = "rustls-native-certs"
+version = "0.8.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dab5152771c58876a2146916e53e35057e1a4dfa2b9df0f0305b07f611fdea4d"
+dependencies = [
+ "openssl-probe",
+ "rustls-pki-types",
+ "schannel",
+ "security-framework",
+]
+
+[[package]]
+name = "rustls-pki-types"
+version = "1.15.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96"
+dependencies = [
+ "web-time",
+ "zeroize",
+]
+
+[[package]]
+name = "rustls-webpki"
+version = "0.103.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2"
+dependencies = [
+ "ring",
+ "rustls-pki-types",
+ "untrusted",
+]
+
+[[package]]
+name = "rustversion"
+version = "1.0.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
+
+[[package]]
+name = "ryu"
+version = "1.0.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
+
+[[package]]
+name = "schannel"
+version = "0.1.29"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939"
+dependencies = [
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "security-framework"
+version = "3.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d"
+dependencies = [
+ "bitflags",
+ "core-foundation",
+ "core-foundation-sys",
+ "libc",
+ "security-framework-sys",
+]
+
+[[package]]
+name = "security-framework-sys"
+version = "2.17.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3"
+dependencies = [
+ "core-foundation-sys",
+ "libc",
+]
+
+[[package]]
+name = "serde"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
+dependencies = [
+ "serde_core",
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_core"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
+dependencies = [
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_derive"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "serde_json"
+version = "1.0.151"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14"
+dependencies = [
+ "itoa",
+ "memchr",
+ "serde",
+ "serde_core",
+ "zmij",
+]
+
+[[package]]
+name = "serde_path_to_error"
+version = "0.1.20"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457"
+dependencies = [
+ "itoa",
+ "serde",
+ "serde_core",
+]
+
+[[package]]
+name = "serde_urlencoded"
+version = "0.7.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd"
+dependencies = [
+ "form_urlencoded",
+ "itoa",
+ "ryu",
+ "serde",
+]
+
+[[package]]
+name = "sha2"
+version = "0.10.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
+dependencies = [
+ "cfg-if",
+ "cpufeatures 0.2.17",
+ "digest",
+]
+
+[[package]]
+name = "shlex"
+version = "2.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
+
+[[package]]
+name = "slab"
+version = "0.4.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
+
+[[package]]
+name = "smallvec"
+version = "1.16.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f9395f0f0eee849a9b707b2f06bb92a6a422090e2123bb2ef8e87a0e61892a8e"
+
+[[package]]
+name = "socket2"
+version = "0.6.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4"
+dependencies = [
+ "libc",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "stable_deref_trait"
+version = "1.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
+
+[[package]]
+name = "strsim"
+version = "0.11.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
+
+[[package]]
+name = "subtle"
+version = "2.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
+
+[[package]]
+name = "syn"
+version = "3.0.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "sync_wrapper"
+version = "1.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263"
+dependencies = [
+ "futures-core",
+]
+
+[[package]]
+name = "synstructure"
+version = "0.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "tempfile"
+version = "3.27.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
+dependencies = [
+ "fastrand",
+ "getrandom 0.4.3",
+ "once_cell",
+ "rustix",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "thiserror"
+version = "2.0.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"
+dependencies = [
+ "thiserror-impl",
+]
+
+[[package]]
+name = "thiserror-impl"
+version = "2.0.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "tinystr"
+version = "0.8.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643"
+dependencies = [
+ "displaydoc",
+ "zerovec",
+]
+
+[[package]]
+name = "tinyvec"
+version = "1.13.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee"
+
+[[package]]
+name = "tokio"
+version = "1.53.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e95f91fcc7a621e8b030f6aa23c71fe9838ae2fb4d8118b75602a328f5144044"
+dependencies = [
+ "bytes",
+ "libc",
+ "mio",
+ "pin-project-lite",
+ "socket2",
+ "tokio-macros",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "tokio-macros"
+version = "2.7.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "tokio-rustls"
+version = "0.26.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db"
+dependencies = [
+ "rustls",
+ "tokio",
+]
+
+[[package]]
+name = "tower"
+version = "0.5.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4"
+dependencies = [
+ "futures-core",
+ "futures-util",
+ "pin-project-lite",
+ "sync_wrapper",
+ "tokio",
+ "tower-layer",
+ "tower-service",
+ "tracing",
+]
+
+[[package]]
+name = "tower-http"
+version = "0.6.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840"
+dependencies = [
+ "bitflags",
+ "bytes",
+ "futures-util",
+ "http",
+ "http-body",
+ "pin-project-lite",
+ "tower",
+ "tower-layer",
+ "tower-service",
+ "url",
+]
+
+[[package]]
+name = "tower-layer"
+version = "0.3.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e"
+
+[[package]]
+name = "tower-service"
+version = "0.3.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3"
+
+[[package]]
+name = "tracing"
+version = "0.1.44"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"
+dependencies = [
+ "log",
+ "pin-project-lite",
+ "tracing-core",
+]
+
+[[package]]
+name = "tracing-core"
+version = "0.1.36"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"
+dependencies = [
+ "once_cell",
+]
+
+[[package]]
+name = "try-lock"
+version = "0.2.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
+
+[[package]]
+name = "typenum"
+version = "1.20.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
+
+[[package]]
+name = "unicode-ident"
+version = "1.0.26"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954"
+
+[[package]]
+name = "untrusted"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
+
+[[package]]
+name = "url"
+version = "2.5.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed"
+dependencies = [
+ "form_urlencoded",
+ "idna",
+ "percent-encoding",
+ "serde",
+]
+
+[[package]]
+name = "utf8_iter"
+version = "1.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
+
+[[package]]
+name = "utf8parse"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
+
+[[package]]
+name = "version_check"
+version = "0.9.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
+
+[[package]]
+name = "want"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b"
+dependencies = [
+ "try-lock",
+]
+
+[[package]]
+name = "wasi"
+version = "0.11.1+wasi-snapshot-preview1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
+
+[[package]]
+name = "wasm-bindgen"
+version = "0.2.129"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409"
+dependencies = [
+ "cfg-if",
+ "once_cell",
+ "rustversion",
+ "wasm-bindgen-macro",
+ "wasm-bindgen-shared",
+]
+
+[[package]]
+name = "wasm-bindgen-futures"
+version = "0.4.79"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3cbab34de2d982e9b48e18d216d04c4a6f641066ff19ffb699980f591ee3610e"
+dependencies = [
+ "js-sys",
+ "tokio",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "wasm-bindgen-macro"
+version = "0.2.129"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535"
+dependencies = [
+ "quote",
+ "wasm-bindgen-macro-support",
+]
+
+[[package]]
+name = "wasm-bindgen-macro-support"
+version = "0.2.129"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7"
+dependencies = [
+ "bumpalo",
+ "proc-macro2",
+ "quote",
+ "syn",
+ "wasm-bindgen-shared",
+]
+
+[[package]]
+name = "wasm-bindgen-shared"
+version = "0.2.129"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "web-sys"
+version = "0.3.106"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "88261b9deccee56594c11a3460c462c41f58d148598fe70ad77070126a68aba4"
+dependencies = [
+ "js-sys",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "web-time"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb"
+dependencies = [
+ "js-sys",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "windows-link"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
+
+[[package]]
+name = "windows-sys"
+version = "0.52.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
+dependencies = [
+ "windows-targets",
+]
+
+[[package]]
+name = "windows-sys"
+version = "0.61.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
+dependencies = [
+ "windows-link",
+]
+
+[[package]]
+name = "windows-targets"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
+dependencies = [
+ "windows_aarch64_gnullvm",
+ "windows_aarch64_msvc",
+ "windows_i686_gnu",
+ "windows_i686_gnullvm",
+ "windows_i686_msvc",
+ "windows_x86_64_gnu",
+ "windows_x86_64_gnullvm",
+ "windows_x86_64_msvc",
+]
+
+[[package]]
+name = "windows_aarch64_gnullvm"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
+
+[[package]]
+name = "windows_aarch64_msvc"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
+
+[[package]]
+name = "windows_i686_gnu"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
+
+[[package]]
+name = "windows_i686_gnullvm"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
+
+[[package]]
+name = "windows_i686_msvc"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
+
+[[package]]
+name = "windows_x86_64_gnu"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
+
+[[package]]
+name = "windows_x86_64_gnullvm"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
+
+[[package]]
+name = "windows_x86_64_msvc"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
+
+[[package]]
+name = "writeable"
+version = "0.6.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc"
+
+[[package]]
+name = "yoke"
+version = "0.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5"
+dependencies = [
+ "stable_deref_trait",
+ "yoke-derive",
+ "zerofrom",
+]
+
+[[package]]
+name = "yoke-derive"
+version = "0.8.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+ "synstructure",
+]
+
+[[package]]
+name = "zerofrom"
+version = "0.1.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272"
+dependencies = [
+ "zerofrom-derive",
+]
+
+[[package]]
+name = "zerofrom-derive"
+version = "0.1.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+ "synstructure",
+]
+
+[[package]]
+name = "zeroize"
+version = "1.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879"
+
+[[package]]
+name = "zerotrie"
+version = "0.2.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f"
+dependencies = [
+ "displaydoc",
+ "yoke",
+ "zerofrom",
+]
+
+[[package]]
+name = "zerovec"
+version = "0.11.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8"
+dependencies = [
+ "yoke",
+ "zerofrom",
+ "zerovec-derive",
+]
+
+[[package]]
+name = "zerovec-derive"
+version = "0.11.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "zmij"
+version = "1.0.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
diff --git a/companions/ai-memory-wikisync/Cargo.toml b/companions/ai-memory-wikisync/Cargo.toml
new file mode 100644
index 00000000..a8a30b73
--- /dev/null
+++ b/companions/ai-memory-wikisync/Cargo.toml
@@ -0,0 +1,24 @@
+[workspace]
+
+[package]
+name = "ai-memory-wikisync"
+version = "0.1.0"
+edition = "2024"
+publish = false
+
+[dependencies]
+anyhow = "1"
+clap = { version = "4", features = ["derive", "env"] }
+# Native roots, matching the workspace: the export reads from the same server
+# an operator may front with a private CA (#492).
+reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls-native-roots"] }
+serde = { version = "1", features = ["derive"] }
+serde_json = "1"
+sha2 = "0.10"
+tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
+url = "2"
+
+[dev-dependencies]
+axum = "0.8"
+tempfile = "3"
+tokio = { version = "1", features = ["net"] }
diff --git a/companions/ai-memory-wikisync/README.md b/companions/ai-memory-wikisync/README.md
new file mode 100644
index 00000000..a1215016
--- /dev/null
+++ b/companions/ai-memory-wikisync/README.md
@@ -0,0 +1,91 @@
+# ai-memory-wikisync
+
+Read-only **team-wiki export** companion for
+[ai-memory](https://github.com/akitaonrails/ai-memory) (issue #986,
+slice 1). It pulls explicitly allowlisted page families from a running
+ai-memory server through the public, read-only `/api/v1` surface into a
+directory inside a project repository, so a team's shared memory can live
+as reviewable markdown in git.
+
+It is a standalone Cargo package (own workspace, own lockfile); the root
+ai-memory workspace does not build or test it:
+
+```bash
+cargo test --manifest-path companions/ai-memory-wikisync/Cargo.toml
+cargo fmt --check --manifest-path companions/ai-memory-wikisync/Cargo.toml
+cargo clippy --manifest-path companions/ai-memory-wikisync/Cargo.toml --all-targets -- -D warnings
+```
+
+## Usage
+
+```bash
+# Always start with a dry-run: lists create/update/unchanged, writes nothing.
+ai-memory-wikisync plan \
+ --server http://127.0.0.1:49374 \
+ --workspace demo --project app \
+ --dest ./wiki \
+ --include _rules --include decisions
+
+# Same listing, then write — export without --apply is still a dry-run.
+ai-memory-wikisync export ... --apply
+```
+
+- `plan` never writes, not even the state file.
+- `export --apply` writes/updates markdown files under `--dest` and prints
+ the `git add` / `git commit` / `git push` commands you may run yourself —
+ the tool never runs git, never commits, never pushes.
+- `--include FAMILY` is a strict, explicit allowlist of top-level wiki
+ directories (`_rules`, `decisions`, …). At least one is required and a
+ bare `*` is refused: only what you name is exported.
+- Auth is a bearer token via `--token` or `AI_MEMORY_AUTH_TOKEN` (plus
+ `AI_MEMORY_SERVER_URL` for the server origin). Tokens are never logged
+ and never written to disk.
+
+## What it writes
+
+Exactly the server's canonical page projection: `path`, `title`, `body`.
+The page body (which carries its own `# H1` title) is transported
+verbatim. The tool never forges attribution, generated, or sync
+frontmatter into page files.
+
+All local bookkeeping lives in **one** state file,
+`.ai-memory-wikisync/state.json` (mode 0600, atomically replaced after
+each successful write batch): per page, the SHA-256 of the bytes last
+written plus the server `ETag` observed at that write. Nothing else is
+stored — no tokens, no server credentials.
+
+## Safety model
+
+- **API-only.** Documented read-only `/api/v1` endpoints (incremental
+ `recent` listing with cursor paging, single-page reads with
+ `ETag`/`If-None-Match` revalidation; the legacy array listing is
+ accepted as a fallback). No MCP, no admin routes, no writes to the
+ server. `401`/`403`/`404` become clear errors; page count and body size
+ are bounded per run.
+- **Path safety.** Every server-reported path is validated into a
+ portable shape (ASCII, no traversal, no dotfiles, no reserved Windows
+ names, `.md` leaf, bounded depth/length) before it is joined onto
+ `--dest`; case-fold collisions are refused; symlinked destinations,
+ symlinked components and symlinked state directories are refused; files
+ are replaced atomically (tmp + rename + fsync).
+- **Local edits win until forced.** Each page is classified three ways —
+ destination file, last exported state, server body. A file that
+ diverged from both is reported with a diff summary and **refused**; the
+ whole batch is refused, nothing is written. `--force` overwrites the
+ divergent files with server content.
+- **Never deletes.** Local files — including brand-new local files inside
+ an allowlisted family — are never deleted. Deletes are slice 4.
+- **Untrusted content.** Page bodies are data: transported verbatim,
+ never executed, never rendered, never interpreted. Paths that would
+ escape `--dest` are refused.
+
+## Roadmap (#986)
+
+This is slice 1 of the accepted team-wiki sync plan:
+
+1. **This release — read-only export** into a project repository.
+2. Conditional mutation seam (compare-and-write) in core, if independently
+ justified.
+3. Bidirectional apply (repo edits flow back through public write tools).
+4. Deletes and conflict reporting.
+5. Post-merge hook / CI integration.
diff --git a/companions/ai-memory-wikisync/src/client.rs b/companions/ai-memory-wikisync/src/client.rs
new file mode 100644
index 00000000..5e70d227
--- /dev/null
+++ b/companions/ai-memory-wikisync/src/client.rs
@@ -0,0 +1,304 @@
+//! Read-only `/api/v1` client.
+//!
+//! Only the documented frontend endpoints are used: incremental `recent`
+//! paging for the page listing (with the legacy bare-array response accepted
+//! as a fallback) and single-page reads with `ETag` / `If-None-Match`
+//! revalidation. No MCP, no admin routes, no writes. The bearer token is
+//! only ever attached as a request header — it never reaches an error
+//! message, a URL, or the state file.
+
+use std::time::Duration;
+
+use anyhow::{Result, anyhow, bail};
+use reqwest::StatusCode;
+use serde::Deserialize;
+use url::Url;
+
+pub const DEFAULT_SERVER_URL: &str = "http://127.0.0.1:49374";
+
+/// Listing anchor: everything strictly after the epoch. `updated_since` is
+/// exclusive, so no page is missed.
+const EPOCH: &str = "1970-01-01T00:00:00Z";
+const RECENT_LIMIT: usize = 100;
+/// Bound on cursor rounds so a hostile server cannot loop the client.
+const MAX_LIST_ROUNDS: usize = 1_000;
+const REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
+
+/// One row of the pages listing (`PageSummary` in `docs/frontend-api.md`).
+#[derive(Debug, Clone, Deserialize)]
+pub struct PageSummary {
+ pub path: String,
+ pub title: String,
+ #[serde(default)]
+ pub kind: String,
+ #[serde(default)]
+ pub tier: String,
+ #[serde(default)]
+ pub updated_at: String,
+}
+
+/// The canonical single-page projection. Only the fields this tool
+/// transports are decoded; everything else the server returns is ignored
+/// rather than stored, and nothing is forged locally.
+#[derive(Debug, Clone, Deserialize)]
+pub struct ApiPage {
+ pub path: String,
+ pub body_markdown: String,
+}
+
+/// Result of one page read: the body on `200`, or `None` on `304 Not
+/// Modified` when the supplied `If-None-Match` still matches.
+#[derive(Debug)]
+pub struct PageRead {
+ pub page: Option<ApiPage>,
+ pub etag: Option<String>,
+}
+
+pub struct ApiClient {
+ http: reqwest::Client,
+ base: Url,
+ token: Option<String>,
+}
+
+#[derive(Deserialize)]
+struct RecentIncremental {
+ pages: Vec<PageSummary>,
+ next_cursor: Option<String>,
+}
+
+impl ApiClient {
+ pub fn new(server_url: &str, token: Option<String>) -> Result<Self> {
+ let mut base =
+ Url::parse(server_url).map_err(|e| anyhow!("invalid --server {server_url:?}: {e}"))?;
+ if !base.username().is_empty() || base.password().is_some() {
+ bail!(
+ "server URL must not embed credentials; pass the token via --token \
+ or AI_MEMORY_AUTH_TOKEN instead"
+ );
+ }
+ if base.path() != "/" && !base.path().is_empty() {
+ bail!(
+ "server URL must be an origin (scheme://host[:port]); base-path \
+ deployments are not supported by this companion"
+ );
+ }
+ if base.query().is_some() || base.fragment().is_some() {
+ bail!("server URL must not carry a query or fragment");
+ }
+ base.set_path("");
+ let http = reqwest::Client::builder()
+ .timeout(REQUEST_TIMEOUT)
+ .build()
+ .context_build()?;
+ Ok(Self { http, base, token })
+ }
+
+ fn api_url(
+ &self,
+ workspace: &str,
+ project: &str,
+ tail: &[&str],
+ query: &[(&str, String)],
+ ) -> Result<Url> {
+ let mut url = self.base.clone();
+ {
+ let mut segments = url
+ .path_segments_mut()
+ .map_err(|_| anyhow!("server URL cannot serve as a base"))?;
+ segments
+ .push("api")
+ .push("v1")
+ .push("workspaces")
+ .push(workspace)
+ .push("projects")
+ .push(project);
+ for segment in tail {
+ segments.push(segment);
+ }
+ }
+ if !query.is_empty() {
+ let mut pairs = url.query_pairs_mut();
+ for (key, value) in query {
+ pairs.append_pair(key, value);
+ }
+ }
+ Ok(url)
+ }
+
+ async fn send(
+ &self,
+ url: &Url,
+ if_none_match: Option<&str>,
+ not_found_hint: &str,
+ ) -> Result<reqwest::Response> {
+ let mut request = self
+ .http
+ .get(url.clone())
+ .header(reqwest::header::ACCEPT, "application/json");
+ if let Some(token) = &self.token {
+ request = request.bearer_auth(token);
+ }
+ if let Some(etag) = if_none_match {
+ request = request.header(reqwest::header::IF_NONE_MATCH, etag);
+ }
+ let response = request
+ .send()
+ .await
+ .map_err(|e| anyhow!("request to {} failed: {e}", url.as_str()))?;
+ match response.status() {
+ StatusCode::OK | StatusCode::NOT_MODIFIED => Ok(response),
+ StatusCode::UNAUTHORIZED => bail!(
+ "GET {} returned 401 Unauthorized — the server requires a bearer token \
+ (pass --token or set AI_MEMORY_AUTH_TOKEN)",
+ url.as_str()
+ ),
+ StatusCode::FORBIDDEN => bail!(
+ "GET {} returned 403 Forbidden — the token was rejected, the caller lacks \
+ access to this scope, or the server's host allowlist refused the request",
+ url.as_str()
+ ),
+ StatusCode::NOT_FOUND => bail!(
+ "GET {} returned 404 Not Found — {not_found_hint}",
+ url.as_str()
+ ),
+ status => bail!("GET {} returned unexpected status {status}", url.as_str()),
+ }
+ }
+
+ /// List the project's latest pages via incremental `recent` paging from
+ /// the epoch. Incremental results already exclude superseded and expired
+ /// pages, which is exactly the latest-only projection an export wants.
+ /// A server without incremental support answers the legacy bare array;
+ /// that is accepted as the full listing.
+ pub async fn list_pages(&self, workspace: &str, project: &str) -> Result<Vec<PageSummary>> {
+ let mut all: Vec<PageSummary> = Vec::new();
+ let mut cursor: Option<String> = None;
+ for _ in 0..MAX_LIST_ROUNDS {
+ let mut query = vec![
+ ("updated_since", EPOCH.to_string()),
+ ("limit", RECENT_LIMIT.to_string()),
+ ];
+ if let Some(value) = &cursor {
+ query.push(("cursor", value.clone()));
+ }
+ let url = self.api_url(workspace, project, &["recent"], &query)?;
+ let response = self.send(&url, None, "check --workspace/--project").await?;
+ let bytes = response
+ .bytes()
+ .await
+ .map_err(|e| anyhow!("reading {} failed: {e}", url.as_str()))?;
+ let first = bytes
+ .iter()
+ .find(|byte| !byte.is_ascii_whitespace())
+ .copied()
+ .unwrap_or(b'{');
+ if first == b'[' {
+ let pages: Vec<PageSummary> = serde_json::from_slice(&bytes).map_err(|e| {
+ anyhow!(
+ "legacy page listing from {} is malformed: {e}",
+ url.as_str()
+ )
+ })?;
+ all.extend(pages);
+ return Ok(all);
+ }
+ let page: RecentIncremental = serde_json::from_slice(&bytes)
+ .map_err(|e| anyhow!("page listing from {} is malformed: {e}", url.as_str()))?;
+ all.extend(page.pages);
+ match page.next_cursor {
+ Some(next) => {
+ if Some(&next) == cursor.as_ref() {
+ bail!(
+ "server repeated the same listing cursor; aborting to avoid \
+ an infinite loop"
+ );
+ }
+ cursor = Some(next);
+ }
+ None => return Ok(all),
+ }
+ }
+ bail!("page listing did not finish within {MAX_LIST_ROUNDS} cursor rounds; aborting");
+ }
+
+ /// Read one full page, revalidating a stored ETag with `If-None-Match`.
+ /// A `404` here means the listing and the read raced (the page was
+ /// deleted or expired mid-run), which fails loudly instead of silently
+ /// skipping.
+ pub async fn read_page(
+ &self,
+ workspace: &str,
+ project: &str,
+ path: &str,
+ if_none_match: Option<&str>,
+ ) -> Result<PageRead> {
+ // Each path segment stays its own path component so the wiki path's
+ // '/' separators are preserved in the request URL.
+ let tail: Vec<&str> = path.split('/').collect();
+ let url = self.build_page_url(workspace, project, &tail)?;
+ let response = self
+ .send(
+ &url,
+ if_none_match,
+ &format!("page {path:?} was not found (deleted or expired mid-run?)"),
+ )
+ .await?;
+ let etag = response
+ .headers()
+ .get(reqwest::header::ETAG)
+ .and_then(|value| value.to_str().ok())
+ .map(str::to_owned)
+ .or_else(|| if_none_match.map(str::to_owned));
+ if response.status() == StatusCode::NOT_MODIFIED {
+ return Ok(PageRead { page: None, etag });
+ }
+ let page: ApiPage = response.json().await.map_err(|e| {
+ anyhow!(
+ "page read from {} returned malformed JSON: {e}",
+ url.as_str()
+ )
+ })?;
+ if page.path != path {
+ bail!(
+ "server answered a read of {path:?} with page {:?}; refusing the mismatch",
+ page.path
+ );
+ }
+ Ok(PageRead {
+ page: Some(page),
+ etag,
+ })
+ }
+
+ fn build_page_url(&self, workspace: &str, project: &str, tail: &[&str]) -> Result<Url> {
+ let mut url = self.base.clone();
+ {
+ let mut segments = url
+ .path_segments_mut()
+ .map_err(|_| anyhow!("server URL cannot serve as a base"))?;
+ segments
+ .push("api")
+ .push("v1")
+ .push("workspaces")
+ .push(workspace)
+ .push("projects")
+ .push(project)
+ .push("pages");
+ for segment in tail {
+ segments.push(segment);
+ }
+ }
+ Ok(url)
+ }
+}
+
+/// Small helper so the client builder error reads like the others.
+trait ContextBuild {
+ fn context_build(self) -> Result<reqwest::Client>;
+}
+
+impl ContextBuild for Result<reqwest::Client, reqwest::Error> {
+ fn context_build(self) -> Result<reqwest::Client> {
+ self.map_err(|e| anyhow!("cannot build HTTP client: {e}"))
+ }
+}
diff --git a/companions/ai-memory-wikisync/src/lib.rs b/companions/ai-memory-wikisync/src/lib.rs
new file mode 100644
index 00000000..27f478d6
--- /dev/null
+++ b/companions/ai-memory-wikisync/src/lib.rs
@@ -0,0 +1,25 @@
+//! `ai-memory-wikisync`: read-only team-wiki export companion (#986, slice 1).
+//!
+//! Pulls explicitly allowlisted page families from a running ai-memory server
+//! through the public, read-only `/api/v1` surface into a directory inside a
+//! project repository. The tool never mutates the server, never deletes local
+//! files (deletes are slice 4), never forges page frontmatter, and never runs
+//! git on the operator's behalf.
+//!
+//! Page bodies are untrusted data: they are transported verbatim into files
+//! whose validated paths cannot escape the destination directory, and are
+//! never executed or rendered.
+
+pub mod client;
+pub mod paths;
+pub mod state;
+pub mod sync;
+
+/// Hard ceiling on pages handled in one run. A hostile or misconfigured
+/// server cannot make the export loop or write unboundedly.
+pub const MAX_PAGES: usize = 10_000;
+/// Hard ceiling on one page body. The server's own HTTP cap is 10 MiB, so
+/// anything near this bound already indicates a broken projection.
+pub const MAX_BODY_BYTES: usize = 8 * 1024 * 1024;
+/// Directory (inside `--dest`) holding the single local state file.
+pub const STATE_DIR: &str = ".ai-memory-wikisync";
diff --git a/companions/ai-memory-wikisync/src/main.rs b/companions/ai-memory-wikisync/src/main.rs
new file mode 100644
index 00000000..ea6bb2ba
--- /dev/null
+++ b/companions/ai-memory-wikisync/src/main.rs
@@ -0,0 +1,140 @@
+//! Thin CLI: parse arguments once, call the library, render output.
+
+use std::path::PathBuf;
+
+use ai_memory_wikisync::client::DEFAULT_SERVER_URL;
+use ai_memory_wikisync::sync::{Mode, RunArgs, run};
+use clap::{Parser, Subcommand};
+
+#[derive(Parser, Debug)]
+#[command(
+ author,
+ version,
+ about = "Read-only team-wiki export companion for ai-memory (#986, slice 1)"
+)]
+struct Cli {
+ #[command(subcommand)]
+ command: Commands,
+}
+
+#[derive(Subcommand, Debug)]
+enum Commands {
+ /// List pages to create/update/unchanged against the destination.
+ /// Never writes files or state.
+ Plan(CommonArgs),
+ /// Export pages into --dest. Dry-run unless --apply is passed.
+ Export(ExportArgs),
+}
+
+#[derive(Parser, Debug, Clone)]
+struct ExportArgs {
+ /// Perform the writes. Without it, export stays a dry-run.
+ #[arg(long)]
+ apply: bool,
+ /// Overwrite files edited locally since the last export.
+ #[arg(long)]
+ force: bool,
+ #[command(flatten)]
+ common: CommonArgs,
+}
+
+#[derive(Parser, Debug, Clone)]
+struct CommonArgs {
+ /// ai-memory server origin, for example http://127.0.0.1:49374.
+ #[arg(long, env = "AI_MEMORY_SERVER_URL", default_value = DEFAULT_SERVER_URL)]
+ server: String,
+ /// Bearer token; reads AI_MEMORY_AUTH_TOKEN when omitted. Never logged.
+ #[arg(long, env = "AI_MEMORY_AUTH_TOKEN", hide_env_values = true)]
+ token: Option<String>,
+ /// Source workspace on the server.
+ #[arg(long)]
+ workspace: String,
+ /// Source project on the server.
+ #[arg(long)]
+ project: String,
+ /// Destination directory inside the repository.
+ #[arg(long)]
+ dest: PathBuf,
+ /// Top-level wiki directory (family) to export; repeatable. The
+ /// allowlist is explicit: '*' is refused.
+ #[arg(long = "include", value_name = "FAMILY")]
+ include: Vec<String>,
+}
+
+impl From<ExportArgs> for RunArgs {
+ fn from(args: ExportArgs) -> Self {
+ Self {
+ server: args.common.server,
+ token: args.common.token,
+ workspace: args.common.workspace,
+ project: args.common.project,
+ dest: args.common.dest,
+ include: args.common.include,
+ force: args.force,
+ }
+ }
+}
+
+impl From<CommonArgs> for RunArgs {
+ fn from(args: CommonArgs) -> Self {
+ Self {
+ server: args.server,
+ token: args.token,
+ workspace: args.workspace,
+ project: args.project,
+ dest: args.dest,
+ include: args.include,
+ force: false,
+ }
+ }
+}
+
+#[tokio::main]
+async fn main() -> anyhow::Result<()> {
+ let cli = Cli::parse();
+ match cli.command {
+ Commands::Plan(args) => run(&RunArgs::from(args), Mode::Plan).await,
+ Commands::Export(args) => {
+ let mode = if args.apply {
+ Mode::Apply
+ } else {
+ Mode::DryRun
+ };
+ run(&RunArgs::from(args), mode).await
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use clap::CommandFactory;
+
+ /// A token in AI_MEMORY_AUTH_TOKEN must never surface in --help: clap
+ /// prints live env values for `env` args unless they are hidden.
+ #[test]
+ fn token_env_value_is_hidden_from_help() {
+ let mut command = Cli::command();
+ let tokens: Vec<_> = command
+ .get_subcommands_mut()
+ .flat_map(|sub| {
+ let name = sub.get_name().to_string();
+ sub.get_arguments()
+ .filter(|arg| arg.get_id() == "token")
+ .map(|arg| (name.clone(), arg.is_hide_env_values_set()))
+ .collect::<Vec<_>>()
+ })
+ .collect();
+ assert!(!tokens.is_empty(), "subcommands expose --token");
+ for (name, hidden) in tokens {
+ assert!(hidden, "--token on {name} must set hide_env_values");
+ }
+ let plan_help = command
+ .get_subcommands_mut()
+ .find(|sub| sub.get_name() == "plan")
+ .expect("plan subcommand")
+ .render_help()
+ .to_string();
+ assert!(plan_help.contains("AI_MEMORY_AUTH_TOKEN"));
+ }
+}
diff --git a/companions/ai-memory-wikisync/src/paths.rs b/companions/ai-memory-wikisync/src/paths.rs
new file mode 100644
index 00000000..0f0d0cbf
--- /dev/null
+++ b/companions/ai-memory-wikisync/src/paths.rs
@@ -0,0 +1,366 @@
+//! Destination-path safety for the read-only export.
+//!
+//! Page paths arrive from the server as untrusted data. Every relative wiki
+//! path is validated into a portable shape before it is ever joined onto the
+//! destination directory, so a hostile server cannot escape `--dest`, clobber
+//! dotfiles, or plant names that behave differently across filesystems.
+
+use std::fs;
+use std::io;
+use std::path::{Component, Path, PathBuf};
+
+use anyhow::{Context, Result, bail};
+
+/// Longest wiki path accepted, in bytes. Stays well under the shortest
+/// common filesystem limit once joined onto a repository path.
+pub const MAX_PATH_BYTES: usize = 180;
+/// Longest single path segment accepted, in bytes.
+pub const MAX_SEGMENT_BYTES: usize = 64;
+/// Deepest wiki path accepted, in segments.
+pub const MAX_DEPTH: usize = 8;
+
+/// Windows reserved device stems: `CON`, `PRN`, `AUX`, `NUL`, `COM1`-`COM9`,
+/// `LPT1`-`LPT9` (the stem is the part before the first dot, so `CON.md`
+/// and `con.x.md` are both refused).
+const RESERVED_STEMS: &[&str] = &[
+ "CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8",
+ "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9",
+];
+
+fn is_reserved_stem(segment: &str) -> bool {
+ let stem = segment.split('.').next().unwrap_or_default();
+ RESERVED_STEMS.contains(&stem.to_ascii_uppercase().as_str())
+}
+
+/// One portable path segment: ASCII letters, digits, dot, dash, underscore.
+/// No leading dot (this also refuses `.`, `..` and `.git`), no trailing dot
+/// (Windows quirk), no reserved device stem.
+fn valid_segment(segment: &str) -> bool {
+ !segment.is_empty()
+ && segment.len() <= MAX_SEGMENT_BYTES
+ && segment
+ .bytes()
+ .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-' | b'_'))
+ && !segment.starts_with('.')
+ && !segment.ends_with('.')
+ && !is_reserved_stem(segment)
+}
+
+/// Validate one `--include` family: a single top-level wiki directory name.
+/// The allowlist is explicit by design, so a bare `*` (or any wildcard) is
+/// refused with its own message instead of a generic charset complaint.
+pub fn validate_family(raw: &str) -> Result<()> {
+ if raw == "*" {
+ bail!("--include '*' is refused: the family allowlist must be explicit");
+ }
+ if raw.contains(['*', '?', '[', ']']) {
+ bail!("--include {raw}: wildcards are not allowed; name concrete families");
+ }
+ if !valid_segment(raw) {
+ bail!(
+ "--include {raw}: not a portable directory name (ASCII letters, digits, '.', '-', '_'; \
+ no leading dot, no reserved Windows name)"
+ );
+ }
+ Ok(())
+}
+
+/// The family of a wiki path is its first segment. A bare top-level page
+/// (`README.md`) is its own family and only matches an identically named
+/// `--include` value.
+pub fn family_of(path: &str) -> &str {
+ path.split('/').next().unwrap_or(path)
+}
+
+/// Validate a server-reported wiki path before anything is joined onto
+/// `--dest`. Refuses traversal, absolute paths, backslashes, dotfiles,
+/// non-portable characters, oversized names and non-`.md` leaves.
+pub fn validate_page_path(raw: &str) -> Result<()> {
+ if raw.is_empty() {
+ bail!("empty page path");
+ }
+ if raw.len() > MAX_PATH_BYTES {
+ bail!("page path longer than {MAX_PATH_BYTES} bytes: {raw}");
+ }
+ if raw.starts_with('/') {
+ bail!("absolute page path refused: {raw}");
+ }
+ if raw.contains('\\') || raw.contains('\0') || raw.bytes().any(|b| !b.is_ascii()) {
+ bail!("non-portable page path refused: {raw:?}");
+ }
+ let segments: Vec<&str> = raw.split('/').collect();
+ if segments.len() > MAX_DEPTH {
+ bail!("page path deeper than {MAX_DEPTH} segments: {raw}");
+ }
+ for segment in &segments {
+ if !valid_segment(segment) {
+ bail!("non-portable path segment refused in {raw}: {segment:?}");
+ }
+ }
+ let last = segments[segments.len() - 1];
+ if !last.ends_with(".md") {
+ bail!("page path does not end in .md: {raw}");
+ }
+ Ok(())
+}
+
+/// Refuse a set of pages whose destination paths collide once case-folded.
+/// Linux is case-sensitive but macOS and Windows checkouts are not, and a
+/// collision would silently clobber depending on the platform.
+pub fn ensure_no_case_fold_collisions(paths: &[String]) -> Result<()> {
+ let mut seen: std::collections::BTreeMap<String, &str> = std::collections::BTreeMap::new();
+ for path in paths {
+ let folded = path.to_ascii_lowercase();
+ if let Some(first) = seen.get(folded.as_str())
+ && *first != path.as_str()
+ {
+ bail!(
+ "case-fold collision between server pages {first:?} and {path:?}; \
+ refusing to export both into one destination"
+ );
+ }
+ seen.entry(folded).or_insert(path.as_str());
+ }
+ Ok(())
+}
+
+/// Join a validated relative wiki path onto the destination root, refusing
+/// the join if any existing component on the way is a symlink. Components
+/// that do not exist yet are fine: the writer creates them as real
+/// directories. An existing non-final component that is not a directory is
+/// refused so a file named like a family cannot swallow writes.
+pub fn secure_join(dest_root: &Path, rel: &str) -> Result<PathBuf> {
+ validate_page_path(rel)?;
+ let segments: Vec<&str> = rel.split('/').collect();
+ let mut current = dest_root.to_path_buf();
+ for (index, segment) in segments.iter().enumerate() {
+ current.push(segment);
+ match fs::symlink_metadata(&current) {
+ Ok(meta) => {
+ if meta.file_type().is_symlink() {
+ bail!("refusing path through symlink: {}", current.display());
+ }
+ let is_last = index + 1 == segments.len();
+ if !is_last && !meta.is_dir() {
+ bail!("path component is not a directory: {}", current.display());
+ }
+ }
+ Err(e) if e.kind() == io::ErrorKind::NotFound => {}
+ Err(e) => {
+ return Err(anyhow::Error::new(e))
+ .context(format!("cannot inspect {}", current.display()));
+ }
+ }
+ }
+ Ok(current)
+}
+
+/// Absolute path with `.` and `..` resolved lexically, without following
+/// symlinks. Comparing this against `canonicalize` detects any symlink on
+/// the way to the destination.
+pub fn lexical_absolute(path: &Path) -> PathBuf {
+ let absolute = if path.is_absolute() {
+ path.to_path_buf()
+ } else {
+ match std::env::current_dir() {
+ Ok(cwd) => cwd.join(path),
+ Err(_) => return path.to_path_buf(),
+ }
+ };
+ let mut normalized = PathBuf::new();
+ for component in absolute.components() {
+ match component {
+ Component::CurDir => {}
+ Component::ParentDir => {
+ normalized.pop();
+ }
+ other => normalized.push(other.as_os_str()),
+ }
+ }
+ normalized
+}
+
+/// 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
+/// canonical-versus-lexical comparison) and non-directories. Returns the
+/// canonical root every later join is anchored to.
+pub fn prepare_dest(dest: &Path) -> Result<PathBuf> {
+ match fs::symlink_metadata(dest) {
+ Ok(meta) => {
+ if meta.file_type().is_symlink() {
+ bail!("--dest is a symlink; pass the real directory instead");
+ }
+ if !meta.is_dir() {
+ bail!("--dest exists and is not a directory");
+ }
+ }
+ Err(e) if e.kind() == io::ErrorKind::NotFound => {
+ fs::create_dir_all(dest)
+ .with_context(|| format!("cannot create --dest {}", dest.display()))?;
+ }
+ Err(e) => {
+ return Err(anyhow::Error::new(e))
+ .context(format!("cannot inspect --dest {}", dest.display()));
+ }
+ }
+ let lexical = lexical_absolute(dest);
+ let canonical = fs::canonicalize(dest)
+ .with_context(|| format!("cannot canonicalize --dest {}", dest.display()))?;
+ if canonical != lexical {
+ bail!(
+ "--dest reaches through a symlink ({} -> {}); pass the resolved path instead",
+ lexical.display(),
+ canonical.display()
+ );
+ }
+ Ok(canonical)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn accepts_portable_page_paths() {
+ for path in [
+ "decisions/0007-db.md",
+ "notes/deep/nested/path/is/fine.md",
+ "_rules/keep-dashes_and.dots.md",
+ "README.md",
+ "conduct.md",
+ ] {
+ validate_page_path(path).unwrap_or_else(|e| panic!("{path}: {e}"));
+ }
+ assert_eq!(family_of("decisions/0007-db.md"), "decisions");
+ assert_eq!(family_of("README.md"), "README.md");
+ }
+
+ #[test]
+ fn refuses_traversal_and_absolute_paths() {
+ for path in [
+ "../escape.md",
+ "notes/../../escape.md",
+ "/etc/passwd.md",
+ "notes//double.md",
+ "notes/./here.md",
+ "notes/.hidden.md",
+ "notes/.git/config.md",
+ "",
+ ] {
+ assert!(validate_page_path(path).is_err(), "should refuse {path:?}");
+ }
+ }
+
+ #[test]
+ fn refuses_non_portable_segments() {
+ for path in [
+ "notes/with space.md",
+ "notes/with*glob.md",
+ "notes/trailing.md.",
+ "notes/COM1.md",
+ "notes/com2.lower.md",
+ "notes/lpt9.md",
+ "notes/beyond\u{e9}.md",
+ "notes/readme.markdown",
+ "notes/not-md.txt",
+ "very/deep/path/that/goes/on/and/on/forever/here.md",
+ ] {
+ assert!(validate_page_path(path).is_err(), "should refuse {path:?}");
+ }
+ let long = format!("notes/{}.md", "a".repeat(MAX_SEGMENT_BYTES));
+ assert!(validate_page_path(&long).is_err());
+ let deep = format!("{}.md", ["d"; MAX_DEPTH + 1].join("/"));
+ assert!(validate_page_path(&deep).is_err());
+ }
+
+ #[test]
+ fn family_allowlist_is_explicit() {
+ assert!(validate_family("decisions").is_ok());
+ assert!(validate_family("_rules").is_ok());
+ // The explicit allowlist rule: bare '*' and wildcards are refused
+ // with their own message, not a generic charset error.
+ let star = validate_family("*").unwrap_err().to_string();
+ assert!(star.contains("must be explicit"), "{star}");
+ assert!(validate_family("notes*").is_err());
+ assert!(validate_family("..").is_err());
+ assert!(validate_family("a/b").is_err());
+ assert!(validate_family("").is_err());
+ }
+
+ #[test]
+ fn detects_case_fold_collisions() {
+ assert!(
+ ensure_no_case_fold_collisions(&[
+ "notes/a.md".to_string(),
+ "decisions/b.md".to_string(),
+ ])
+ .is_ok()
+ );
+ let err =
+ ensure_no_case_fold_collisions(&["Notes/a.md".to_string(), "notes/A.md".to_string()])
+ .unwrap_err()
+ .to_string();
+ assert!(err.contains("case-fold collision"), "{err}");
+ }
+
+ #[test]
+ fn prepare_dest_refuses_symlinks_and_files() {
+ let tmp = tempfile::tempdir().unwrap();
+ let dest = tmp.path().canonicalize().unwrap();
+
+ assert_eq!(prepare_dest(&dest).unwrap(), dest);
+
+ let child = dest.join("real");
+ fs::create_dir_all(&child).unwrap();
+ assert_eq!(prepare_dest(&child).unwrap(), child);
+
+ #[cfg(unix)]
+ {
+ let link = dest.join("link");
+ std::os::unix::fs::symlink(&child, &link).unwrap();
+ let err = prepare_dest(&link).unwrap_err().to_string();
+ assert!(err.contains("symlink"), "{err}");
+ // A symlinked *component* on the way is refused too.
+ let through = link.join("sub");
+ let err = prepare_dest(&through).unwrap_err().to_string();
+ assert!(err.contains("symlink"), "{err}");
+ }
+
+ let file = dest.join("file");
+ fs::write(&file, b"x").unwrap();
+ let err = prepare_dest(&file).unwrap_err().to_string();
+ assert!(err.contains("not a directory"), "{err}");
+ }
+
+ #[test]
+ fn prepare_dest_creates_missing_directories() {
+ let tmp = tempfile::tempdir().unwrap();
+ let dest = tmp.path().canonicalize().unwrap().join("a/b/c");
+ let made = prepare_dest(&dest).unwrap();
+ assert!(made.is_dir());
+ }
+
+ #[test]
+ fn secure_join_stays_under_root_and_refuses_symlink_components() {
+ let tmp = tempfile::tempdir().unwrap();
+ let root = tmp.path().canonicalize().unwrap();
+ let joined = secure_join(&root, "notes/page.md").unwrap();
+ assert_eq!(joined, root.join("notes/page.md"));
+ assert!(secure_join(&root, "../escape.md").is_err());
+
+ #[cfg(unix)]
+ {
+ fs::create_dir_all(root.join("notes")).unwrap();
+ std::os::unix::fs::symlink("/tmp", root.join("notes/elsewhere")).unwrap();
+ let err = secure_join(&root, "notes/elsewhere/page.md")
+ .unwrap_err()
+ .to_string();
+ assert!(err.contains("symlink"), "{err}");
+ }
+
+ // A file squatting on a family directory name is refused.
+ fs::write(root.join("blob.md"), b"x").unwrap();
+ assert!(secure_join(&root, "blob.md/child.md").is_err());
+ }
+}
diff --git a/companions/ai-memory-wikisync/src/state.rs b/companions/ai-memory-wikisync/src/state.rs
new file mode 100644
index 00000000..4e910f96
--- /dev/null
+++ b/companions/ai-memory-wikisync/src/state.rs
@@ -0,0 +1,249 @@
+//! Clone-local export state: one JSON file under the destination.
+//!
+//! The state file is the only thing wikisync writes besides page bodies. It
+//! records, per exported page, the hash of the exact bytes last written and
+//! the server ETag observed at that write, so later runs can revalidate with
+//! `If-None-Match` and detect local edits with a three-way comparison. No
+//! token, server credential, or page frontmatter ever lands in it.
+
+use std::collections::BTreeMap;
+use std::fs;
+use std::io::Write;
+use std::path::{Path, PathBuf};
+
+use anyhow::{Context, Result, bail};
+use serde::{Deserialize, Serialize};
+use sha2::{Digest, Sha256};
+
+use crate::STATE_DIR;
+
+const STATE_FILE: &str = "state.json";
+const STATE_VERSION: u32 = 1;
+const TMP_SUFFIX: &str = ".tmp";
+
+/// SHA-256 of `bytes` as lowercase hex.
+pub fn sha256_hex(bytes: &[u8]) -> String {
+ let digest = Sha256::digest(bytes);
+ let mut out = String::with_capacity(digest.len() * 2);
+ for byte in digest {
+ use std::fmt::Write as _;
+ let _ = out.write_fmt(format_args!("{byte:02x}"));
+ }
+ out
+}
+
+/// Per-page export state: what this tool last wrote, and the server
+/// revision (ETag) it came from.
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+pub struct PageState {
+ /// SHA-256 of the exact bytes last written to the destination file.
+ pub hash: String,
+ /// Server ETag captured at that write, for `If-None-Match` revalidation.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub etag: Option<String>,
+}
+
+/// 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,
+ pub pages: BTreeMap<String, PageState>,
+}
+
+impl Default for SyncState {
+ fn default() -> Self {
+ Self {
+ version: STATE_VERSION,
+ pages: BTreeMap::new(),
+ }
+ }
+}
+
+/// Path of the single state file inside a destination root.
+pub fn state_path(dest_root: &Path) -> PathBuf {
+ dest_root.join(STATE_DIR).join(STATE_FILE)
+}
+
+/// The state directory must be a real directory, never a symlink: a symlink
+/// planted on `.ai-memory-wikisync` would move state (and lock the writer
+/// into trusting it) outside the destination.
+fn ensure_real_state_dir(dir: &Path) -> Result<()> {
+ match fs::symlink_metadata(dir) {
+ Ok(meta) => {
+ if meta.file_type().is_symlink() {
+ bail!("state directory is a symlink: {}", dir.display());
+ }
+ if !meta.is_dir() {
+ bail!("state path is not a directory: {}", dir.display());
+ }
+ Ok(())
+ }
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
+ Err(e) => Err(anyhow::Error::new(e))
+ .context(format!("cannot inspect state directory {}", dir.display())),
+ }
+}
+
+/// Load the state for a destination root. A missing file is an empty state
+/// (first export). A corrupt or future-version file fails closed: guessing
+/// would risk overwriting local edits.
+pub fn load(dest_root: &Path) -> Result<SyncState> {
+ let path = state_path(dest_root);
+ ensure_real_state_dir(path.parent().unwrap_or(dest_root))?;
+ if !path.exists() {
+ return Ok(SyncState::default());
+ }
+ let raw = fs::read_to_string(&path)
+ .with_context(|| format!("cannot read state file {}", path.display()))?;
+ let state: SyncState = serde_json::from_str(&raw)
+ .with_context(|| format!("state file {} is corrupt", path.display()))?;
+ if state.version != STATE_VERSION {
+ bail!(
+ "state file {} has version {}; this build understands version {STATE_VERSION}; \
+ resolve it manually before exporting again",
+ path.display(),
+ state.version
+ );
+ }
+ Ok(state)
+}
+
+/// Atomically persist the state: tmp file in the same directory, fsync,
+/// rename over the old file. Called once after each successful write batch,
+/// so a crash mid-batch leaves the previous state intact and the next run
+/// re-classifies through the three-way comparison instead of trusting it.
+pub fn save(dest_root: &Path, state: &SyncState) -> Result<()> {
+ let path = state_path(dest_root);
+ let dir = path.parent().unwrap_or(dest_root);
+ ensure_real_state_dir(dir)?;
+ fs::create_dir_all(dir).with_context(|| format!("cannot create {}", dir.display()))?;
+ if fs::symlink_metadata(dir)
+ .map(|meta| meta.file_type().is_symlink())
+ .unwrap_or(false)
+ {
+ bail!("state directory became a symlink: {}", dir.display());
+ }
+ let json = serde_json::to_vec_pretty(state).context("cannot serialize state")?;
+ let tmp = PathBuf::from(format!("{}{TMP_SUFFIX}", path.display()));
+ // Leftover tmp from a crashed run is ours by name; clear it.
+ match fs::remove_file(&tmp) {
+ Ok(()) => {}
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
+ Err(e) => {
+ return Err(anyhow::Error::new(e))
+ .context(format!("cannot clear stale {}", tmp.display()));
+ }
+ }
+ {
+ let mut file =
+ fs::File::create(&tmp).with_context(|| format!("cannot create {}", tmp.display()))?;
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ fs::set_permissions(&tmp, fs::Permissions::from_mode(0o600))
+ .with_context(|| format!("cannot restrict permissions on {}", tmp.display()))?;
+ }
+ file.write_all(&json)
+ .with_context(|| format!("cannot write {}", tmp.display()))?;
+ file.sync_all()
+ .with_context(|| format!("cannot sync {}", tmp.display()))?;
+ }
+ fs::rename(&tmp, &path)
+ .with_context(|| format!("cannot move {} over {}", tmp.display(), path.display()))?;
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn page(hash: &str, etag: Option<&str>) -> PageState {
+ PageState {
+ hash: hash.to_string(),
+ etag: etag.map(str::to_owned),
+ }
+ }
+
+ #[test]
+ fn round_trips_through_disk() {
+ let tmp = tempfile::tempdir().unwrap();
+ let root = tmp.path().canonicalize().unwrap();
+ let mut state = SyncState::default();
+ state.pages.insert(
+ "notes/a.md".to_string(),
+ page(&"a".repeat(64), Some("\"v1\"")),
+ );
+ save(&root, &state).unwrap();
+ assert_eq!(load(&root).unwrap(), state);
+ // No tmp file is left behind.
+ let dir = fs::read_dir(root.join(STATE_DIR)).unwrap();
+ let names: Vec<String> = dir
+ .flatten()
+ .map(|entry| entry.file_name().to_string_lossy().into_owned())
+ .collect();
+ assert_eq!(names, vec!["state.json".to_string()]);
+ }
+
+ #[test]
+ fn state_file_is_owner_only_on_unix() {
+ let tmp = tempfile::tempdir().unwrap();
+ let root = tmp.path().canonicalize().unwrap();
+ save(&root, &SyncState::default()).unwrap();
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ let mode = fs::metadata(state_path(&root))
+ .unwrap()
+ .permissions()
+ .mode();
+ assert_eq!(mode & 0o777, 0o600);
+ }
+ }
+
+ #[test]
+ fn missing_state_is_empty_and_corrupt_state_fails_closed() {
+ let tmp = tempfile::tempdir().unwrap();
+ let root = tmp.path().canonicalize().unwrap();
+ assert_eq!(load(&root).unwrap(), SyncState::default());
+
+ fs::create_dir_all(root.join(STATE_DIR)).unwrap();
+ fs::write(state_path(&root), "{ not json").unwrap();
+ let err = load(&root).unwrap_err().to_string();
+ assert!(err.contains("corrupt"), "{err}");
+
+ let future = SyncState {
+ version: 99,
+ pages: BTreeMap::new(),
+ };
+ 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 refuses_symlinked_state_dir() {
+ let tmp = tempfile::tempdir().unwrap();
+ let root = tmp.path().canonicalize().unwrap();
+ let elsewhere = root.join("elsewhere");
+ fs::create_dir_all(&elsewhere).unwrap();
+ #[cfg(unix)]
+ {
+ std::os::unix::fs::symlink(&elsewhere, root.join(STATE_DIR)).unwrap();
+ let err = load(&root).unwrap_err().to_string();
+ assert!(err.contains("symlink"), "{err}");
+ let err = save(&root, &SyncState::default()).unwrap_err().to_string();
+ assert!(err.contains("symlink"), "{err}");
+ }
+ }
+
+ #[test]
+ fn save_survives_a_stale_tmp_file() {
+ let tmp = tempfile::tempdir().unwrap();
+ let root = tmp.path().canonicalize().unwrap();
+ fs::create_dir_all(root.join(STATE_DIR)).unwrap();
+ fs::write(root.join(STATE_DIR).join("state.json.tmp"), b"junk").unwrap();
+ save(&root, &SyncState::default()).unwrap();
+ assert!(load(&root).unwrap() == SyncState::default());
+ }
+}
diff --git a/companions/ai-memory-wikisync/src/sync.rs b/companions/ai-memory-wikisync/src/sync.rs
new file mode 100644
index 00000000..5b526744
--- /dev/null
+++ b/companions/ai-memory-wikisync/src/sync.rs
@@ -0,0 +1,747 @@
+//! The plan/export engine: three-way classification and batched writes.
+//!
+//! For every allowlisted page the tool compares three versions — the
+//! destination file (mine), the state entry (base: what this tool last
+//! wrote), and the server body (theirs, revalidated through the ETag) — and
+//! refuses to choose a winner when the destination has diverged from both.
+//! Writes happen only in one batch per run, and the state file is replaced
+//! atomically after the whole batch succeeds, so a crash at any point leaves
+//! a consistent (old) state that the next run re-classifies safely.
+
+use std::fs;
+use std::io::Write;
+use std::path::{Path, PathBuf};
+
+use anyhow::{Context, Result, bail};
+
+use crate::client::{ApiClient, PageSummary};
+use crate::paths;
+use crate::state::{self, PageState, SyncState};
+use crate::{MAX_BODY_BYTES, MAX_PAGES};
+
+/// Why a planned write touches the file.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum WriteKind {
+ /// No destination file: the server body creates one.
+ Create,
+ /// Destination still equals the base state: fast-forward to the server.
+ Update,
+ /// Destination diverged and `--force` chose the server version.
+ Forced,
+}
+
+impl WriteKind {
+ fn label(self) -> &'static str {
+ match self {
+ Self::Create => "create",
+ Self::Update => "update",
+ Self::Forced => "forced",
+ }
+ }
+}
+
+/// Why a destination file refuses to be overwritten.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum DivergentReason {
+ /// Edited locally since the last export.
+ LocalEdit,
+ /// Present on disk but never written by this tool.
+ UnknownFile,
+ /// Begins with a YAML frontmatter delimiter this tool never writes.
+ LocalFrontmatter,
+}
+
+impl DivergentReason {
+ fn describe(self) -> &'static str {
+ match self {
+ Self::LocalEdit => "edited locally since the last export",
+ Self::UnknownFile => "exists on disk but was never written by wikisync",
+ Self::LocalFrontmatter => {
+ "edited locally since the last export (file begins with a YAML \
+ frontmatter delimiter; wikisync never writes frontmatter)"
+ }
+ }
+ }
+}
+
+/// What a page's classification means for the filesystem.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum Classification {
+ /// Destination matches the server byte-for-byte: nothing to do.
+ Unchanged,
+ /// Safe to write the server body (see [`WriteKind`]).
+ Write(WriteKind),
+ /// Destination differs from both base and server: a local edit this
+ /// tool refuses to overwrite without `--force`.
+ Divergent(DivergentReason),
+}
+
+/// One planned or performed write.
+#[derive(Debug, Clone)]
+pub struct PlannedWrite {
+ pub kind: WriteKind,
+ pub path: String,
+ pub title: String,
+ pub body: String,
+ pub etag: Option<String>,
+}
+
+/// A destination file that diverged, with a bounded diff summary.
+#[derive(Debug, Clone)]
+pub struct Divergence {
+ pub path: String,
+ pub reason: DivergentReason,
+ pub summary: String,
+}
+
+/// Everything one run decided, for printing (and for tests).
+#[derive(Debug, Default)]
+pub struct Report {
+ pub writes: Vec<PlannedWrite>,
+ pub unchanged: Vec<String>,
+ pub divergent: Vec<Divergence>,
+ pub listed: usize,
+ pub matched: usize,
+ /// Total bytes the batch would write.
+ pub bytes_to_write: u64,
+}
+
+impl Report {
+ fn count(&self, kind: WriteKind) -> usize {
+ self.writes
+ .iter()
+ .filter(|write| write.kind == kind)
+ .count()
+ }
+}
+
+/// How the run treats the filesystem.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Mode {
+ /// `plan`: never writes anything, not even the state file.
+ Plan,
+ /// `export` without `--apply`: still a dry-run.
+ DryRun,
+ /// `export --apply`.
+ Apply,
+}
+
+/// Arguments shared by `plan` and `export`.
+#[derive(Debug, Clone)]
+pub struct RunArgs {
+ pub server: String,
+ pub token: Option<String>,
+ pub workspace: String,
+ pub project: String,
+ pub dest: PathBuf,
+ /// Explicit family allowlist. Must be non-empty; `*` is refused.
+ pub include: Vec<String>,
+ /// Overwrite files that diverged locally since the last export.
+ pub force: bool,
+}
+
+/// Classify one page from its three versions. Pure: all IO happens around
+/// it, which is what makes the three-way rules testable.
+pub fn classify(
+ disk: Option<&[u8]>,
+ base: Option<&PageState>,
+ server: Option<&[u8]>,
+) -> Classification {
+ let disk_hash = disk.map(state::sha256_hex);
+ let server_hash = server.map(state::sha256_hex);
+ // Order matters: a byte-identical server match is Unchanged even with
+ // no base entry (the file may be left over from an interrupted run
+ // after the write but before the state save).
+ let disk_equals_server = disk_hash.is_some() && disk_hash == server_hash;
+ let disk_equals_base = match (&disk_hash, base) {
+ (Some(disk), Some(base)) => disk == &base.hash,
+ _ => false,
+ };
+ match (disk, base) {
+ (None, _) => Classification::Write(WriteKind::Create),
+ (Some(_), _) if disk_equals_server => Classification::Unchanged,
+ (Some(_), Some(_)) if disk_equals_base => match server {
+ // Server unchanged since the base (304): the file is current.
+ None => Classification::Unchanged,
+ Some(_) => Classification::Write(WriteKind::Update),
+ },
+ (Some(_), None) => Classification::Divergent(DivergentReason::UnknownFile),
+ (Some(disk), Some(_)) => {
+ if disk.starts_with(b"---") {
+ Classification::Divergent(DivergentReason::LocalFrontmatter)
+ } else {
+ Classification::Divergent(DivergentReason::LocalEdit)
+ }
+ }
+ }
+}
+
+/// Bounded, printable diff summary for a divergent file: sizes, line counts
+/// and the first differing line, with control characters neutralised so a
+/// page body cannot smuggle terminal escapes into the output.
+pub fn diff_summary(disk: Option<&[u8]>, server: Option<&[u8]>) -> String {
+ let Some(disk) = disk else {
+ return "no local file".to_string();
+ };
+ let Some(server) = server else {
+ return "server content unchanged since the last export (revalidated by ETag)".to_string();
+ };
+ let local_lines = disk.iter().filter(|byte| **byte == b'\n').count();
+ let server_lines = server.iter().filter(|byte| **byte == b'\n').count();
+ let first_difference = disk
+ .split(|byte| *byte == b'\n')
+ .zip(server.split(|byte| *byte == b'\n'))
+ .position(|(local, remote)| local != remote)
+ .map_or(0, |index| index + 1);
+ let local_line = disk
+ .split(|byte| *byte == b'\n')
+ .nth(first_difference.saturating_sub(1))
+ .unwrap_or_default();
+ let server_line = server
+ .split(|byte| *byte == b'\n')
+ .nth(first_difference.saturating_sub(1))
+ .unwrap_or_default();
+ format!(
+ "local {} bytes/{} lines vs server {} bytes/{} lines; first difference at line \
+ {}: local {:?} vs server {:?}",
+ disk.len(),
+ local_lines,
+ server.len(),
+ server_lines,
+ first_difference,
+ preview(local_line),
+ preview(server_line),
+ )
+}
+
+fn preview(line: &[u8]) -> String {
+ line.iter()
+ .take(60)
+ .map(|byte| {
+ if byte.is_ascii_graphic() || *byte == b' ' {
+ *byte as char
+ } else {
+ '?'
+ }
+ })
+ .collect()
+}
+
+/// Atomic file replacement inside the destination: write a hidden tmp file
+/// next to the target, fsync, rename. The tmp name is namespaced by this
+/// tool so a crash never leaves an ambiguous artifact next to page files.
+pub fn atomic_write(dest_root: &Path, rel: &str, bytes: &[u8]) -> Result<()> {
+ let target = paths::secure_join(dest_root, rel)?;
+ if let Some(parent) = target.parent() {
+ fs::create_dir_all(parent)
+ .with_context(|| format!("cannot create directory {}", parent.display()))?;
+ }
+ let file_name = target
+ .file_name()
+ .map(|name| name.to_string_lossy().into_owned())
+ .unwrap_or_else(|| "page.md".to_string());
+ let tmp = target
+ .parent()
+ .unwrap_or(dest_root)
+ .join(format!(".wikisync-tmp-{file_name}"));
+ {
+ let mut file =
+ fs::File::create(&tmp).with_context(|| format!("cannot create {}", tmp.display()))?;
+ file.write_all(bytes)
+ .with_context(|| format!("cannot write {}", tmp.display()))?;
+ file.sync_all()
+ .with_context(|| format!("cannot sync {}", tmp.display()))?;
+ }
+ fs::rename(&tmp, &target)
+ .with_context(|| format!("cannot move {} into place", tmp.display()))?;
+ Ok(())
+}
+
+/// Validate the allowlist: explicit, concrete families only.
+pub fn validate_allowlist(include: &[String]) -> Result<Vec<String>> {
+ if include.is_empty() {
+ bail!(
+ "at least one --include FAMILY is required; the family allowlist must be \
+ explicit (for example --include _rules --include decisions)"
+ );
+ }
+ let mut families = Vec::new();
+ for family in include {
+ paths::validate_family(family)?;
+ if !families.contains(family) {
+ families.push(family.clone());
+ }
+ }
+ Ok(families)
+}
+
+/// Select, validate and bound the server listing down to the allowlisted
+/// families. Deduplicates by path: incremental paging can legitimately
+/// re-deliver a page that was updated mid-iteration.
+pub fn select_pages(summaries: Vec<PageSummary>, families: &[String]) -> Result<Vec<PageSummary>> {
+ let mut by_path: std::collections::BTreeMap<String, PageSummary> =
+ std::collections::BTreeMap::new();
+ for summary in summaries {
+ if !families
+ .iter()
+ .any(|family| paths::family_of(&summary.path) == family.as_str())
+ {
+ continue;
+ }
+ paths::validate_page_path(&summary.path)?;
+ by_path.insert(summary.path.clone(), summary);
+ }
+ let selected: Vec<PageSummary> = by_path.into_values().collect();
+ if selected.len() > MAX_PAGES {
+ bail!(
+ "{} allowlisted pages exceed the per-run ceiling of {MAX_PAGES}; narrow --include",
+ selected.len()
+ );
+ }
+ let paths: Vec<String> = selected.iter().map(|page| page.path.clone()).collect();
+ paths::ensure_no_case_fold_collisions(&paths)?;
+ Ok(selected)
+}
+
+fn read_disk(dest_root: &Path, path: &str) -> Result<Option<Vec<u8>>> {
+ let target = paths::secure_join(dest_root, path)?;
+ match fs::read(&target) {
+ Ok(bytes) => Ok(Some(bytes)),
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
+ Err(e) => Err(anyhow::Error::new(e)).context(format!("cannot read {}", target.display())),
+ }
+}
+
+/// 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.
+async fn run_batch(
+ client: &ApiClient,
+ args: &RunArgs,
+ dest_root: &Path,
+ old_state: &SyncState,
+ mode: Mode,
+) -> Result<(Report, SyncState, bool)> {
+ let summaries = client.list_pages(&args.workspace, &args.project).await?;
+ let listed = summaries.len();
+ let selected = select_pages(summaries, &args.include)?;
+
+ let mut report = Report {
+ listed,
+ matched: selected.len(),
+ ..Report::default()
+ };
+ let mut new_state = old_state.clone();
+
+ for page in selected {
+ let disk = read_disk(dest_root, &page.path)?;
+ let base = old_state.pages.get(&page.path);
+ // A 304 can only prove something when there is a file to compare
+ // against; a missing file always needs the full body.
+ let etag_hint = if disk.is_some() {
+ base.and_then(|entry| entry.etag.as_deref())
+ } else {
+ None
+ };
+ let read = client
+ .read_page(&args.workspace, &args.project, &page.path, etag_hint)
+ .await?;
+ let mut body = read.page.map(|api_page| api_page.body_markdown);
+ if let Some(body) = body.as_ref()
+ && body.len() > MAX_BODY_BYTES
+ {
+ bail!(
+ "page {} is {} bytes; refusing bodies over {MAX_BODY_BYTES} bytes",
+ page.path,
+ body.len()
+ );
+ }
+ let mut decision = classify(
+ disk.as_deref(),
+ base,
+ body.as_deref().map(|b: &str| b.as_bytes()),
+ );
+ if matches!(decision, Classification::Divergent(_)) && args.force && body.is_none() {
+ // A 304 proves the server is unchanged, but --force still needs
+ // the bytes to overwrite the divergent file.
+ let refetch = client
+ .read_page(&args.workspace, &args.project, &page.path, None)
+ .await?;
+ body = refetch.page.map(|api_page| api_page.body_markdown);
+ if let Some(body) = body.as_ref()
+ && body.len() > MAX_BODY_BYTES
+ {
+ bail!(
+ "page {} is {} bytes; refusing bodies over {MAX_BODY_BYTES} bytes",
+ page.path,
+ body.len()
+ );
+ }
+ decision = classify(
+ disk.as_deref(),
+ base,
+ body.as_deref().map(|b: &str| b.as_bytes()),
+ );
+ }
+ record_decision(
+ &mut report,
+ &mut new_state,
+ page,
+ disk.as_deref(),
+ body,
+ read.etag,
+ decision,
+ args.force,
+ )?;
+ }
+
+ report.bytes_to_write = report
+ .writes
+ .iter()
+ .map(|write| write.body.len() as u64)
+ .sum();
+
+ 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())?;
+ }
+ // 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
+ // classification adopts any file that already matches the server.
+ state::save(dest_root, &new_state)?;
+ }
+ Ok((report, new_state, applied))
+}
+
+#[allow(clippy::too_many_arguments)]
+fn record_decision(
+ report: &mut Report,
+ new_state: &mut SyncState,
+ page: PageSummary,
+ disk: Option<&[u8]>,
+ body: Option<String>,
+ etag: Option<String>,
+ decision: Classification,
+ force: bool,
+) -> Result<()> {
+ match decision {
+ Classification::Unchanged => {
+ if let Some(body) = &body {
+ // The file already equals the server (for example after a
+ // crash between write and state save): adopt it.
+ new_state.pages.insert(
+ page.path.clone(),
+ PageState {
+ hash: state::sha256_hex(body.as_bytes()),
+ etag,
+ },
+ );
+ }
+ report.unchanged.push(page.path.clone());
+ }
+ Classification::Write(kind) => {
+ let Some(body) = body else {
+ bail!(
+ "server returned 304 Not Modified for {} although no destination \
+ file exists; cannot classify the page",
+ page.path
+ );
+ };
+ new_state.pages.insert(
+ page.path.clone(),
+ PageState {
+ hash: state::sha256_hex(body.as_bytes()),
+ etag: etag.clone(),
+ },
+ );
+ report.writes.push(PlannedWrite {
+ kind,
+ path: page.path.clone(),
+ title: page.title,
+ body,
+ etag,
+ });
+ }
+ Classification::Divergent(reason) => {
+ let summary = diff_summary(disk, body.as_deref().map(|b: &str| b.as_bytes()));
+ report.divergent.push(Divergence {
+ path: page.path.clone(),
+ reason,
+ summary,
+ });
+ if force {
+ // --force only ever overwrites with server content; the
+ // tool still never deletes anything.
+ if let Some(body) = &body {
+ new_state.pages.insert(
+ page.path.clone(),
+ PageState {
+ hash: state::sha256_hex(body.as_bytes()),
+ etag: etag.clone(),
+ },
+ );
+ report.writes.push(PlannedWrite {
+ kind: WriteKind::Forced,
+ path: page.path.clone(),
+ title: page.title.clone(),
+ body: body.clone(),
+ etag,
+ });
+ }
+ }
+ }
+ }
+ Ok(())
+}
+
+fn print_report(args: &RunArgs, report: &Report, mode: Mode, families: &[String], applied: bool) {
+ println!(
+ "ai-memory-wikisync: {}/{} -> {}",
+ args.workspace,
+ args.project,
+ args.dest.display()
+ );
+ println!(
+ " allowlist: {}; server listed {} page(s), {} in allowlisted families",
+ families.join(", "),
+ report.listed,
+ report.matched
+ );
+ for write in &report.writes {
+ println!(
+ " {:<9} {} ({} bytes) {:?}",
+ write.kind.label(),
+ write.path,
+ write.body.len(),
+ write.title
+ );
+ }
+ for path in &report.unchanged {
+ println!(" {:<9} {path}", "unchanged");
+ }
+ for divergence in &report.divergent {
+ println!(
+ " {:<9} {} — {} ({})",
+ "REFUSED",
+ divergence.path,
+ divergence.reason.describe(),
+ divergence.summary
+ );
+ }
+ println!(
+ " plan: {} create, {} update, {} unchanged, {} refused; {} bytes to write",
+ report.count(WriteKind::Create),
+ report.count(WriteKind::Update),
+ report.unchanged.len(),
+ report.divergent.len(),
+ report.bytes_to_write
+ );
+ match mode {
+ Mode::Plan => println!(" dry run: `plan` never writes files or state"),
+ Mode::DryRun => println!(" dry run: no files were written (pass --apply to export)"),
+ Mode::Apply if applied => {}
+ Mode::Apply => println!(" nothing was written"),
+ }
+}
+
+fn print_git_hints(args: &RunArgs) {
+ println!(
+ "this tool never runs git; to commit the export you may run:\
+ \n git add -- {}\
+ \n git commit -m \"chore(wikisync): export team wiki from {}/{}\"\
+ \n git push",
+ args.dest.display(),
+ args.workspace,
+ args.project
+ );
+}
+
+/// Validate the destination root. `Apply` creates a missing directory;
+/// dry-run modes never touch the filesystem, so for them a missing
+/// destination is simply an empty destination (validated only lexically).
+fn resolve_dest(dest: &Path, mode: Mode) -> Result<PathBuf> {
+ match mode {
+ Mode::Apply => paths::prepare_dest(dest),
+ Mode::Plan | Mode::DryRun => {
+ if dest.exists() {
+ paths::prepare_dest(dest)
+ } else {
+ Ok(paths::lexical_absolute(dest))
+ }
+ }
+ }
+}
+
+/// Entry point behind both CLI subcommands.
+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 client = ApiClient::new(&args.server, args.token.clone())?;
+
+ let (report, _new_state, applied) =
+ run_batch(&client, args, &dest_root, &old_state, mode).await?;
+
+ print_report(args, &report, mode, &families, applied);
+
+ if mode == Mode::Apply && !report.divergent.is_empty() && !args.force {
+ bail!(
+ "{} file(s) diverged locally since the last export; nothing was written. \
+ Inspect the diff summaries above, restore the files, or re-run with --force",
+ report.divergent.len()
+ );
+ }
+ if mode == Mode::Apply && applied {
+ print_git_hints(args);
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn base(hash: &str, etag: Option<&str>) -> PageState {
+ PageState {
+ hash: hash.to_string(),
+ etag: etag.map(str::to_owned),
+ }
+ }
+
+ #[test]
+ fn classify_three_way_matrix() {
+ let disk = b"# page\nbody\n";
+ let disk_hash = state::sha256_hex(disk);
+ let server = b"# page\nbody\n";
+ let edited = b"# page\nedited\n";
+
+ // No file: always a create, even when the server is unchanged.
+ assert_eq!(
+ classify(None, None, Some(server)),
+ Classification::Write(WriteKind::Create)
+ );
+ assert_eq!(
+ classify(None, Some(&base(&disk_hash, None)), Some(server)),
+ Classification::Write(WriteKind::Create)
+ );
+
+ // File equals server: unchanged, with or without a base entry.
+ assert_eq!(
+ classify(Some(disk), None, Some(server)),
+ Classification::Unchanged
+ );
+ assert_eq!(
+ classify(Some(disk), Some(&base("other", None)), Some(server)),
+ Classification::Unchanged
+ );
+
+ // File equals base: 304 keeps it current, a new body fast-forwards.
+ assert_eq!(
+ classify(Some(disk), Some(&base(&disk_hash, None)), None),
+ Classification::Unchanged
+ );
+ assert_eq!(
+ classify(Some(disk), Some(&base(&disk_hash, None)), Some(edited)),
+ Classification::Write(WriteKind::Update)
+ );
+
+ // File differs from base and server: divergent, never a winner.
+ assert_eq!(
+ classify(Some(edited), Some(&base(&disk_hash, None)), Some(server)),
+ Classification::Divergent(DivergentReason::LocalEdit)
+ );
+ assert_eq!(
+ classify(Some(edited), Some(&base(&disk_hash, None)), None),
+ Classification::Divergent(DivergentReason::LocalEdit)
+ );
+ assert_eq!(
+ classify(Some(edited), None, Some(server)),
+ Classification::Divergent(DivergentReason::UnknownFile)
+ );
+ // Frontmatter this tool never wrote reads as a local edit with a
+ // specific reason.
+ let with_fm = b"---\ntitle: forged\n---\n# page\n";
+ assert_eq!(
+ classify(Some(with_fm), Some(&base(&disk_hash, None)), Some(server)),
+ Classification::Divergent(DivergentReason::LocalFrontmatter)
+ );
+ }
+
+ #[test]
+ fn diff_summary_points_at_first_difference() {
+ let disk = b"one\ntwo local\nthree\n";
+ let server = b"one\ntwo server\nthree\n";
+ let summary = diff_summary(Some(disk), Some(server));
+ assert!(summary.contains("line 2"), "{summary}");
+ assert!(summary.contains("local"), "{summary}");
+ let revalidated = diff_summary(Some(disk), None);
+ assert!(revalidated.contains("revalidated by ETag"), "{revalidated}");
+ }
+
+ #[test]
+ fn atomic_write_replaces_and_never_deletes_siblings() {
+ let tmp = tempfile::tempdir().unwrap();
+ let root = tmp.path().canonicalize().unwrap();
+ atomic_write(&root, "notes/a.md", b"v1").unwrap();
+ assert_eq!(fs::read(root.join("notes/a.md")).unwrap(), b"v1");
+ atomic_write(&root, "notes/a.md", b"v2").unwrap();
+ assert_eq!(fs::read(root.join("notes/a.md")).unwrap(), b"v2");
+ // No tmp artifacts left next to the page.
+ let names: Vec<String> = fs::read_dir(root.join("notes"))
+ .unwrap()
+ .flatten()
+ .map(|entry| entry.file_name().to_string_lossy().into_owned())
+ .collect();
+ assert_eq!(names, vec!["a.md".to_string()]);
+ }
+
+ #[test]
+ fn allowlist_must_be_explicit() {
+ assert!(validate_allowlist(&[]).is_err());
+ let err = validate_allowlist(&["*".to_string()])
+ .unwrap_err()
+ .to_string();
+ assert!(err.contains("must be explicit"), "{err}");
+ let both = validate_allowlist(&[
+ "notes".to_string(),
+ "notes".to_string(),
+ "decisions".to_string(),
+ ])
+ .unwrap();
+ assert_eq!(both, vec!["notes".to_string(), "decisions".to_string()]);
+ }
+
+ fn summary(path: &str) -> PageSummary {
+ PageSummary {
+ path: path.to_string(),
+ title: format!("title {path}"),
+ kind: "note".to_string(),
+ tier: "semantic".to_string(),
+ updated_at: "2026-10-01T00:00:00Z".to_string(),
+ }
+ }
+
+ #[test]
+ fn select_pages_filters_families_and_dedupes() {
+ let families = vec!["notes".to_string()];
+ let selected = select_pages(
+ vec![
+ summary("notes/a.md"),
+ summary("notes/a.md"),
+ summary("decisions/skip.md"),
+ summary("notes/b.md"),
+ ],
+ &families,
+ )
+ .unwrap();
+ let paths: Vec<&str> = selected.iter().map(|p| p.path.as_str()).collect();
+ assert_eq!(paths, vec!["notes/a.md", "notes/b.md"]);
+
+ // A hostile server cannot smuggle traversal through the listing.
+ let err = select_pages(vec![summary("notes/../escape.md")], &families)
+ .unwrap_err()
+ .to_string();
+ assert!(err.contains("refused"), "{err}");
+ }
+}
diff --git a/companions/ai-memory-wikisync/tests/api_server.rs b/companions/ai-memory-wikisync/tests/api_server.rs
new file mode 100644
index 00000000..fdd06942
--- /dev/null
+++ b/companions/ai-memory-wikisync/tests/api_server.rs
@@ -0,0 +1,506 @@
+//! Integration tests against a fixture `/api/v1` server (axum, temp port):
+//! 200/ETag/304/401/404 and incremental-cursor pagination, plus the
+//! end-to-end plan/export/local-edit-refusal flow through `run`.
+
+use std::collections::BTreeMap;
+use std::fs;
+use std::net::SocketAddr;
+use std::path::PathBuf;
+use std::sync::Arc;
+use std::sync::atomic::{AtomicUsize, Ordering};
+
+use ai_memory_wikisync::state::{self, SyncState};
+use ai_memory_wikisync::sync::{Mode, RunArgs, run};
+use axum::extract::{Path, Query, State};
+use axum::http::{HeaderMap, StatusCode, header};
+use axum::response::IntoResponse;
+use axum::routing::get;
+use axum::{Json, Router};
+use serde_json::json;
+use tokio::net::TcpListener;
+
+/// Fixture server state: pages, optional bearer token, call counters.
+struct Fixture {
+ /// (path, body) in listing order.
+ pages: Vec<(String, String)>,
+ token: Option<&'static str>,
+ project_exists: bool,
+ /// Page advertised by the listing but missing on read, to simulate a
+ /// delete/expiry racing the run.
+ unreachable: Option<&'static str>,
+ recent_calls: AtomicUsize,
+ page_reads_200: AtomicUsize,
+ page_reads_304: AtomicUsize,
+}
+
+impl Fixture {
+ fn new(pages: Vec<(String, String)>) -> Self {
+ Self {
+ pages,
+ token: None,
+ project_exists: true,
+ unreachable: None,
+ recent_calls: AtomicUsize::new(0),
+ page_reads_200: AtomicUsize::new(0),
+ page_reads_304: AtomicUsize::new(0),
+ }
+ }
+
+ fn with_token(mut self, token: &'static str) -> Self {
+ self.token = Some(token);
+ self
+ }
+
+ fn missing_project(mut self) -> Self {
+ self.project_exists = false;
+ self
+ }
+
+ fn with_unreachable(mut self, path: &'static str) -> Self {
+ self.unreachable = Some(path);
+ self
+ }
+
+ fn body_of(&self, path: &str) -> Option<&str> {
+ self.pages
+ .iter()
+ .find(|(candidate, _)| candidate == path)
+ .map(|(_, body)| body.as_str())
+ }
+
+ fn authorize(&self, headers: &HeaderMap) -> Result<(), Box<axum::response::Response>> {
+ let expected = match self.token {
+ None => return Ok(()),
+ Some(token) => format!("Bearer {token}"),
+ };
+ match headers
+ .get(header::AUTHORIZATION)
+ .and_then(|value| value.to_str().ok())
+ {
+ Some(value) if value == expected => Ok(()),
+ _ => Err(Box::new(error_json(
+ StatusCode::UNAUTHORIZED,
+ "unauthorized",
+ ))),
+ }
+ }
+}
+
+fn error_json(status: StatusCode, message: &str) -> axum::response::Response {
+ (status, Json(json!({ "error": message }))).into_response()
+}
+
+/// Incremental `recent` listing with a page size of 2, so tests exercise
+/// cursor pagination. The cursor is an opaque index string.
+async fn recent_handler(
+ State(fixture): State<Arc<Fixture>>,
+ Path((workspace, project)): Path<(String, String)>,
+ Query(query): Query<BTreeMap<String, String>>,
+ headers: HeaderMap,
+) -> axum::response::Response {
+ fixture.recent_calls.fetch_add(1, Ordering::SeqCst);
+ if let Err(response) = fixture.authorize(&headers) {
+ return *response;
+ }
+ if !fixture.project_exists || workspace != "demo" || project != "app" {
+ return error_json(StatusCode::NOT_FOUND, "workspace or project not found");
+ }
+ // Ignore updated_since; the fixture serves everything after the epoch.
+ let start: usize = query
+ .get("cursor")
+ .and_then(|value| value.strip_prefix("idx:"))
+ .and_then(|value| value.parse().ok())
+ .unwrap_or(0);
+ let end = (start + 2).min(fixture.pages.len());
+ let pages: Vec<serde_json::Value> = fixture.pages[start..end]
+ .iter()
+ .enumerate()
+ .map(|(offset, (path, _))| {
+ json!({
+ "path": path,
+ "title": format!("title {path}"),
+ "kind": "note",
+ "tier": "semantic",
+ "updated_at": format!("2026-10-0{}T00:00:00Z", start + offset + 1),
+ })
+ })
+ .collect();
+ let next_cursor = if end < fixture.pages.len() {
+ json!(format!("idx:{end}"))
+ } else {
+ json!(null)
+ };
+ (
+ [(header::CACHE_CONTROL, "private, no-store")],
+ Json(json!({ "pages": pages, "next_cursor": next_cursor })),
+ )
+ .into_response()
+}
+
+/// Page read with the server's exact-ETag 304 contract.
+async fn page_handler(
+ State(fixture): State<Arc<Fixture>>,
+ Path((workspace, project, path)): Path<(String, String, String)>,
+ headers: HeaderMap,
+) -> axum::response::Response {
+ if let Err(response) = fixture.authorize(&headers) {
+ return *response;
+ }
+ if !fixture.project_exists || workspace != "demo" || project != "app" {
+ return error_json(StatusCode::NOT_FOUND, "workspace or project not found");
+ }
+ if fixture.unreachable == Some(path.as_str()) {
+ return error_json(StatusCode::NOT_FOUND, "page not found");
+ }
+ let Some(body) = fixture.body_of(&path) else {
+ return error_json(StatusCode::NOT_FOUND, "page not found");
+ };
+ let etag = format!("\"{}\"", state::sha256_hex(body.as_bytes()));
+ if let Some(if_none_match) = headers
+ .get(header::IF_NONE_MATCH)
+ .and_then(|v| v.to_str().ok())
+ && if_none_match == etag
+ {
+ fixture.page_reads_304.fetch_add(1, Ordering::SeqCst);
+ return (
+ StatusCode::NOT_MODIFIED,
+ [(header::ETAG, etag)],
+ axum::body::Body::empty(),
+ )
+ .into_response();
+ }
+ fixture.page_reads_200.fetch_add(1, Ordering::SeqCst);
+ (
+ StatusCode::OK,
+ [
+ (header::ETAG, etag),
+ (header::CONTENT_TYPE, "application/json".to_string()),
+ ],
+ Json(json!({
+ "project": project,
+ "workspace": workspace,
+ "path": path,
+ "title": format!("title {path}"),
+ "kind": "note",
+ "tier": "semantic",
+ "pinned": false,
+ "created_at": "2026-10-01T00:00:00Z",
+ "updated_at": "2026-10-01T00:00:00Z",
+ "supersedes": null,
+ "frontmatter": {},
+ "body_markdown": body,
+ "links": [],
+ "backlinks": [],
+ })),
+ )
+ .into_response()
+}
+
+async fn serve(fixture: Fixture) -> (SocketAddr, Arc<Fixture>) {
+ let shared = Arc::new(fixture);
+ let app = Router::new()
+ .route(
+ "/api/v1/workspaces/{workspace}/projects/{project}/recent",
+ get(recent_handler),
+ )
+ .route(
+ "/api/v1/workspaces/{workspace}/projects/{project}/pages/{*path}",
+ get(page_handler),
+ )
+ .with_state(shared.clone());
+ let listener = TcpListener::bind("127.0.0.1:0")
+ .await
+ .expect("bind fixture server");
+ let addr = listener.local_addr().expect("fixture addr");
+ tokio::spawn(async move {
+ axum::serve(listener, app).await.expect("fixture server");
+ });
+ (addr, shared)
+}
+
+fn args(addr: SocketAddr, dest: &std::path::Path, families: &[&str]) -> RunArgs {
+ RunArgs {
+ server: format!("http://{addr}"),
+ token: None,
+ workspace: "demo".to_string(),
+ project: "app".to_string(),
+ dest: dest.to_path_buf(),
+ include: families.iter().map(|f| f.to_string()).collect(),
+ force: false,
+ }
+}
+
+fn fixture_pages() -> Vec<(String, String)> {
+ vec![
+ (
+ "_rules/postgres.md".to_string(),
+ "# Postgres only\nUse Postgres.\n".to_string(),
+ ),
+ (
+ "decisions/0001-db.md".to_string(),
+ "# Standardised on Postgres\nBody.\n".to_string(),
+ ),
+ ("notes/a.md".to_string(), "# A\nalpha\n".to_string()),
+ ("notes/b.md".to_string(), "# B\nbeta\n".to_string()),
+ ("notes/c.md".to_string(), "# C\ngamma\n".to_string()),
+ ]
+}
+
+fn temp_dest() -> (tempfile::TempDir, PathBuf) {
+ let tmp = tempfile::tempdir().expect("tempdir");
+ // Canonicalize so the symlink-free destination guard passes on every OS.
+ let root = tmp.path().canonicalize().unwrap().join("wiki");
+ (tmp, root)
+}
+
+#[tokio::test]
+async fn plan_lists_actions_without_writing() {
+ let (addr, _fixture) = serve(Fixture::new(fixture_pages())).await;
+ let (_tmp, dest) = temp_dest();
+ run(&args(addr, &dest, &["notes"]), Mode::Plan)
+ .await
+ .expect("plan succeeds");
+ assert!(!dest.exists(), "plan must not create the destination");
+}
+
+#[tokio::test]
+async fn export_apply_writes_files_and_state() {
+ let (addr, _fixture) = serve(Fixture::new(fixture_pages())).await;
+ let (_tmp, dest) = temp_dest();
+
+ run(&args(addr, &dest, &["notes", "_rules"]), Mode::Apply)
+ .await
+ .expect("first export");
+
+ assert_eq!(fs::read(dest.join("notes/a.md")).unwrap(), b"# A\nalpha\n");
+ assert_eq!(
+ fs::read(dest.join("_rules/postgres.md")).unwrap(),
+ b"# Postgres only\nUse Postgres.\n"
+ );
+ // Only allowlisted families land on disk.
+ assert!(!dest.join("decisions/0001-db.md").exists());
+
+ let state = state::load(&dest).unwrap();
+ assert_eq!(state.pages.len(), 4, "notes/* plus _rules/postgres.md");
+ for path in [
+ "notes/a.md",
+ "notes/b.md",
+ "notes/c.md",
+ "_rules/postgres.md",
+ ] {
+ let entry = state.pages.get(path).expect(path);
+ assert!(entry.etag.is_some(), "etag recorded for {path}");
+ }
+}
+
+#[tokio::test]
+async fn reexport_revalidates_with_etag_and_writes_nothing() {
+ let (addr, fixture) = serve(Fixture::new(fixture_pages())).await;
+ let (_tmp, dest) = temp_dest();
+ run(&args(addr, &dest, &["notes"]), Mode::Apply)
+ .await
+ .expect("first export");
+ let before = fs::read(dest.join("notes/a.md")).unwrap();
+ let reads_before = fixture.page_reads_200.load(Ordering::SeqCst);
+
+ run(&args(addr, &dest, &["notes"]), Mode::Apply)
+ .await
+ .expect("second export");
+ assert!(
+ fixture.page_reads_304.load(Ordering::SeqCst) >= 3,
+ "every unchanged page revalidated via 304"
+ );
+ assert_eq!(
+ fixture.page_reads_200.load(Ordering::SeqCst),
+ reads_before,
+ "no full page body was fetched again"
+ );
+ assert_eq!(fs::read(dest.join("notes/a.md")).unwrap(), before);
+}
+
+#[tokio::test]
+async fn local_edits_are_refused_until_forced() {
+ let (addr, _fixture) = serve(Fixture::new(fixture_pages())).await;
+ let (_tmp, dest) = temp_dest();
+ run(&args(addr, &dest, &["notes"]), Mode::Apply)
+ .await
+ .expect("first export");
+
+ fs::write(dest.join("notes/b.md"), b"# B\nlocally edited\n").unwrap();
+ // A brand-new local file inside an allowlisted family is unknown, not
+ // ours to clobber.
+ fs::write(dest.join("notes/zz-new.md"), b"# local\n").unwrap();
+
+ let refused = run(&args(addr, &dest, &["notes"]), Mode::Apply)
+ .await
+ .expect_err("must refuse when files diverged");
+ let message = refused.to_string();
+ assert!(message.contains("diverged"), "{message}");
+ assert_eq!(
+ fs::read(dest.join("notes/b.md")).unwrap(),
+ b"# B\nlocally edited\n",
+ "diverged file is untouched"
+ );
+ assert_eq!(fs::read(dest.join("notes/a.md")).unwrap(), b"# A\nalpha\n");
+ assert_eq!(
+ fs::read(dest.join("notes/zz-new.md")).unwrap(),
+ b"# local\n",
+ "unknown local file is untouched"
+ );
+
+ let mut force_args = args(addr, &dest, &["notes"]);
+ force_args.force = true;
+ run(&force_args, Mode::Apply)
+ .await
+ .expect("--force exports");
+ assert_eq!(fs::read(dest.join("notes/b.md")).unwrap(), b"# B\nbeta\n");
+ assert_eq!(
+ fs::read(dest.join("notes/zz-new.md")).unwrap(),
+ b"# local\n",
+ "--force overwrites divergent server pages; it still never deletes"
+ );
+ // State reflects the forced page.
+ let state = state::load(&dest).unwrap();
+ assert_eq!(
+ state.pages["notes/b.md"].hash,
+ state::sha256_hex(b"# B\nbeta\n")
+ );
+}
+
+#[tokio::test]
+async fn unauthorized_is_a_clear_error() {
+ let (addr, _fixture) = serve(Fixture::new(fixture_pages()).with_token("sekrit")).await;
+ let (_tmp, dest) = temp_dest();
+ let err = run(&args(addr, &dest, &["notes"]), Mode::Plan)
+ .await
+ .expect_err("must fail");
+ let message = err.to_string();
+ assert!(message.contains("401"), "{message}");
+ assert!(message.contains("AI_MEMORY_AUTH_TOKEN"), "{message}");
+ assert!(!message.contains("sekrit"), "token never leaks: {message}");
+
+ let mut authed = args(addr, &dest, &["notes"]);
+ authed.token = Some("sekrit".to_string());
+ run(&authed, Mode::Plan).await.expect("authorized plan");
+}
+
+#[tokio::test]
+async fn unknown_scope_is_a_clear_404() {
+ let (addr, _fixture) = serve(Fixture::new(fixture_pages()).missing_project()).await;
+ let (_tmp, dest) = temp_dest();
+ let err = run(&args(addr, &dest, &["notes"]), Mode::Plan)
+ .await
+ .expect_err("must fail");
+ let message = err.to_string();
+ assert!(message.contains("404"), "{message}");
+ assert!(message.contains("--workspace/--project"), "{message}");
+}
+
+#[tokio::test]
+async fn listing_follows_cursors_to_the_last_page() {
+ // Five pages with a fixture page size of 2 means three listing rounds.
+ let (addr, fixture) = serve(Fixture::new(fixture_pages())).await;
+ let (_tmp, dest) = temp_dest();
+ run(&args(addr, &dest, &["notes"]), Mode::Apply)
+ .await
+ .expect("export");
+ assert!(
+ fixture.recent_calls.load(Ordering::SeqCst) >= 3,
+ "cursor pagination was exercised"
+ );
+ assert!(dest.join("notes/c.md").exists(), "last page reached");
+}
+
+#[tokio::test]
+async fn server_page_paths_escaping_dest_are_refused() {
+ let hostile = vec![
+ ("notes/ok.md".to_string(), "# ok\n".to_string()),
+ (
+ "notes/../../escape.md".to_string(),
+ "# escape\n".to_string(),
+ ),
+ ];
+ let (addr, _fixture) = serve(Fixture::new(hostile)).await;
+ let (tmp, dest) = temp_dest();
+ let err = run(&args(addr, &dest, &["notes"]), Mode::Apply)
+ .await
+ .expect_err("hostile listing refused");
+ assert!(err.to_string().contains("refused"), "{err}");
+ // The batch failed during selection: no page files, nothing outside dest.
+ assert!(!dest.join("notes/ok.md").exists());
+ assert!(
+ !tmp.path().join("escape.md").exists(),
+ "nothing outside dest"
+ );
+}
+
+#[tokio::test]
+async fn case_fold_collisions_from_server_are_refused() {
+ let colliding = vec![
+ ("notes/a.md".to_string(), "# a\n".to_string()),
+ ("Notes/A.md".to_string(), "# A\n".to_string()),
+ ];
+ let (addr, _fixture) = serve(Fixture::new(colliding)).await;
+ let (_tmp, dest) = temp_dest();
+ let err = run(&args(addr, &dest, &["notes", "Notes"]), Mode::Apply)
+ .await
+ .expect_err("collision refused");
+ assert!(err.to_string().contains("case-fold"), "{}", err);
+}
+
+#[tokio::test]
+async fn allowlist_rules_apply_end_to_end() {
+ let (addr, _fixture) = serve(Fixture::new(fixture_pages())).await;
+ let (_tmp, dest) = temp_dest();
+
+ let none = RunArgs {
+ include: vec![],
+ ..args(addr, &dest, &[])
+ };
+ let err = run(&none, Mode::Plan).await.expect_err("empty allowlist");
+ assert!(err.to_string().contains("must be explicit"), "{err}");
+
+ let star = RunArgs {
+ include: vec!["*".to_string()],
+ ..args(addr, &dest, &[])
+ };
+ let err = run(&star, Mode::Plan).await.expect_err("bare star refused");
+ assert!(err.to_string().contains("'*'"), "{err}");
+}
+
+#[tokio::test]
+async fn page_missing_on_read_fails_loudly() {
+ // The listing advertises a page the read cannot find (deleted or
+ // expired mid-run): the run must fail instead of skipping silently.
+ let mut pages = fixture_pages();
+ pages.push(("notes/ghost.md".to_string(), "# ghost\n".to_string()));
+ let (addr, _fixture) = serve(Fixture::new(pages).with_unreachable("notes/ghost.md")).await;
+ let (_tmp, dest) = temp_dest();
+ let err = run(&args(addr, &dest, &["notes"]), Mode::Apply)
+ .await
+ .expect_err("ghost page must fail the run");
+ assert!(
+ err.to_string().contains("404") || err.to_string().contains("ghost"),
+ "{err}"
+ );
+ assert!(
+ !dest.join("notes/a.md").exists(),
+ "a failed batch writes nothing"
+ );
+}
+
+#[tokio::test]
+async fn empty_state_after_user_deletes_local_file_recreates_it() {
+ let (addr, _fixture) = serve(Fixture::new(fixture_pages())).await;
+ let (_tmp, dest) = temp_dest();
+ run(&args(addr, &dest, &["notes"]), Mode::Apply)
+ .await
+ .expect("first export");
+ fs::remove_file(dest.join("notes/b.md")).unwrap();
+ run(&args(addr, &dest, &["notes"]), Mode::Apply)
+ .await
+ .expect("recreate");
+ assert_eq!(fs::read(dest.join("notes/b.md")).unwrap(), b"# B\nbeta\n");
+ let state: SyncState = state::load(&dest).unwrap();
+ assert!(state.pages.contains_key("notes/b.md"));
+}
diff --git a/docs/companion-crates.md b/docs/companion-crates.md
index 7074ef41..3da0da61 100644
--- a/docs/companion-crates.md
+++ b/docs/companion-crates.md
@@ -79,6 +79,10 @@ the public MCP write/delete tools. It must never open the wiki directory or
SQLite directly. The core read seam is `/api/v1` in API-only mode; the supported
MCP page arguments are documented in [programmatic memory](programmatic-memory.md).
+Slice 1 (read-only export) shipped as
+[`ai-memory-wikisync`](#ai-memory-wikisync-read-only-team-wiki-export)
+below; the remaining slices are tracked in #986.
+
## `ai-memory-client`: shared private capture privacy
[`ai-memory-client`](../companions/ai-memory-client) supplies four privacy
@@ -230,6 +234,75 @@ Re-home by kind:
6. Only after repeated usage, consider whether ai-memory core lacks a small,
generic API seam; do not start by patching core endpoints.
+## `ai-memory-wikisync`: read-only team-wiki export
+
+Slice 1 of the accepted [team-wiki sync](#proposed-team-wiki-sync-986)
+shape, implemented at [`companions/ai-memory-wikisync`](../companions/ai-memory-wikisync)
+as a standalone Cargo package with its own `[workspace]` (mirroring the
+importer): it is not a member of the root workspace and is not covered by
+root `cargo test --workspace`.
+
+### Goal
+
+Mirror a team's shared ai-memory pages into a project repository as
+reviewable markdown, so the wiki a team actually maintains can travel with
+the code it documents — read-only, family-scoped, and dry-run by default.
+
+### How it talks to ai-memory
+
+- `plan` (always dry-run) and `export` (dry-run unless `--apply`) against
+ the documented read-only `/api/v1` surface: incremental `recent` listing
+ with cursor paging (legacy array accepted) plus single-page reads with
+ `ETag` / `If-None-Match` revalidation. No MCP, no admin routes, no
+ writes to the server.
+- `--include FAMILY` is an explicit, repeatable allowlist of top-level
+ wiki directories; at least one is required and a bare `*` is refused.
+- Auth is a bearer token via `--token` or `AI_MEMORY_AUTH_TOKEN` only;
+ tokens are never logged or persisted.
+- Writes exactly the server's canonical projection (path, title, body)
+ with no forged attribution/generated frontmatter. All local bookkeeping
+ lives in one state file under the destination
+ (`.ai-memory-wikisync/state.json`, 0600, atomically replaced after each
+ successful write batch).
+
+### Safety requirements honored
+
+- Three-way classification per page (destination file, last exported
+ state, server body): files edited locally since the last export are
+ reported with a diff summary and the whole batch is refused without
+ `--force`.
+- Never deletes anything (deletes are slice 4); never runs git, commits,
+ or pushes — it prints the commands the operator may run.
+- Destination-path safety: traversal, dotfiles, reserved Windows names,
+ non-portable characters, case-fold collisions, oversized bodies,
+ symlinked destinations/components/state directories, and unknown page
+ frontmatter are all refused; files are replaced atomically
+ (tmp + rename + fsync).
+- Page bodies are untrusted data, transported verbatim and never executed
+ or rendered.
+
+### Validation
+
+```bash
+cargo fmt --check --manifest-path companions/ai-memory-wikisync/Cargo.toml
+cargo test --manifest-path companions/ai-memory-wikisync/Cargo.toml
+cargo clippy --manifest-path companions/ai-memory-wikisync/Cargo.toml --all-targets -- -D warnings
+```
+
+Unit tests cover the path-safety matrix, the allowlist rules, state
+hash/crash behavior and local-edit refusal; integration tests run the
+full plan/export flow against a fixture axum server serving `/api/v1`
+responses (200/ETag/304/401/404 and cursor pagination).
+
+### Roadmap (#986)
+
+1. This slice — read-only export into a project repository.
+2. Conditional mutation seam (compare-and-write) in core, if independently
+ justified.
+3. Bidirectional apply through public write tools.
+4. Deletes and conflict reporting.
+5. Post-merge hook / CI integration.
+
## `ai-memory-macos`: menu bar wrapper
Self-contained macOS accessory app at
diff --git a/docs/cookbook.md b/docs/cookbook.md
index b6cdc777..4efa173b 100644
--- a/docs/cookbook.md
+++ b/docs/cookbook.md
@@ -119,6 +119,28 @@ Once the material is saved as pages in the right scope, any project can search
it (`memory_query`) and read a specific document in full (`memory_read_page`)
before implementing against it.
+## Recipe: mirror a team wiki into the repository (team wiki sync)
+
+To keep a team's shared memory reviewable next to the code it documents, use
+the [`ai-memory-wikisync`](../companions/ai-memory-wikisync) companion
+(boundary in [`companion-crates.md`](companion-crates.md)). It exports
+explicitly allowlisted page families from the server's read-only `/api/v1`
+surface into a directory in your repo — dry-run by default:
+
+```bash
+ai-memory-wikisync plan --server http://127.0.0.1:49374 \
+ --workspace demo --project app --dest ./wiki \
+ --include _rules --include decisions # lists create/update/unchanged; never writes
+ai-memory-wikisync export ...same args... --apply # writes; prints the git commands to run
+```
+
+Everything is opt-in and fail-safe: the family allowlist must be explicit
+(`*` is refused), files edited locally since the last export are reported
+with a diff summary and refused without `--force`, nothing is ever deleted
+(that is a later slice), no frontmatter is forged, and the tool never runs
+git itself. Slice 1 is read-only export; bidirectional sync, deletes and
+conflict handling are tracked in #986.
+
## Recipe: control what gets kept, aged, or consolidated
By default nothing you have to think about: memory decays on a single gentle