Skip to content

Write HTML. Render video. Built for agents.

32.9 KB
Raw Blame
// @vitest-environment node
import { spawn } from "node:child_process";
import {
  chmodSync,
  existsSync,
  mkdirSync,
  mkdtempSync,
  readdirSync,
  readFileSync,
  renameSync,
  rmSync,
  utimesSync,
  watch,
  writeFileSync,
} from "node:fs";
import type { AddressInfo } from "node:net";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { createAdaptorServer } from "@hono/node-server";
import {
  createStudioApi,
  fileContentVersion,
  openProjectHistory,
  type StudioApiAdapter,
} from "@hyperframes/studio-server";
import { runCommand } from "citty";
import { Hono } from "hono";
import { afterEach, describe, expect, it, onTestFinished, vi } from "vitest";
import { consumeCommandResult } from "../utils/commandResult.js";
import { historyDeps, withOwner, withReader } from "../utils/historyOwner.js";
import historyCommand from "./history.js";

/** History's clock, a day ahead of the file system's, so each write is dated by the mtime it is stamped with. */
const clock = { at: 0 };
const advance = (ms: number) => void (clock.at += ms);

const tracked = vi.hoisted(() => [] as Array<{ action: string; via: string }>);
vi.mock("../telemetry/events.js", () => ({
  trackHistoryAction: (props: { action: string; via: string }) => tracked.push(props),
}));

afterEach(() => {
  tracked.length = 0;
});

function tempDir(prefix: string): string {
  const dir = mkdtempSync(join(tmpdir(), prefix));
  onTestFinished(() => rmSync(dir, { recursive: true, force: true }));
  return dir;
}

/** A project of index.html "A" and notes.html "N", its history kept in a temp root, no preview running. */
function project() {
  const dir = tempDir("hf-history-cli-");
  writeFileSync(join(dir, "index.html"), "A");
  writeFileSync(join(dir, "notes.html"), "N");
  historyDeps.historyRoot = tempDir("hf-history-cli-root-");
  historyDeps.findServer = async () => null;
  historyDeps.turnIdleMs = 60_000;
  historyDeps.ownerWaitMs = undefined;
  clock.at = Date.now() + 86_400_000;
  historyDeps.now = () => clock.at;
  const write = (path: string, text: string) => {
    writeFileSync(join(dir, path), text);
    utimesSync(join(dir, path), clock.at / 1000, clock.at / 1000);
  };
  const read = (path: string) => readFileSync(join(dir, path), "utf-8");
  const files = () => [read("index.html"), read("notes.html")];
  async function hf(...args: string[]) {
    const log = vi.spyOn(console, "log").mockImplementation(() => {});
    const error = vi.spyOn(console, "error").mockImplementation(() => {});
    try {
      await runCommand(historyCommand, { rawArgs: [...args, "--dir", dir] });
      const out = log.mock.calls.map((call) => call.join(" ")).join("\n");
      const err = error.mock.calls.map((call) => call.join(" ")).join("\n");
      return { out, err, code: consumeCommandResult().exitCode };
    } finally {
      log.mockRestore();
      error.mockRestore();
    }
  }
  const json = async (...args: string[]) => JSON.parse((await hf(...args, "--json")).out);
  /** One agent turn that writes `path`. */
  async function turn(name: string, label: string, path: string, text: string) {
    await hf("begin", "--who", name, "--label", label);
    write(path, text);
    return (await json("end")).entry;
  }
  return { dir, write, read, files, hf, json, turn };
}

/** A running preview over the project's history, as `hyperframes preview` serves it. */
async function preview(dir: string) {
  const history = await openProjectHistory({
    projectDir: dir,
    historyRoot: historyDeps.historyRoot,
    now: () => historyDeps.now(),
    quietMs: 20,
  });
  const adapter = {
    listProjects: () => [],
    resolveProject: (id: string) => (id === "demo" ? { id, dir } : null),
    history: () => history,
  } as unknown as StudioApiAdapter;
  const server = createAdaptorServer({
    fetch: new Hono().route("/api", createStudioApi(adapter)).fetch,
  });
  await new Promise<void>((ready) => server.listen(0, "127.0.0.1", ready));
  onTestFinished(async () => {
    server.close();
    await history.close();
  });
  const { port } = server.address() as AddressInfo;
  historyDeps.findServer = async () =>
    ({
      port,
      host: "127.0.0.1",
      projectName: "demo",
      projectDir: dir,
      version: "test",
      pid: null,
    }) as never;
  return history;
}

async function turnCutByStudio(
  dir: string,
  write: (path: string, text: string) => void,
  hf: (...args: string[]) => Promise<unknown>,
) {
  const held = await preview(dir);
  const studio = { kind: "person", name: "You" } as const;
  await hf("begin", "--who", "claude", "--label", "Retitle");
  write("index.html", "A2");
  await held.claim(studio, "Nothing", []); // a claim scans first: the agent's write is seen
  write("index.html", "A3");
  await held.claim(studio, "Dragged Title", ["index.html"], {
    overwrote: { "index.html": fileContentVersion("A2") },
  });
  return held;
}

describe.each(["direct", "preview"])("hyperframes history (%s)", (mode) => {
  async function setup() {
    const p = project();
    await p.hf(); // the first open records the baseline
    const held = mode === "preview" ? await preview(p.dir) : null;
    /** A person's edit, taken in as preview's file watcher would. */
    async function personWrites(path: string, text: string) {
      p.write(path, text);
      if (!held) return;
      held.noteChange(path);
      await vi.waitFor(() => expect(held.list().at(-1)?.files[0]?.path).toBe(path));
    }
    return { ...p, personWrites };
  }

  it("an agent's labelled turn, a person's edit after it: --since shows both, undo of the turn keeps the edit", async () => {
    const { json, hf, turn, personWrites, files } = await setup();
    const startedAt = new Date(clock.at - 1).toISOString();
    await turn("claude", "Bigger title", "index.html", "A2");
    await personWrites("notes.html", "N2");

    const both = (await json("--since", startedAt)).entries;
    expect(both.map((entry: { who: object; files: string[] }) => [entry.who, entry.files])).toEqual(
      [
        [{ kind: "outside", name: "Outside" }, ["notes.html"]],
        [{ kind: "agent", name: "claude" }, ["index.html"]],
      ],
    );
    const mine = (await json("--since", "mine", "--who", "claude")).entries;
    expect(mine).toMatchObject([{ who: { name: "Outside" }, files: ["notes.html"] }]);

    const undo = await hf("undo", "--who", "claude");
    expect(undo.code, undo.err).toBe(0);
    expect(files()).toEqual(["A", "N2"]);
    expect(tracked.map((event) => event.via)).toContain(mode);
    expect(tracked.map((event) => event.action)).toEqual(
      expect.arrayContaining(["begin", "end", "list", "undo"]),
    );
  });

  it("a turn left open ends after the idle limit: a person's later edit stays theirs through undo of the turn", async () => {
    const { write, hf, personWrites, files } = await setup();
    historyDeps.turnIdleMs = 300;
    await hf("begin", "--who", "claude", "--label", "Retitle");
    write("index.html", "A2");
    advance(600);
    await personWrites("notes.html", "N2");

    const undo = await hf("undo", "--who", "claude");
    expect(undo.code, undo.err).toBe(0);
    expect(files()).toEqual(["A", "N2"]);
  });

  it("undo by one agent leaves another agent's open turn open", async () => {
    const { write, read, json, hf, turn } = await setup();
    await turn("gemini", "Notes", "notes.html", "N2");
    await hf("begin", "--who", "claude", "--label", "Bigger title");
    write("index.html", "A2");

    expect((await hf("undo", "--who", "gemini")).code).toBe(0);
    expect(read("notes.html")).toBe("N");
    expect((await hf("end")).code).toBe(0);
    const claude = (await json()).entries.filter(
      (e: { who: { name: string } }) => e.who.name === "claude",
    );
    expect(claude).toMatchObject([{ files: ["index.html"] }]);
  });

  it("undo of an id without --who is the person's, and leaves an agent's open turn open", async () => {
    const { write, json, hf, turn } = await setup();
    const notes = await turn("gemini", "Notes", "notes.html", "N2");
    await hf("begin", "--who", "claude", "--label", "Bigger title");
    write("index.html", "A2");

    expect((await json("undo", notes.id)).entry.who).toEqual({ kind: "person", name: "You" });
    expect((await hf("end")).code).toBe(0);
  });

  it("undo refuses a conflict with exit 2, names the newer entries and both choices, then takes one", async () => {
    const { read, hf, turn } = await setup();
    const first = await turn("claude", "First", "index.html", "A2");
    await turn("gemini", "Second", "index.html", "A3");

    const refused = await hf("undo", first.id.slice(0, 8));
    expect(refused.code).toBe(2);
    expect(refused.out).toContain("Second");
    expect(refused.out).toMatch(/--just-this[\s\S]*--back-to-before/);
    expect(read("index.html")).toBe("A3");

    expect((await hf("undo", first.id, "--just-this")).code).toBe(0);
    expect(read("index.html")).toBe("A");
  });

  it("show lists an entry's files and --diff prints the text change", async () => {
    const { hf, turn } = await setup();
    const entry = await turn("claude", "Retitle", "index.html", "A2");
    expect((await hf("show", entry.id)).out).toContain("M index.html");
    const diff = (await hf("show", entry.id.slice(0, 8), "--diff")).out;
    expect(diff).toMatch(/-A\n\\ No newline at end of file\n\+A2/);
  });

  it("peek reads a file as it was without writing, and restore puts every file back", async () => {
    const { read, hf, turn } = await setup();
    const entry = await turn("claude", "Retitle", "index.html", "A2");
    await turn("claude", "Again", "index.html", "A3");

    const stdout = vi.spyOn(process.stdout, "write").mockImplementation(() => true);
    await hf("peek", entry.id, "index.html");
    expect(String(stdout.mock.calls[0]?.[0])).toBe("A2");
    stdout.mockRestore();
    expect(read("index.html")).toBe("A3");

    expect((await hf("restore", "start")).code).toBe(0);
    expect(read("index.html")).toBe("A");
  });

  it("pin marks an entry kept, --off unmarks it", async () => {
    const { json, hf, turn } = await setup();
    const entry = await turn("claude", "Retitle", "index.html", "A2");
    await hf("pin", entry.id);
    expect((await json()).entries[0]).toMatchObject({ id: entry.id, pinned: true });
    await hf("pin", entry.id, "--off");
    expect((await json()).entries[0]).toMatchObject({ pinned: false });
  });
});

describe("hyperframes history, one owner", () => {
  it("lets go of the history when a new project takes the folder's path mid-command", async () => {
    const { dir, hf } = project();
    await hf("begin", "--who", "claude", "--label", "Retitle");
    const moved = `${dir}-moved`;
    onTestFinished(() => rmSync(moved, { recursive: true, force: true }));
    const swap = async () => {
      renameSync(dir, moved);
      mkdirSync(dir);
    };
    await expect(withOwner(dir, swap)).rejects.toThrow("now another project");
    const reopened = await openProjectHistory({
      projectDir: moved,
      historyRoot: historyDeps.historyRoot,
      ownerWaitMs: 200,
    });
    await reopened.close();
  });

  it("goes through a running preview, so the log keeps one baseline and every entry once", async () => {
    const { dir, json, turn } = project();
    const held = await preview(dir);
    await turn("claude", "Retitle", "index.html", "A2");
    await json();
    const log = readFileSync(join(historyDeps.historyRoot, held.projectId, "log.jsonl"), "utf-8");
    const records = log
      .trim()
      .split("\n")
      .map((row) => JSON.parse(row).type);
    expect(records).toEqual(["baseline", "entry"]);
  });

  it("a turn begun through a preview that stopped without closing it is still the agent's", async () => {
    const { dir, write, json, hf } = project();
    await hf();
    const turn = {
      via: "preview",
      id: "turn-1",
      who: { kind: "agent", name: "claude" },
      label: "Retitle",
      startedAt: 1,
      lastWriteAt: clock.at,
    };
    writeFileSync(join(dir, ".hyperframes", "history-turn.json"), JSON.stringify(turn));
    write("index.html", "A2");

    expect((await json("end")).entry).toMatchObject({
      id: "turn-1",
      who: turn.who,
      files: ["index.html"],
    });
  });

  it("undo --who also reverts the part of a turn that a Studio edit cut off", async () => {
    const { dir, write, hf, json, files } = project();
    await turnCutByStudio(dir, write, hf);
    write("notes.html", "N2");
    expect((await json("end")).parts).toHaveLength(2);

    const undo = await hf("undo", "--who", "claude", "--just-this");
    expect(undo.code, undo.err).toBe(0);
    expect(files()).toEqual(["A", "N"]);
  });

  it("undo --who reverts a turn a Studio edit cut off whole, after the preview stopped", async () => {
    const { dir, read, write, hf, json } = project();
    const held = await turnCutByStudio(dir, write, hf);
    await held.close();
    historyDeps.findServer = async () => null;
    expect((await json("end")).parts).toHaveLength(1);

    const undo = await hf("undo", "--who", "claude", "--just-this");
    expect(undo.code, undo.err).toBe(0);
    expect(read("index.html")).toBe("A");
  });

  it("a turn whose writes come closer together than the idle limit stays the agent's past it", async () => {
    const { write, json, hf } = project();
    await hf();
    historyDeps.turnIdleMs = 1000;
    // Each write 600 ms after the one before, past 1000 ms in all.
    await hf("begin", "--who", "claude", "--label", "Retitle");
    advance(600);
    write("index.html", "2");
    await hf(); // a command mid-turn files the turn so far; the rest counts from index.html
    advance(600);
    write("notes.html", "2");
    advance(600);
    write("extra.html", "2");
    await hf("end");
    const entries = (await json()).entries.reverse();
    expect(
      entries.map((entry: { who: object; files: string[] }) => [entry.who, entry.files]),
    ).toEqual([
      [{ kind: "agent", name: "claude" }, ["index.html"]],
      [{ kind: "agent", name: "claude" }, ["extra.html", "notes.html"]],
    ]);
  });

  it("undo --who refuses when the agent's last turn recorded nothing, and leaves its earlier turn alone", async () => {
    const { write, hf, turn, files } = project();
    await hf();
    historyDeps.turnIdleMs = 400;
    await turn("claude", "Earlier", "notes.html", "N2");
    await hf("begin", "--who", "claude", "--label", "Retitle");
    // The only change lands past the idle limit (the person's edit over the agent's), so it is Outside.
    advance(700);
    write("index.html", "A2");

    const refused = await hf("undo", "--who", "claude");
    expect([refused.code, refused.err]).toEqual([
      2,
      "claude's last turn has no change still in effect; undo an older entry by its id",
    ]);
    expect(files()).toEqual(["A2", "N2"]);
  });

  it("undo --who reverts every part of a turn that a mid-turn command split", async () => {
    const { write, hf, json, files } = project();
    await hf();
    await hf("begin", "--who", "claude", "--label", "Retitle");
    write("index.html", "A2");
    await hf(); // files the turn so far as its first part
    write("notes.html", "N2");
    expect((await json("end")).parts).toHaveLength(2);

    const undo = await hf("undo", "--who", "claude");
    expect(undo.code, undo.err).toBe(0);
    expect(files()).toEqual(["A", "N"]);
  });

  it("undo --who of a split turn with a conflict changes nothing and offers the choices for the whole turn", async () => {
    const { write, hf, files } = project();
    await hf();
    await hf("begin", "--who", "claude", "--label", "Retitle");
    write("index.html", "A2");
    await hf(); // files the turn so far as its first part
    write("notes.html", "N2");
    await hf("end");
    write("index.html", "A3"); // the person's edit over the first part

    const refused = await hf("undo", "--who", "claude");
    expect(refused.code).toBe(2);
    expect(refused.out).toContain("hyperframes history undo --who claude --just-this");
    expect(files(), "no part stays undone").toEqual(["A3", "N2"]);

    expect((await hf("undo", "--who", "claude", "--just-this")).code).toBe(0);
    expect(files()).toEqual(["A", "N"]);
  });

  it("a turn marker with no last write time has ended, so the next edit is not the agent's", async () => {
    const { dir, write, json, hf } = project();
    await hf();
    const who = { kind: "agent", name: "claude" };
    const marker = { via: "direct", id: "turn-1", who, label: "Retitle", startedAt: 1 };
    writeFileSync(join(dir, ".hyperframes", "history-turn.json"), JSON.stringify(marker));
    write("index.html", "A2");

    expect((await json()).entries[0]).toMatchObject({ who: { kind: "outside" } });
  });

  it("a CLI run waits while another process holds the history, instead of forking its log", async () => {
    const { dir, write } = project();
    const home = tempDir("hf-history-cli-home-");
    const historyRoot = join(home, ".cache", "hyperframes", "history");
    const held = await openProjectHistory({ projectDir: dir, historyRoot });
    // The CLI's first try at the lock leaves a claim draft beside owner.pid: proof it found the history held.
    const triedLock = new Promise<void>((tried) => {
      const watcher = watch(join(historyRoot, held.projectId), (_event, name) => {
        if (!name?.startsWith("owner.pid-")) return;
        watcher.close();
        tried();
      });
      onTestFinished(() => watcher.close());
    });
    write("index.html", "A2");
    const cli = resolve(fileURLToPath(import.meta.url), "..", "..", "cli.ts");
    const child = spawn("bun", ["run", cli, "history", "--dir", dir], {
      env: {
        ...process.env,
        HOME: home,
        USERPROFILE: home,
        HYPERFRAMES_SKIP_UPDATE_CHECK: "1",
        HYPERFRAMES_NO_TELEMETRY: "1",
      },
    });
    onTestFinished(() => void child.kill());
    const exited = new Promise<number | null>((done) => child.on("exit", done));
    const logFile = join(historyRoot, held.projectId, "log.jsonl");
    await Promise.race([
      triedLock,
      exited.then((code) => {
        throw new Error(`the CLI exited (${code}) before trying the held lock`);
      }),
    ]);
    expect(
      readFileSync(logFile, "utf-8").trim().split("\n"),
      "nothing written while held",
    ).toHaveLength(1);

    await held.close(); // commits the outside edit once
    expect(await exited).toBe(0);
    const types = readFileSync(logFile, "utf-8")
      .trim()
      .split("\n")
      .map((row) => JSON.parse(row).type);
    expect(types).toEqual(["baseline", "entry"]);
  });
});

describe("hyperframes history, refusals", () => {
  it("undo --who refuses once the agent's newest entry is already undone", async () => {
    const { read, hf, turn } = project();
    await hf();
    await turn("claude", "Retitle", "index.html", "A2");
    expect((await hf("undo", "--who", "claude")).code).toBe(0);

    const again = await hf("undo", "--who", "claude");
    expect([again.code, again.err]).toEqual([
      2,
      "claude's last turn has no change still in effect; undo an older entry by its id",
    ]);
    expect(read("index.html")).toBe("A");
  });

  it("restore refuses a ref that is neither an entry nor a date, instead of reading it as a time", async () => {
    const { read, write, hf, json, turn } = project();
    await hf();
    await turn("claude", "Retitle", "index.html", "A2");
    write("added.html", "new");
    const ids = (await json()).entries.map((entry: { id: string }) => entry.id);
    const digit = [..."0123456789"].find((d) => !ids.some((id: string) => id.startsWith(d)))!;

    const refused = await hf("restore", digit);
    expect([refused.code, refused.err]).toEqual([2, `No entry "${digit}" in this history`]);
    expect((await hf("restore", "2026-02-31")).err).toBe('"2026-02-31" is not a date');
    expect(read("added.html")).toBe("new");
  });

  it.each(["direct", "preview"])(
    "begin --exclusive starts once another agent's turn has been idle (%s)",
    async (mode) => {
      const { dir, hf } = project();
      await hf();
      if (mode === "preview") await preview(dir);
      historyDeps.turnIdleMs = 300;
      await hf("begin", "--who", "codex", "--label", "Retitle");
      advance(1_000);

      const begun = await hf("begin", "--who", "claude", "--label", "Notes", "--exclusive");
      expect([begun.code, begun.err]).toEqual([0, ""]);
      expect((await hf("end", "--who", "claude")).code).toBe(0);
    },
  );

  it("begin --exclusive through a preview refuses another agent's open turn", async () => {
    const { dir, hf } = project();
    await hf();
    await preview(dir);
    await hf("begin", "--who", "codex", "--label", "Retitle");
    const refused = await hf("begin", "--who", "claude", "--label", "Notes", "--exclusive");
    expect([refused.code, refused.err]).toEqual([
      2,
      "codex's turn is open; it has to end before yours begins",
    ]);
  });

  it("begin --exclusive through a preview lets only one of two agents win", async () => {
    const { dir, hf } = project();
    await hf();
    await preview(dir);
    const begin = (who: string) =>
      withOwner(dir, async (owner) => {
        await owner.begin({ kind: "agent", name: who }, who, true);
      }).then(
        () => "won",
        (error: Error) => error.message,
      );
    const results = await Promise.all([begin("codex"), begin("claude")]);
    expect(results.filter((result) => result === "won")).toHaveLength(1);
    expect(results.find((result) => result !== "won")).toMatch(
      /^(codex|claude)'s turn is open; it has to end before yours begins$/,
    );
  });

  it("begin --exclusive refuses another agent's open turn and keeps it open", async () => {
    const { write, hf, json } = project();
    await hf();
    await hf("begin", "--who", "codex", "--label", "Retitle");
    write("index.html", "A2");

    const refused = await hf("begin", "--who", "claude", "--label", "Notes", "--exclusive");
    expect([refused.code, refused.err]).toEqual([
      2,
      "codex's turn is open; it has to end before yours begins",
    ]);
    expect((await hf("end", "--who", "codex")).code).toBe(0);
    const entries = (await json()).entries as Array<{ who: { name: string }; files: string[] }>;
    expect(entries.filter((entry) => entry.who.name === "codex")).toMatchObject([
      { files: ["index.html"] },
    ]);
  });

  it("serializes concurrent begin --exclusive claims under the history owner lock", async () => {
    const { dir } = project();
    const historyRoot = tempDir("hf-history-cli-root-");
    const held = await openProjectHistory({ projectDir: dir, historyRoot });
    const home = join(historyRoot, held.projectId);
    const claimers = new Set<string>();
    const bothWaiting = new Promise<void>((resolveWaiting) => {
      const inspect = (_event: string, name: string | null) => {
        const pid = name?.match(/^owner\.pid-(\d+)-/)?.[1];
        if (pid) claimers.add(pid);
        if (claimers.size < 2) return;
        watcher.close();
        resolveWaiting();
      };
      const watcher = watch(home, inspect);
      onTestFinished(() => watcher.close());
    });
    const cli = resolve(fileURLToPath(import.meta.url), "..", "..", "cli.ts");
    const begin = (who: string) => {
      const child = spawn(
        "bun",
        ["run", cli, "history", "begin", "--who", who, "--label", who, "--exclusive", "--dir", dir],
        {
          env: {
            ...process.env,
            HYPERFRAMES_HISTORY_ROOT: historyRoot,
            HYPERFRAMES_SKIP_UPDATE_CHECK: "1",
            HYPERFRAMES_NO_TELEMETRY: "1",
          },
        },
      );
      onTestFinished(() => void child.kill());
      return new Promise<{ code: number | null; error: string }>((done) => {
        let error = "";
        child.stderr.on("data", (chunk) => (error += chunk));
        child.on("exit", (code) => done({ code, error: error.trim() }));
      });
    };
    const results = [begin("codex"), begin("claude")];
    await bothWaiting;
    await held.close();

    const settled = await Promise.all(results);
    expect(settled.map((result) => result.code).sort()).toEqual([0, 2]);
    expect(settled.find((result) => result.code === 2)?.error).toMatch(
      /'s turn is open; it has to end before yours begins$/,
    );
  });

  it("end --who refuses another agent's turn, and --if-open succeeds with none open", async () => {
    const { hf, json } = project();
    await hf();
    expect(await json("end", "--if-open")).toMatchObject({ entry: null, parts: [] });
    expect((await hf("end")).code).toBe(2);

    await hf("begin", "--who", "codex", "--label", "Retitle");
    const refused = await hf("end", "--who", "claude", "--if-open");
    expect([refused.code, refused.err]).toEqual([2, "The open turn is codex's, not claude's"]);
    expect((await hf("end", "--who", "codex")).code).toBe(0);
  });

  it("--json refusals go to stdout as {ok: false, error}", async () => {
    const { hf } = project();
    await hf();
    const refused = await hf("show", "zzzz", "--json");
    expect(refused.code).toBe(2);
    expect(JSON.parse(refused.out)).toMatchObject({
      ok: false,
      error: 'No entry "zzzz" in this history',
    });
    expect((await hf("--limit", "0")).code).toBe(2);
  });

  it("refuses a folder with no index.html, and records nothing for it", async () => {
    project();
    const folder = tempDir("hf-history-cli-not-a-project-");
    const error = vi.spyOn(console, "error").mockImplementation(() => {});
    await expect(runCommand(historyCommand, { rawArgs: ["--dir", folder] })).rejects.toThrow();
    error.mockRestore();
    expect(readdirSync(historyDeps.historyRoot)).toEqual([]);
  });

  it("reads the history while another app keeps it open, and refuses to change it there", async () => {
    const { dir, read, hf, turn } = project();
    await hf();
    const first = await turn("claude", "Retitle", "index.html", "A2");
    await turn("claude", "Again", "index.html", "A3");
    await hf("begin", "--who", "codex", "--label", "Open turn");
    const marker = () => readFileSync(join(dir, ".hyperframes", "history-turn.json"), "utf-8");
    const before = marker();
    const held = await openProjectHistory({
      projectDir: dir,
      historyRoot: historyDeps.historyRoot,
    });
    onTestFinished(() => held.close());
    historyDeps.ownerWaitMs = 0;

    const listed = await hf("--json", "--limit", "2");
    expect(listed.code).toBe(0);
    const labels = JSON.parse(listed.out).entries.map((entry: { label: string }) => entry.label);
    expect(labels).toEqual(["Again", "Retitle"]);
    expect((await hf("show", first.id)).out).toContain("M index.html");
    const stdout = vi.spyOn(process.stdout, "write").mockImplementation(() => true);
    await hf("peek", first.id, "index.html");
    expect(String(stdout.mock.calls[0]?.[0])).toBe("A2");
    stdout.mockRestore();
    expect(marker()).toBe(before);

    const refused = await hf("undo", first.id);
    expect([refused.code, refused.err]).toEqual([
      2,
      `This project is open in another app (pid ${process.pid}), which keeps its history: undo, restore or pin there.`,
    ]);
    expect(read("index.html")).toBe("A3");
  });

  it("still refuses a history id it cannot read, instead of reading the history as empty", async () => {
    const { dir, hf } = project();
    mkdirSync(join(dir, ".hyperframes"), { recursive: true });
    writeFileSync(join(dir, ".hyperframes", "history-id"), "garbage\n");
    const refused = await hf();
    expect(refused.code).toBe(2);
    expect(refused.err).toContain("holds no history id this version can read");
  });

  it("peek refuses cleanly when another app pruned the point's file after its log was read", async () => {
    const { dir, hf, turn } = project();
    await hf();
    const first = await turn("claude", "Retitle", "index.html", "A2");
    const held = await openProjectHistory({
      projectDir: dir,
      historyRoot: historyDeps.historyRoot,
    });
    onTestFinished(() => held.close());
    historyDeps.ownerWaitMs = 0;
    const hash = held.peek(first.id)!["index.html"]!;
    rmSync(join(historyDeps.historyRoot, held.projectId, "blobs", hash.slice(0, 2), hash));

    const refused = await hf("peek", first.id, "index.html");
    expect([refused.code, refused.err]).toEqual([2, "That point is no longer kept"]);
  });
});

describe.skipIf(process.platform === "win32" || process.getuid?.() === 0)(
  "hyperframes history, a history this run cannot write",
  () => {
    /** The project's history folder (or a folder in it) set to `mode` for the rest of the test. */
    function lock(mode: number, ...parts: string[]) {
      const [id] = readdirSync(historyDeps.historyRoot).filter((name) =>
        existsSync(join(historyDeps.historyRoot, name, "log.jsonl")),
      );
      const path = join(historyDeps.historyRoot, id!, ...parts);
      const dirs = [
        path,
        ...readdirSync(path, { recursive: true, withFileTypes: true })
          .filter((entry) => entry.isDirectory())
          .map((entry) => join(entry.parentPath, entry.name)),
      ];
      for (const dir of dirs.reverse()) chmodSync(dir, mode);
      onTestFinished(() => dirs.forEach((dir) => chmodSync(dir, 0o755)));
    }

    it("lists the history as last recorded when its folder cannot be written, and says so", async () => {
      const { hf, turn } = project();
      await hf();
      const entry = await turn("claude", "Retitle", "index.html", "A2");
      lock(0o555);
      const listed = await hf("--json");
      expect(listed.code).toBe(0);
      expect(JSON.parse(listed.out).entries.map((item: { id: string }) => item.id)).toContain(
        entry.id,
      );
      expect(listed.err).toMatch(/could not write this project's history/i);
    });

    it("lists the history when its log can be read but not appended to", async () => {
      const { hf, write, turn } = project();
      await hf();
      const entry = await turn("claude", "Retitle", "index.html", "A2");
      const [id] = readdirSync(historyDeps.historyRoot).filter((name) =>
        existsSync(join(historyDeps.historyRoot, name, "log.jsonl")),
      );
      const log = join(historyDeps.historyRoot, id!, "log.jsonl");
      chmodSync(log, 0o444);
      onTestFinished(() => chmodSync(log, 0o644));
      write("notes.html", "N2");
      const listed = await hf("--json");
      expect(listed.code).toBe(0);
      expect(JSON.parse(listed.out).entries.map((item: { id: string }) => item.id)).toContain(
        entry.id,
      );
      expect(listed.err).toMatch(/could not write this project's history/i);
    });

    it("lists the history when only its stored file copies cannot be written", async () => {
      const { hf, write, turn } = project();
      await hf();
      const entry = await turn("claude", "Retitle", "index.html", "A2");
      lock(0o555, "blobs");
      write("notes.html", "N2");
      const listed = await hf("--json");
      expect(listed.code).toBe(0);
      expect(JSON.parse(listed.out).entries.map((item: { id: string }) => item.id)).toContain(
        entry.id,
      );
    });

    it("never runs a read twice: a write error after it started is the command's own", async () => {
      const { dir, hf } = project();
      await hf();
      let runs = 0;
      const unwritable = Object.assign(new Error("no space"), { code: "ENOSPC", syscall: "write" });
      await expect(
        withReader(dir, async () => {
          runs += 1;
          throw unwritable;
        }),
      ).rejects.toBe(unwritable);
      expect(runs).toBe(1);
    });

    it("a folder it cannot read fails the read with that error, never as one it could not write", async () => {
      const { hf, turn } = project();
      await hf();
      await turn("claude", "Retitle", "index.html", "A2");
      lock(0o111, "blobs");
      const error = vi.spyOn(console, "error").mockImplementation(() => {});
      try {
        await expect(hf("--json")).rejects.toMatchObject({ code: "EACCES", syscall: "scandir" });
        expect(error.mock.calls.flat().join(" ")).not.toMatch(/could not write/i);
      } finally {
        error.mockRestore();
      }
    });

    it("an owner file it cannot read fails the read with that error, never as one it could not write", async () => {
      const { hf, turn } = project();
      await hf();
      await turn("claude", "Retitle", "index.html", "A2");
      const [id] = readdirSync(historyDeps.historyRoot).filter((name) =>
        existsSync(join(historyDeps.historyRoot, name, "log.jsonl")),
      );
      const owner = join(historyDeps.historyRoot, id!, "owner.pid");
      writeFileSync(owner, "999999999");
      chmodSync(owner, 0o000);
      onTestFinished(() => chmodSync(owner, 0o644));
      const error = vi.spyOn(console, "error").mockImplementation(() => {});
      try {
        await expect(hf("--json")).rejects.toMatchObject({ code: "EACCES", syscall: "open" });
        expect(error.mock.calls.flat().join(" ")).not.toMatch(/could not write/i);
      } finally {
        error.mockRestore();
      }
    });

    it("still fails an undo it cannot record, and leaves the files as they are", async () => {
      const { hf, read, turn } = project();
      await hf();
      await turn("claude", "Retitle", "index.html", "A2");
      lock(0o555);
      await expect(hf("undo", "--who", "claude")).rejects.toMatchObject({ code: "EACCES" });
      expect(read("index.html")).toBe("A2");
    });
  },
);