Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

39.7 KB
Raw Blame
import { readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { createAgentCard } from "./chat-widgets.ts";
import { DATA_DIR } from "./config.ts";
import { Store, UNTITLED_TASK } from "./store.ts";
import { RoutineManager } from "./routines.ts";
import { createTeamBackup, importTeamBackup } from "./team-backup.ts";
import { parseTeamBackup } from "../shared/team-backup.ts";
import { AFTER_RESET_MS } from "../shared/limit-reset.ts";
import { approvalModeFor } from "../shared/approval-mode.ts";
import { WIDGET_SAMPLES } from "../shared/widget-samples.ts";
import { soulFile, soulHash } from "./bot-folder.ts";
import { appendMemoryLog, readMemoryFile, readMemoryLog, readMemoryTopic, searchMemoryFiles, updateMemory, workspaceDir, writeMemoryTopic } from "./workspace.ts";

const selection = () => ({ instanceId: "fixture", model: "fixture-model" });
const KNOWN_RESET_AT = Date.parse("2026-11-26T12:00:00.000Z");
const knownLimitResetAt = (engine: string) => engine === "claude" ? KNOWN_RESET_AT : null;

function openRoutines(store: Store, options: { limitResetAt?: (engine: string) => number | null; file?: string } = {}) {
  return new RoutineManager({
    ...(options.file ? { file: options.file } : {}),
    ...(options.limitResetAt ? { limitResetAt: options.limitResetAt } : {}),
    botState: (id) => store.bot(id) ? "ready" : "missing",
    goalState: (id, botId) => store.group(id ?? "")?.memberIds.includes(botId) ? "ready" : "missing",
    createTask: (id, title) => store.createTask(id, title),
    startTurn: async () => { throw new Error("Import must never run a bot"); },
  });
}

function fixture(options: { limitResetAt?: (engine: string) => number | null } = {}) {
  const store = new Store(selection);
  const routines = openRoutines(store, options);
  const chief = store.createBot({ name: "Mira", section: "Engineering", description: "Full instructions\n".repeat(400) }, { seedMessages: false });
  store.setSoul(chief.id, "  Cite sources.\nRespect the user's current request. 🐭\n");
  const scout = store.createBot({ name: "Scout", section: "Engineering", mascotBody: "circle", mascotFaceColor: "black", mascotBodyColor: "#12ab9f", mascotMaterial: "fluffy" }, { seedMessages: false });
  const otherChief = store.createBot({ name: "Ava", section: "Operations" }, { seedMessages: false });
  const archived = store.createBot({ name: "Archived" }, { seedMessages: false });
  store.patchBot(archived.id, { hidden: true });
  store.patchBot(chief.id, { chiefOfStaff: true, autoApprove: true, approvalMode: "full", alwaysAllow: ["Bash"], cwd: "/private/old-workspace", composio: true,
    playbooks: [{ key: "research", name: "Research", summary: "Find evidence", triggers: ["research"], instructions: "Cite sources" }] });
  store.setChiefOfStaff(otherChief.id);
  const root = store.appendMessage(chief.threadId, { role: "user", kind: "text", text: "Original question", at: 100 });
  const answer = store.appendMessage(chief.threadId, { role: "bot", kind: "text", text: "Original answer", at: 101 });
  store.branchMessage(chief.threadId, root.id, "Edited question");
  store.setActiveLeaf(chief.threadId, answer.id);
  store.renameTask(chief.id, chief.threadId, "First conversation");
  // Created first: tasks are newest-first, and the tests read tasks[0], which must stay the conversation with messages.
  const strangers = store.createTask(chief.id, "Opened by a deleted bot", false, undefined, { botId: "gone-bot", name: "Gone", at: 98 })!;
  store.setTaskClosedBy(chief.id, strangers.threadId, { botId: "gone-bot", name: "Gone", at: 102 });
  const active = store.createTask(chief.id, "Second conversation")!;
  store.setTaskOpenedBy(chief.id, active.threadId, { botId: scout.id, name: scout.name, delegationId: "do-not-resume-delegation", kind: "pair", at: 99 });
  store.setTaskClosedBy(chief.id, active.threadId, { botId: scout.id, name: scout.name, at: 103 });
  store.appendMessage(active.threadId, { role: "user", kind: "text", text: "Current question", queued: true, queueId: "do-not-replay" });
  store.appendMessage(active.threadId, { role: "bot", kind: "options", card: {
    title: "Permission request", subtitle: "Old approval", options: ["Allow"], requestId: "do-not-resume", allowKey: "Bash",
  } });
  store.appendMessage(active.threadId, { role: "user", kind: "text", text: "An image", attachments: [{ kind: "image", path: "/private/image.png", mime: "image/png" }] });
  const group = store.createGroup("Project room", [chief.id, scout.id], false, "Engineering", {
    bulletin: "Build carefully", defaultResponder: { kind: "member", botId: chief.id }, completed: true,
  });
  store.appendMessage(group.threadId, { role: "bot", kind: "text", text: "Room answer", from: { botId: scout.id, name: scout.name, color: scout.color }, peerPost: { unattended: true } });
  store.createGroupTask(group.id, "Second room task", false);
  routines.create({ name: "Daily", prompt: "Report progress", botId: chief.id, enabled: true, schedule: { type: "daily", time: "09:00", weekdays: [1, 2, 3, 4, 5] } });
  routines.create({ name: "Standup", prompt: "Discuss progress", target: "room-goal", groupId: group.id, botId: chief.id, enabled: true, schedule: { type: "interval", everyMinutes: 30, anchorAt: 0 } });
  return { store, routines, chief, scout, otherChief, archived, group };
}

function portableBackup(store: Store, routines: RoutineManager, name: string) {
  return JSON.parse(JSON.stringify(createTeamBackup(store, routines.listRoutines(), name))) as ReturnType<typeof createTeamBackup>;
}

function restoredRoutine(store: Store, routines: RoutineManager, backup: ReturnType<typeof portableBackup>, name: string) {
  const imported = importTeamBackup(store, routines, backup, selection());
  const owner = imported.bots.find((bot) => bot.name === "Mira 2")!;
  const routine = imported.routines.find((item) => item.name === name)!;
  return { owner, routine };
}

describe("additive portable team backups", () => {
  beforeEach(() => rmSync(DATA_DIR, { recursive: true, force: true }));

  it("keeps fixed goal-history codes through two export/import cycles, without restoring a live card", () => {
    const { store, routines, chief } = fixture();
    store.appendMessage(chief.threadId, { role: "bot", kind: "goal.run", text: "Goal completed: Model's outcome", goalRun: {
      runId: "history", goal: "Check the release", status: "completed", coordinatorBotId: chief.id, coordinatorName: chief.name,
      turnCount: 1, maxTurns: 13, detail: "Model's outcome", startedAt: 1,
    } });
    let botId = chief.id;
    for (const cycle of [1, 2]) {
      const backup = parseTeamBackup(JSON.parse(JSON.stringify(createTeamBackup(store, routines.listRoutines(), `Goal history ${cycle}`))));
      const botIndex = backup.bots.findIndex((bot) => bot.key === botId);
      const saved = backup.bots[botIndex]!.tasks.flatMap((task) => task.messages).find((message) => message.text.includes("[Goal: completed]"))!;
      expect(saved).toMatchObject({ text: "Goal completed: Model's outcome\n[Goal: completed]\nCheck the release\nModel's outcome", textCode: "chat.notice.exportedGoal.completed", textParams: { before: "Goal completed: Model's outcome\n", content: "\nCheck the release\nModel's outcome" } });
      const imported = importTeamBackup(store, routines, backup, selection()).bots[botIndex]!;
      const restored = imported.tasks!.flatMap((task) => store.messagesFor(task.threadId)).find((message) => message.text?.includes("[Goal: completed]"))!;
      expect(restored).toMatchObject({ kind: "text", text: saved.text, textCode: saved.textCode, textParams: saved.textParams });
      expect(restored).not.toHaveProperty("goalRun");
      botId = imported.id;
    }
  });

  it("carries tool restrictions through backup and import without restoring execution grants", () => {
    const { store, routines, chief, scout } = fixture();
    const scope = { allow: ["native:read", "mcp:notes:read"], deny: ["mcp:notes:write"] };
    store.patchBot(chief.id, { toolScope: scope } as never);
    store.patchBot(scout.id, { toolScope: { allow: [] } } as never);
    const backup = createTeamBackup(store, routines.listRoutines(), "Selected tools");
    expect(backup.bots.find((bot) => bot.key === chief.id)).toHaveProperty("toolScope", scope);
    const restored = importTeamBackup(store, routines, backup, selection());
    expect(restored.bots.find((bot) => bot.name === "Mira 2")).toMatchObject({ toolScope: scope, computer: "off", composio: false, connectorTools: {} });
    expect(approvalModeFor(restored.bots.find((bot) => bot.name === "Mira 2")!)).toBe("full");
    expect(restored.bots.find((bot) => bot.name === "Scout 2")).toHaveProperty("toolScope", { allow: [] });
    const invalid = structuredClone(backup) as unknown as { bots: Array<{ toolScope: unknown }> };
    invalid.bots[0].toolScope = { allow: null };
    expect(() => parseTeamBackup(invalid)).toThrow();
  });

  it("backs up and restores a silver bot in silver", () => {
    const { store, routines } = fixture();
    const maus = store.createBot({ name: "MausBot", color: "silver" }, { seedMessages: false });
    const backup = createTeamBackup(store, routines.listRoutines(), "With MausBot");
    expect(backup.bots.find((bot) => bot.key === maus.id)?.color).toBe("silver");
    const restored = importTeamBackup(store, routines, JSON.parse(JSON.stringify(backup)), selection());
    expect(restored.bots.find((bot) => bot.name === "MausBot 2")?.color).toBe("silver");
  });

  it("carries a bot's never-use-the-helper switch through backup and import, so its restored notes and chats stay off the helper", () => {
    const { store, routines, chief, scout } = fixture();
    store.patchBot(chief.id, { helperModel: false });
    store.patchBot(scout.id, { helperModel: true });
    // part of the bot's saved record: a restart reads it back
    expect(new Store(selection).bot(chief.id)).toHaveProperty("helperModel", false);
    const backup = createTeamBackup(store, routines.listRoutines(), "Private bots");
    // only "never" travels: allowed is what a bot without the field already is
    expect(backup.bots.find((bot) => bot.key === chief.id)).toHaveProperty("helperModel", false);
    expect(backup.bots.find((bot) => bot.key === scout.id)).not.toHaveProperty("helperModel");
    // through the file, as an import reads it
    const restored = importTeamBackup(store, routines, parseTeamBackup(JSON.parse(JSON.stringify(backup))), selection());
    expect(restored.bots.find((bot) => bot.name === "Mira 2")).toHaveProperty("helperModel", false);
    expect(restored.bots.find((bot) => bot.name === "Scout 2")).not.toHaveProperty("helperModel");
    // a file that says true imports like any other, and changes nothing: allowed is what a new bot already is
    const saysTrue = structuredClone(backup) as unknown as { bots: Array<{ key: string; helperModel?: unknown }> };
    for (const entry of saysTrue.bots) entry.helperModel = true;
    const again = importTeamBackup(store, routines, parseTeamBackup(saysTrue), selection());
    expect(again.bots).toHaveLength(backup.bots.length);
    for (const restoredBot of again.bots) expect(restoredBot, restoredBot.name).not.toHaveProperty("helperModel");
    // anything that is not true or false is still a malformed file
    const malformed = structuredClone(backup) as unknown as { bots: Array<{ helperModel?: unknown }> };
    malformed.bots[0]!.helperModel = "false";
    expect(() => parseTeamBackup(malformed)).toThrow();
  });

  it("writes a hand-edited switch as never: what is not an absent switch or a strict true does not become allowed in a backup", () => {
    const { store, routines, chief, scout } = fixture();
    store.patchBot(chief.id, { helperModel: "false" } as never);
    store.patchBot(scout.id, { helperModel: 0 } as never);
    const backup = createTeamBackup(store, routines.listRoutines(), "Hand-edited");
    expect(backup.bots.find((bot) => bot.key === chief.id)).toHaveProperty("helperModel", false);
    expect(backup.bots.find((bot) => bot.key === scout.id)).toHaveProperty("helperModel", false);
  });

  it("carries each bot's memory, topic notes and daily logs, scrubbed on the way out and private on the way in", () => {
    const { store, routines, chief, scout } = fixture();
    const now = new Date(2026, 8, 10, 12);
    updateMemory(chief.id, { action: "append", text: "The user's name is Ada" }, { source: 'chat "Setup"', now });
    writeMemoryTopic(chief.id, "deploys.md", "railway up from main\n");
    appendMemoryLog(chief.id, "shipped 0.1.70", { source: 'chat "Deploy"', now });
    const key = `sk-ant-api03-${"k".repeat(40)}`;
    writeFileSync(join(workspaceDir(chief.id), "memory", "keys.md"), `anthropic: ${key}\n`);

    const backup = createTeamBackup(store, routines.listRoutines(), "With memory");
    const exported = backup.bots.find((bot) => bot.key === chief.id)!.memory!;
    expect(exported.file).toBe('- 2026-09-10 · from chat "Setup" · The user\'s name is Ada\n');
    expect(exported.topics.map((topic) => topic.name)).toEqual(["deploys.md", "keys.md"]);
    expect(exported.topics[1].text).not.toContain(key);
    expect(exported.topics[1].text).toContain("anthropic: «redacted");
    expect(exported.logs).toEqual([{ name: "2026-09-10.md", text: '- 12:00 · from chat "Deploy" · shipped 0.1.70\n' }]);
    expect(backup.bots.find((bot) => bot.key === scout.id)!.memory).toBeUndefined();
    expect(JSON.stringify(backup)).not.toContain(key);

    const result = importTeamBackup(store, routines, JSON.parse(JSON.stringify(backup)), selection());
    const imported = result.bots.find((bot) => bot.name === "Mira 2")!;
    expect(readMemoryFile(imported.id).text).toBe(exported.file);
    expect(readMemoryTopic(imported.id, "deploys.md")).toBe("railway up from main\n");
    expect(readMemoryTopic(imported.id, "keys.md")).toBe(exported.topics[1].text);
    expect(readMemoryLog(imported.id, "2026-09-10.md")).toBe(exported.logs[0].text);
    expect(readFileSync(soulFile(imported.id), "utf8")).toBe(chief.soul);
    if (process.platform !== "win32") {
      const dir = workspaceDir(imported.id);
      expect(statSync(join(dir, "memory")).mode & 0o777).toBe(0o700);
      expect(statSync(join(dir, "memory", "log")).mode & 0o777).toBe(0o700);
      for (const file of ["MEMORY.md", "memory/deploys.md", "memory/keys.md", "memory/log/2026-09-10.md"]) {
        expect(statSync(join(dir, file)).mode & 0o777, file).toBe(0o600);
      }
    }
    expect(searchMemoryFiles(imported.id, "railway").map((hit) => hit.file)).toEqual(["memory/deploys.md"]);
    expect(readMemoryFile(chief.id).text).toBe(exported.file);
    const noMemory = result.bots.find((bot) => bot.name === "Scout 2")!;
    expect(readMemoryFile(noMemory.id).text).toBe("");
  });

  it("exports a disabled limit-reset routine and restores it paused on its new owner", () => {
    const { store, routines, chief } = fixture();
    const created = routines.create({
      name: "After Claude resets", prompt: "Finish the report.", botId: chief.id, enabled: false,
      schedule: { type: "limit_reset", engine: "claude", repeat: "once" },
    });
    const backup = portableBackup(store, routines, "Limit reset once");
    const saved = backup.routines.find((routine) => routine.name === "After Claude resets")!;
    expect(saved.schedule).toEqual(created.schedule);
    const { owner, routine } = restoredRoutine(store, routines, backup, "After Claude resets");
    expect(routine.schedule).toEqual(created.schedule);
    expect(routine.botId).toBe(owner.id);
    expect(routine.enabled).toBe(false);
    expect(routine.nextRunAt).toBeNull();
  });

  it("exports a disabled limit-reset routine that repeats every reset", () => {
    const { store, routines, chief } = fixture();
    const created = routines.create({
      name: "Every Claude reset", prompt: "Pick up the next report.", botId: chief.id, enabled: false,
      schedule: { type: "limit_reset", engine: "claude", repeat: "every_reset" },
    });
    const backup = portableBackup(store, routines, "Limit reset repeat");
    const saved = backup.routines.find((routine) => routine.name === "Every Claude reset")!;
    expect(saved.schedule).toEqual(created.schedule);
    const { owner, routine } = restoredRoutine(store, routines, backup, "Every Claude reset");
    expect(routine.schedule).toEqual(created.schedule);
    expect(routine.botId).toBe(owner.id);
    expect(routine.enabled).toBe(false);
    expect(routine.nextRunAt).toBeNull();
  });

  it("preserves a known limit-reset time through backup and import with the same provider", () => {
    const { store, routines, chief } = fixture({ limitResetAt: knownLimitResetAt });
    const created = routines.create({
      name: "Known Claude reset", prompt: "Continue after the known reset.", botId: chief.id, enabled: false,
      schedule: { type: "limit_reset", engine: "claude", repeat: "once" },
    });
    expect(created.schedule).toEqual({ type: "limit_reset", engine: "claude", repeat: "once", at: KNOWN_RESET_AT + AFTER_RESET_MS });
    const backup = portableBackup(store, routines, "Known limit reset");
    const saved = backup.routines.find((routine) => routine.name === "Known Claude reset")!;
    expect(saved.schedule).toEqual(created.schedule);
    const { owner, routine } = restoredRoutine(store, routines, backup, "Known Claude reset");
    expect(routine.schedule).toEqual(created.schedule);
    expect(routine.botId).toBe(owner.id);
    expect(routine.enabled).toBe(false);
    expect(routine.nextRunAt).toBeNull();
  });

  it("keeps a limit-reset snapshot in the file and pauses the import when the destination has no reset time", () => {
    const { store, routines, chief } = fixture({ limitResetAt: knownLimitResetAt });
    const created = routines.create({
      name: "Snapshot Claude reset", prompt: "Keep the snapshot.", botId: chief.id, enabled: false,
      schedule: { type: "limit_reset", engine: "claude", repeat: "once" },
    });
    const backup = portableBackup(store, routines, "Limit reset snapshot");
    const saved = backup.routines.find((routine) => routine.name === "Snapshot Claude reset")!;
    expect(saved.schedule).toEqual(created.schedule);
    expect(saved.schedule).toEqual({ type: "limit_reset", engine: "claude", repeat: "once", at: KNOWN_RESET_AT + AFTER_RESET_MS });
    const destination = openRoutines(store, { file: join(DATA_DIR, "routines-no-reset.json") });
    const { owner, routine } = restoredRoutine(store, destination, backup, "Snapshot Claude reset");
    expect(routine.schedule).toEqual({ type: "limit_reset", engine: "claude", repeat: "once", at: null });
    expect(routine.botId).toBe(owner.id);
    expect(routine.enabled).toBe(false);
    expect(routine.nextRunAt).toBeNull();
  });

  it("exports an enabled cron routine and restores it paused", () => {
    const { store, routines, chief } = fixture();
    const created = routines.create({
      name: "Weekday cron", prompt: "Send the weekday brief.", botId: chief.id, enabled: true,
      schedule: { type: "cron", expression: "15 9 * * 1-5", timeZone: "Asia/Kuala_Lumpur" },
    });
    expect(created.enabled).toBe(true);
    const backup = portableBackup(store, routines, "Cron");
    const saved = backup.routines.find((routine) => routine.name === "Weekday cron")!;
    expect(saved.schedule).toEqual(created.schedule);
    const { owner, routine } = restoredRoutine(store, routines, backup, "Weekday cron");
    expect(routine.schedule).toEqual(created.schedule);
    expect(routine.botId).toBe(owner.id);
    expect(routine.enabled).toBe(false);
    expect(routine.nextRunAt).toBeNull();
  });

  it("round-trips an interval's weekdays, window and end", () => {
    const { store, routines, chief } = fixture();
    const anchorAt = Date.UTC(2026, 7, 17, 8, 5);
    const endsAt = Date.UTC(2099, 0, 1);
    const created = routines.create({
      name: "Support hours", prompt: "Check during support hours.", botId: chief.id, enabled: true,
      schedule: {
        type: "interval", everyMinutes: 30, anchorAt,
        weekdays: [1, 3, 5], window: { start: "09:00", end: "17:00" }, endsAt,
      },
    });
    const backup = portableBackup(store, routines, "Constrained interval");
    const saved = backup.routines.find((routine) => routine.name === "Support hours")!;
    expect(saved.schedule).toEqual(created.schedule);
    const { owner, routine } = restoredRoutine(store, routines, backup, "Support hours");
    expect(routine.schedule).toEqual(created.schedule);
    expect(routine.botId).toBe(owner.id);
    expect(routine.enabled).toBe(false);
    expect(routine.nextRunAt).toBeNull();
  });

  it("round-trips all bots, sections, Chiefs, rooms, tasks and branches without changing originals", () => {
    const { store, routines, chief, scout, otherChief, archived, group } = fixture();
    const backup = createTeamBackup(store, routines.listRoutines(), "My team");
    const originalBots = structuredClone(store.bots);
    const originalGroups = structuredClone(store.groups);
    const originalRoutines = routines.listRoutines();
    const result = importTeamBackup(store, routines, JSON.parse(JSON.stringify(backup)), selection());
    expect(result.bots).toHaveLength(4);
    expect(result.groups).toHaveLength(1);
    for (const bot of originalBots) expect(store.bot(bot.id)).toEqual(bot);
    for (const room of originalGroups) expect(store.group(room.id)).toEqual(room);
    for (const routine of originalRoutines) expect(routines.listRoutines().find((r) => r.id === routine.id)).toEqual(routine);
    const importedChief = result.bots.find((bot) => bot.name === "Mira 2")!;
    const importedScout = result.bots.find((bot) => bot.name === "Scout 2")!;
    expect(importedChief.soul).toBe(chief.soul);
    expect(importedChief.soulHash).toBe(soulHash(chief.soul!));
    expect(readFileSync(soulFile(importedChief.id), "utf8")).toBe(chief.soul);
    expect(importedChief).toMatchObject({ section: "Engineering 2", chiefOfStaff: true, description: chief.description, computer: "off", composio: false, browser: false, resumeCursors: {}, playbooks: chief.playbooks });
    expect(approvalModeFor(importedChief)).toBe("full");
    expect(result.bots.find((bot) => bot.name === "Ava 2")).toMatchObject({ section: "Operations 2", chiefOfStaff: true });
    expect(result.bots.find((bot) => bot.name === "Archived 2")).toMatchObject({ hidden: true });
    expect(importedChief).not.toHaveProperty("cwd");
    expect(importedChief).not.toHaveProperty("alwaysAllow");
    expect(importedChief.tasks?.every((task) => task.activity === "idle" && task.busy === false
      && task.unread === false && task.modelSelection === undefined
      && store.projectBotForTask(importedChief.id, task.threadId)?.modelSelection.instanceId === selection().instanceId)).toBe(true);
    expect(store.bot(otherChief.id)?.chiefOfStaff).toBe(true);
    expect(store.bot(archived.id)?.hidden).toBe(true);
    expect(importedScout.mascotBody).toBe(scout.mascotBody);
    expect(importedScout.mascotFaceColor).toBe("black");
    expect(importedScout.mascotBodyColor).toBe("#12ab9f");
    expect(importedScout.mascotMaterial).toBe("fluffy");
    expect(result.groups[0]).toMatchObject({ name: "Project room 2", section: "Engineering 2", memberIds: [importedChief.id, importedScout.id], defaultResponder: { kind: "member", botId: importedChief.id } });
    expect(result.groups[0].tasks?.map((task) => [task.title, task.createdAt])).toEqual(group.tasks?.map((task) => [task.title, task.createdAt]));
    const roomMessage = store.messagesFor(result.groups[0].threadId)[0];
    expect(roomMessage).toMatchObject({ text: "Room answer", from: { botId: importedScout.id }, peerPost: { unattended: true } });
    expect(result.routines.every((routine) => !routine.enabled && routine.nextRunAt === null)).toBe(true);
    expect(result.routines.find((routine) => routine.target === "room-goal")).toMatchObject({ botId: importedChief.id, groupId: result.groups[0].id });
    expect(importedChief.tasks!.find((task) => task.title === "Second conversation")!.openedBy)
      .toEqual({ botId: importedScout.id, name: scout.name, kind: "pair", at: 99 });
    expect(importedChief.tasks!.find((task) => task.title === "Opened by a deleted bot")).not.toHaveProperty("openedBy");
    expect(importedChief.tasks!.find((task) => task.title === "First conversation")).not.toHaveProperty("openedBy");
    expect(importedChief.tasks!.find((task) => task.title === "Second conversation")!.closedBy)
      .toEqual({ botId: importedScout.id, name: scout.name, at: 103 });
    expect(importedChief.tasks!.find((task) => task.title === "Opened by a deleted bot")).not.toHaveProperty("closedBy");
    expect(importedChief.tasks!.find((task) => task.title === "First conversation")).not.toHaveProperty("closedBy");
    const firstTask = importedChief.tasks!.find((task) => task.title === "First conversation")!;
    expect(store.messagesFor(firstTask.threadId).map((message) => message.text)).toEqual(["Original question", "Original answer", "Edited question"]);
    expect(store.activePath(firstTask.threadId).map((message) => message.text)).toEqual(["Original question", "Original answer"]);
    const importedHistory = store.messagesFor(importedChief.threadId);
    expect(importedHistory.every((message) => message.kind === "text" && !message.queued && !message.card)).toBe(true);
    expect(importedHistory[1].text).toContain("Permission request");
    expect(importedHistory[2].text).toContain("file not included");
    expect(JSON.stringify(backup)).not.toMatch(/do-not-replay|do-not-resume|\/private\/image|\/private\/old-workspace|alwaysAllow|autoApprove|modelSelection|delegationId/);
    const reloaded = new Store(selection);
    expect(reloaded.bot(importedChief.id)?.soul).toBe(chief.soul);
    expect(reloaded.activePath(firstTask.threadId)).toEqual(store.activePath(firstTask.threadId));
    expect(reloaded.bot(importedChief.id)?.tasks).toEqual(importedChief.tasks);
    expect(reloaded.messagesFor(chief.threadId)).toEqual(store.messagesFor(chief.threadId));
    const second = importTeamBackup(store, routines, backup, selection());
    expect(second.bots.find((bot) => bot.name === "Mira 3")).toMatchObject({ section: "Engineering 3", chiefOfStaff: true });
    expect(store.bot(importedChief.id)).toEqual(importedChief);
  });

  it("carries connector grants in the private backup but lands imported bots grant-less", () => {
    const { store, routines, chief } = fixture();
    store.patchBot(chief.id, { connectorTools: { gmail: { tools: ["GMAIL_SEND_EMAIL", "GMAIL_SEND_EMAIL"] } } });
    const backup = createTeamBackup(store, routines.listRoutines(), "Granted team");
    expect(backup.bots.find((bot) => bot.key === chief.id)?.connectorTools).toEqual({
      gmail: { tools: ["GMAIL_SEND_EMAIL"] },
    });
    const result = importTeamBackup(store, routines, JSON.parse(JSON.stringify(backup)), selection());
    const imported = result.bots.find((bot) => bot.name === "Mira 2")!;
    expect(imported.composio).toBe(false);
    expect(imported.connectorTools).toEqual({});
    const tampered = JSON.parse(JSON.stringify(backup)) as { bots: { key: string; connectorTools: unknown }[] };
    tampered.bots[0].connectorTools = { gmail: { tools: [] } };
    expect(() => parseTeamBackup(tampered)).toThrow();
  });

  it("keeps a conversation that work from outside reached marked through backup and restore", () => {
    const { store, routines, chief } = fixture();
    const reached = store.createTask(chief.id, "Event chat", false)!.threadId;
    store.patchTask(chief.id, reached, { outside: true });
    const backup = createTeamBackup(store, routines.listRoutines(), "Marked");
    const result = importTeamBackup(store, routines, JSON.parse(JSON.stringify(backup)), selection());
    const restored = result.bots.find((bot) => bot.name === "Mira 2")!.tasks!;
    expect(restored.find((task) => task.title === "Event chat")!.outside).toBe(true);
    expect(restored.find((task) => task.title === "First conversation")).not.toHaveProperty("outside");
  });

  it("keeps first-message title markers armed-once through backup and restore", () => {
    const { store, routines, chief, group } = fixture();
    const titled = store.createTask(chief.id, undefined, false)!.threadId;
    store.titleTaskFromFirstMessage(chief.id, "Audit the payroll export", titled);
    const channelTask = store.createGroupTask(group.id, undefined, false)!.threadId;
    store.titleGroupTaskFromFirstMessage(group.id, "Plan the launch review", channelTask);
    const backup = createTeamBackup(store, routines.listRoutines(), "Markers");
    expect(backup.bots.find((bot) => bot.name === "Mira")!.tasks.find((task) => task.key === titled)!.titleFromFirstMessage).toBe(true);
    expect(backup.groups[0].tasks.find((task) => task.key === channelTask)!.titleFromFirstMessage).toBe(true);

    const result = importTeamBackup(store, routines, JSON.parse(JSON.stringify(backup)), selection());
    const restoredBot = result.bots.find((bot) => bot.name === "Mira 2")!;
    const restored = restoredBot.tasks!.find((task) => task.title === "Audit the payroll export")!;
    expect(restored.titleFromFirstMessage).toBe(true);
    expect(restored.titleMode).toBe("automatic");
    store.renameTask(restoredBot.id, restored.threadId, UNTITLED_TASK);
    expect(restored.titleMode).toBe("manual");
    expect(store.titleTaskFromFirstMessage(restoredBot.id, "A later message", restored.threadId)).toBeNull();
    const restoredGroup = result.groups[0];
    const restoredChannel = restoredGroup.tasks!.find((task) => task.title === "Plan the launch review")!;
    expect(restoredChannel.titleFromFirstMessage).toBe(true);
    expect(restoredChannel.titleMode).toBe("automatic");
    store.patchGroupTask(restoredGroup.id, restoredChannel.threadId, { title: UNTITLED_TASK });
    expect(restoredChannel.titleMode).toBe("manual");
    expect(store.titleGroupTaskFromFirstMessage(restoredGroup.id, "A later message", restoredChannel.threadId)).toBeNull();
    expect(restoredBot.tasks!.find((task) => task.title === "First conversation")).not.toHaveProperty("titleFromFirstMessage");
  });

  it("keeps a conversation's longer turn limit through backup and restore", () => {
    const { store, routines, chief, scout, group } = fixture();
    const threadId = group.tasks!.find((task) => task.title === "Second room task")!.threadId;
    store.patchGroupTask(group.id, threadId, { turnTimeoutMinutes: 30 });
    const dm = store.createGroup("Direct", [chief.id, scout.id], true);
    store.patchGroup(dm.id, { turnTimeoutMinutes: 45 });

    const backup = createTeamBackup(store, routines.listRoutines(), "Limits");
    const roomTask = backup.groups.find((candidate) => candidate.key === group.id)!.tasks.find((task) => task.key === threadId)!;
    expect(roomTask.turnTimeoutMinutes).toBe(30);
    expect(backup.groups.find((candidate) => candidate.key === dm.id)!.tasks[0].turnTimeoutMinutes).toBe(45);
    expect(backup.bots.every((bot) => bot.tasks.every((task) => task.turnTimeoutMinutes === undefined))).toBe(true);

    const result = importTeamBackup(store, routines, JSON.parse(JSON.stringify(backup)), selection());
    const restored = result.groups.find((candidate) => candidate.name.startsWith("Project room"))!;
    expect(restored.tasks!.find((task) => task.title === "Second room task")!.turnTimeoutMinutes).toBe(30);
    const restoredDm = result.groups.find((candidate) => candidate.name.startsWith("Direct"))!;
    expect(restoredDm.turnTimeoutMinutes).toBe(45);
    expect(restoredDm.dm).toBe(true);
  });

  it.each(["unknown-version", "duplicate-bot", "cycle", "dangling-room", "dangling-task", "duplicate-chief", "oversized-soul"])("rejects %s before any writes", (corruption) => {
    const { store, routines } = fixture();
    const backup = createTeamBackup(store, routines.listRoutines(), "My team");
    const before = readFileSync(join(DATA_DIR, "bots.json"), "utf8");
    const groupsBefore = readFileSync(join(DATA_DIR, "groups.json"), "utf8");
    const source = backup.bots.find((bot) => bot.name === "Mira")!;
    if (corruption === "unknown-version") Object.assign(backup, { version: 2 });
    if (corruption === "duplicate-bot") backup.bots.push(source);
    if (corruption === "cycle") source.tasks[0].messages[0].parentId = source.tasks[0].messages[0].id;
    if (corruption === "dangling-room") backup.groups[0].memberIds.push("missing");
    if (corruption === "dangling-task") source.activeTask = "missing";
    if (corruption === "duplicate-chief") backup.bots.find((bot) => bot.name === "Scout")!.chiefOfStaff = true;
    if (corruption === "oversized-soul") source.soul = "🐭".repeat(6_001);
    expect(() => importTeamBackup(store, routines, backup, selection())).toThrow("Invalid backup");
    expect(readFileSync(join(DATA_DIR, "bots.json"), "utf8")).toBe(before);
    expect(readFileSync(join(DATA_DIR, "groups.json"), "utf8")).toBe(groupsBefore);
  });

  it("accepts legacy backups without soul and enforces its UTF-8 byte cap", () => {
    const { store, routines } = fixture();
    const backup = createTeamBackup(store, routines.listRoutines(), "Legacy team");
    for (const bot of backup.bots) delete bot.soul;
    expect(importTeamBackup(store, routines, backup, selection()).bots.every((bot) => bot.soul === "")).toBe(true);
    backup.bots[0].soul = "🐭".repeat(6_000);
    expect(parseTeamBackup(backup).bots[0].soul).toBe(backup.bots[0].soul);
    backup.bots[0].soul += "!";
    expect(() => parseTeamBackup(backup)).toThrow("24000 bytes");
  });

  it("strips injected permissions, IDs and live actions from untrusted files", () => {
    const { store, routines, chief } = fixture();
    const backup = createTeamBackup(store, routines.listRoutines(), "My team");
    const source = backup.bots.find((bot) => bot.name === "Mira")!;
    Object.assign(source, { id: chief.id, threadId: chief.threadId, cwd: "/tmp", composio: true, approvalMode: "full", autoApprove: true, browser: true, computer: "local", resumeCursors: { fixture: "secret-session" } });
    Object.assign(source.tasks[0].messages[0], { kind: "options", queued: true, card: { requestId: "live-approval" }, attachments: [{ path: "/etc/passwd" }] });
    const imported = importTeamBackup(store, routines, backup, selection()).bots.find((bot) => bot.name === "Mira 2")!;
    expect(imported.id).not.toBe(chief.id);
    expect(imported.threadId).not.toBe(chief.threadId);
    expect(imported.approvalMode).toBeUndefined();
    expect(approvalModeFor(imported)).toBe("full");
    expect(JSON.stringify(parseTeamBackup(backup))).not.toMatch(/live-approval|secret-session|\/etc\/passwd|approvalMode/);
  });

  it("rolls back fresh bots, rooms and transcripts after a late failure", () => {
    const { store, routines } = fixture();
    const beforeSections = [...store.sections];
    const backup = createTeamBackup(store, routines.listRoutines(), "My team");
    const before = createTeamBackup(store, routines.listRoutines(), "My team");
    const write = vi.spyOn(routines, "create").mockImplementationOnce(() => { throw new Error("fixture disk failure"); });
    expect(() => importTeamBackup(store, routines, backup, selection())).toThrow("fixture disk failure");
    write.mockRestore();
    const after = createTeamBackup(new Store(selection), routines.listRoutines(), "My team");
    expect({ ...after, exportedAt: 0 }).toEqual({ ...before, exportedAt: 0 });
    expect(new Store(selection).sections).toEqual(beforeSections);
  });

  it("refuses to populate a thread that already has history", () => {
    const { store, chief } = fixture();
    const before = structuredClone(store.messagesFor(chief.threadId));
    expect(() => store.importTranscript(chief.threadId, [], null)).toThrow("existing conversation");
    expect(store.messagesFor(chief.threadId)).toEqual(before);
  });

  it("also rolls back a creation that throws before returning its new record", () => {
    const { store, routines } = fixture();
    const beforeSections = [...store.sections];
    const backup = createTeamBackup(store, routines.listRoutines(), "My team");
    const before = structuredClone(store.bots);
    const create = store.createBot.bind(store);
    const fail = vi.spyOn(store, "createBot").mockImplementationOnce((...args) => {
      create(...args);
      throw new Error("creation failed before returning");
    });
    expect(() => importTeamBackup(store, routines, backup, selection())).toThrow("creation failed");
    fail.mockRestore();
    expect(store.bots).toEqual(before);
    expect(new Store(selection).bots.map((bot) => bot.id)).toEqual(before.map((bot) => bot.id));
    expect(new Store(selection).sections).toEqual(beforeSections);
  });

  it("keeps case-distinct sections and their Chiefs separate", () => {
    const { store, routines } = fixture();
    const second = store.createBot({ name: "Another chief", section: "engineering" }, { seedMessages: false });
    store.setChiefOfStaff(second.id);
    const imported = importTeamBackup(store, routines, createTeamBackup(store, routines.listRoutines(), "My team"), selection());
    const chief = imported.bots.find((bot) => bot.name === "Mira 2")!;
    const other = imported.bots.find((bot) => bot.name === "Another chief 2")!;
    expect(chief.chiefOfStaff).toBe(true);
    expect(other.chiefOfStaff).toBe(true);
    expect(chief.section?.toLowerCase()).not.toBe(other.section?.toLowerCase());
    const reloaded = new Store(selection);
    expect(reloaded.bot(chief.id)?.chiefOfStaff).toBe(true);
    expect(reloaded.bot(other.id)?.chiefOfStaff).toBe(true);
  });

  it("backs a widget up as its text fallback and restores it as plain text, with the answer still a reply to it", () => {
    const { store, routines, scout } = fixture();
    const shown = createAgentCard({ store, bot: scout, threadId: scout.threadId, input: { tool: "show_widget", widget: WIDGET_SAMPLES.spendTable } });
    if (!shown.ok) throw new Error(shown.error);
    store.appendMessage(scout.threadId, { role: "user", kind: "text", text: "Looks right", replyToId: shown.messageId });
    const fallback = "**Spend by bot** · Last 7 days · $42.10\nBot | Runs | Cost\nScout | 38 | $21.40\nChief of Staff | 7 | $9.85\nKiwi | 52 | $6.35\nJev | 11 | $4.50";
    const backup = createTeamBackup(store, routines.listRoutines(), "My team");
    const saved = backup.bots.find((bot) => bot.key === scout.id)!.tasks[0].messages;
    expect(saved.map((message) => [message.role, message.text])).toEqual([["bot", fallback], ["user", "Looks right"]]);
    expect(JSON.stringify(saved)).not.toContain("Table.Row");
    const restored = importTeamBackup(store, routines, JSON.parse(JSON.stringify(backup)), selection());
    const [card, answer] = store.messagesFor(restored.bots.find((bot) => bot.name === "Scout 2")!.threadId);
    expect(card).toMatchObject({ role: "bot", kind: "text", text: fallback });
    expect(card).not.toHaveProperty("widget");
    expect(answer).toMatchObject({ role: "user", kind: "text", text: "Looks right", replyToId: card.id });
  });

  it("backs up room history even when old deletions left dangling memberships and routines", () => {
    const { store, routines, chief, scout, group } = fixture();
    const dm = store.createGroup("Old direct message", [chief.id, scout.id], true);
    store.appendMessage(dm.threadId, { role: "bot", kind: "text", text: "Keep this old reply", from: { botId: chief.id, name: chief.name, color: chief.color } });
    store.deleteBot(chief.id);
    // Recreate the pre-repair records this legacy-export regression covers.
    Object.assign(group, { memberIds: [chief.id, scout.id], defaultResponder: { kind: "member", botId: chief.id } });
    const backup = createTeamBackup(store, routines.listRoutines(), "My team");
    expect(backup.warnings).toHaveLength(4);
    expect(backup.routines).toEqual([]);
    expect(backup.groups.find((room) => room.key === group.id)).toMatchObject({ memberIds: [scout.id], defaultResponder: { kind: "mentions" } });
    expect(backup.groups.find((room) => room.key === dm.id)?.dm).toBe(false);
    const restored = importTeamBackup(store, routines, backup, selection());
    const restoredDm = restored.groups.find((room) => room.name === "Old direct message 2")!;
    expect(store.messagesFor(restoredDm.threadId)[0]).toMatchObject({ text: "Mira:\nKeep this old reply" });
    expect(store.group(group.id)?.memberIds).toEqual([chief.id, scout.id]);
  });
});