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
9.5 KB
Raw Blame
/**
 * `o2b init --interactive` — wizard tests.
 *
 * The wizard composes existing commands via an injected runner; we
 * verify the command sequence under scripted user input.
 */

import { describe, expect, test, beforeEach, afterEach, setDefaultTimeout } from "bun:test";
import { existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { Writable } from "node:stream";

import { CLI_SPAWN_BUDGET_MS } from "../helpers/cli-timeout.ts";
import { runCli as baseRunCli } from "../helpers/run-cli.ts";
import {
  runWizard,
  type WizardOpts,
  type WizardReader,
  type WizardRunner,
} from "../../src/cli/install/init-interactive.ts";

// The M2 end-to-end case runs the wizard as a real subprocess so the
// queued commands go through the default runner (main()) with a non-TTY
// stdin - the piped-answers shape the headless refusal was breaking.
setDefaultTimeout(CLI_SPAWN_BUDGET_MS);

let home: string;

beforeEach(() => {
  home = mkdtempSync(join(tmpdir(), "osb-wizard-h-"));
});
afterEach(() => {
  try {
    rmSync(home, { recursive: true, force: true });
  } catch {}
});

function scriptedReader(answers: string[]): WizardReader {
  let i = 0;
  return {
    async read() {
      if (i >= answers.length) return null;
      const a = answers[i]!;
      i += 1;
      return a;
    },
  };
}

function silentStreams() {
  const stdoutBuf: string[] = [];
  const stderrBuf: string[] = [];
  const stdout = new Writable({
    write(chunk, _e, cb) {
      stdoutBuf.push(chunk.toString());
      cb();
    },
  });
  const stderr = new Writable({
    write(chunk, _e, cb) {
      stderrBuf.push(chunk.toString());
      cb();
    },
  });
  return {
    stdout: stdout as unknown as NodeJS.WriteStream,
    stderr: stderr as unknown as NodeJS.WriteStream,
    stdoutBuf,
    stderrBuf,
  };
}

/** A vault that already holds a legacy `Brain/` tree. */
function legacyVault(): string {
  const vault = join(home, "vault");
  mkdirSync(join(vault, "Brain"), { recursive: true });
  return vault;
}

function recordingRunner(): { runner: WizardRunner; calls: string[][] } {
  const calls: string[][] = [];
  const runner: WizardRunner = async (cmd) => {
    calls.push([...cmd]);
    return { exitCode: 0, stdout: "", stderr: "" };
  };
  return { runner, calls };
}

describe("init wizard", () => {
  test("happy path: confirm yes runs init + brain init + per-target installs", async () => {
    const vaultPath = legacyVault();
    // ensure no candidate vault directory exists, so prompt 1 needs explicit path
    const answers = [
      vaultPath, // vault path
      "claude-vps", // agent name
      "UTC", // timezone
      "en", // language
      "1,2", // pick targets 1 and 2 (whichever they are)
      "y", // brain init
      "n", // starter
      "yes", // confirm
    ];
    const { runner, calls } = recordingRunner();
    const { stdout, stderr } = silentStreams();
    const opts: WizardOpts = {
      reader: scriptedReader(answers),
      stdout,
      stderr,
      runner,
    };
    const r = await runWizard(opts);
    expect(r.exitCode).toBe(0);
    const argv0s = calls.map((c) => c[0]);
    expect(argv0s).toContain("init");
    expect(argv0s).toContain("brain");
    expect(argv0s).toContain("install");
    // First call must be `o2b init --vault ... --agent-name ... --timezone ...`
    const initCall = calls.find((c) => c[0] === "init")!;
    expect(initCall).toContain("--vault");
    expect(initCall).toContain("--agent-name");
    expect(initCall).toContain("--timezone");
    expect(initCall).toContain("claude-vps");
    expect(initCall).toContain("UTC");
    // Final call must be `o2b install --check`
    expect(calls[calls.length - 1]).toEqual(["install", "--check"]);
    // At least one pre-check call must be a per-target install with --apply.
    // The scripted answer "1,2" selects targets 1 and 2 in the detected list;
    // both should yield `o2b install --target <name> --apply` invocations.
    const perTargetApplies = calls
      .slice(0, -1)
      .filter((c) => c[0] === "install" && c.includes("--apply") && c.includes("--target"));
    expect(perTargetApplies.length).toBe(2);
    for (const c of perTargetApplies) {
      const tIdx = c.indexOf("--target");
      // --target must be followed by a non-flag target name
      expect(c[tIdx + 1]).toBeDefined();
      expect((c[tIdx + 1] ?? "").startsWith("--")).toBe(false);
    }
  });

  test("a fresh vault plans no brain init and scaffolds no Brain/ tree", async () => {
    const vaultPath = join(home, "vault");
    const answers = [vaultPath, "claude-vps", "UTC", "en", "none", "yes"];
    const { runner, calls } = recordingRunner();
    const { stdout, stderr, stdoutBuf } = silentStreams();
    const r = await runWizard({ reader: scriptedReader(answers), stdout, stderr, runner });
    expect(r.exitCode).toBe(0);
    expect(calls.map((c) => c[0])).toEqual(["init", "install"]);
    const out = stdoutBuf.join("");
    expect(out).not.toContain("o2b brain init");
    expect(out).toContain("creates the brain store");
  });

  test("'no' at confirmation runs nothing", async () => {
    const vaultPath = join(home, "vault");
    const answers = [
      vaultPath,
      "claude-vps",
      "UTC",
      "en",
      "none", // no targets
      "no", // do not confirm (a fresh vault asks nothing about brain init)
    ];
    const { runner, calls } = recordingRunner();
    const { stdout, stderr } = silentStreams();
    const opts: WizardOpts = {
      reader: scriptedReader(answers),
      stdout,
      stderr,
      runner,
    };
    const r = await runWizard(opts);
    expect(r.exitCode).toBe(0);
    expect(calls.length).toBe(0);
  });

  test("invalid tz prompts for retry until valid", async () => {
    const vaultPath = join(home, "vault");
    const answers = [
      vaultPath,
      "claude-vps",
      "Mars/Cydonia", // invalid IANA
      "Europe/Belgrade", // valid retry
      "en",
      "none",
      "no",
    ];
    const { runner, calls } = recordingRunner();
    const { stdout, stderr, stdoutBuf } = silentStreams();
    const opts: WizardOpts = {
      reader: scriptedReader(answers),
      stdout,
      stderr,
      runner,
    };
    const r = await runWizard(opts);
    expect(r.exitCode).toBe(0);
    expect(stdoutBuf.join("")).toContain("invalid IANA");
    expect(calls.length).toBe(0);
  });

  test("brain init with starter adds --starter flag", async () => {
    const vaultPath = legacyVault();
    const answers = [vaultPath, "claude-vps", "UTC", "en", "none", "y", "y", "yes"];
    const { runner, calls } = recordingRunner();
    const { stdout, stderr } = silentStreams();
    const opts: WizardOpts = {
      reader: scriptedReader(answers),
      stdout,
      stderr,
      runner,
    };
    const r = await runWizard(opts);
    expect(r.exitCode).toBe(0);
    const brainCall = calls.find((c) => c[0] === "brain" && c[1] === "init")!;
    expect(brainCall).toContain("--starter");
  });

  test("runner failure surfaces non-zero exit code", async () => {
    const vaultPath = join(home, "vault");
    const answers = [vaultPath, "claude-vps", "UTC", "en", "none", "yes"];
    const runner: WizardRunner = async () => ({ exitCode: 1, stdout: "", stderr: "init failed" });
    const { stdout, stderr } = silentStreams();
    const opts: WizardOpts = {
      reader: scriptedReader(answers),
      stdout,
      stderr,
      runner,
    };
    const r = await runWizard(opts);
    expect(r.exitCode).toBe(1);
  });

  test("piped answers run to completion: the queued installs carry --yes (M2)", async () => {
    // M2: the wizard queues ["install", "--target", t, "--apply"] after
    // it has already collected "Run these commands now? yes", so the
    // headless consent refusal fired INSIDE the wizard - a piped run
    // stopped at exit 6 halfway through setup, and a TTY run was asked
    // twice for the same consent. The wizard executes through the
    // default runner in a fresh process with non-TTY stdin: exactly the
    // piped shape.
    const setupHome = mkdtempSync(join(tmpdir(), "osb-wizard-run-h-"));
    const configPath = join(setupHome, "config.yaml");
    // A detectable runtime: the gemini-cli adapter's marker file, so
    // the detected list is non-empty and index 5 names gemini-cli
    // (registry order is the alphabetical registration barrel).
    mkdirSync(join(setupHome, ".gemini"), { recursive: true });
    writeFileSync(join(setupHome, ".gemini", "settings.json"), "{}\n");
    const vaultPath = join(setupHome, "vault");
    const answers = [
      `${vaultPath}\n`,
      "wiz-agent\n",
      "UTC\n",
      "en\n",
      "5\n", // gemini-cli in the detected list
      "yes\n", // confirm (a fresh vault: no brain init question)
    ];
    try {
      const r = await baseRunCli(["init", "--interactive"], {
        env: { HOME: setupHome, OPEN_SECOND_BRAIN_CONFIG: configPath },
        stdin: answers.join(""),
        subprocess: true,
      });
      // Before the fix the wizard died here with the install's exit 6.
      expect(r.returncode).toBe(0);
      expect(r.stdout).not.toContain("exited with code 6");
      // The consented install actually landed the MCP entry.
      expect(existsSync(join(setupHome, ".gemini", "settings.json"))).toBe(true);
      expect(readFileSync(join(setupHome, ".gemini", "settings.json"), "utf8")).toContain(
        "open-second-brain",
      );
      // A fresh vault keeps its brain in the store: no legacy tree is scaffolded.
      expect(existsSync(join(vaultPath, "Brain"))).toBe(false);
    } finally {
      rmSync(setupHome, { recursive: true, force: true });
    }
  });
});