Skip to content

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

Rust

feat(wikisync): sync --check and a post-merge hook (#986 slice 5)

AkitaOnRails53736dffffc6
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7bf89221..4b4aee91 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -15,6 +15,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
current version, and changes nothing. `memory_read_page` returns the version
as `page_id` and `/api/v1` pages as `id`. This is the compare-and-write the
team-wiki sync needed (#986).
+- The `ai-memory-wikisync` companion gained CI and post-merge integration
+ (#986, slice 5): `sync --check` writes nothing and exits 0 in sync, 3 on
+ drift and 4 on conflicts or refusals (a clone without sync state compares
+ the repository with the server directly), and `install-hook` /
+ `uninstall-hook` manage a marked git `post-merge` block that runs `sync`
+ after each merge — a dry-run report unless `--on-merge apply`, never with
+ `--prefer`, and never with a stored token. The cookbook has a GitHub
+ Actions recipe. (#986)
- The `ai-memory-wikisync` companion now propagates deletes with
`sync --propagate-deletes` (#986, slice 4): a file deleted in the repository
deletes its server page through `memory_delete_page`, and a page deleted on
diff --git a/companions/ai-memory-wikisync/README.md b/companions/ai-memory-wikisync/README.md
index 1795aa49..49dc48cc 100644
--- a/companions/ai-memory-wikisync/README.md
+++ b/companions/ai-memory-wikisync/README.md
@@ -2,7 +2,7 @@
**Team-wiki sync** companion for
[ai-memory](https://github.com/akitaonrails/ai-memory) (issue #986, slices
-1, 3 and 4). It keeps explicitly allowlisted page families of a running
+1, 3, 4 and 5). It keeps explicitly allowlisted page families of a running
ai-memory server in step with a directory inside a project repository, so a
team's shared memory can live as reviewable markdown in git:
@@ -10,6 +10,8 @@ team's shared memory can live as reviewable markdown in git:
- `sync` also sends repository edits back to the server, through the public
`memory_write_page` MCP tool, and with `--propagate-deletes` carries
deletes both ways through `memory_delete_page`.
+- `sync --check` is a read-only CI gate, and `install-hook` runs `sync`
+ after every git merge.
`sync --apply` needs ai-memory 2.7 or later: every write and delete is
conditional on the page version the plan saw, and an older server would
@@ -174,12 +176,64 @@ Safety rules:
prints the `git rm` to stage the deletes. Apply order is imports, exports,
server deletes, file deletes.
+## CI and post-merge
+
+`sync --check` writes nothing — no files, no state — and reports through its
+exit code:
+
+| Exit | Meaning |
+|---|---|
+| 0 | in sync |
+| 1 | error (server unreachable or refusing the request, invalid destination, …) |
+| 2 | usage error (clap) |
+| 3 | drift: imports, exports or deletes are pending (unpropagated deletes count) |
+| 4 | conflicts or refusals need a person; wins over 3 |
+
+A clone without a state file (every CI checkout: the state is never
+committed) compares the repository with the server directly, so a page that
+differs is drift (3), not a conflict. `--check` cannot be combined with
+`--apply`. See [the cookbook](../../docs/cookbook.md) for a GitHub Actions job.
+
+`install-hook` writes a git `post-merge` hook so a pull or merge reports
+(or, opt-in, applies) a sync:
+
+```bash
+ai-memory-wikisync install-hook --workspace demo --project app \
+ --dest docs/wiki --include _rules --include decisions \
+ [--on-merge report|apply] [--propagate-deletes] \
+ [--hooks-dir DIR] [--append] [--print]
+ai-memory-wikisync uninstall-hook --dest docs/wiki [--hooks-dir DIR]
+```
+
+- The hook runs `( command -v ai-memory-wikisync >/dev/null &&
+ ai-memory-wikisync sync … ) || true`: a missing binary or a failed sync
+ never fails the merge. It reports by default; `--on-merge apply` adds
+ `--apply`. It never passes `--prefer`, and passes `--propagate-deletes`
+ only if it was given at install.
+- It lives between `# >>> ai-memory-wikisync >>>` and
+ `# <<< ai-memory-wikisync <<<`. Re-running `install-hook` replaces that
+ block; `uninstall-hook` removes only the block (and the file, if nothing
+ but a shebang is left).
+- The hooks directory is found by walking up from `--dest` to `.git`,
+ following a worktree's `gitdir:` file and `commondir`, so one hook serves
+ every worktree; `--dest` is written relative to the repository root. If
+ `core.hooksPath` is set in the repository's config, the install is refused:
+ pass `--hooks-dir` with that directory, or `--print` the block for your hook
+ manager.
+- No token is ever written (`--token` is refused; the hook reads
+ `AI_MEMORY_AUTH_TOKEN` when it runs), every argument is single-quoted, and
+ newlines or NUL are refused. The file is replaced atomically with mode
+ 0755; a symlinked hook is refused, and an existing hook without the block
+ is refused unless `--append` is given and its shebang is a POSIX shell.
+ The companion never runs git.
+
## Roadmap (#986)
1. Read-only export into a project repository (`export`).
2. Conditional mutation seam (compare-and-write) in core (ai-memory 2.7).
3. Two-way sync (`sync`): repository edits flow back through the public MCP
write tool.
-4. **This release — deletes and conflict reporting** (`--propagate-deletes`,
- conditional writes).
-5. Post-merge hook / CI integration.
+4. Deletes and conflict reporting (`--propagate-deletes`, conditional
+ writes).
+5. **This release — post-merge hook and CI integration** (`install-hook`,
+ `sync --check`).
diff --git a/companions/ai-memory-wikisync/src/hook.rs b/companions/ai-memory-wikisync/src/hook.rs
new file mode 100644
index 00000000..2b2e995d
--- /dev/null
+++ b/companions/ai-memory-wikisync/src/hook.rs
@@ -0,0 +1,715 @@
+//! `install-hook` / `uninstall-hook`: a git `post-merge` hook that runs
+//! `sync` after every merge or pull.
+//!
+//! The hook is a marked block, so it can share a file with other hooks and be
+//! replaced or removed without touching them. It reports by default (a sync
+//! dry-run) and applies only when installed with `--on-merge apply`; it never
+//! passes `--prefer`, so a conflict always waits for a person. The companion
+//! never runs git: the hooks directory is found by reading `.git` itself.
+//!
+//! The hook file is executable shell, so everything that reaches it is
+//! single-quoted, and no token is ever written: at merge time `sync` reads
+//! `AI_MEMORY_AUTH_TOKEN` from the environment like any other run.
+
+use std::fs;
+use std::io::Write;
+use std::path::{Path, PathBuf};
+
+use anyhow::{Context, Result, bail};
+
+use crate::{paths, sync};
+
+pub const BEGIN_MARKER: &str = "# >>> ai-memory-wikisync >>>";
+pub const END_MARKER: &str = "# <<< ai-memory-wikisync <<<";
+const HOOK_NAME: &str = "post-merge";
+const FRESH_SHEBANG: &str = "#!/bin/sh\n";
+/// Interpreters that run the block's POSIX shell unchanged.
+const SH_COMPATIBLE: &[&str] = &["sh", "bash", "dash", "ksh", "zsh", "ash"];
+
+/// What the hook does after a merge.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum OnMerge {
+ /// `sync` dry-run: print what would change.
+ Report,
+ /// `sync --apply`.
+ Apply,
+}
+
+/// The `sync` invocation the hook runs.
+#[derive(Debug, Clone)]
+pub struct HookSpec {
+ /// Written only when given explicitly; otherwise the hook uses
+ /// `AI_MEMORY_SERVER_URL` or the default at merge time.
+ pub server: Option<String>,
+ pub workspace: String,
+ pub project: String,
+ pub dest: PathBuf,
+ pub include: Vec<String>,
+ pub on_merge: OnMerge,
+ pub propagate_deletes: bool,
+}
+
+/// Arguments of `install-hook`.
+#[derive(Debug, Clone)]
+pub struct InstallArgs {
+ pub spec: HookSpec,
+ /// Print the block instead of writing it.
+ pub print: bool,
+ /// Install here instead of the repository's `.git/hooks`.
+ pub hooks_dir: Option<PathBuf>,
+ /// Add the block to an existing hook that does not have it yet.
+ pub append: bool,
+}
+
+/// The git directories that matter for a hook.
+#[derive(Debug, Clone, PartialEq, Eq)]
+struct GitDirs {
+ /// The working tree root: git runs hooks from here.
+ top: PathBuf,
+ /// This worktree's git directory (`config.worktree` lives here).
+ gitdir: PathBuf,
+ /// The directory shared by all worktrees (`config`, `hooks`).
+ common: PathBuf,
+}
+
+/// Single-quote one argument for `sh`. A newline or NUL could not survive a
+/// one-line hook and has no business in these arguments, so it is refused.
+fn quote(arg: &str) -> Result<String> {
+ if arg.contains(['\n', '\r', '\0']) {
+ bail!("refusing a hook argument with a newline or NUL: {arg:?}");
+ }
+ Ok(format!("'{}'", arg.replace('\'', r"'\''")))
+}
+
+/// The marked block, ending in a newline.
+fn render_block(spec: &HookSpec, dest_arg: &str) -> Result<String> {
+ let families = sync::validate_allowlist(&spec.include)?;
+ let mut args: Vec<String> = vec![
+ "--workspace".into(),
+ quote(&spec.workspace)?,
+ "--project".into(),
+ quote(&spec.project)?,
+ "--dest".into(),
+ quote(dest_arg)?,
+ ];
+ for family in &families {
+ args.push("--include".into());
+ args.push(quote(family)?);
+ }
+ if let Some(server) = &spec.server {
+ args.push("--server".into());
+ args.push(quote(server)?);
+ }
+ if spec.on_merge == OnMerge::Apply {
+ args.push("--apply".into());
+ }
+ if spec.propagate_deletes {
+ args.push("--propagate-deletes".into());
+ }
+ Ok(format!(
+ "{BEGIN_MARKER}\n\
+ # Managed by `ai-memory-wikisync install-hook`; re-run it to change this block.\n\
+ # A missing binary or a failed sync never fails the merge.\n\
+ ( command -v ai-memory-wikisync >/dev/null && ai-memory-wikisync sync {} ) || true\n\
+ {END_MARKER}\n",
+ args.join(" ")
+ ))
+}
+
+/// Walk up from `start` to the first `.git`: a directory, or a worktree's
+/// `gitdir:` file whose git directory may name a shared `commondir`.
+fn find_git(start: &Path) -> Result<Option<GitDirs>> {
+ let mut dir = Some(start);
+ while let Some(current) = dir {
+ let dot_git = current.join(".git");
+ match fs::symlink_metadata(&dot_git) {
+ Ok(meta) if meta.is_dir() => {
+ return Ok(Some(GitDirs {
+ top: current.to_path_buf(),
+ gitdir: dot_git.clone(),
+ common: dot_git,
+ }));
+ }
+ Ok(meta) if meta.is_file() => {
+ let text = fs::read_to_string(&dot_git)
+ .with_context(|| format!("cannot read {}", dot_git.display()))?;
+ let Some(target) = text.trim().strip_prefix("gitdir:") else {
+ bail!("{} is not a `gitdir:` file", dot_git.display());
+ };
+ let gitdir = paths::lexical_absolute(&current.join(target.trim()));
+ let common = match fs::read_to_string(gitdir.join("commondir")) {
+ Ok(common) => paths::lexical_absolute(&gitdir.join(common.trim())),
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => gitdir.clone(),
+ Err(e) => {
+ return Err(anyhow::Error::new(e))
+ .context(format!("cannot read {}/commondir", gitdir.display()));
+ }
+ };
+ return Ok(Some(GitDirs {
+ top: current.to_path_buf(),
+ gitdir,
+ common,
+ }));
+ }
+ Ok(_) => bail!("{} is neither a directory nor a file", dot_git.display()),
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => dir = current.parent(),
+ Err(e) => {
+ return Err(anyhow::Error::new(e))
+ .context(format!("cannot inspect {}", dot_git.display()));
+ }
+ }
+ }
+ Ok(None)
+}
+
+/// The config file that sets `core.hooksPath`, if any. Git then ignores
+/// `.git/hooks`, so a hook written there would silently never run.
+fn hooks_path_config(git: &GitDirs) -> Result<Option<PathBuf>> {
+ for config in [
+ git.common.join("config"),
+ git.gitdir.join("config.worktree"),
+ ] {
+ let text = match fs::read_to_string(&config) {
+ Ok(text) => text,
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
+ Err(e) => {
+ return Err(anyhow::Error::new(e))
+ .context(format!("cannot read {}", config.display()));
+ }
+ };
+ if sets_hooks_path(&text) {
+ return Ok(Some(config));
+ }
+ }
+ Ok(None)
+}
+
+/// Whether a git config text sets `hooksPath` in its `[core]` section. Keys
+/// and section names are case-insensitive in git.
+fn sets_hooks_path(config: &str) -> bool {
+ let mut in_core = false;
+ for line in config.lines() {
+ let line = line.trim();
+ if let Some(section) = line.strip_prefix('[') {
+ let name = section.split([']', ' ', '"']).next().unwrap_or_default();
+ in_core = name.eq_ignore_ascii_case("core");
+ continue;
+ }
+ let key = line.split(['=', ' ', '\t']).next().unwrap_or_default();
+ if in_core && key.eq_ignore_ascii_case("hookspath") {
+ return true;
+ }
+ }
+ false
+}
+
+/// `--dest` as the hook passes it: relative to the working tree root, where
+/// git runs hooks, so one hook serves every worktree of the repository.
+fn dest_arg(dest: &Path, git: Option<&GitDirs>) -> Result<String> {
+ let absolute = paths::lexical_absolute(dest);
+ let shown = match git.and_then(|git| absolute.strip_prefix(&git.top).ok()) {
+ Some(relative) if relative.as_os_str().is_empty() => PathBuf::from("."),
+ Some(relative) => relative.to_path_buf(),
+ None => absolute,
+ };
+ shown
+ .to_str()
+ .map(str::to_owned)
+ .with_context(|| format!("--dest {} is not valid UTF-8", shown.display()))
+}
+
+fn hooks_dir(explicit: Option<&Path>, git: Option<&GitDirs>) -> Result<PathBuf> {
+ if let Some(dir) = explicit {
+ return Ok(dir.to_path_buf());
+ }
+ let Some(git) = git else {
+ bail!("no git repository found at or above --dest; pass --hooks-dir or --print");
+ };
+ if let Some(config) = hooks_path_config(git)? {
+ bail!(
+ "core.hooksPath is set in {}, so git ignores {}; pass --hooks-dir with that \
+ directory, or --print and add the block to your hook manager",
+ config.display(),
+ git.common.join("hooks").display()
+ );
+ }
+ Ok(git.common.join("hooks"))
+}
+
+/// The current hook text, or `None` when there is none. A symlinked hook is
+/// refused: writing through it would change a file outside the hooks dir.
+fn read_hook(hook: &Path) -> Result<Option<String>> {
+ match fs::symlink_metadata(hook) {
+ Ok(meta) if meta.file_type().is_symlink() => {
+ bail!("{} is a symlink; refusing to edit it", hook.display())
+ }
+ Ok(meta) if !meta.is_file() => bail!("{} is not a regular file", hook.display()),
+ Ok(_) => fs::read_to_string(hook)
+ .map(Some)
+ .with_context(|| format!("cannot read {} as text", hook.display())),
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
+ Err(e) => Err(anyhow::Error::new(e)).context(format!("cannot inspect {}", hook.display())),
+ }
+}
+
+/// Byte range of the marked block, through the end marker's line.
+fn block_range(text: &str) -> Result<Option<(usize, usize)>> {
+ let Some(begin) = text.find(BEGIN_MARKER) else {
+ if text.contains(END_MARKER) {
+ bail!("the hook has an end marker without a begin marker; fix it by hand");
+ }
+ return Ok(None);
+ };
+ let Some(end) = text[begin..].find(END_MARKER).map(|end| begin + end) else {
+ bail!("the hook's ai-memory-wikisync block has no end marker; fix it by hand");
+ };
+ let end = text[end..]
+ .find('\n')
+ .map_or(text.len(), |newline| end + newline + 1);
+ if text[end..].contains(BEGIN_MARKER) {
+ bail!("the hook has more than one ai-memory-wikisync block; fix it by hand");
+ }
+ Ok(Some((begin, end)))
+}
+
+/// Whether a hook's shebang runs the block's POSIX shell.
+fn sh_compatible(text: &str) -> bool {
+ let Some(shebang) = text.lines().next().and_then(|line| line.strip_prefix("#!")) else {
+ return false;
+ };
+ let mut words = shebang.split_whitespace();
+ let program = words.next().unwrap_or_default();
+ let name = program.rsplit('/').next().unwrap_or_default();
+ let interpreter = if name == "env" {
+ words.next().unwrap_or_default()
+ } else {
+ name
+ };
+ SH_COMPATIBLE.contains(&interpreter)
+}
+
+/// The hook text with `block` installed: a fresh file, a replaced block, or
+/// (with `append`) the block after an existing shell hook.
+fn merge_hook(existing: Option<&str>, block: &str, append: bool) -> Result<String> {
+ let Some(text) = existing else {
+ return Ok(format!("{FRESH_SHEBANG}{block}"));
+ };
+ if let Some((begin, end)) = block_range(text)? {
+ return Ok(format!("{}{block}{}", &text[..begin], &text[end..]));
+ }
+ if !append {
+ bail!(
+ "a post-merge hook already exists without an ai-memory-wikisync block; pass \
+ --append to add the block to it, or --print to add it yourself"
+ );
+ }
+ if !sh_compatible(text) {
+ bail!(
+ "the existing post-merge hook does not start with a POSIX shell shebang \
+ (sh, bash, dash, ksh, zsh); use --print and add the block yourself"
+ );
+ }
+ let separator = if text.ends_with('\n') { "" } else { "\n" };
+ Ok(format!("{text}{separator}{block}"))
+}
+
+/// Replace the hook atomically (tmp + fsync + rename) with mode 0755.
+fn write_hook(hook: &Path, text: &str) -> Result<()> {
+ let dir = hook.parent().context("hook path has no directory")?;
+ fs::create_dir_all(dir).with_context(|| format!("cannot create {}", dir.display()))?;
+ let tmp = dir.join(".post-merge.wikisync-tmp");
+ 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::OpenOptions::new()
+ .write(true)
+ .create_new(true)
+ .open(&tmp)
+ .with_context(|| format!("cannot create {}", tmp.display()))?;
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ fs::set_permissions(&tmp, fs::Permissions::from_mode(0o755))
+ .with_context(|| format!("cannot make {} executable", tmp.display()))?;
+ }
+ file.write_all(text.as_bytes())
+ .with_context(|| format!("cannot write {}", tmp.display()))?;
+ file.sync_all()
+ .with_context(|| format!("cannot sync {}", tmp.display()))?;
+ }
+ fs::rename(&tmp, hook).with_context(|| format!("cannot move {} into place", tmp.display()))
+}
+
+/// Entry point behind `install-hook`.
+pub fn install(args: &InstallArgs) -> Result<()> {
+ let git = find_git(&paths::lexical_absolute(&args.spec.dest))?;
+ let block = render_block(&args.spec, &dest_arg(&args.spec.dest, git.as_ref())?)?;
+ if args.print {
+ print!("{block}");
+ return Ok(());
+ }
+ let hook = hooks_dir(args.hooks_dir.as_deref(), git.as_ref())?.join(HOOK_NAME);
+ let existing = read_hook(&hook)?;
+ write_hook(
+ &hook,
+ &merge_hook(existing.as_deref(), &block, args.append)?,
+ )?;
+ let action = match args.spec.on_merge {
+ OnMerge::Report => "report what a sync would change",
+ OnMerge::Apply => "apply a sync",
+ };
+ println!(
+ "installed {}: after each merge it will {action}",
+ hook.display()
+ );
+ Ok(())
+}
+
+/// Entry point behind `uninstall-hook`: removes only the marked block, and
+/// the file too when nothing but a shebang would remain.
+pub fn uninstall(dest: &Path, explicit_hooks_dir: Option<&Path>) -> Result<()> {
+ let git = find_git(&paths::lexical_absolute(dest))?;
+ let hook = hooks_dir(explicit_hooks_dir, git.as_ref())?.join(HOOK_NAME);
+ let Some(text) = read_hook(&hook)? else {
+ println!("no {} hook; nothing to remove", hook.display());
+ return Ok(());
+ };
+ let Some((begin, end)) = block_range(&text)? else {
+ println!(
+ "{} has no ai-memory-wikisync block; nothing to remove",
+ hook.display()
+ );
+ return Ok(());
+ };
+ let rest = format!("{}{}", &text[..begin], &text[end..]);
+ let mut lines = rest.lines().filter(|line| !line.trim().is_empty());
+ let only_shebang = match lines.next() {
+ None => true,
+ Some(first) => first.starts_with("#!") && lines.next().is_none(),
+ };
+ if only_shebang {
+ fs::remove_file(&hook).with_context(|| format!("cannot remove {}", hook.display()))?;
+ println!("removed {}", hook.display());
+ } else {
+ write_hook(&hook, &rest)?;
+ println!(
+ "removed the ai-memory-wikisync block from {}",
+ hook.display()
+ );
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn spec(dest: &Path) -> HookSpec {
+ HookSpec {
+ server: None,
+ workspace: "demo".into(),
+ project: "app".into(),
+ dest: dest.to_path_buf(),
+ include: vec!["decisions".into()],
+ on_merge: OnMerge::Report,
+ propagate_deletes: false,
+ }
+ }
+
+ fn install_args(dest: &Path) -> InstallArgs {
+ InstallArgs {
+ spec: spec(dest),
+ print: false,
+ hooks_dir: None,
+ append: false,
+ }
+ }
+
+ /// A repository root with a bare-bones `.git` directory: all the hook
+ /// installer reads. No git binary is involved.
+ fn repo() -> (tempfile::TempDir, PathBuf) {
+ let tmp = tempfile::tempdir().unwrap();
+ let root = tmp.path().canonicalize().unwrap().join("repo");
+ fs::create_dir_all(root.join(".git/hooks")).unwrap();
+ fs::write(root.join(".git/config"), "[core]\n\tbare = false\n").unwrap();
+ fs::create_dir_all(root.join("docs/wiki")).unwrap();
+ (tmp, root)
+ }
+
+ fn hook_of(root: &Path) -> PathBuf {
+ root.join(".git/hooks/post-merge")
+ }
+
+ #[test]
+ fn quoting_is_inert_and_refuses_newlines() {
+ assert_eq!(quote("plain").unwrap(), "'plain'");
+ assert_eq!(quote("it's").unwrap(), r"'it'\''s'");
+ assert_eq!(quote("$(touch x)`y`").unwrap(), "'$(touch x)`y`'");
+ assert!(quote("a\nb").is_err());
+ assert!(quote("a\0b").is_err());
+ assert!(quote("a\rb").is_err());
+ }
+
+ #[test]
+ fn fresh_install_writes_an_executable_report_hook() {
+ let (_tmp, root) = repo();
+ install(&install_args(&root.join("docs/wiki"))).unwrap();
+ let text = fs::read_to_string(hook_of(&root)).unwrap();
+ assert!(text.starts_with("#!/bin/sh\n"), "{text}");
+ assert!(
+ text.contains(BEGIN_MARKER) && text.contains(END_MARKER),
+ "{text}"
+ );
+ assert!(
+ text.contains(
+ "( command -v ai-memory-wikisync >/dev/null && ai-memory-wikisync sync \
+ --workspace 'demo' --project 'app' --dest 'docs/wiki' --include 'decisions' ) \
+ || true"
+ ),
+ "{text}"
+ );
+ for flag in [
+ "--apply",
+ "--prefer",
+ "--propagate-deletes",
+ "--server",
+ "--token",
+ ] {
+ assert!(!text.contains(flag), "{flag} in a default hook: {text}");
+ }
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ let mode = fs::metadata(hook_of(&root)).unwrap().permissions().mode();
+ assert_eq!(mode & 0o777, 0o755);
+ }
+ }
+
+ #[test]
+ fn opt_ins_reach_the_hook_and_prefer_never_does() {
+ let (_tmp, root) = repo();
+ let mut args = install_args(&root.join("docs/wiki"));
+ args.spec.on_merge = OnMerge::Apply;
+ args.spec.propagate_deletes = true;
+ args.spec.server = Some("http://127.0.0.1:49374".into());
+ install(&args).unwrap();
+ let text = fs::read_to_string(hook_of(&root)).unwrap();
+ assert!(
+ text.contains(" --apply --propagate-deletes ) || true"),
+ "{text}"
+ );
+ assert!(text.contains("--server 'http://127.0.0.1:49374'"), "{text}");
+ assert!(!text.contains("--prefer"), "{text}");
+ }
+
+ #[test]
+ fn reinstall_replaces_the_block_in_place() {
+ let (_tmp, root) = repo();
+ let args = install_args(&root.join("docs/wiki"));
+ install(&args).unwrap();
+ let first = fs::read_to_string(hook_of(&root)).unwrap();
+ install(&args).unwrap();
+ assert_eq!(fs::read_to_string(hook_of(&root)).unwrap(), first);
+
+ let mut apply = args.clone();
+ apply.spec.on_merge = OnMerge::Apply;
+ install(&apply).unwrap();
+ let text = fs::read_to_string(hook_of(&root)).unwrap();
+ assert_eq!(text.matches(BEGIN_MARKER).count(), 1, "{text}");
+ assert!(text.contains("--apply"), "{text}");
+ }
+
+ #[test]
+ fn a_foreign_hook_is_kept_unless_appended_to_with_a_shell_shebang() {
+ let (_tmp, root) = repo();
+ let foreign = "#!/usr/bin/env bash\necho other hook\n";
+ fs::write(hook_of(&root), foreign).unwrap();
+ let mut args = install_args(&root.join("docs/wiki"));
+ let err = install(&args).unwrap_err().to_string();
+ assert!(err.contains("--append"), "{err}");
+ assert_eq!(fs::read_to_string(hook_of(&root)).unwrap(), foreign);
+
+ args.append = true;
+ install(&args).unwrap();
+ let text = fs::read_to_string(hook_of(&root)).unwrap();
+ assert!(text.starts_with(foreign), "{text}");
+ assert!(text.contains(BEGIN_MARKER), "{text}");
+ // Appending again replaces the block instead of adding a second.
+ install(&args).unwrap();
+ assert_eq!(fs::read_to_string(hook_of(&root)).unwrap(), text);
+
+ uninstall(&root.join("docs/wiki"), None).unwrap();
+ assert_eq!(fs::read_to_string(hook_of(&root)).unwrap(), foreign);
+ }
+
+ #[test]
+ fn append_refuses_a_hook_that_is_not_shell() {
+ let (_tmp, root) = repo();
+ for foreign in [
+ "#!/usr/bin/env python3\nprint('x')\n",
+ "#!/usr/bin/node\n",
+ "echo no shebang\n",
+ ] {
+ fs::write(hook_of(&root), foreign).unwrap();
+ let mut args = install_args(&root.join("docs/wiki"));
+ args.append = true;
+ let err = install(&args).unwrap_err().to_string();
+ assert!(err.contains("shebang"), "{foreign:?}: {err}");
+ assert_eq!(fs::read_to_string(hook_of(&root)).unwrap(), foreign);
+ }
+ assert!(sh_compatible("#!/bin/sh -e\n"));
+ assert!(sh_compatible("#!/usr/bin/env zsh\n"));
+ }
+
+ #[test]
+ fn uninstall_removes_a_hook_it_created() {
+ let (_tmp, root) = repo();
+ install(&install_args(&root.join("docs/wiki"))).unwrap();
+ uninstall(&root.join("docs/wiki"), None).unwrap();
+ assert!(!hook_of(&root).exists());
+ // Nothing to remove is not an error.
+ uninstall(&root.join("docs/wiki"), None).unwrap();
+ }
+
+ #[test]
+ fn hooks_path_is_refused_unless_the_dir_is_given() {
+ let (_tmp, root) = repo();
+ fs::write(
+ root.join(".git/config"),
+ "[core]\n\tbare = false\n[Core]\n\tHooksPath = .githooks\n",
+ )
+ .unwrap();
+ let mut args = install_args(&root.join("docs/wiki"));
+ let err = install(&args).unwrap_err().to_string();
+ assert!(err.contains("core.hooksPath"), "{err}");
+ assert!(!hook_of(&root).exists());
+
+ args.hooks_dir = Some(root.join(".githooks"));
+ install(&args).unwrap();
+ assert!(root.join(".githooks/post-merge").exists());
+
+ assert!(!sets_hooks_path(
+ "[core]\n\tbare = false\n[hooks]\n\thookspath = x\n"
+ ));
+ assert!(sets_hooks_path("[core]\nhooksPath=x\n"));
+ }
+
+ #[test]
+ fn a_worktree_installs_into_the_shared_hooks_dir() {
+ let (_tmp, root) = repo();
+ let wt_gitdir = root.join(".git/worktrees/feature");
+ fs::create_dir_all(&wt_gitdir).unwrap();
+ fs::write(wt_gitdir.join("commondir"), "../..\n").unwrap();
+ let worktree = root.parent().unwrap().join("feature");
+ fs::create_dir_all(worktree.join("docs/wiki")).unwrap();
+ fs::write(
+ worktree.join(".git"),
+ format!("gitdir: {}\n", wt_gitdir.display()),
+ )
+ .unwrap();
+
+ install(&install_args(&worktree.join("docs/wiki"))).unwrap();
+ let text = fs::read_to_string(hook_of(&root)).unwrap();
+ assert!(text.contains("--dest 'docs/wiki'"), "{text}");
+
+ // A worktree config can set hooksPath too.
+ fs::write(wt_gitdir.join("config.worktree"), "[core]\nhooksPath = x\n").unwrap();
+ let err = install(&install_args(&worktree.join("docs/wiki")))
+ .unwrap_err()
+ .to_string();
+ assert!(err.contains("core.hooksPath"), "{err}");
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn a_symlinked_hook_is_refused() {
+ let (tmp, root) = repo();
+ let elsewhere = tmp.path().join("elsewhere.sh");
+ fs::write(&elsewhere, "#!/bin/sh\n").unwrap();
+ std::os::unix::fs::symlink(&elsewhere, hook_of(&root)).unwrap();
+ let mut args = install_args(&root.join("docs/wiki"));
+ args.append = true;
+ let err = install(&args).unwrap_err().to_string();
+ assert!(err.contains("symlink"), "{err}");
+ assert_eq!(fs::read_to_string(&elsewhere).unwrap(), "#!/bin/sh\n");
+ }
+
+ #[test]
+ fn print_writes_nothing() {
+ let (_tmp, root) = repo();
+ let mut args = install_args(&root.join("docs/wiki"));
+ args.print = true;
+ install(&args).unwrap();
+ assert!(!hook_of(&root).exists());
+ }
+
+ #[test]
+ fn newline_arguments_are_refused_before_writing() {
+ let (_tmp, root) = repo();
+ let mut args = install_args(&root.join("docs/wiki"));
+ args.spec.project = "app\nrm -rf ~".into();
+ assert!(install(&args).is_err());
+ assert!(!hook_of(&root).exists());
+ }
+
+ /// The installed hook, run by `sh` with a stand-in binary on PATH: a
+ /// command substitution in a workspace name arrives as a literal
+ /// argument and never runs.
+ #[cfg(unix)]
+ #[test]
+ fn hostile_names_stay_inert_when_the_hook_runs() {
+ use std::os::unix::fs::PermissionsExt;
+ let (tmp, root) = repo();
+ let pwned = tmp.path().join("pwned");
+ let mut args = install_args(&root.join("docs/wiki"));
+ args.spec.workspace = format!("$(touch {})'`touch {}`", pwned.display(), pwned.display());
+ install(&args).unwrap();
+
+ let bin = tmp.path().join("bin");
+ fs::create_dir_all(&bin).unwrap();
+ let fake = bin.join("ai-memory-wikisync");
+ let seen = tmp.path().join("argv");
+ fs::write(
+ &fake,
+ format!("#!/bin/sh\nprintf '%s\\n' \"$@\" > '{}'\n", seen.display()),
+ )
+ .unwrap();
+ fs::set_permissions(&fake, fs::Permissions::from_mode(0o755)).unwrap();
+
+ let status = std::process::Command::new("sh")
+ .arg(hook_of(&root))
+ .current_dir(&root)
+ .env("PATH", format!("{}:/usr/bin:/bin", bin.display()))
+ .status()
+ .unwrap();
+ assert!(status.success());
+ assert!(!pwned.exists(), "the substitution ran");
+ let argv = fs::read_to_string(&seen).unwrap();
+ let lines: Vec<&str> = argv.lines().collect();
+ assert_eq!(lines[0], "sync");
+ assert_eq!(lines[2], args.spec.workspace, "{argv}");
+ }
+
+ /// Without the binary on PATH the hook is a no-op that still succeeds.
+ #[cfg(unix)]
+ #[test]
+ fn a_missing_binary_never_fails_the_merge() {
+ let (tmp, root) = repo();
+ install(&install_args(&root.join("docs/wiki"))).unwrap();
+ let empty = tmp.path().join("empty-bin");
+ fs::create_dir_all(&empty).unwrap();
+ let status = std::process::Command::new("/bin/sh")
+ .arg(hook_of(&root))
+ .current_dir(&root)
+ .env("PATH", &empty)
+ .status()
+ .unwrap();
+ assert!(status.success());
+ }
+}
diff --git a/companions/ai-memory-wikisync/src/lib.rs b/companions/ai-memory-wikisync/src/lib.rs
index 6805d234..62059c99 100644
--- a/companions/ai-memory-wikisync/src/lib.rs
+++ b/companions/ai-memory-wikisync/src/lib.rs
@@ -1,4 +1,4 @@
-//! `ai-memory-wikisync`: team-wiki sync companion (#986, slices 1, 3 and 4).
+//! `ai-memory-wikisync`: team-wiki sync companion (#986, slices 1, 3, 4 and 5).
//!
//! Keeps explicitly allowlisted page families of a running ai-memory server
//! in step with a directory inside a project repository. Reads go through
@@ -14,6 +14,7 @@
pub mod bidi;
pub mod client;
+pub mod hook;
pub mod mcp;
pub mod page_file;
pub mod paths;
diff --git a/companions/ai-memory-wikisync/src/main.rs b/companions/ai-memory-wikisync/src/main.rs
index 34e9d3bd..bdd47a1a 100644
--- a/companions/ai-memory-wikisync/src/main.rs
+++ b/companions/ai-memory-wikisync/src/main.rs
@@ -1,17 +1,28 @@
//! Thin CLI: parse arguments once, call the library, render output.
use std::path::PathBuf;
+use std::process::ExitCode;
-use ai_memory_wikisync::bidi::{self, DEFAULT_MAX_DELETES, Prefer, SyncArgs, SyncMode};
+use ai_memory_wikisync::bidi::{
+ self, CheckStatus, DEFAULT_MAX_DELETES, Prefer, SyncArgs, SyncMode,
+};
use ai_memory_wikisync::client::DEFAULT_SERVER_URL;
+use ai_memory_wikisync::hook::{self, HookSpec, InstallArgs, OnMerge};
use ai_memory_wikisync::sync::{Mode, RunArgs, run};
use clap::{Parser, Subcommand, ValueEnum};
+/// Exit codes. 2 is left to clap's usage errors.
+const EXIT_ERROR: u8 = 1;
+/// `sync --check`: imports, exports or deletes are pending.
+const EXIT_DRIFT: u8 = 3;
+/// `sync --check`: conflicts or refusals need a person; wins over drift.
+const EXIT_BLOCKED: u8 = 4;
+
#[derive(Parser, Debug)]
#[command(
author,
version,
- about = "Team-wiki sync companion for ai-memory (#986): export and two-way sync"
+ about = "Team-wiki sync companion for ai-memory (#986): export, two-way sync, CI check and post-merge hook"
)]
struct Cli {
#[command(subcommand)]
@@ -27,7 +38,13 @@ enum Commands {
Export(ExportArgs),
/// Sync both ways: repository edits go to the server through MCP,
/// server edits come to --dest. Dry-run unless --apply is passed.
+ /// With --check, exits 0 in sync, 3 on drift, 4 on conflicts or refusals.
Sync(SyncCliArgs),
+ /// Install a git post-merge hook that runs `sync` after each merge: a
+ /// dry-run report unless --on-merge apply. Never stores a token.
+ InstallHook(InstallHookArgs),
+ /// Remove the post-merge hook block install-hook wrote, and nothing else.
+ UninstallHook(UninstallHookArgs),
}
#[derive(Parser, Debug, Clone)]
@@ -35,6 +52,11 @@ struct SyncCliArgs {
/// Perform the writes. Without it, sync stays a dry-run.
#[arg(long)]
apply: bool,
+ /// Read-only CI check: write nothing (not even state) and exit 0 in
+ /// sync, 3 when changes are pending, 4 on conflicts or refusals. A clone
+ /// without sync state compares the repository with the server directly.
+ #[arg(long, conflicts_with = "apply")]
+ check: bool,
/// Which side wins a page changed in the repository and on the server.
/// Without it, such a page is a conflict and nothing is written.
#[arg(long, value_enum)]
@@ -53,6 +75,61 @@ struct SyncCliArgs {
common: CommonArgs,
}
+#[derive(Parser, Debug, Clone)]
+struct InstallHookArgs {
+ /// Print the hook block instead of writing it.
+ #[arg(long)]
+ print: bool,
+ /// What the hook does after a merge.
+ #[arg(long, value_enum, default_value = "report")]
+ on_merge: OnMergeArg,
+ /// Have the hook pass --propagate-deletes.
+ #[arg(long)]
+ propagate_deletes: bool,
+ /// Hooks directory to write to, instead of the repository's .git/hooks.
+ #[arg(long, value_name = "DIR")]
+ hooks_dir: Option<PathBuf>,
+ /// Add the block to an existing post-merge hook (POSIX shell only).
+ #[arg(long)]
+ append: bool,
+ /// Server origin to bake into the hook. Without it the hook uses
+ /// AI_MEMORY_SERVER_URL or the default when it runs.
+ #[arg(long)]
+ server: Option<String>,
+ /// Refused: the hook reads AI_MEMORY_AUTH_TOKEN when it runs, so no
+ /// token is ever written to disk.
+ #[arg(long, hide = 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 sync; repeatable.
+ #[arg(long = "include", value_name = "FAMILY")]
+ include: Vec<String>,
+}
+
+#[derive(Parser, Debug, Clone)]
+struct UninstallHookArgs {
+ /// A directory inside the repository whose hook to remove.
+ #[arg(long, default_value = ".")]
+ dest: PathBuf,
+ /// Hooks directory to edit, instead of the repository's .git/hooks.
+ #[arg(long, value_name = "DIR")]
+ hooks_dir: Option<PathBuf>,
+}
+
+#[derive(ValueEnum, Debug, Clone, Copy)]
+enum OnMergeArg {
+ Report,
+ Apply,
+}
+
#[derive(ValueEnum, Debug, Clone, Copy)]
enum PreferArg {
Repo,
@@ -136,28 +213,75 @@ impl From<SyncCliArgs> for SyncArgs {
}
}
+impl InstallHookArgs {
+ fn into_install(self) -> anyhow::Result<InstallArgs> {
+ if self.token.is_some() {
+ anyhow::bail!(
+ "install-hook never stores a token; the hook reads AI_MEMORY_AUTH_TOKEN from \
+ the environment git runs it in"
+ );
+ }
+ Ok(InstallArgs {
+ spec: HookSpec {
+ server: self.server,
+ workspace: self.workspace,
+ project: self.project,
+ dest: self.dest,
+ include: self.include,
+ on_merge: match self.on_merge {
+ OnMergeArg::Report => OnMerge::Report,
+ OnMergeArg::Apply => OnMerge::Apply,
+ },
+ propagate_deletes: self.propagate_deletes,
+ },
+ print: self.print,
+ hooks_dir: self.hooks_dir,
+ append: self.append,
+ })
+ }
+}
+
#[tokio::main]
-async fn main() -> anyhow::Result<()> {
- let cli = Cli::parse();
+async fn main() -> ExitCode {
+ match dispatch(Cli::parse()).await {
+ Ok(code) => code,
+ Err(error) => {
+ eprintln!("Error: {error:?}");
+ ExitCode::from(EXIT_ERROR)
+ }
+ }
+}
+
+async fn dispatch(cli: Cli) -> anyhow::Result<ExitCode> {
match cli.command {
- Commands::Plan(args) => run(&RunArgs::from(args), Mode::Plan).await,
+ 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
+ run(&RunArgs::from(args), mode).await?
}
Commands::Sync(args) => {
- let mode = if args.apply {
- SyncMode::Apply
- } else {
- SyncMode::DryRun
+ let mode = match (args.check, args.apply) {
+ (true, _) => SyncMode::Check,
+ (false, true) => SyncMode::Apply,
+ (false, false) => SyncMode::DryRun,
};
- bidi::run(&SyncArgs::from(args), mode).await.map(|_| ())
+ let outcome = bidi::run(&SyncArgs::from(args), mode).await?;
+ if mode == SyncMode::Check {
+ return Ok(match outcome.status() {
+ CheckStatus::InSync => ExitCode::SUCCESS,
+ CheckStatus::Drift => ExitCode::from(EXIT_DRIFT),
+ CheckStatus::Blocked => ExitCode::from(EXIT_BLOCKED),
+ });
+ }
}
+ Commands::InstallHook(args) => hook::install(&args.into_install()?)?,
+ Commands::UninstallHook(args) => hook::uninstall(&args.dest, args.hooks_dir.as_deref())?,
}
+ Ok(ExitCode::SUCCESS)
}
#[cfg(test)]
@@ -175,7 +299,8 @@ mod tests {
.flat_map(|sub| {
let name = sub.get_name().to_string();
sub.get_arguments()
- .filter(|arg| arg.get_id() == "token")
+ // install-hook's --token reads no env var; it is refused.
+ .filter(|arg| arg.get_id() == "token" && arg.get_env().is_some())
.map(|arg| (name.clone(), arg.is_hide_env_values_set()))
.collect::<Vec<_>>()
})
diff --git a/companions/ai-memory-wikisync/tests/api_server.rs b/companions/ai-memory-wikisync/tests/api_server.rs
index 79ee96ea..63b5538b 100644
--- a/companions/ai-memory-wikisync/tests/api_server.rs
+++ b/companions/ai-memory-wikisync/tests/api_server.rs
@@ -1431,3 +1431,185 @@ async fn sync_upgrades_a_slice_one_export_without_importing() {
DECISION_FILE
);
}
+
+/// Run the built binary with a clean environment: no server or token
+/// leaks in from the developer's shell.
+async fn wikisync(args: Vec<String>, envs: Vec<(&'static str, &'static str)>) -> (i32, String) {
+ tokio::task::spawn_blocking(move || {
+ let output = std::process::Command::new(env!("CARGO_BIN_EXE_ai-memory-wikisync"))
+ .args(&args)
+ .env_remove("AI_MEMORY_SERVER_URL")
+ .env_remove("AI_MEMORY_AUTH_TOKEN")
+ .envs(envs)
+ .output()
+ .expect("run ai-memory-wikisync");
+ let text = format!(
+ "{}{}",
+ String::from_utf8_lossy(&output.stdout),
+ String::from_utf8_lossy(&output.stderr)
+ );
+ (output.status.code().unwrap_or(-1), text)
+ })
+ .await
+ .expect("join")
+}
+
+fn check_args(addr: SocketAddr, dest: &std::path::Path, extra: &[&str]) -> Vec<String> {
+ let mut args: Vec<String> = [
+ "sync",
+ "--check",
+ "--server",
+ &format!("http://{addr}"),
+ "--workspace",
+ "demo",
+ "--project",
+ "app",
+ "--dest",
+ dest.to_str().unwrap(),
+ "--include",
+ "decisions",
+ ]
+ .iter()
+ .map(|arg| arg.to_string())
+ .collect();
+ args.extend(extra.iter().map(|arg| arg.to_string()));
+ args
+}
+
+/// Every file under `root` with its bytes, so a test can prove a run left
+/// the tree exactly as it was.
+fn snapshot(root: &std::path::Path) -> BTreeMap<PathBuf, Vec<u8>> {
+ let mut files = BTreeMap::new();
+ let mut pending = vec![root.to_path_buf()];
+ while let Some(dir) = pending.pop() {
+ let Ok(entries) = fs::read_dir(&dir) else {
+ continue;
+ };
+ for entry in entries.flatten() {
+ let path = entry.path();
+ if path.is_dir() {
+ pending.push(path);
+ } else {
+ files.insert(path.clone(), fs::read(&path).unwrap());
+ }
+ }
+ }
+ files
+}
+
+#[tokio::test]
+async fn sync_check_exit_codes_and_writes_nothing() {
+ let (addr, fixture) = serve(Fixture::with_pages(vec![decision()])).await;
+ let (_tmp, dest) = temp_dest();
+ sync(addr, &dest).await.expect("first sync");
+
+ let (code, out) = wikisync(check_args(addr, &dest, &[]), vec![]).await;
+ assert_eq!(code, 0, "in sync: {out}");
+
+ // Drift: the server moved on.
+ fixture.update("decisions/db.md", |page| {
+ page.body = "# DB\nServer edit.\n".into()
+ });
+ let before = snapshot(&dest);
+ let (code, out) = wikisync(check_args(addr, &dest, &[]), vec![]).await;
+ assert_eq!(code, 3, "drift: {out}");
+ assert_eq!(snapshot(&dest), before, "--check wrote something");
+
+ // A conflict outranks drift.
+ fs::write(
+ dest.join("decisions/db.md"),
+ DECISION_FILE.replace("Use Postgres.", "Repo edit."),
+ )
+ .unwrap();
+ fs::write(
+ dest.join("decisions/new.md"),
+ "---\ntitle: \"New\"\n---\n# New\n",
+ )
+ .unwrap();
+ let before = snapshot(&dest);
+ let (code, out) = wikisync(check_args(addr, &dest, &[]), vec![]).await;
+ assert_eq!(code, 4, "conflict: {out}");
+ assert_eq!(snapshot(&dest), before, "--check wrote something");
+ assert!(fixture.mcp_calls.lock().unwrap().is_empty());
+
+ // An unreachable server is an error, not a verdict.
+ let mut unreachable = check_args(addr, &dest, &[]);
+ unreachable[3] = "http://127.0.0.1:1".to_string();
+ let (code, out) = wikisync(unreachable, vec![]).await;
+ assert_eq!(code, 1, "error: {out}");
+
+ // --check and --apply cannot be combined (a clap usage error).
+ let (code, _) = wikisync(check_args(addr, &dest, &["--apply"]), vec![]).await;
+ assert_eq!(code, 2);
+}
+
+/// A CI checkout has no state (it is never committed): the repository is
+/// compared with the server directly, and a difference is drift.
+#[tokio::test]
+async fn sync_check_in_a_fresh_clone_reports_drift_not_conflict() {
+ let mut other = decision();
+ other.path = "decisions/other.md".to_string();
+ let (addr, fixture) = serve(Fixture::with_pages(vec![decision(), other])).await;
+ let (_tmp, dest) = temp_dest();
+ sync(addr, &dest).await.expect("first sync");
+ fs::remove_dir_all(dest.join(".ai-memory-wikisync")).unwrap();
+
+ let (code, out) = wikisync(check_args(addr, &dest, &[]), vec![]).await;
+ assert_eq!(code, 0, "a matching clone is in sync: {out}");
+
+ fixture.update("decisions/db.md", |page| {
+ page.body = "# DB\nServer edit.\n".into()
+ });
+ let before = snapshot(&dest);
+ let (code, out) = wikisync(check_args(addr, &dest, &[]), vec![]).await;
+ assert_eq!(code, 3, "differs is drift: {out}");
+ assert!(out.contains("differs"), "{out}");
+ assert_eq!(snapshot(&dest), before);
+ assert!(
+ !dest.join(".ai-memory-wikisync").exists(),
+ "--check never creates state"
+ );
+}
+
+#[tokio::test]
+async fn install_hook_never_writes_a_token() {
+ let tmp = tempfile::tempdir().unwrap();
+ let root = tmp.path().canonicalize().unwrap();
+ fs::create_dir_all(root.join(".git/hooks")).unwrap();
+ fs::create_dir_all(root.join("docs/wiki")).unwrap();
+ let dest = root.join("docs/wiki");
+ let base = |extra: &[&str]| {
+ let mut args: Vec<String> = [
+ "install-hook",
+ "--workspace",
+ "demo",
+ "--project",
+ "app",
+ "--dest",
+ dest.to_str().unwrap(),
+ "--include",
+ "decisions",
+ ]
+ .iter()
+ .map(|arg| arg.to_string())
+ .collect();
+ args.extend(extra.iter().map(|arg| arg.to_string()));
+ args
+ };
+
+ let (code, out) = wikisync(base(&["--token", "sekrit-flag"]), vec![]).await;
+ assert_eq!(code, 1, "{out}");
+ assert!(out.contains("never stores a token"), "{out}");
+ assert!(!root.join(".git/hooks/post-merge").exists());
+
+ let (code, out) = wikisync(
+ base(&["--on-merge", "apply"]),
+ vec![("AI_MEMORY_AUTH_TOKEN", "sekrit-env")],
+ )
+ .await;
+ assert_eq!(code, 0, "{out}");
+ let hook = fs::read_to_string(root.join(".git/hooks/post-merge")).unwrap();
+ assert!(!hook.contains("sekrit"), "{hook}");
+ assert!(!hook.contains("AI_MEMORY_AUTH_TOKEN"), "{hook}");
+ assert!(!out.contains("sekrit"), "{out}");
+}
diff --git a/docs/companion-crates.md b/docs/companion-crates.md
index ec4d73ac..b8a847ca 100644
--- a/docs/companion-crates.md
+++ b/docs/companion-crates.md
@@ -80,7 +80,8 @@ 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), slice 3 (two-way sync through the MCP write
-tool) and slice 4 (conditional writes and opt-in deletes) ship as
+tool), slice 4 (conditional writes and opt-in deletes) and slice 5 (the CI
+check and post-merge hook) ship as
[`ai-memory-wikisync`](#ai-memory-wikisync-team-wiki-export-and-sync)
below; the remaining slices are tracked in #986.
@@ -237,7 +238,7 @@ Re-home by kind:
## `ai-memory-wikisync`: team-wiki export and sync
-Slices 1, 3 and 4 of the accepted [team-wiki sync](#proposed-team-wiki-sync-986)
+Slices 1, 3, 4 and 5 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
@@ -263,6 +264,12 @@ family-scoped and dry-run by default.
(`expected_page_id`, or `create_only` for a new page). It never opens the
wiki directory or SQLite, and refuses to write to a server older than 2.7,
which would ignore the precondition.
+- `sync --check` is read-only (no files, no state) and exits 0 in sync,
+ 3 on drift, 4 on conflicts or refusals; a clone without state compares
+ the repository with the server directly. `install-hook` writes a marked
+ git `post-merge` block that runs `sync` (a dry-run report unless
+ `--on-merge apply`; never `--prefer`) and `uninstall-hook` removes only
+ that block.
- `--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;
@@ -302,6 +309,14 @@ family-scoped and dry-run by default.
only through the write path checks (no symlinks, confined to `--dest`) and
only if it still holds the classified bytes. A delete that is not
propagated keeps its state entry.
+- The post-merge hook never stores a token (`--token` is refused; the hook
+ reads `AI_MEMORY_AUTH_TOKEN` at merge time), single-quotes every argument
+ and refuses newlines or NUL, is written atomically with mode 0755, refuses
+ a symlinked hook, appends to a foreign hook only with `--append` and a
+ POSIX shell shebang, and refuses a repository whose config sets
+ `core.hooksPath` (use `--hooks-dir` or `--print`). The hooks directory is
+ found by reading `.git` (worktree `gitdir:` and `commondir` included); git
+ is never run.
- An import requires the file's frontmatter (a write clears what it omits),
and is refused for a server page carrying any metadata the write cannot
carry (`summary`, `sources`, `kind`, …), naming the keys.
@@ -328,7 +343,12 @@ metadata-loss refusal, the version preconditions the fixture enforces (a
stale version is reported while the other pages apply), the old-server
refusal, delete notices and propagated deletes with each `--prefer`, the
delete ceiling, the pinned-page and symlink refusals, sanitizer rewrites and
-the upgrade of a slice 1 export.
+the upgrade of a slice 1 export. Binary-level tests check the `--check` exit
+codes, that it leaves the destination untouched, and drift in a clone without
+state; hook tests cover fresh install, reinstall, foreign hooks and
+`--append`, shebangs, `core.hooksPath`, worktrees, a `$(…)` workspace name
+that stays inert when the hook runs, and that a token in the environment
+never reaches the hook file.
### Roadmap (#986)
@@ -340,7 +360,8 @@ the upgrade of a slice 1 export.
3. Bidirectional apply through public write tools (shipped as `sync`).
4. Deletes and conflict reporting (shipped: `sync --propagate-deletes`,
`--max-deletes`, conditional writes and deletes).
-5. Post-merge hook / CI integration.
+5. Post-merge hook / CI integration (shipped: `install-hook`,
+ `uninstall-hook`, `sync --check`).
## `ai-memory-macos`: menu bar wrapper
diff --git a/docs/cookbook.md b/docs/cookbook.md
index 56b8ea7e..4366b22b 100644
--- a/docs/cookbook.md
+++ b/docs/cookbook.md
@@ -136,10 +136,53 @@ ai-memory-wikisync export ...same args... --apply # writes; prints the git com
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.
+with a diff summary and refused without `--force`, no frontmatter is forged,
+and the tool never runs git itself. `sync` sends reviewed repository edits
+back through MCP (each write conditional on the version it planned against;
+needs ai-memory 2.7+), and deletes travel only with `--propagate-deletes`.
+
+### Keep it in step after merges and in CI
+
+`install-hook` writes a git `post-merge` hook that runs `sync` after every
+merge or pull — a dry-run report by default, `--on-merge apply` to write. It
+never stores a token (the hook reads `AI_MEMORY_AUTH_TOKEN` when it runs) and
+never passes `--prefer`, so conflicts still wait for a person:
+
+```bash
+ai-memory-wikisync install-hook --workspace demo --project app \
+ --dest docs/wiki --include _rules --include decisions
+ai-memory-wikisync uninstall-hook --dest docs/wiki # removes only its block
+```
+
+In CI, `sync --check` writes nothing and exits `0` in sync, `3` when the
+repository and the server differ, and `4` on conflicts or refusals. A CI
+checkout has no sync state, so it compares the repository with the server
+directly. A GitHub Actions job that flags drift on wiki pull requests:
+
+```yaml
+name: team-wiki
+on:
+ pull_request:
+ paths: ["docs/wiki/**"]
+jobs:
+ wiki-drift:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - run: cargo install --locked --git https://github.com/akitaonrails/ai-memory ai-memory-wikisync
+ - name: Compare docs/wiki with the team's ai-memory server
+ env:
+ AI_MEMORY_SERVER_URL: ${{ secrets.AI_MEMORY_SERVER_URL }}
+ AI_MEMORY_AUTH_TOKEN: ${{ secrets.AI_MEMORY_AUTH_TOKEN }}
+ run: |
+ ai-memory-wikisync sync --check \
+ --workspace demo --project app --dest docs/wiki \
+ --include _rules --include decisions
+```
+
+The server must be reachable from the runner (`serve --enable-api` behind a
+token). To tolerate drift and fail only on refusals, end the command with
+`|| [ $? -eq 3 ]`.
## Recipe: control what gets kept, aged, or consolidated