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
18.5 KB
Raw Blame
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";

import { FileAlreadyExistsError } from "../../src/core/fs-atomic.ts";
import {
  allocateAndCreate,
  allocateSlug,
  brainConfigPath,
  brainDirs,
  brainDirsOf,
  brainManualPath,
  brainVaultRelative,
  logPath,
  preferencePath,
  preferencePathOf,
  processedSignalPath,
  retiredPath,
  retiredPathOf,
  signalPath,
  snapshotPath,
  snapshotsDir,
  validateIsoDate,
  validateRunId,
  validateSlug,
} from "../../src/core/brain/paths.ts";
import { freshVaultStateRoot } from "../../src/core/state/machine-state.ts";

let tmp: string;

beforeEach(() => {
  tmp = mkdtempSync(join(tmpdir(), "o2b-brain-paths-"));
});

afterEach(() => {
  rmSync(tmp, { recursive: true, force: true });
});

describe("brainDirs", () => {
  test("composes the canonical Brain/ layout", () => {
    const dirs = brainDirs("/vault");
    expect(dirs.brain).toBe(join(resolve("/vault"), "Brain"));
    expect(dirs.inbox).toBe(join(resolve("/vault"), "Brain", "inbox"));
    expect(dirs.processed).toBe(join(resolve("/vault"), "Brain", "inbox", "processed"));
    expect(dirs.preferences).toBe(join(resolve("/vault"), "Brain", "preferences"));
    expect(dirs.retired).toBe(join(resolve("/vault"), "Brain", "retired"));
    expect(dirs.log).toBe(join(resolve("/vault"), "Brain", "log"));
    expect(dirs.snapshots).toBe(join(resolve("/vault"), "Brain", ".snapshots"));
  });
});

describe("path constructors", () => {
  test("brainConfigPath / brainManualPath", () => {
    expect(brainConfigPath("/v")).toBe(join(resolve("/v"), "Brain", "_brain.yaml"));
    expect(brainManualPath("/v")).toBe(join(resolve("/v"), "Brain", "_BRAIN.md"));
  });

  test("signalPath, processedSignalPath", () => {
    expect(signalPath("/v", "2026-05-14", "no-internal-abbrev")).toBe(
      join(resolve("/v"), "Brain", "inbox", "sig-2026-05-14-no-internal-abbrev.md"),
    );
    expect(processedSignalPath("/v", "2026-05-14", "no-internal-abbrev")).toBe(
      join(resolve("/v"), "Brain", "inbox", "processed", "sig-2026-05-14-no-internal-abbrev.md"),
    );
  });

  test("preferencePath / retiredPath / logPath / snapshotsDir / snapshotPath", () => {
    expect(preferencePath("/v", "no-internal-abbrev")).toBe(
      join(resolve("/v"), "Brain", "preferences", "pref-no-internal-abbrev.md"),
    );
    expect(retiredPath("/v", "no-internal-abbrev")).toBe(
      join(resolve("/v"), "Brain", "retired", "ret-no-internal-abbrev.md"),
    );
    expect(logPath("/v", "2026-05-14")).toBe(join(resolve("/v"), "Brain", "log", "2026-05-14.md"));
    // Snapshots are machine state: a legacy vault (one with `Brain/`)
    // keeps them; a vault with no `Brain/` is store-only and keeps them
    // device-local.
    const legacy = mkdtempSync(join(tmpdir(), "o2b-paths-legacy-"));
    try {
      mkdirSync(join(legacy, "Brain"));
      expect(snapshotsDir(legacy)).toBe(join(resolve(legacy), "Brain", ".snapshots"));
      expect(snapshotPath(legacy, "dream-2026-05-14-104200")).toBe(
        join(resolve(legacy), "Brain", ".snapshots", "dream-2026-05-14-104200.tar.zst"),
      );
    } finally {
      rmSync(legacy, { recursive: true, force: true });
    }
    const bare = mkdtempSync(join(tmpdir(), "o2b-paths-bare-"));
    try {
      const dir = snapshotsDir(bare);
      expect(dir.startsWith(resolve(bare))).toBe(false);
      expect(dir.startsWith(freshVaultStateRoot(bare))).toBe(true);
      expect(snapshotPath(bare, "dream-2026-05-14-104200").startsWith(dir)).toBe(true);
    } finally {
      rmSync(bare, { recursive: true, force: true });
    }
  });

  test("with no vault, the path builders give POSIX vault-relative names", () => {
    expect(preferencePathOf(null, "no-internal-abbrev")).toBe(
      "Brain/preferences/pref-no-internal-abbrev.md",
    );
    expect(retiredPathOf(null, "no-internal-abbrev")).toBe(
      "Brain/retired/ret-no-internal-abbrev.md",
    );
    const dirs = brainDirsOf(null);
    expect([dirs.brain, dirs.inbox, dirs.preferences, dirs.retired, dirs.log]).toEqual([
      "Brain",
      "Brain/inbox",
      "Brain/preferences",
      "Brain/retired",
      "Brain/log",
    ]);
    // A slug is validated the same way with no vault.
    expect(() => preferencePathOf(null, "../escape")).toThrow();
    expect(() => retiredPathOf(null, "a/b")).toThrow();
    // With a vault they are the vault's absolute paths.
    expect(preferencePathOf("/v", "x")).toBe(preferencePath("/v", "x"));
    expect(retiredPathOf("/v", "x")).toBe(retiredPath("/v", "x"));
    expect(brainDirsOf("/v")).toEqual(brainDirs("/v"));
  });

  test("signalPath validates date format", () => {
    expect(() => signalPath("/v", "2026.05.14", "slug")).toThrow();
    expect(() => signalPath("/v", "14-05-2026", "slug")).toThrow();
    expect(() => signalPath("/v", "2026-13-01", "slug")).toThrow();
  });

  test("logPath validates date", () => {
    expect(() => logPath("/v", "nope")).toThrow();
    expect(() => logPath("/v", "2025-02-29")).toThrow();
  });
});

describe("validateSlug", () => {
  test("accepts plain slugs", () => {
    expect(validateSlug("no-internal-abbrev")).toBe("no-internal-abbrev");
    expect(validateSlug("alpha_beta-2")).toBe("alpha_beta-2");
  });

  test("admits email-style and plus-addressed identifiers", () => {
    // The structural whitelist must keep passing `@` and `+` so a
    // caller-supplied identity (email, plus-addressed alias) can still
    // become a file basename without escaping its directory. Pinned so a
    // later sanitization tweak cannot silently drop these characters.
    expect(validateSlug("[email protected]")).toBe("[email protected]");
    expect(validateSlug("[email protected]")).toBe("[email protected]");
    expect(validateSlug("first.last+filter")).toBe("first.last+filter");
    // A single embedded dot is fine; only the `..` traversal token is not.
    expect(validateSlug("v1.2.3")).toBe("v1.2.3");
  });

  test("rejects path separators", () => {
    expect(() => validateSlug("a/b")).toThrow(/path separators/);
    expect(() => validateSlug("a\\b")).toThrow(/path separators/);
  });

  test("rejects traversal", () => {
    expect(() => validateSlug("..")).toThrow(/traversal/);
    expect(() => validateSlug("..-evil")).toThrow(/traversal/);
    expect(() => validateSlug("evil-..")).toThrow(/traversal/);
  });

  test("rejects empty", () => {
    expect(() => validateSlug("")).toThrow();
    expect(() => validateSlug("   ")).toThrow();
  });

  test("trims whitespace", () => {
    expect(validateSlug("  ok-slug  ")).toBe("ok-slug");
  });

  test("rejects Windows-reserved basenames", () => {
    expect(() => validateSlug("CON")).toThrow(/Windows-reserved/);
    expect(() => validateSlug("nul.md")).toThrow(/Windows-reserved/);
  });

  test("rejects Windows-invalid filename characters", () => {
    expect(() => validateSlug("slug:with-colon")).toThrow(/invalid character/);
    expect(() => validateSlug("slug*with-star")).toThrow(/invalid character/);
    expect(() => validateSlug('slug"quote')).toThrow(/invalid character/);
    expect(() => validateSlug("slug<lt")).toThrow(/invalid character/);
    expect(() => validateSlug("slug>gt")).toThrow(/invalid character/);
    expect(() => validateSlug("slug|pipe")).toThrow(/invalid character/);
    expect(() => validateSlug("slug?question")).toThrow(/invalid character/);
  });

  test("rejects ASCII control characters in slug", () => {
    expect(() => validateSlug("slug\x00null")).toThrow(/invalid character/);
    expect(() => validateSlug("slug\nnewline")).toThrow(/invalid character/);
    expect(() => validateSlug("slug\x1Fus")).toThrow(/invalid character/);
  });
});

describe("validateIsoDate", () => {
  test("accepts well-formed ISO dates", () => {
    expect(validateIsoDate("2026-05-14")).toBe("2026-05-14");
    expect(validateIsoDate("2024-02-29")).toBe("2024-02-29");
  });

  test("rejects bad shapes", () => {
    expect(() => validateIsoDate("nope")).toThrow(/format/);
    expect(() => validateIsoDate("2026/05/14")).toThrow();
  });

  test("rejects impossible calendar dates", () => {
    expect(() => validateIsoDate("2025-02-29")).toThrow(/valid calendar date/);
    expect(() => validateIsoDate("2026-13-01")).toThrow(/valid calendar date/);
  });
});

describe("validateRunId", () => {
  test("accepts dream run ids", () => {
    expect(validateRunId("dream-2026-05-14-104200")).toBe("dream-2026-05-14-104200");
  });

  test("rejects empty / separators / traversal", () => {
    expect(() => validateRunId("")).toThrow();
    expect(() => validateRunId("a/b")).toThrow();
    expect(() => validateRunId("..")).toThrow();
    expect(() => validateRunId("dream..2026")).toThrow();
  });

  test("rejects leading dot", () => {
    expect(() => validateRunId(".hidden")).toThrow();
  });

  test("rejects Windows-reserved", () => {
    expect(() => validateRunId("con")).toThrow(/Windows-reserved/);
  });
});

describe("path-safety", () => {
  test("signalPath rejects traversal slugs (defense in depth)", () => {
    expect(() => signalPath("/v", "2026-05-14", "../escape")).toThrow();
  });

  test("preferencePath rejects path-separator slug", () => {
    expect(() => preferencePath("/v", "a/b")).toThrow();
  });

  test("snapshotPath rejects bogus run_id", () => {
    expect(() => snapshotPath("/v", "../etc/passwd")).toThrow();
    expect(() => snapshotPath("/v", "")).toThrow();
  });
});

describe("brainVaultRelative", () => {
  test("renders posix-style relative path", () => {
    const abs = join(resolve("/vault"), "Brain", "preferences", "pref-x.md");
    expect(brainVaultRelative(abs, "/vault")).toBe("Brain/preferences/pref-x.md");
  });
});

describe("allocateSlug — collision allocator", () => {
  test("returns bare slug when target is free", () => {
    const targetDir = join(tmp, "Brain", "inbox");
    mkdirSync(targetDir, { recursive: true });
    const result = allocateSlug({
      vault: tmp,
      targetDir,
      prefix: "sig-2026-05-14",
      slug: "no-internal-abbrev",
    });
    expect(result.slug).toBe("no-internal-abbrev");
    expect(result.suffix).toBeNull();
    expect(result.path).toBe(join(targetDir, "sig-2026-05-14-no-internal-abbrev.md"));
  });

  test("appends -2 on first collision", () => {
    const targetDir = join(tmp, "Brain", "inbox");
    mkdirSync(targetDir, { recursive: true });
    writeFileSync(join(targetDir, "sig-2026-05-14-no-internal-abbrev.md"), "stub", "utf8");

    const result = allocateSlug({
      vault: tmp,
      targetDir,
      prefix: "sig-2026-05-14",
      slug: "no-internal-abbrev",
    });
    expect(result.slug).toBe("no-internal-abbrev-2");
    expect(result.suffix).toBe(2);
    expect(result.path).toBe(join(targetDir, "sig-2026-05-14-no-internal-abbrev-2.md"));
  });

  test("appends -3 on second collision", () => {
    const targetDir = join(tmp, "Brain", "inbox");
    mkdirSync(targetDir, { recursive: true });
    writeFileSync(join(targetDir, "sig-2026-05-14-no-internal-abbrev.md"), "stub", "utf8");
    writeFileSync(join(targetDir, "sig-2026-05-14-no-internal-abbrev-2.md"), "stub", "utf8");

    const result = allocateSlug({
      vault: tmp,
      targetDir,
      prefix: "sig-2026-05-14",
      slug: "no-internal-abbrev",
    });
    expect(result.slug).toBe("no-internal-abbrev-3");
    expect(result.suffix).toBe(3);
  });

  test("each successive call increments deterministically", () => {
    const targetDir = join(tmp, "Brain", "preferences");
    mkdirSync(targetDir, { recursive: true });

    const expected: Array<readonly [string, number | null]> = [
      ["foo", null],
      ["foo-2", 2],
      ["foo-3", 3],
      ["foo-4", 4],
    ];
    for (const [slug, suffix] of expected) {
      const r = allocateSlug({
        vault: tmp,
        targetDir,
        prefix: "pref",
        slug: "foo",
      });
      expect(r.slug).toBe(slug);
      expect(r.suffix).toBe(suffix);
      // Create the file so the next iteration sees a collision.
      writeFileSync(r.path, "stub", "utf8");
    }
  });

  test("rejects slug with traversal up-front", () => {
    const targetDir = join(tmp, "Brain", "inbox");
    mkdirSync(targetDir, { recursive: true });
    expect(() =>
      allocateSlug({
        vault: tmp,
        targetDir,
        prefix: "sig-2026-05-14",
        slug: "..",
      }),
    ).toThrow();
  });

  test("rejects empty or path-dirty prefix", () => {
    const targetDir = join(tmp, "Brain", "inbox");
    mkdirSync(targetDir, { recursive: true });
    expect(() =>
      allocateSlug({
        vault: tmp,
        targetDir,
        prefix: "",
        slug: "ok",
      }),
    ).toThrow(/prefix/);
    expect(() =>
      allocateSlug({
        vault: tmp,
        targetDir,
        prefix: "evil/dir",
        slug: "ok",
      }),
    ).toThrow(/prefix/);
  });

  test("aborts when maxAttempts exhausted instead of looping forever", () => {
    const targetDir = join(tmp, "Brain", "inbox");
    mkdirSync(targetDir, { recursive: true });
    // Seed two collisions then cap at 2.
    writeFileSync(join(targetDir, "sig-stub-x.md"), "1", "utf8");
    writeFileSync(join(targetDir, "sig-stub-x-2.md"), "1", "utf8");
    expect(() =>
      allocateSlug({
        vault: tmp,
        targetDir,
        prefix: "sig-stub",
        slug: "x",
        maxAttempts: 2,
      }),
    ).toThrow(/could not find a free name/);
  });

  test("refuses a targetDir outside the vault", () => {
    // Pick a sibling path that exists (tmpdir itself) so the realpath
    // probe doesn't short-circuit before lexical comparison; the lexical
    // check still rejects it because it's not under tmp/.
    const outside = mkdtempSync(join(tmpdir(), "o2b-brain-outside-"));
    try {
      expect(() =>
        allocateSlug({
          vault: tmp,
          targetDir: outside,
          prefix: "sig",
          slug: "x",
        }),
      ).toThrow(/path escapes vault/);
    } finally {
      rmSync(outside, { recursive: true, force: true });
    }
  });
});

describe("allocateAndCreate — fused allocation and exclusive create", () => {
  /**
   * The losing side of the race, replayed byte-exactly and without any
   * mocking: the injected `create` writes the winner's file itself and
   * then throws the collision the exclusive create would have thrown.
   * That is precisely what the second of two concurrent processes
   * observes, and it is deterministic because the seam is a callback
   * rather than a wall-clock overlap.
   */
  test("retries the next candidate when the create loses the race", () => {
    const targetDir = join(tmp, "Brain", "inbox");
    mkdirSync(targetDir, { recursive: true });

    let calls = 0;
    const out = allocateAndCreate(
      { vault: tmp, targetDir, prefix: "sig-2026-05-14", slug: "race" },
      (allocation) => {
        calls += 1;
        if (calls === 1) {
          writeFileSync(allocation.path, "winner", "utf8");
          throw new FileAlreadyExistsError(allocation.path);
        }
        writeFileSync(allocation.path, "loser", "utf8");
        return allocation.slug;
      },
    );

    expect(calls).toBe(2);
    expect(out.allocation.slug).toBe("race-2");
    expect(out.allocation.suffix).toBe(2);
    expect(out.allocation.path).toBe(join(targetDir, "sig-2026-05-14-race-2.md"));
    expect(out.value).toBe("race-2");
  });

  test("recognises a collision that reached it wrapped on `cause`", () => {
    const targetDir = join(tmp, "Brain", "inbox");
    mkdirSync(targetDir, { recursive: true });

    let calls = 0;
    const out = allocateAndCreate(
      { vault: tmp, targetDir, prefix: "de-2026-05-14", slug: "wrapped" },
      (allocation) => {
        calls += 1;
        if (calls === 1) {
          writeFileSync(allocation.path, "winner", "utf8");
          // The shape a wrapper above the leaf writer produces.
          throw new Error("dead-end already exists: Brain/dead-ends/x.md", {
            cause: new FileAlreadyExistsError(allocation.path),
          });
        }
        return allocation.path;
      },
    );

    expect(calls).toBe(2);
    expect(out.allocation.slug).toBe("wrapped-2");
  });

  test("propagates a non-collision error from the first attempt, untouched", () => {
    const targetDir = join(tmp, "Brain", "inbox");
    mkdirSync(targetDir, { recursive: true });

    const disk = Object.assign(new Error("no space left on device"), { code: "ENOSPC" });
    let calls = 0;
    expect(() =>
      allocateAndCreate({ vault: tmp, targetDir, prefix: "sig", slug: "boom" }, () => {
        calls += 1;
        throw disk;
      }),
    ).toThrow(disk);
    expect(calls).toBe(1);
  });

  test("exhausts a small maxAttempts loudly and names the lost races", () => {
    const targetDir = join(tmp, "Brain", "inbox");
    mkdirSync(targetDir, { recursive: true });

    let calls = 0;
    let thrown: unknown;
    try {
      allocateAndCreate(
        { vault: tmp, targetDir, prefix: "sig", slug: "always", maxAttempts: 3 },
        (allocation) => {
          calls += 1;
          throw new FileAlreadyExistsError(allocation.path, { kind: "signal" });
        },
      );
    } catch (err) {
      thrown = err;
    }

    expect(calls).toBe(3);
    expect((thrown as Error).message).toMatch(/could not find a free name after 3 attempts/);
    expect((thrown as Error).message).toMatch(/lost to a concurrent create/);
    // The last collision travels as the cause, so the loud bound never
    // costs the operator the underlying report.
    expect(((thrown as Error).cause as Error).message).toBe(
      `signal already exists: ${join(targetDir, "sig-always-3.md")}`,
    );
  });

  test("skips names already on disk without invoking create", () => {
    const targetDir = join(tmp, "Brain", "inbox");
    mkdirSync(targetDir, { recursive: true });
    writeFileSync(join(targetDir, "pref-taken.md"), "stub", "utf8");

    const seen: string[] = [];
    const out = allocateAndCreate(
      { vault: tmp, targetDir, prefix: "pref", slug: "taken" },
      (allocation) => {
        seen.push(allocation.slug);
        writeFileSync(allocation.path, "new", "utf8");
        return allocation.slug;
      },
    );

    expect(seen).toEqual(["taken-2"]);
    expect(out.allocation.suffix).toBe(2);
  });

  test("refuses a targetDir outside the vault before calling create", () => {
    const outside = mkdtempSync(join(tmpdir(), "o2b-brain-outside-create-"));
    let calls = 0;
    try {
      expect(() =>
        allocateAndCreate({ vault: tmp, targetDir: outside, prefix: "sig", slug: "x" }, () => {
          calls += 1;
          return null;
        }),
      ).toThrow(/path escapes vault/);
    } finally {
      rmSync(outside, { recursive: true, force: true });
    }
    expect(calls).toBe(0);
  });
});