Skip to content

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

Rust
12.0 KB
Raw Blame
//! An external capture owner silences the generated TypeScript integration's
//! transport without silencing its context delivery.
//!
//! The native binary's own gate is covered by `external_capture`, which drives
//! the real CLI. This file covers the other enforcement point: the
//! `capturePolicy` the shared template bakes into every generated
//! JavaScript/TypeScript integration. It renders the real OpenCode plugin
//! through the shipped binary, then runs it in Node against a loopback counter
//! standing in for the server — runtime evidence about the generated *client*
//! (what it sends, queues and spools), not about server behaviour.
//!
//! Scope of the gate, as measured here: no new capture POST, no queue entry,
//! no new spool file. It is not a claim that the client goes quiet altogether.
//! The consumer resolves routing marker params before it ever calls
//! `capturePolicy`, the handoff fetch is a separate path (asserted below), and
//! a spool backlog written before the handover can still drain — dispose calls
//! `requestHookDrain`, and the patched `drainHookQueue` fires
//! `requestSpoolDrain` even with an empty queue. Suppressing new capture is the
//! contract; erasing the backlog is not.
//!
//! Tiered slow: rendering the plugin spawns the CLI and each case spawns Node.
//!
//! Fixtures are retained deliberately. The generated plugin and the harness
//! that drove it are the evidence; nothing here deletes them.

/// Slow tier: three process spawns per case (CLI render plus one Node run).
mod slow_generated_runtime {
    use std::path::Path;
    use std::process::Command;

    use serde_json::Value;

    use crate::e2e_support::{free_port, hermetic};

    const BIN: &str = env!("CARGO_BIN_EXE_ai-memory");

    /// Node is not a build dependency, so a box without it (or on a Node too
    /// old for type stripping) skips instead of failing.
    fn node_strip_types_available() -> bool {
        match Command::new("node")
            .args(["--experimental-strip-types", "--version"])
            .output()
        {
            Ok(output) if output.status.success() => true,
            _ => {
                eprintln!(
                    "skipping generated-plugin runtime test: node lacks --experimental-strip-types"
                );
                false
            }
        }
    }

    /// The plugin exactly as `install-hooks` would write it, minus the three
    /// human-facing comment lines the non-`--apply` render prints first.
    fn render_opencode_plugin(home: &Path, server_url: &str) -> String {
        let bin = home.join("bin");
        std::fs::create_dir_all(&bin).unwrap();
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt as _;
            let opencode = bin.join("opencode");
            std::fs::write(&opencode, "#!/bin/sh\nprintf '1.18.34\\n'\n").unwrap();
            let mut permissions = std::fs::metadata(&opencode).unwrap().permissions();
            permissions.set_mode(0o755);
            std::fs::set_permissions(&opencode, permissions).unwrap();
        }
        #[cfg(windows)]
        std::fs::write(bin.join("opencode.cmd"), "@echo off\r\necho 1.18.34\r\n").unwrap();
        let output = hermetic(BIN)
            .args(["install-hooks", "--agent", "opencode", "--server-url"])
            .arg(server_url)
            .env("HOME", home)
            .env("USERPROFILE", home)
            .env("AI_MEMORY_HOME", home)
            .env("PATH", bin)
            .current_dir(home)
            .output()
            .expect("render opencode plugin");
        assert!(
            output.status.success(),
            "install-hooks failed: {}",
            String::from_utf8_lossy(&output.stderr)
        );
        let stdout = String::from_utf8(output.stdout).expect("plugin is utf-8");
        let start = stdout
            .find("// Auto-generated by")
            .expect("generated plugin banner");
        stdout[start..].to_string()
    }

    /// Drives the generated plugin through its public surface: a session
    /// start, a user prompt, the system-prompt transform that fetches a
    /// handoff, and dispose (which posts session-end and flushes the queue).
    /// The loopback server counts what actually leaves the client.
    const HARNESS: &str = r#"import { createServer } from "node:http";
import AiMemoryHooks from "./ai-memory.ts";

const port = Number(process.argv[2]);
const directory = process.argv[3]!;
const events: string[] = [];
let handoffs = 0;
const unmarked: string[] = [];
const server = createServer((req, res) => {
  const url = new URL(req.url ?? "/", "http://127.0.0.1");
  req.resume();
  if (req.headers["x-ai-memory-client"] !== "open-code") unmarked.push(url.pathname);
  if (url.pathname === "/hook") {
    events.push(url.searchParams.get("event") ?? "?");
    res.writeHead(204);
    res.end();
    return;
  }
  if (url.pathname === "/handoff") {
    handoffs++;
    res.writeHead(200, { "content-type": "text/plain" });
    res.end("HANDOFF_SENTINEL");
    return;
  }
  res.writeHead(404);
  res.end();
});
await new Promise<void>((resolve, reject) => {
  server.once("error", reject);
  server.listen(port, "127.0.0.1", () => resolve());
}).catch((error) => {
  // Taken before Node could bind it; nothing has run yet, so the test retries.
  if (error?.code === "EADDRINUSE") process.exit(75);
  throw error;
});

const hooks: any = await (AiMemoryHooks as any)({ directory });
await hooks.event({ event: { type: "session.created", properties: { info: { id: "s1", directory } } } });
await hooks["chat.message"]({ sessionID: "s1" }, { parts: [{ type: "text", text: "PROMPT_SENTINEL" }] });
const transformed: { system: string[] } = { system: [] };
await hooks["experimental.chat.system.transform"]({ sessionID: "s1" }, transformed);
await hooks.dispose();
server.close();
console.log(JSON.stringify({ events, handoffs, unmarked, system: transformed.system }));
"#;

    /// One plugin run. `hermetic` drops every ambient `AI_MEMORY_*` var, and
    /// `HOME`/`USERPROFILE`/`AI_MEMORY_HOME` point at the fixture, so the
    /// generated client cannot fall back to the developer's config, token
    /// file, or spool. The inherited `GIT_*` state goes too: the plugin shells
    /// out to `git rev-parse` for repo-root routing, and a `GIT_DIR` or
    /// `GIT_CONFIG_*` leaking in from the harness would point it somewhere
    /// outside the fixture. `PATH` and the rest of the environment stay so
    /// Node and git still resolve.
    fn run_plugin(dir: &Path, port: u16, owner: Option<&str>) -> Option<Value> {
        let mut command = hermetic("node");
        for (key, _) in std::env::vars_os() {
            if key.to_string_lossy().starts_with("GIT_") {
                command.env_remove(key);
            }
        }
        command
            .args(["--experimental-strip-types", "harness.ts"])
            .arg(port.to_string())
            .arg(dir)
            .current_dir(dir)
            .env("HOME", dir)
            .env("USERPROFILE", dir)
            .env("AI_MEMORY_HOME", dir)
            .env("AI_MEMORY_DATA_DIR", dir.join("data"))
            .env("GIT_CONFIG_GLOBAL", dir.join("absent-gitconfig"))
            .env("GIT_CONFIG_SYSTEM", dir.join("absent-gitconfig"));
        if let Some(owner) = owner {
            command.env("AI_MEMORY_CAPTURE_OWNER", owner);
        }
        let output = command.output().expect("run generated plugin");
        if output.status.code() == Some(PORT_TAKEN) {
            return None;
        }
        assert!(
            output.status.success(),
            "generated plugin run failed (owner={owner:?})\nstdout:\n{}\nstderr:\n{}",
            String::from_utf8_lossy(&output.stdout),
            String::from_utf8_lossy(&output.stderr),
        );
        Some(serde_json::from_slice(&output.stdout).expect("harness JSON"))
    }

    /// The harness's exit code when its port was taken before it could bind.
    const PORT_TAKEN: i32 = 75;

    /// Writes the plugin, rendered for `port`, and the harness into `dir`.
    fn write_fixture(dir: &Path, port: u16) {
        let plugin = render_opencode_plugin(dir, &format!("http://127.0.0.1:{port}"));
        std::fs::write(dir.join("ai-memory.ts"), &plugin).unwrap();
        std::fs::write(dir.join("harness.ts"), HARNESS).unwrap();
    }

    /// One plugin run on `port`. The plugin names its server at render time,
    /// and [`free_port`] releases the port before Node binds it, so under a
    /// parallel test load another socket can take it first. The harness then
    /// stops before the plugin runs and the fixture moves to a fresh port.
    fn run_on_free_port(dir: &Path, port: &mut u16, owner: Option<&str>) -> Value {
        for _ in 0..5 {
            if let Some(run) = run_plugin(dir, *port, owner) {
                return run;
            }
            *port = free_port();
            write_fixture(dir, *port);
        }
        panic!("the harness could not bind a free port in 5 attempts");
    }

    fn spooled_entries(dir: &Path) -> usize {
        std::fs::read_dir(dir.join("data/hook-spool"))
            .map(|entries| entries.flatten().count())
            .unwrap_or(0)
    }

    fn delivered_events(run: &Value) -> Vec<&str> {
        run["events"]
            .as_array()
            .expect("events array")
            .iter()
            .map(|event| event.as_str().expect("event name"))
            .collect()
    }

    #[test]
    fn generated_plugin_stops_capture_for_an_external_owner_but_still_fetches_context() {
        if !node_strip_types_available() {
            return;
        }
        let guard = tempfile::tempdir().expect("fixture root");
        let dir = guard.path().to_path_buf();
        let mut port = free_port();
        write_fixture(&dir, port);

        let owned = run_on_free_port(&dir, &mut port, Some("orchestrator-a"));
        assert!(
            delivered_events(&owned).is_empty(),
            "owned run must POST nothing: {owned}"
        );
        assert_eq!(spooled_entries(&dir), 0, "owned run must spool nothing new");
        // Context delivery is a separate path and must survive the handover.
        assert_eq!(owned["handoffs"], 1, "{owned}");
        assert_eq!(owned["unmarked"], serde_json::json!([]), "{owned}");
        assert_eq!(owned["system"][0], "HANDOFF_SENTINEL", "{owned}");

        // Controls: unset and whitespace-only are not an owner, so the same
        // plugin and harness must capture normally. Without them the
        // assertions above could pass on a harness that never delivers.
        for (label, owner) in [("unset", None), ("whitespace", Some(" \t\n"))] {
            let captured = run_on_free_port(&dir, &mut port, owner);
            let events = delivered_events(&captured);
            for expected in ["session-start", "user-prompt", "session-end"] {
                assert!(
                    events.contains(&expected),
                    "{label}: missing {expected} in {events:?}"
                );
            }
            assert_eq!(captured["handoffs"], 1, "{label}: {captured}");
            // An unauthenticated server reached by a LAN name refuses a
            // handoff fetch without the client marker.
            assert_eq!(
                captured["unmarked"],
                serde_json::json!([]),
                "{label}: requests without the client marker: {captured}"
            );
            assert_eq!(
                captured["system"][0], "HANDOFF_SENTINEL",
                "{label}: {captured}"
            );
        }
    }

    /// A port taken before Node binds it moves the fixture to a fresh one
    /// instead of failing the run.
    #[test]
    fn generated_plugin_fixture_moves_off_a_taken_port() {
        if !node_strip_types_available() {
            return;
        }
        let guard = tempfile::tempdir().expect("fixture root");
        let dir = guard.path().to_path_buf();
        let taken = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let busy = taken.local_addr().unwrap().port();
        let mut port = busy;
        write_fixture(&dir, port);
        let run = run_on_free_port(&dir, &mut port, None);
        assert_ne!(port, busy);
        assert!(delivered_events(&run).contains(&"session-start"), "{run}");
    }
}