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
30.9 KB
Raw Blame
/**
 * Note-file lifecycle: rename, move, delete, archive (B2).
 *
 * The defect. `brain_create_note`, `brain_update_note` and
 * `brain_append_note` are the whole of the note-file surface: a note can
 * be brought into existence and edited, and after that it is immovable
 * and undeletable through every surface this project ships. An agent that
 * mis-named a note had exactly one remedy - create the correct one and
 * leave the wrong one behind - which is how a vault accumulates the
 * duplicates the dedup pass then has to reason about.
 *
 * The second defect, and the harder one. A rename that reports success
 * without qualifying it is a lie: the Brain backlink index is a full scan
 * and Brain-scoped, the vault-wide `links` table is only as fresh as the
 * last `indexVault` pass, and no write hook updates either. So these
 * tests assert what the result SAYS as hard as they assert what it did -
 * that the bare-basename spelling is withheld when another note shares
 * the name, and that the search index's staleness travels back on the
 * result instead of being silently absorbed.
 *
 * Deliberately NOT covered here: the MCP argument coercion (its own file
 * under `tests/mcp/`), the CLI flag surface (`tests/cli/`), and whether a
 * snapshot archive can be extracted again - that is `snapshot.ts`'s own
 * suite, and duplicating it here would assert the tar pipeline twice.
 */

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

import { bootstrapBrain } from "../../../../src/core/brain/init.ts";
import {
  BASENAME_REWRITE,
  INDEX_EVIDENCE,
  INDEX_REFRESH,
  INDEX_REFRESHES,
  isIndexRefresh,
  isNoteLifecycleAction,
  NOTE_ARCHIVE_ROOT,
  NOTE_LIFECYCLE_ACTION,
  NOTE_LIFECYCLE_ACTIONS,
  noteLifecycle,
  NoteLifecycleError,
} from "../../../../src/core/brain/notes/lifecycle.ts";
import { RECOVERABILITY_STATE } from "../../../../src/core/brain/gates/recoverability.ts";
import { CountGuardError } from "../../../../src/core/brain/count-guard.ts";
import { atomicWriteFileSync } from "../../../../src/core/fs-atomic.ts";
import {
  FRESHEN_PENDING_FILE,
  readFreshenPending,
  settleFreshenPending,
} from "../../../../src/core/search/freshen.ts";

let vault: string;
let configHome: string;
let configPath: string;

beforeEach(() => {
  vault = mkdtempSync(join(tmpdir(), "o2b-note-lifecycle-"));
  configHome = mkdtempSync(join(tmpdir(), "o2b-note-lifecycle-cfg-"));
  configPath = join(configHome, "config.yaml");
  atomicWriteFileSync(configPath, `vault: ${vault}\n`);
  bootstrapBrain(vault, { configPath });
});

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

/** Write a note verbatim, creating its parents. */
function note(rel: string, body: string): void {
  const abs = join(vault, rel);
  mkdirSync(join(abs, ".."), { recursive: true });
  writeFileSync(abs, body);
}

function read(rel: string): string {
  return readFileSync(join(vault, rel), "utf8");
}

describe("the action vocabulary", () => {
  test("every declared action is a member and the guard refuses everything else", () => {
    expect([...NOTE_LIFECYCLE_ACTIONS].toSorted()).toEqual(
      Object.values(NOTE_LIFECYCLE_ACTION).toSorted(),
    );
    for (const action of NOTE_LIFECYCLE_ACTIONS) expect(isNoteLifecycleAction(action)).toBe(true);
    for (const outsider of [null, 42, {}, "", "Rename"]) {
      expect(isNoteLifecycleAction(outsider)).toBe(false);
    }
  });
});

describe("the index-refresh vocabulary", () => {
  // The guard ships beside its siblings' (isIndexEvidenceState,
  // isBasenameRewrite): a token a caller reads back out of a report or a
  // persisted payload has to survive the round trip through a string.
  test("every declared refresh token is a member and the guard refuses everything else", () => {
    expect([...INDEX_REFRESHES].toSorted()).toEqual(Object.values(INDEX_REFRESH).toSorted());
    for (const token of INDEX_REFRESHES) expect(isIndexRefresh(token)).toBe(true);
    for (const outsider of [null, 42, {}, "", "Claimed", "not-claimed", undefined]) {
      expect(isIndexRefresh(outsider)).toBe(false);
    }
  });
});

describe("rename", () => {
  test("moves the bytes and rewrites path-spelled inbound wikilinks to the minimal spelling", async () => {
    note("Projects/Old.md", "---\ntitle: Old\n---\n\nbody\n");
    note(
      "Projects/Ref.md",
      "see [[Projects/Old]] and [[Projects/Old.md]] and [[Projects/Old|x]]\n",
    );

    const res = await noteLifecycle(vault, {
      action: NOTE_LIFECYCLE_ACTION.rename,
      path: "Projects/Old.md",
      to: "Projects/New.md",
      apply: true,
    });

    expect(res.applied).toBe(true);
    expect(res.from).toBe("Projects/Old.md");
    expect(res.to).toBe("Projects/New.md");
    expect(existsSync(join(vault, "Projects/Old.md"))).toBe(false);
    expect(read("Projects/New.md")).toContain("body");

    const ref = read("Projects/Ref.md");
    // Minimal spellings, not form preservation: the new basename is
    // unique after the move, so every old form collapses onto `[[New]]`
    // instead of each link keeping its original length.
    expect(ref).toBe("see [[New]] and [[New]] and [[New|x]]\n");
    expect(ref).not.toContain("Old");
    expect(res.references?.filesRewritten).toBe(1);
    expect(res.references?.rewrittenSpellings).toEqual([
      { from: "Projects/Old.md", to: "New" },
      { from: "Projects/Old", to: "New" },
      { from: "Old", to: "New" },
    ]);
  });

  test("rewrites path-spelled links to the suffix-less form when the destination basename is contested", async () => {
    note("Projects/Old.md", "x\n");
    note("Elsewhere/New.md", "another note that will still own the name\n");
    note("Projects/Ref.md", "pathed [[Projects/Old]] and suffixed [[Projects/Old.md]]\n");

    const res = await noteLifecycle(vault, {
      action: NOTE_LIFECYCLE_ACTION.rename,
      path: "Projects/Old.md",
      to: "Projects/New.md",
      apply: true,
    });

    // Bare `New` would have two carriers after the move and resolve, by
    // the ladder's own rule, to neither - so the shortest HONEST
    // spelling is the suffix-less path. The destination basename being
    // contested does NOT withhold the moved note's own bare `[[Old]]`
    // rewrite: it named exactly one note before the move, and its
    // rewrite target is the minimal spelling `Projects/New`, which is
    // unambiguous by construction.
    expect(res.references?.basename).toBe(BASENAME_REWRITE.applied);
    expect(read("Projects/Ref.md")).toBe("pathed [[Projects/New]] and suffixed [[Projects/New]]\n");
    expect(res.references?.rewrittenSpellings).toContainEqual({
      from: "Old",
      to: "Projects/New",
    });
  });

  test("rewrites references that live inside Brain/, not only outside it", async () => {
    note("Projects/Old.md", "x\n");
    // A Brain artifact citing a note by path holds an ordinary
    // reference: it dangles exactly like a user note's would, so it is
    // in range. The append-only log is the one exception, and it has
    // its own test below.
    note("Brain/reports/weekly.md", "- ref [[Projects/Old]]\n");

    const res = await noteLifecycle(vault, {
      action: NOTE_LIFECYCLE_ACTION.rename,
      path: "Projects/Old.md",
      to: "Projects/New.md",
      apply: true,
    });

    expect(read("Brain/reports/weekly.md")).toContain("[[New]]");
    expect(res.references?.filesRewritten).toBe(1);
  });

  test("rewrites the bare-basename spelling when exactly one note carries it", async () => {
    note("Projects/Old.md", "x\n");
    note("Projects/Ref.md", "bare [[Old]]\n");

    const res = await noteLifecycle(vault, {
      action: NOTE_LIFECYCLE_ACTION.rename,
      path: "Projects/Old.md",
      to: "Projects/New.md",
      apply: true,
    });

    expect(res.references?.basename).toBe(BASENAME_REWRITE.applied);
    expect(read("Projects/Ref.md")).toContain("[[New]]");
  });

  test("withholds the bare-basename rewrite when another note shares the basename", async () => {
    note("Projects/Old.md", "x\n");
    note("Archive-elsewhere/Old.md", "a different note with the same basename\n");
    note("Projects/Ref.md", "bare [[Old]] and pathed [[Projects/Old]]\n");

    const res = await noteLifecycle(vault, {
      action: NOTE_LIFECYCLE_ACTION.rename,
      path: "Projects/Old.md",
      to: "Projects/New.md",
      apply: true,
    });

    expect(res.references?.basename).toBe(BASENAME_REWRITE.ambiguous);
    const ref = read("Projects/Ref.md");
    // The path spelling collapses onto the (uncontested) new basename;
    // the bare `[[Old]]` is left exactly as it was, because it may name
    // the other note.
    expect(ref).toBe("bare [[Old]] and pathed [[New]]\n");
  });

  test("refuses a destination in another directory - that is a move", async () => {
    note("Projects/Old.md", "x\n");
    await expect(
      noteLifecycle(vault, {
        action: NOTE_LIFECYCLE_ACTION.rename,
        path: "Projects/Old.md",
        to: "Other/Old.md",
        apply: true,
      }),
    ).rejects.toThrow(NoteLifecycleError);
    expect(existsSync(join(vault, "Projects/Old.md"))).toBe(true);
  });

  test("refuses an occupied destination rather than clobbering it", async () => {
    note("Projects/Old.md", "old\n");
    note("Projects/New.md", "occupied\n");
    await expect(
      noteLifecycle(vault, {
        action: NOTE_LIFECYCLE_ACTION.rename,
        path: "Projects/Old.md",
        to: "Projects/New.md",
        apply: true,
      }),
    ).rejects.toThrow(NoteLifecycleError);
    expect(read("Projects/New.md")).toBe("occupied\n");
  });

  test("puts the DESTINATION through the same path envelope as the source", async () => {
    note("Projects/Old.md", "x\n");
    // The Brain machinery root is refused for a create; it must be
    // refused for a rename destination too, or the envelope has a hole.
    await expect(
      noteLifecycle(vault, {
        action: NOTE_LIFECYCLE_ACTION.rename,
        path: "Projects/Old.md",
        to: "Brain/Sneaky.md",
        apply: true,
      }),
    ).rejects.toThrow();
    await expect(
      noteLifecycle(vault, {
        action: NOTE_LIFECYCLE_ACTION.rename,
        path: "Projects/Old.md",
        to: "Projects/../../escape.md",
        apply: true,
      }),
    ).rejects.toThrow();
    expect(existsSync(join(vault, "Projects/Old.md"))).toBe(true);
  });

  test("a missing source is a typed refusal, never a silent no-op", async () => {
    await expect(
      noteLifecycle(vault, {
        action: NOTE_LIFECYCLE_ACTION.rename,
        path: "Projects/Nope.md",
        to: "Projects/New.md",
        apply: true,
      }),
    ).rejects.toThrow(NoteLifecycleError);
  });

  test("dry run is the default: it reports the blast radius and writes nothing", async () => {
    note("Projects/Old.md", "x\n");
    note("Projects/Ref.md", "[[Projects/Old]]\n");

    const res = await noteLifecycle(vault, {
      action: NOTE_LIFECYCLE_ACTION.rename,
      path: "Projects/Old.md",
      to: "Projects/New.md",
    });

    expect(res.applied).toBe(false);
    expect(res.references?.inboundFiles).toEqual(["Projects/Ref.md"]);
    expect(res.references?.filesRewritten).toBe(0);
    // The plan is reported in the spellings it would write, minimal
    // forms included, so a dry run previews exactly the apply.
    expect(res.references?.rewrittenSpellings).toEqual([
      { from: "Projects/Old.md", to: "New" },
      { from: "Projects/Old", to: "New" },
      { from: "Old", to: "New" },
    ]);
    expect(existsSync(join(vault, "Projects/Old.md"))).toBe(true);
    expect(read("Projects/Ref.md")).toContain("[[Projects/Old]]");
  });
});

describe("the freshness of the evidence a rename acted on", () => {
  test("names the search index as absent when the vault has never been indexed", async () => {
    note("Projects/Old.md", "x\n");
    const res = await noteLifecycle(vault, {
      action: NOTE_LIFECYCLE_ACTION.rename,
      path: "Projects/Old.md",
      to: "Projects/New.md",
      apply: true,
    });
    expect(res.references?.index.state).toBe(INDEX_EVIDENCE.absent);
    expect(res.references?.index.lastIndexedAt).toBeNull();
    // A next command, so the caller is never left with a bare verdict.
    expect(res.references?.index.nextCommand.length).toBeGreaterThan(0);
  });

  test("the live scan is reported as what it is: the files it actually read", async () => {
    note("Projects/Old.md", "x\n");
    note("Projects/Ref.md", "[[Projects/Old]]\n");
    const res = await noteLifecycle(vault, {
      action: NOTE_LIFECYCLE_ACTION.rename,
      path: "Projects/Old.md",
      to: "Projects/New.md",
      apply: true,
    });
    expect(res.references?.filesScanned).toBeGreaterThanOrEqual(2);
  });
});

/** Stamp a vault's index without running a full index pass. */
async function stampIndex(at: string): Promise<void> {
  const { resolveSearchConfig } = await import("../../../../src/core/search/index.ts");
  const { LAST_INDEXED_AT_STATE_KEY, Store } = await import("../../../../src/core/search/store.ts");
  const store = await Store.open(resolveSearchConfig({ vault }), { mode: "write" });
  store.setState(LAST_INDEXED_AT_STATE_KEY, at);
  await store.close();
}

/** The rename input every refresh test moves the same note with. */
function renameInput(apply: boolean) {
  return {
    action: NOTE_LIFECYCLE_ACTION.rename,
    path: "Projects/Old.md",
    to: "Projects/New.md",
    ...(apply ? { apply: true } : {}),
  } as const;
}

/**
 * The detached refresh an applied write claims (F2).
 *
 * The tests run with the suite-wide freshen-off default and turn the
 * interval on only inside the specific tests that need it, so no real
 * indexer is ever left behind; the spawn is always intercepted by the
 * `refreshSpawn` seam. The "force was passed" evidence is indirect but
 * binding: the index stamp in these fixtures is SECONDS old, so an
 * unforced call would answer `fresh` and spawn nothing.
 */
describe("the detached refresh an applied write claims", () => {
  const FRESHEN_INTERVAL_ENV = "OPEN_SECOND_BRAIN_SEARCH_FRESHEN_INTERVAL_S";
  let savedInterval: string | undefined;
  let intervalWasSaved = false;

  beforeEach(() => {
    savedInterval = undefined;
    intervalWasSaved = false;
  });
  afterEach(() => {
    if (!intervalWasSaved) return;
    // Restore whatever the environment ACTUALLY held, including its
    // absence. Writing back a hardcoded "60" here once leaked a freshen
    // interval onto every follower test file sharing the process.
    if (savedInterval === undefined) delete process.env[FRESHEN_INTERVAL_ENV];
    else process.env[FRESHEN_INTERVAL_ENV] = savedInterval;
    intervalWasSaved = false;
  });

  /** Capture the interval the environment holds right now, once. */
  function saveInterval(): void {
    if (intervalWasSaved) return;
    savedInterval = process.env[FRESHEN_INTERVAL_ENV];
    intervalWasSaved = true;
  }

  function withFreshenOn(): void {
    saveInterval();
    process.env[FRESHEN_INTERVAL_ENV] = "60";
  }

  test("an applied rename claims one detached refresh, and the child is the freshen run", async () => {
    withFreshenOn();
    // A stamp younger than the interval: only the force path spawns here.
    await stampIndex(new Date().toISOString());
    note("Projects/Old.md", "x\n");
    const spawned: string[][] = [];

    const res = await noteLifecycle(vault, {
      ...renameInput(true),
      refreshSpawn: (argv: string[]) => spawned.push(argv),
    });

    expect(res.references?.refresh).toBe(INDEX_REFRESH.claimed);
    // A claim that started names no refusal, so the reason is null
    // rather than a bare absent key a reader would have to guess about.
    expect(res.references?.refreshReason).toBeNull();
    expect(spawned).toHaveLength(1);
    const argv = spawned[0]!.join(" ");
    expect(argv).toContain("search index");
    expect(argv).toContain("--freshen");
    expect(argv).toContain("--freshen-state");
    // The evidence read stays synchronous: the report still describes
    // the index as it stood at the end of the call.
    expect(res.references?.index.state).toBe(INDEX_EVIDENCE.stale);
  });

  test("the claim resolves through the config file the caller passed, not the environment alone", async () => {
    // The interval is 0 by CONFIG FILE here - the suite-wide env default
    // is scrubbed - so the claim reads `off` only if it resolves the
    // search config through the caller's refreshConfigPath. Resolved
    // without it, the default interval stands and the rename claims a
    // run the operator's config refused.
    await stampIndex(new Date().toISOString());
    note("Projects/Old.md", "x\n");
    atomicWriteFileSync(configPath, `vault: ${vault}\nsearch_freshen_interval_s: 0\n`);
    const key = "OPEN_SECOND_BRAIN_SEARCH_FRESHEN_INTERVAL_S";
    const saved = process.env[key];
    delete process.env[key];
    try {
      const res = await noteLifecycle(vault, {
        ...renameInput(true),
        refreshConfigPath: configPath,
      });
      expect(res.references?.refresh).toBe(INDEX_REFRESH.notClaimed);
      expect(res.references?.refreshReason).toBe("off");
    } finally {
      if (saved === undefined) delete process.env[key];
      else process.env[key] = saved;
    }
  });

  test("claim exclusivity prevents doubles: a second applied write spawns nothing", async () => {
    withFreshenOn();
    await stampIndex(new Date().toISOString());
    note("Projects/Old.md", "x\n");
    const first: string[][] = [];
    const second: string[][] = [];

    const one = await noteLifecycle(vault, {
      ...renameInput(true),
      refreshSpawn: (argv: string[]) => first.push(argv),
    });
    const two = await noteLifecycle(vault, {
      action: NOTE_LIFECYCLE_ACTION.rename,
      path: "Projects/New.md",
      to: "Projects/Newer.md",
      apply: true,
      refreshSpawn: (argv: string[]) => second.push(argv),
    });

    expect(one.references?.refresh).toBe(INDEX_REFRESH.claimed);
    // The intercepted spawn never runs a child, so the first claim is
    // still held - and the second write must not spawn past it. Its
    // refusal names the reason instead of leaving `not_claimed` to be
    // read as a deliberate config-off.
    expect(two.references?.refresh).toBe(INDEX_REFRESH.notClaimed);
    expect(two.references?.refreshReason).toBe("claimed");
    expect(second).toHaveLength(0);
  });

  test("a freshen interval of 0 disables the post-write spawn - config off means off", async () => {
    saveInterval();
    process.env[FRESHEN_INTERVAL_ENV] = "0";
    await stampIndex(new Date().toISOString());
    note("Projects/Old.md", "x\n");
    const spawned: string[][] = [];

    const res = await noteLifecycle(vault, {
      ...renameInput(true),
      refreshSpawn: (argv: string[]) => spawned.push(argv),
    });

    expect(res.references?.refresh).toBe(INDEX_REFRESH.notClaimed);
    // `not_claimed` alone cannot distinguish a broken freshen path from
    // a deliberate off; the reason can.
    expect(res.references?.refreshReason).toBe("off");
    expect(spawned).toHaveLength(0);
  });

  test("a plan-only run claims nothing", async () => {
    withFreshenOn();
    await stampIndex(new Date().toISOString());
    note("Projects/Old.md", "x\n");
    const spawned: string[][] = [];

    const res = await noteLifecycle(vault, {
      ...renameInput(false),
      refreshSpawn: (argv: string[]) => spawned.push(argv),
    });

    expect(res.applied).toBe(false);
    expect(res.references?.refresh).toBe(INDEX_REFRESH.notClaimed);
    // No write, no attempt: a plan-only run refused nothing, so there is
    // no reason to name - null, not a borrowed skip token.
    expect(res.references?.refreshReason).toBeNull();
    expect(spawned).toHaveLength(0);
  });

  test("an unindexed vault claims nothing - there is nothing to refresh", async () => {
    withFreshenOn();
    note("Projects/Old.md", "x\n");
    const spawned: string[][] = [];

    const res = await noteLifecycle(vault, {
      ...renameInput(true),
      refreshSpawn: (argv: string[]) => spawned.push(argv),
    });

    expect(res.references?.index.state).toBe(INDEX_EVIDENCE.absent);
    expect(res.references?.refresh).toBe(INDEX_REFRESH.notClaimed);
    // Nothing to refresh is itself a stated reason: the machinery's own
    // no-index token, not a bare unexplained refusal.
    expect(res.references?.refreshReason).toBe("no_index");
    expect(spawned).toHaveLength(0);
  });

  test("a write landing while a run is in flight is queued: two rapid renames produce a second pass", async () => {
    withFreshenOn();
    await stampIndex(new Date().toISOString());
    note("Projects/Old.md", "x\n");
    const first: string[][] = [];
    const second: string[][] = [];

    // The first rename claims the run; the intercepted spawn never runs
    // a child, so the claim stays held - the shape of a refresh still in
    // flight.
    await noteLifecycle(vault, {
      ...renameInput(true),
      refreshSpawn: (argv: string[]) => first.push(argv),
    });
    // The run's scan has (conceptually) started; the second rename lands
    // DURING it.
    const scanStart = Date.now();
    const two = await noteLifecycle(vault, {
      action: NOTE_LIFECYCLE_ACTION.rename,
      path: "Projects/New.md",
      to: "Projects/Newer.md",
      apply: true,
      refreshSpawn: (argv: string[]) => second.push(argv),
    });

    expect(two.references?.refresh).toBe(INDEX_REFRESH.notClaimed);
    expect(second).toHaveLength(0);
    // ...but the write is no longer dropped. A durable marker beside the
    // freshen state says a write is pending since that instant.
    const { resolveSearchConfig } = await import("../../../../src/core/search/index.ts");
    const stateDir = dirname(resolveSearchConfig({ vault }).dbPath);
    const marker = readFreshenPending(stateDir);
    expect(marker).not.toBeNull();
    expect(marker!.since).toBeGreaterThanOrEqual(scanStart);
    expect(existsSync(join(stateDir, FRESHEN_PENDING_FILE))).toBe(true);

    // The child's settle, before releasing the claim: the marker is
    // newer than the scan start, so ONE bounded extra pass runs and the
    // pass that covered it clears the marker. No loop, no leak.
    let passes = 0;
    const ran = await settleFreshenPending(stateDir, scanStart, async () => {
      passes++;
    });
    expect(ran).toBe(true);
    expect(passes).toBe(1);
    expect(readFreshenPending(stateDir)).toBeNull();
  });

  test("an interval of 0 never spawns and never marks - config off means off", async () => {
    saveInterval();
    process.env[FRESHEN_INTERVAL_ENV] = "0";
    await stampIndex(new Date().toISOString());
    note("Projects/Old.md", "x\n");
    // A held claim, so anything that tried to refresh would answer
    // `claimed` - only config-off stands between this write and it.
    const { resolveSearchConfig } = await import("../../../../src/core/search/index.ts");
    const stateDir = dirname(resolveSearchConfig({ vault }).dbPath);
    const { claimFreshen } = await import("../../../../src/core/search/freshen.ts");
    expect(claimFreshen(stateDir, Date.now())).toBeString();
    const spawned: string[][] = [];

    const res = await noteLifecycle(vault, {
      ...renameInput(true),
      refreshSpawn: (argv: string[]) => spawned.push(argv),
    });

    expect(res.references?.refresh).toBe(INDEX_REFRESH.notClaimed);
    expect(res.references?.refreshReason).toBe("off");
    expect(spawned).toHaveLength(0);
    // Off is off: no run is queued either, because an operator who
    // disabled freshening asked for exactly that.
    expect(readFreshenPending(stateDir)).toBeNull();
    expect(existsSync(join(stateDir, FRESHEN_PENDING_FILE))).toBe(false);
  });

  test("a spawn failure never fails the write", async () => {
    withFreshenOn();
    await stampIndex(new Date().toISOString());
    note("Projects/Old.md", "body\n");
    note("Projects/Ref.md", "see [[Projects/Old]]\n");

    const res = await noteLifecycle(vault, {
      ...renameInput(true),
      refreshSpawn: () => {
        throw new Error("no fork");
      },
    });

    expect(res.applied).toBe(true);
    expect(res.references?.refresh).toBe(INDEX_REFRESH.notClaimed);
    expect(read("Projects/New.md")).toContain("body");
    expect(read("Projects/Ref.md")).toContain("[[New]]");
  });

  test("an applied delete claims the same refresh", async () => {
    withFreshenOn();
    await stampIndex(new Date().toISOString());
    note("Projects/Gone.md", "x\n");
    const spawned: string[][] = [];

    const res = await noteLifecycle(vault, {
      action: NOTE_LIFECYCLE_ACTION.delete,
      path: "Projects/Gone.md",
      apply: true,
      confirm: true,
      refreshSpawn: (argv: string[]) => spawned.push(argv),
    });

    expect(res.applied).toBe(true);
    expect(res.references?.refresh).toBe(INDEX_REFRESH.claimed);
    expect(spawned).toHaveLength(1);
  });
});

describe("move", () => {
  test("relocates across directories and rewrites the path spelling", async () => {
    note("Inbox/Note.md", "---\ntitle: Note\n---\n\nbody\n");
    note("Inbox/Ref.md", "[[Inbox/Note]]\n");

    const res = await noteLifecycle(vault, {
      action: NOTE_LIFECYCLE_ACTION.move,
      path: "Inbox/Note.md",
      to: "Projects/Note.md",
      apply: true,
    });

    expect(res.applied).toBe(true);
    expect(read("Projects/Note.md")).toContain("body");
    expect(existsSync(join(vault, "Inbox/Note.md"))).toBe(false);
    // The basename stays unique through the move, so the rewritten link
    // comes out at its minimal spelling.
    expect(read("Inbox/Ref.md")).toContain("[[Note]]");
    // The basename did not change, so there was no bare spelling to fix.
    expect(res.references?.basename).toBe(BASENAME_REWRITE.notNeeded);
  });

  test("refuses a destination in the same directory - that is a rename", async () => {
    note("Inbox/Note.md", "x\n");
    await expect(
      noteLifecycle(vault, {
        action: NOTE_LIFECYCLE_ACTION.move,
        path: "Inbox/Note.md",
        to: "Inbox/Other.md",
        apply: true,
      }),
    ).rejects.toThrow(NoteLifecycleError);
  });
});

describe("archive", () => {
  test("displaces the note under the archive root, mirroring its path", async () => {
    note("Projects/Done.md", "---\ntitle: Done\n---\n\nbody\n");

    const res = await noteLifecycle(vault, {
      action: NOTE_LIFECYCLE_ACTION.archive,
      path: "Projects/Done.md",
      apply: true,
    });

    expect(res.to).toBe(`${NOTE_ARCHIVE_ROOT}/Projects/Done.md`);
    expect(read(`${NOTE_ARCHIVE_ROOT}/Projects/Done.md`)).toContain("body");
    expect(existsSync(join(vault, "Projects/Done.md"))).toBe(false);
  });

  test("destroys nothing, and the verdict says exactly that", async () => {
    note("Projects/Done.md", "x\n");
    const res = await noteLifecycle(vault, {
      action: NOTE_LIFECYCLE_ACTION.archive,
      path: "Projects/Done.md",
      apply: true,
    });
    expect(res.recoverability.state).toBe(RECOVERABILITY_STATE.nothingAtRisk);
    expect(res.recoverability.blockers).toEqual([]);
  });

  test("refuses an occupied archive destination instead of overwriting it", async () => {
    note("Projects/Done.md", "second\n");
    note(`${NOTE_ARCHIVE_ROOT}/Projects/Done.md`, "first\n");
    await expect(
      noteLifecycle(vault, {
        action: NOTE_LIFECYCLE_ACTION.archive,
        path: "Projects/Done.md",
        apply: true,
      }),
    ).rejects.toThrow(NoteLifecycleError);
    expect(read(`${NOTE_ARCHIVE_ROOT}/Projects/Done.md`)).toBe("first\n");
  });

  test("refuses to archive something already under the archive root", async () => {
    note(`${NOTE_ARCHIVE_ROOT}/Projects/Done.md`, "x\n");
    await expect(
      noteLifecycle(vault, {
        action: NOTE_LIFECYCLE_ACTION.archive,
        path: `${NOTE_ARCHIVE_ROOT}/Projects/Done.md`,
        apply: true,
      }),
    ).rejects.toThrow(NoteLifecycleError);
  });
});

describe("delete", () => {
  test("refuses without an explicit confirm, and writes nothing", async () => {
    note("Projects/Gone.md", "x\n");
    await expect(
      noteLifecycle(vault, {
        action: NOTE_LIFECYCLE_ACTION.delete,
        path: "Projects/Gone.md",
        apply: true,
      }),
    ).rejects.toThrow(NoteLifecycleError);
    expect(existsSync(join(vault, "Projects/Gone.md"))).toBe(true);
  });

  test("removes the file under an explicit confirm", async () => {
    note("Projects/Gone.md", "x\n");
    const res = await noteLifecycle(vault, {
      action: NOTE_LIFECYCLE_ACTION.delete,
      path: "Projects/Gone.md",
      apply: true,
      confirm: true,
    });
    expect(res.applied).toBe(true);
    expect(res.to).toBeNull();
    expect(existsSync(join(vault, "Projects/Gone.md"))).toBe(false);
  });

  test("takes a recovery point AND says it does not cover the note", async () => {
    note("Projects/Gone.md", "x\n");
    const res = await noteLifecycle(vault, {
      action: NOTE_LIFECYCLE_ACTION.delete,
      path: "Projects/Gone.md",
      apply: true,
      confirm: true,
    });
    // The archive exists...
    expect(res.snapshot).not.toBeNull();
    expect(existsSync(res.snapshot!.path)).toBe(true);
    // ...and it holds Brain/, which a note never lives in. Reporting the
    // archive path with no verdict beside it is the misleading success
    // this release exists to remove.
    expect(res.recoverability.state).toBe(RECOVERABILITY_STATE.unproven);
    expect(res.recoverability.blockers).toContain("outside_brain_root");
    expect(res.recoverability.coverage).toEqual([]);
  });

  test("honours --expect over the inbound references it will leave dangling", async () => {
    note("Projects/Gone.md", "x\n");
    note("Projects/A.md", "[[Projects/Gone]]\n");
    note("Projects/B.md", "[[Projects/Gone]]\n");

    await expect(
      noteLifecycle(vault, {
        action: NOTE_LIFECYCLE_ACTION.delete,
        path: "Projects/Gone.md",
        apply: true,
        confirm: true,
        expect: 1,
      }),
    ).rejects.toThrow(CountGuardError);
    expect(existsSync(join(vault, "Projects/Gone.md"))).toBe(true);

    const res = await noteLifecycle(vault, {
      action: NOTE_LIFECYCLE_ACTION.delete,
      path: "Projects/Gone.md",
      apply: true,
      confirm: true,
      expect: 2,
    });
    expect(res.applied).toBe(true);
  });

  test("counts the inbound references it will strand, and rewrites none of them", async () => {
    note("Projects/Gone.md", "x\n");
    note("Projects/A.md", "[[Projects/Gone]]\n");
    const res = await noteLifecycle(vault, {
      action: NOTE_LIFECYCLE_ACTION.delete,
      path: "Projects/Gone.md",
      apply: true,
      confirm: true,
    });
    expect(res.references?.inboundFiles).toEqual(["Projects/A.md"]);
    expect(res.references?.filesRewritten).toBe(0);
    expect(read("Projects/A.md")).toContain("[[Projects/Gone]]");
  });

  test("a dry run reports the blast radius and leaves the file alone", async () => {
    note("Projects/Gone.md", "x\n");
    const res = await noteLifecycle(vault, {
      action: NOTE_LIFECYCLE_ACTION.delete,
      path: "Projects/Gone.md",
      confirm: true,
    });
    expect(res.applied).toBe(false);
    expect(res.snapshot).toBeNull();
    expect(existsSync(join(vault, "Projects/Gone.md"))).toBe(true);
  });
});