Skip to content

Local-first 🧠 memory for Hermes Agent that lives in your Obsidian vault and remembers project context. Nightly 😴 dream passes turn repeat corrections into confirmed preferences with measurable confidence. Adapters ship for Claude Code, Codex, and OpenClaw, with an MCP server for anything else.

TypeScript
5.4 KB
Raw Blame
/**
 * Resilience contract for the `scripts/o2b-hook` wrapper.
 *
 * These guard the two guarantees that keep plugin updates from bricking the
 * agent (see docs/updating.md):
 *   1. fail-soft: a missing/unresolvable hook exits 0, never 2.
 *   2. version-current resolution: $CLAUDE_PLUGIN_ROOT wins over the wrapper's
 *      own (possibly stale-symlinked) location, so a stale ~/.local/bin link
 *      cannot strand the hook on an old plugin version.
 */
import { afterEach, describe, expect, setDefaultTimeout, test } from "bun:test";
import { spawnSync } from "node:child_process";
import {
  chmodSync,
  cpSync,
  mkdirSync,
  mkdtempSync,
  rmSync,
  symlinkSync,
  writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { CLI_SPAWN_BUDGET_MS } from "../helpers/cli-timeout.ts";

// Tests here spawn processes; see tests/helpers/cli-timeout.ts.
setDefaultTimeout(CLI_SPAWN_BUDGET_MS);

const REPO = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..");
const WRAPPER = join(REPO, "scripts", "o2b-hook");

const tmps: string[] = [];
function freshRoot(withHook: string | null): string {
  const root = mkdtempSync(join(tmpdir(), "o2bhook-"));
  tmps.push(root);
  mkdirSync(join(root, "hooks"), { recursive: true });
  mkdirSync(join(root, "scripts"), { recursive: true });
  cpSync(WRAPPER, join(root, "scripts", "o2b-hook"));
  if (withHook !== null) {
    writeFileSync(join(root, "hooks", `${withHook}.ts`), `console.log("PROBE_OK:${withHook}");\n`);
  }
  return root;
}

// Run the wrapper with a controlled env. CLAUDE_PLUGIN_ROOT is cleared unless given.
function runHook(wrapperPath: string, args: string[], env: Record<string, string | undefined>) {
  const baseEnv = { ...process.env };
  delete baseEnv["CLAUDE_PLUGIN_ROOT"];
  delete baseEnv["OSB_PLUGIN_ROOT"];
  return spawnSync("bash", [wrapperPath, ...args], {
    env: { ...baseEnv, ...env },
    encoding: "utf8",
  });
}

afterEach(() => {
  while (tmps.length) {
    try {
      rmSync(tmps.pop()!, { recursive: true, force: true });
    } catch {
      // ignore
    }
  }
});

// The wrapper under test is a bash script; native Windows ships
// `scripts/o2b-hook.cmd` instead, and `bash` there is WSL's, not a host shell.
describe.skipIf(process.platform === "win32")("o2b-hook resilience", () => {
  test("resolves the hook via CLAUDE_PLUGIN_ROOT and runs it", () => {
    const root = freshRoot("probe");
    const r = runHook(WRAPPER, ["probe"], { CLAUDE_PLUGIN_ROOT: root });
    expect(r.status).toBe(0);
    expect(r.stdout).toContain("PROBE_OK:probe");
  });

  test("missing hook fails soft: exit 0, never 2, with a warning", () => {
    // No CLAUDE_PLUGIN_ROOT, and the repo checkout has no such hook file.
    const r = runHook(WRAPPER, ["definitely-not-a-real-hook"], {});
    expect(r.status).toBe(0);
    expect(r.status).not.toBe(2);
    expect(r.stderr).toContain("could not locate");
  });

  test("a hook that exits 2 is suppressed to exit 0 (never blocks)", () => {
    const root = freshRoot(null);
    writeFileSync(join(root, "hooks", "boom.ts"), `process.exit(2);\n`);
    const r = runHook(WRAPPER, ["boom"], { CLAUDE_PLUGIN_ROOT: root });
    expect(r.status).toBe(0);
    expect(r.status).not.toBe(2);
  });

  test("adopts ~/.bun/bin when a minimal PATH hides an installed Bun", () => {
    // The wrapper does not source scripts/_bun-precheck.sh, so it carries its
    // own copy of that PATH repair. Without it a gateway-spawned hook skips
    // over a Bun sitting one directory away (issue #173).
    const root = freshRoot("probe");
    const home = mkdtempSync(join(tmpdir(), "o2bhome-"));
    tmps.push(home);
    const bunBin = join(home, ".bun", "bin");
    mkdirSync(bunBin, { recursive: true });
    symlinkSync(process.execPath, join(bunBin, "bun"));
    chmodSync(bunBin, 0o755);

    // The wrapper's own utilities and provably no bun, so the only Bun the
    // child can reach is the one the repair is supposed to find.
    const bin = mkdtempSync(join(tmpdir(), "o2bbin-iso-"));
    tmps.push(bin);
    for (const name of ["bash", "realpath", "dirname", "cat", "tr", "head"]) {
      const resolved = Bun.which(name);
      if (!resolved) throw new Error(`test prerequisite missing from this machine: ${name}`);
      symlinkSync(resolved, join(bin, name));
    }
    expect(Bun.which("bun", { PATH: bin })).toBeNull();

    const r = spawnSync("bash", [WRAPPER, "probe"], {
      env: { HOME: home, PATH: bin, CLAUDE_PLUGIN_ROOT: root },
      encoding: "utf8",
    });
    expect(r.status).toBe(0);
    expect(r.stderr).not.toContain("bun not on PATH");
    expect(r.stdout).toContain("PROBE_OK:probe");
  });

  test("CLAUDE_PLUGIN_ROOT wins over a stale wrapper location (heals broken install)", () => {
    // Simulate the broken Mac: a ~/.local/bin symlink that points into an OLD
    // checkout which lacks the hook, while Claude Code passes the current root.
    const oldRoot = freshRoot(null); // old version: wrapper present, hook absent
    const newRoot = freshRoot("probe"); // active version: has the hook
    const linkDir = mkdtempSync(join(tmpdir(), "o2bbin-"));
    tmps.push(linkDir);
    const link = join(linkDir, "o2b-hook");
    symlinkSync(join(oldRoot, "scripts", "o2b-hook"), link);

    const r = runHook(link, ["probe"], { CLAUDE_PLUGIN_ROOT: newRoot });
    expect(r.status).toBe(0);
    expect(r.stdout).toContain("PROBE_OK:probe");
  });
});