Skip to content

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

99.3 KB
Raw Blame
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";

import { afterEach, describe, expect, it, vi } from "vitest";

import {
  RoutineRequestError,
  RoutineRequestService,
  consequenceLine,
  routineRequestFingerprint,
  type RoutineProposalInput,
  type RoutineRequestMessage,
  type RoutineRequestOptionCard,
  type RoutineRequestStore,
  type RoutineToolDefinitionInput,
} from "./routine-requests.ts";
import { RoutineManager, type RoutineInput } from "./routines.ts";
import { routineRequestCardDataSchema } from "./routine-request-schemas.ts";
import type { JsonValue } from "./schema.ts";
import "./server-line-packs.ts";
import { setConversationLanguage } from "./server-lines.ts";
import { directApply, type DirectApplyCheck } from "./direct-apply.ts";

class MemoryStore implements RoutineRequestStore {
  readonly threads = new Map<string, RoutineRequestMessage[]>();
  private sequence = 0;

  messagesFor(threadId: string): RoutineRequestMessage[] {
    return this.threads.get(threadId) ?? [];
  }

  appendMessage(
    threadId: string,
    message: { role: "bot"; kind: "options"; card: RoutineRequestOptionCard },
  ): RoutineRequestMessage {
    const stored = { id: `message-${++this.sequence}`, card: message.card };
    const messages = this.threads.get(threadId) ?? [];
    messages.push(stored);
    this.threads.set(threadId, messages);
    return stored;
  }

  patchMessage(
    threadId: string,
    messageId: string,
    patch: { card: RoutineRequestOptionCard },
  ): RoutineRequestMessage | null {
    const message = this.messagesFor(threadId).find((candidate) => candidate.id === messageId);
    if (!message) return null;
    message.card = patch.card;
    return message;
  }
}

const tempDirs: string[] = [];
afterEach(() => {
  setConversationLanguage(() => undefined);
  for (const dir of tempDirs.splice(0)) rmSync(dir, { recursive: true, force: true });
});

function harness(
  start = Date.parse("2026-08-28T10:00:00Z"),
  cloudReady?: (botId: string) => Promise<{ ready: boolean; reason?: string }>,
  canPersist?: (
    botId: string,
    threadId: string,
    opensCard: boolean,
  ) => { ok: true } | { ok: false; status: number; error: string },
  autoApply?: DirectApplyCheck,
) {
  const clock = { now: start };
  const dir = mkdtempSync(join(tmpdir(), "omb-routine-request-"));
  tempDirs.push(dir);
  const routines = new RoutineManager({
    file: join(dir, "routines.json"),
    now: () => clock.now,
    botState: (botId) => (botId === "missing" ? "missing" : "busy"),
    goalState: () => "busy",
    createTask: () => null,
    startTurn: async () => {},
  });
  const store = new MemoryStore();
  const service = new RoutineRequestService({
    store,
    routines,
    now: () => clock.now,
    timeZone: () => "Asia/Kolkata",
    cloudReady,
    canPersist,
    autoApply,
  });
  return { clock, routines, service, store };
}

function createProposal(overrides: Partial<RoutineToolDefinitionInput> = {}): RoutineProposalInput {
  return {
    action: "create",
    routine: {
      name: "Morning brief",
      instructions: "Summarize the overnight support queue.",
      schedule: { type: "weekly", time: "09:00", weekdays: ["monday", "wednesday"] },
      ...overrides,
    },
  };
}

function malformedProposal(value: JsonValue): RoutineProposalInput {
  // SAFETY: deliberately malformed to exercise the runtime Zod boundary.
  return value as RoutineProposalInput;
}

function cardFingerprint(card: RoutineRequestOptionCard, messageId: string): string {
  if (!card.routineRequest) throw new Error("missing routine request payload");
  return routineRequestFingerprint(card.routineRequest, messageId);
}

describe("RoutineRequestService", () => {
  it("refuses instruction replacement after redaction without saving a card or changing other fields", async () => {
    const { routines, service, store } = harness();
    const prompt = "Review the queue.\n".repeat(180) + "Use sk-ant-api03-abcdefghijklmnopqrstuvwxyz0123456789.";
    const saved = routines.create({ name: "Private instructions", prompt, botId: "bot-a", target: "bot", runOn: "maus", enabled: false,
      durationMinutes: 30, schedule: { type: "interval", everyMinutes: 60, anchorAt: Date.now() + 3_600_000 } });
    const submit = (changes: unknown) => service.submit({ botId: "bot-a", threadId: "thread-a", proposal: { action: "update", routineId: saved.id, changes } });
    const before = structuredClone(routines.listRoutines());
    await expect(submit({ name: "Must not apply", instructions: "Only the visible text." })).rejects.toMatchObject({ status: 409 });
    expect(routines.listRoutines()).toEqual(before);
    expect(store.messagesFor("thread-a")).toHaveLength(0);
    await submit({ name: "Safe rename" });
    expect(routines.listRoutines()[0]).toMatchObject({ name: "Safe rename", prompt });
  });

  describe("duplicate creation", () => {
    const existingInput: RoutineInput = {
      botId: "bot-a", name: "Already scheduled", prompt: "Summarize the overnight support queue.",
      schedule: { type: "daily", time: "09:00", weekdays: [1, 3] },
    };

    it("refuses a renamed duplicate before creating another approval card", async () => {
      const { service, routines, store } = harness();
      const existing = routines.create(existingInput);
      await expect(service.propose({ botId: "bot-a", threadId: "thread-a", proposal: createProposal() }))
        .rejects.toMatchObject({ status: 409, message: expect.stringContaining(existing.id) });
      expect(store.messagesFor("thread-a")).toHaveLength(0);
      expect(routines.listRoutines()).toHaveLength(1);
    });

    it("rechecks two pending cards at confirmation and leaves replay settlement working", async () => {
      const { service, routines, store } = harness();
      const first = await service.propose({ botId: "bot-a", threadId: "thread-a", proposal: createProposal() });
      const second = await service.propose({ botId: "bot-a", threadId: "thread-b", proposal: createProposal() });
      const resolve = (threadId: string, requestId: string) => service.resolve({ botId: "bot-a", threadId, requestId, behavior: "allow" });
      expect(resolve("thread-a", first.requestId)).toMatchObject({ state: "applied" });
      expect(resolve("thread-b", second.requestId)).toMatchObject({ state: "invalid", status: 409 });
      expect(resolve("thread-a", first.requestId)).toMatchObject({ state: "already_settled" });
      expect(service.resolve({ botId: "bot-a", threadId: "thread-b", requestId: second.requestId, behavior: "deny" }))
        .toMatchObject({ claimed: true, state: "invalid", status: 409 });
      expect(store.messagesFor("thread-b")[0]!.card).toMatchObject({ expired: true, options: [] });
      expect(routines.listRoutines()).toHaveLength(1);
    });

    it.each<Partial<RoutineInput>>([
      { enabled: false }, { botId: "bot-b" }, { target: "room-goal", groupId: "room-a" },
      { runOn: "cloud" }, { continuity: true }, { sameConversation: true }, { timeoutMinutes: 10 }, { durationMinutes: 60 }, { overlap: "queue" },
      { runOnStartup: true },
      { schedule: { type: "daily", time: "10:00", weekdays: [1, 3] } },
      { attachments: [{ id: "context", name: "Context", path: "/fixture/context.txt", kind: "file", size: 20 }] },
    ])("does not confuse different execution settings with a duplicate: %j", async (patch) => {
      const { service, routines } = harness();
      routines.create({ ...existingInput, ...patch });
      await expect(service.propose({ botId: "bot-a", threadId: "thread-a", proposal: createProposal() }))
        .resolves.toMatchObject({ requestId: expect.any(String) });
    });

    it.each([
      ["Notify when balance < -10", "Notify when balance > 10"],
      ["Inspect C++", "Inspect C"],
      ["Read /work/A.txt", "Read /work/a.txt"],
    ])("preserves meaningful instruction text: %s / %s", async (existing, proposed) => {
      const { service, routines } = harness();
      routines.create({ ...existingInput, prompt: existing });
      await expect(service.propose({ botId: "bot-a", threadId: "thread-a", proposal: createProposal({ instructions: proposed }) }))
        .resolves.toMatchObject({ requestId: expect.any(String) });
    });

    it("matches implicit interval starts without ignoring an explicitly chosen phase or restrictions", async () => {
      const { service, routines, clock } = harness();
      const anchorAt = clock.now;
      routines.create({ ...existingInput, schedule: { type: "interval", everyMinutes: 60, anchorAt } });
      clock.now += 30_000;
      const propose = (schedule: RoutineToolDefinitionInput["schedule"]) => service.propose({
        botId: "bot-a", threadId: "thread-a", proposal: createProposal({ schedule }),
      });
      await expect(propose({ type: "interval", everyMinutes: 60 })).rejects.toMatchObject({ status: 409 });
      await expect(propose({ type: "interval", everyMinutes: 60, anchorAt: new Date(anchorAt).toISOString() }))
        .rejects.toMatchObject({ status: 409 });
      await expect(propose({ type: "interval", everyMinutes: 60, anchorAt: new Date(clock.now).toISOString() }))
        .resolves.toMatchObject({ requestId: expect.any(String) });
      await expect(propose({ type: "interval", everyMinutes: 60, weekdays: ["monday"] }))
        .resolves.toMatchObject({ requestId: expect.any(String) });
    });

    it("checks the target bot rather than the bot proposing work for a peer", async () => {
      const { service, routines } = harness();
      routines.create({ ...existingInput, botId: "bot-b" });
      const proposal = createProposal();
      if (proposal.action !== "create") throw new Error("Expected create");
      await expect(service.propose({ botId: "bot-a", threadId: "thread-a", proposal: {
        ...proposal, forBot: { botId: "bot-b", name: "Peer" },
      } })).rejects.toMatchObject({ status: 409 });
    });

    it("does not create repeated Full Access schedules", async () => {
      const { service, routines } = harness(undefined, undefined, undefined, () => "full-access");
      const args = { botId: "bot-a", threadId: "thread-a", proposal: createProposal() };
      expect(await service.submit(args)).toMatchObject({ state: "applied" });
      await expect(service.submit(args)).rejects.toMatchObject({ status: 409 });
      expect(routines.listRoutines()).toHaveLength(1);
    });
  });

  it("applies Full Access routine actions using only the source thread grant and settles replay receipts", async () => {
    const autoApply = vi.fn((_botId: string, threadId: string, _target: string) => (threadId === "full-thread" ? "full-access" as const : null));
    const { service, routines, store } = harness(undefined, undefined, undefined, autoApply);
    const appended: RoutineRequestOptionCard[] = [];
    const append = store.appendMessage.bind(store);
    vi.spyOn(store, "appendMessage").mockImplementation((threadId, message) => {
      appended.push(structuredClone(message.card));
      return append(threadId, message);
    });
    // No grant still applies (Triggers v2): the grant only names why, for the decision log.
    const ask = await service.submit({ botId: "bot-a", threadId: "ask-thread", proposal: createProposal({ instructions: "From the Ask thread." }) });
    expect(ask).toMatchObject({ state: "applied", result: { action: "create" } });
    expect(ask).not.toHaveProperty("appliedBy");
    expect(routines.listRoutines()).toHaveLength(1);
    expect(appended[0]).toMatchObject({ options: [], dismissed: true });

    const submit = (proposal: RoutineProposalInput) => service.submit({ botId: "bot-a", threadId: "full-thread", proposal });
    const created = await submit(createProposal());
    expect(created).toMatchObject({ state: "applied", result: { action: "create" } });
    const routineId = created.result!.resultId;
    expect(routines.listRoutines()).toHaveLength(2);
    expect(await submit({ action: "update", routineId, changes: { name: "Updated brief" } }))
      .toMatchObject({ state: "applied", result: { action: "update", resultId: routineId } });
    expect(routines.listRoutines().find((routine) => routine.id === routineId)?.name).toBe("Updated brief");
    expect(await submit({ action: "pause", routineId })).toMatchObject({ state: "applied" });
    expect(routines.listRoutines().find((routine) => routine.id === routineId)?.enabled).toBe(false);
    expect(await submit({ action: "resume", routineId })).toMatchObject({ state: "applied" });
    const run = await submit({ action: "run_now", routineId });
    expect(run).toMatchObject({ state: "applied", result: { action: "run_now" } });
    expect(routines.listRuns()).toHaveLength(1);
    expect(service.resolve({ botId: "bot-a", threadId: "full-thread", requestId: run.requestId, behavior: "allow" }))
      .toMatchObject({ state: "already_settled", behavior: "allow" });
    expect(routines.listRuns()).toHaveLength(1);
    expect(await submit({ action: "delete", routineId })).toMatchObject({ state: "applied" });
    expect(routines.listRoutines().find((routine) => routine.id === routineId)).toBeUndefined();
    expect(appended.every((card) => card.dismissed && card.options.length === 0)).toBe(true);
    expect(store.messagesFor("full-thread").every((message) => message.card?.answered === "allow")).toBe(true);
    expect(autoApply).toHaveBeenLastCalledWith("bot-a", "full-thread", "bot-a");
  });

  it("reads the grant after cloud readiness for the log, applies either way, and preserves scope validation", async () => {
    let full = true;
    const { service, routines, store } = harness(undefined, async () => {
      full = false;
      return { ready: true };
    }, undefined, () => (full ? "full-access" : null));
    const changed = await service.submit({ botId: "bot-a", threadId: "thread-a", proposal: createProposal({ runOn: "cloud", instructions: "On the cloud computer." }) });
    expect(changed.state).toBe("applied");
    expect(changed).not.toHaveProperty("appliedBy");
    expect(routines.listRoutines()).toHaveLength(1);
    expect(store.messagesFor("thread-a")[0]?.card?.dismissed).toBe(true);
    full = true;
    const own = await service.submit({ botId: "bot-a", threadId: "thread-a", proposal: createProposal() });
    await expect(service.submit({ botId: "bot-b", threadId: "thread-b", proposal: { action: "delete", routineId: own.result!.resultId } }))
      .rejects.toThrow();
    expect(routines.listRoutines()).toHaveLength(2);
    expect(store.messagesFor("thread-b")).toHaveLength(0);
    await expect(service.submit({ botId: "bot-a", threadId: "thread-a", proposal: createProposal({ instructions: "A different cancelled request." }), canCommit: () => false }))
      .rejects.toThrow("requesting turn ended");
  });

  it("reports a committed Full Access routine even if receipt settlement fails and never runs it twice", async () => {
    const { service, routines, store } = harness(undefined, undefined, undefined, () => "full-access");
    const created = await service.submit({ botId: "bot-a", threadId: "thread-a", proposal: createProposal() });
    const settle = vi.spyOn(store, "patchMessage").mockImplementation(() => { throw new Error("receipt write failed"); });
    const run = await service.submit({ botId: "bot-a", threadId: "thread-a", proposal: { action: "run_now", routineId: created.result!.resultId } });
    expect(run).toMatchObject({ state: "applied", result: { action: "run_now", settlementPending: true } });
    expect(routines.listRuns()).toHaveLength(1);
    expect(store.messagesFor("thread-a").at(-1)?.card).toMatchObject({ dismissed: true, options: [] });
    settle.mockRestore();
    expect(service.resolve({ botId: "bot-a", threadId: "thread-a", requestId: run.requestId, behavior: "allow" }))
      .toMatchObject({ state: "applied", resultId: run.result!.resultId });
    expect(routines.listRuns()).toHaveLength(1);
    expect(routines.routineRequestReceipt(run.requestId)).toBeNull();
  });

  it("does not report Full Access success when the scheduler commit fails", async () => {
    const { service, routines, store } = harness(undefined, undefined, undefined, () => "full-access");
    vi.spyOn(routines, "create").mockImplementationOnce(() => { throw new Error("scheduler write failed"); });
    await expect(service.submit({ botId: "bot-a", threadId: "thread-a", proposal: createProposal() }))
      .rejects.toThrow("scheduler write failed");
    expect(routines.listRoutines()).toHaveLength(0);
    expect(store.messagesFor("thread-a")[0]?.card).toMatchObject({ dismissed: true, options: [] });
  });

  it("writes a cron schedule in the conversation person's language", async () => {
    setConversationLanguage((threadId) => threadId === "thread-a" ? "pt-br" : undefined);
    const { service, store } = harness();
    const schedule = { type: "cron" as const, expression: "0 9 * * 6#L", timeZone: "UTC" };
    await service.propose({ botId: "bot-a", threadId: "thread-a", proposal: createProposal({ schedule }) });
    expect(store.messagesFor("thread-a")[0]!.card?.subtitle).toContain("Schedule: Todo mês no último sábado às 09:00 UTC · Cron: 0 9 * * 6#L");
  });

  it("keeps a monthly cron rule and its own timezone through confirmation, update, pause and resume", async () => {
    const { service, store, routines, clock } = harness(Date.parse("2026-08-28T10:00:00Z"));
    const schedule = { type: "cron" as const, expression: "0 9 1 * *", timeZone: "America/New_York" };
    const proposed = await service.propose({
      botId: "bot-a", threadId: "thread-a",
      proposal: createProposal({ name: "Monthly report", schedule: { ...schedule, expression: " 0  9 1 * * " } }),
    });
    expect(routines.listRoutines()).toHaveLength(0);
    expect(proposed.timeZone).toBe("America/New_York");
    expect(proposed.summary).toContain("0 9 1 * *");
    expect(proposed.summary).toContain("Monthly on day 1 at 9:00 Eastern time");
    expect(`${proposed.summary}\n${proposed.detail}`).not.toContain("America/New_York");
    expect(proposed.detail).toContain("Next 3 runs (Eastern time): Sep 1, 2026, 9:00 AM · Oct 1, 2026, 9:00 AM · Nov 1, 2026, 9:00 AM");
    expect(proposed.nextRunAt).toBe(Date.parse("2026-09-01T13:00:00Z"));
    const message = store.messagesFor("thread-a")[0]!;
    message.card = JSON.parse(JSON.stringify(message.card)) as RoutineRequestOptionCard;
    expect(message.card.routineRequest).toMatchObject({ version: 1, operation: { routine: { schedule } } });
    expect(service.resolve({ botId: "bot-a", threadId: "thread-a", requestId: proposed.requestId, behavior: "allow" }))
      .toMatchObject({ state: "applied", action: "create" });
    const routineId = routines.listRoutines()[0]!.id;
    expect(routines.listRoutines()[0]).toMatchObject({ schedule, enabled: true, nextRunAt: proposed.nextRunAt });
    const apply = async (proposal: RoutineProposalInput) => {
      clock.now += 1;
      const card = await service.propose({ botId: "bot-a", threadId: "thread-a", proposal });
      expect(service.resolve({ botId: "bot-a", threadId: "thread-a", requestId: card.requestId, behavior: "allow" }).state).toBe("applied");
      return card;
    };
    const lastDay = { ...schedule, expression: "0 9 L * *" };
    const update = await apply({ action: "update", routineId, changes: { schedule: lastDay } });
    expect(update.detail).toContain("Aug 31, 2026, 9:00 AM");
    expect(routines.listRoutines()[0]!.schedule).toEqual(lastDay);
    const paused = await apply({ action: "pause", routineId });
    expect(paused.detail).not.toContain("Next 3 runs");
    expect(routines.listRoutines()[0]).toMatchObject({ schedule: lastDay, enabled: false, nextRunAt: null });
    const whilePaused = await apply({ action: "update", routineId, changes: { schedule: { ...schedule, expression: "0 9 * * MON#2" } } });
    expect(whilePaused.detail).toContain("remains paused");
    expect(whilePaused.detail).not.toContain("Next 3 runs");
    const resumed = await apply({ action: "resume", routineId });
    expect(resumed.detail).toContain("Sep 14, 2026, 9:00 AM");
    expect(routines.listRoutines()[0]).toMatchObject({ enabled: true, nextRunAt: Date.parse("2026-09-14T13:00:00Z") });
  });

  it.each<Record<string, JsonValue>>([
    { expression: "0 9 1 * *" },
    { expression: "0 9 1 * *", timeZone: "+05:30" },
    { expression: "0 9 1 * *", timeZone: "Mars/Olympus" },
    { expression: "0 0 9 1 * *", timeZone: "UTC" },
    { expression: "@monthly", timeZone: "UTC" },
    { expression: "0 9 31 2 *", timeZone: "UTC" },
    { expression: "0 9 1 * *", timeZone: "UTC", weekdays: ["monday"] },
  ])("refuses invalid or extra cron constraints before saving a card: %j", async (schedule) => {
    const { service, store, routines } = harness();
    await expect(service.propose({ botId: "bot-a", threadId: "thread-a", proposal: malformedProposal({
      action: "create", routine: { name: "Bad schedule", instructions: "Do not run", schedule: { type: "cron", ...schedule } },
    }) })).rejects.toMatchObject({ status: 400 });
    expect(store.messagesFor("thread-a")).toHaveLength(0);
    expect(routines.listRoutines()).toHaveLength(0);
  });

  it("revalidates a corrupted stored cron card without creating a routine", async () => {
    const { service, store, routines } = harness();
    const proposed = await service.propose({ botId: "bot-a", threadId: "thread-a", proposal: createProposal({
      schedule: { type: "cron", expression: "0 9 1 * *", timeZone: "UTC" },
    }) });
    const card = store.messagesFor("thread-a")[0]!.card!;
    const operation = card.routineRequest!.operation;
    if (operation.action !== "create") throw new Error("Expected create");
    Object.assign(operation.routine.schedule, { expression: "0 9 31 2 *" });
    expect(service.resolve({ botId: "bot-a", threadId: "thread-a", requestId: proposed.requestId, behavior: "allow" }))
      .toMatchObject({ state: "invalid", status: 400 });
    expect(routines.listRoutines()).toHaveLength(0);
    expect(card.answered).toBeUndefined();
  });

  it("normalizes weekly input, scrubs hidden payload text, and creates a durable confirmation card", async () => {
    const { service, store, routines } = harness();
    const secret = "sk-proj-abcdefghijklmnopqrstuv";
    const proposed = await service.propose({
      botId: "bot-a",
      threadId: "thread-a",
      proposal: createProposal({ instructions: `Use ${secret} to prepare the brief.` }),
    });

    expect(routines.listRoutines()).toHaveLength(0);
    expect(proposed.timeZone).toBe("Asia/Kolkata");
    expect(proposed.summary).toContain("Monday, Wednesday at 9:00 India time");
    expect(proposed.summary).not.toContain("Asia/Kolkata");
    const card = store.messagesFor("thread-a")[0]!.card!;
    expect(card.requestId).toBe(proposed.requestId);
    expect(card.tool).toBe("schedule_routine");
    expect(card.options).toEqual(["Confirm", "Cancel"]);
    expect(card.routineRequest?.operation).toMatchObject({
      action: "create",
      routine: { schedule: { type: "daily", time: "09:00", weekdays: [1, 3] } },
    });
    expect(JSON.stringify(card)).not.toContain(secret);
    expect(JSON.stringify(card)).toContain("redacted");
  });

  it("carries same_conversation from the proposal through the card to the created routine", async () => {
    const { service, store, routines } = harness();
    const proposed = await service.propose({ botId: "bot-a", threadId: "thread-a", proposal: createProposal({ sameConversation: true }) });
    expect(proposed.detail).toContain("Continuity: Each run continues the previous run's conversation");
    expect(proposed.detail).toContain("each run continues the previous run's conversation.");
    expect(store.messagesFor("thread-a")[0]!.card!.routineRequest?.operation).toMatchObject({ action: "create", routine: { sameConversation: true } });
    expect(service.resolve({ botId: "bot-a", threadId: "thread-a", requestId: proposed.requestId, behavior: "allow" }).state).toBe("applied");
    expect(routines.listRoutines().find((routine) => routine.name === "Morning brief")?.sameConversation).toBe(true);
  });

  it("carries continuity from the proposal through the card to the created routine", async () => {
    const { service, store, routines } = harness();

    const plain = await service.propose({
      botId: "bot-a",
      threadId: "thread-plain",
      proposal: createProposal(),
    });
    expect(plain.detail).toContain("Continuity: Each run starts fresh");

    const proposed = await service.propose({
      botId: "bot-a",
      threadId: "thread-a",
      proposal: createProposal({ continuity: true }),
    });
    expect(proposed.detail).toContain("Continuity: Carries the previous run's report into the next run");

    const card = store.messagesFor("thread-a")[0]!.card!;
    expect(card.routineRequest?.operation).toMatchObject({
      action: "create",
      routine: { continuity: true },
    });

    const result = service.resolve({
      botId: "bot-a",
      threadId: "thread-a",
      requestId: proposed.requestId,
      behavior: "allow",
    });
    expect(result.state).toBe("applied");
    expect(routines.listRoutines().find((routine) => routine.name === "Morning brief")?.continuity).toBe(true);
  });

  it("carries run on startup from the proposal through the card to the created routine", async () => {
    const { service, store, routines } = harness();
    const plain = await service.propose({ botId: "bot-a", threadId: "thread-plain", proposal: createProposal() });
    expect(plain.detail).not.toContain("On startup:");

    const proposed = await service.propose({ botId: "bot-a", threadId: "thread-a", proposal: createProposal({ runOnStartup: true }) });
    expect(proposed.detail).toContain("On startup: Also runs once each time OpenMausBot starts");
    expect(store.messagesFor("thread-a")[0]!.card!.routineRequest?.operation).toMatchObject({ action: "create", routine: { runOnStartup: true } });
    expect(service.resolve({ botId: "bot-a", threadId: "thread-a", requestId: proposed.requestId, behavior: "allow" }).state).toBe("applied");
    const routine = routines.listRoutines().find((candidate) => candidate.name === "Morning brief")!;
    expect(routine.runOnStartup).toBe(true);

    const off = await service.propose({ botId: "bot-a", threadId: "thread-b", proposal: { action: "update", routineId: routine.id, changes: { runOnStartup: false } } });
    expect(off.detail).toContain("On startup: Runs only on its schedule");
    expect(service.resolve({ botId: "bot-a", threadId: "thread-b", requestId: off.requestId, behavior: "allow" }).state).toBe("applied");
    expect(routines.listRoutines().find((candidate) => candidate.id === routine.id)?.runOnStartup).toBeUndefined();
  });

  it("refuses run on startup for a one-time routine", async () => {
    const { service, routines } = harness();
    await expect(service.propose({
      botId: "bot-a", threadId: "thread-a",
      proposal: createProposal({ runOnStartup: true, schedule: { type: "once", at: "2026-08-29T09:00:00Z" } }),
    })).rejects.toThrow("Only a repeating routine");
    const once = routines.create({ botId: "bot-a", name: "Once", prompt: "Once.", schedule: { type: "once", at: Date.parse("2026-08-29T09:00:00Z") } });
    await expect(service.propose({ botId: "bot-a", threadId: "thread-a", proposal: { action: "update", routineId: once.id, changes: { runOnStartup: true } } }))
      .rejects.toThrow("Only a repeating routine");
  });

  it("reviews and persists queue policy changes without losing them in tool normalization", async () => {
    const { service, routines } = harness();
    const created = await service.propose({ botId: "bot-a", threadId: "thread-a", proposal: createProposal({ overlap: "queue" }) });
    expect(created.detail).toContain("Queue one scheduled run; skip further occurrences");
    service.resolve({ botId: "bot-a", threadId: "thread-a", requestId: created.requestId, behavior: "allow" });
    const routine = routines.listRoutines()[0];
    expect(routine.overlap).toBe("queue");
    const update = await service.propose({ botId: "bot-a", threadId: "thread-a", proposal: { action: "update", routineId: routine.id, changes: { overlap: "skip" } } });
    expect(update.detail).toContain("Skip overlapping scheduled occurrences");
    service.resolve({ botId: "bot-a", threadId: "thread-a", requestId: update.requestId, behavior: "allow" });
    expect(routines.listRoutines()[0].overlap).toBeUndefined();
  });

  it("canonicalizes receipt fingerprints and binds them to the card's conversation", async () => {
    const { service, store } = harness();
    await service.propose({ botId: "bot-a", threadId: "thread-a", proposal: createProposal() });
    const messageId = store.messagesFor("thread-a")[0]!.id;
    const original = store.messagesFor("thread-a")[0]!.card!.routineRequest!;
    if (original.operation.action !== "create") throw new Error("Expected a create proposal");
    const routine = original.operation.routine;
    const reordered: typeof original = {
      operation: {
        routine: {
          durationMinutes: routine.durationMinutes,
          schedule: routine.schedule.type === "once"
            ? { at: routine.schedule.at, type: "once" }
            : routine.schedule.type === "interval"
              ? {
                  anchorAt: routine.schedule.anchorAt,
                  everyMinutes: routine.schedule.everyMinutes,
                  type: "interval",
                }
              : routine.schedule.type === "cron" || routine.schedule.type === "limit_reset"
                ? { ...routine.schedule }
                : { weekdays: [...routine.schedule.weekdays], time: routine.schedule.time, type: "daily" },
          instructions: routine.instructions,
          runOn: routine.runOn,
          name: routine.name,
        },
        action: "create",
      },
      createdAt: original.createdAt,
      threadId: original.threadId,
      botId: original.botId,
      requestId: original.requestId,
      version: 1,
    };

    expect(routineRequestFingerprint(reordered, messageId)).toBe(routineRequestFingerprint(original, messageId));
    expect(routineRequestFingerprint({ ...reordered, threadId: "thread-b" }, messageId))
      .not.toBe(routineRequestFingerprint(original, messageId));
    expect(routineRequestFingerprint(reordered, "another-message"))
      .not.toBe(routineRequestFingerprint(original, messageId));
  });

  it("shows the exact action, name, and complete executable instructions in the approval detail", async () => {
    const { service, store } = harness();
    const instructions = `BEGIN-${"work carefully. ".repeat(120)}-END`;
    const proposed = await service.propose({
      botId: "bot-a",
      threadId: "thread-a",
      proposal: createProposal({ name: "Full fidelity brief", instructions }),
    });
    const message = store.messagesFor("thread-a")[0]!;
    const card = message.card!;
    card.held = "Temporary persistence error";

    expect(proposed.summary).toContain("Schedule “Full fidelity brief”");
    expect(proposed.summary).not.toContain(instructions);
    expect(proposed.detail).toBe(card.subtitle);
    expect(card.subtitle).toContain("Action: Create routine");
    expect(card.subtitle).toContain("Name: Full fidelity brief");
    expect(card.subtitle).toContain(`Instructions:\n${instructions}`);
    expect(card.subtitle).toContain("-END");
  });

  it("states the run cadence consequence before Instructions for an interval routine", async () => {
    const { service, store } = harness();
    await service.propose({
      botId: "bot-a",
      threadId: "thread-a",
      proposal: createProposal({ schedule: { type: "interval", everyMinutes: 5 } }),
    });
    const card = store.messagesFor("thread-a")[0]!.card!;

    expect(card.subtitle).toContain(
      "Will run about 288 times a day; each run starts a fresh session.\n\nInstructions:",
    );
  });

  it("states the run cadence consequence for a weekday routine", async () => {
    const { service, store } = harness();
    await service.propose({
      botId: "bot-a",
      threadId: "thread-a",
      proposal: createProposal({
        schedule: {
          type: "weekly",
          time: "09:00",
          weekdays: ["monday", "tuesday", "wednesday", "thursday", "friday"],
        },
      }),
    });
    const card = store.messagesFor("thread-a")[0]!.card!;

    expect(card.subtitle).toContain(
      "Will run 5 days a week; each run starts a fresh session.\n\nInstructions:",
    );
  });

  it("states every day for a full-week routine and once for a one-time routine", async () => {
    const { service, store, clock } = harness();
    await service.propose({
      botId: "bot-a",
      threadId: "thread-a",
      proposal: createProposal({
        schedule: {
          type: "weekly",
          time: "09:00",
          weekdays: ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"],
        },
      }),
    });
    const everyDayCard = store.messagesFor("thread-a")[0]!.card!;
    expect(everyDayCard.subtitle).toContain(
      "Will run every day; each run starts a fresh session.\n\nInstructions:",
    );

    await service.propose({
      botId: "bot-a",
      threadId: "thread-b",
      proposal: createProposal({
        schedule: { type: "once", at: new Date(clock.now + 60_000).toISOString() },
      }),
    });
    const onceCard = store.messagesFor("thread-b")[0]!.card!;
    expect(onceCard.subtitle).toContain(
      "Will run once; that run starts a fresh session.\n\nInstructions:",
    );
  });

  it("recomputes the run cadence line from the routine's effective schedule, not the change set", async () => {
    const { service, store, routines } = harness();
    const created = await service.propose({
      botId: "bot-a",
      threadId: "thread-a",
      proposal: createProposal({ schedule: { type: "interval", everyMinutes: 5 } }),
    });
    expect(service.resolve({
      botId: "bot-a",
      threadId: "thread-a",
      requestId: created.requestId,
      behavior: "allow",
    })).toMatchObject({ claimed: true, state: "applied", action: "create" });
    const routineId = routines.listRoutines()[0]!.id;

    const apply = async (proposal: RoutineProposalInput) => {
      await service.propose({ botId: "bot-a", threadId: "thread-a", proposal });
      const card = store.messagesFor("thread-a").at(-1)!.card!;
      const result = service.resolve({
        botId: "bot-a",
        threadId: "thread-a",
        requestId: card.requestId!,
        behavior: "allow",
      });
      expect(result).toMatchObject({ claimed: true, state: "applied" });
      return card;
    };

    const scheduleChanged = await apply({
      action: "update",
      routineId,
      changes: { schedule: { type: "interval", everyMinutes: 60 } },
    });
    expect(scheduleChanged.subtitle).toContain(
      "Will run about 24 times a day; each run starts a fresh session.",
    );

    const nameOnly = await apply({
      action: "update",
      routineId,
      changes: { name: "Renamed brief" },
    });
    expect(nameOnly.subtitle).toContain(
      "Will run about 24 times a day; each run starts a fresh session.",
    );
  });

  it("never returns an existing routine's credential-shaped text to the proposing bot", async () => {
    const { service, routines, store } = harness();
    const secret = "sk-proj-existingroutineabcdefghijkl";
    const nameSecret = "sk-proj-existingnameabcdefghijkl";
    const routine = routines.create({
      botId: "bot-a",
      name: `Existing ${nameSecret}`,
      prompt: `Use ${secret} and then prepare the brief.`,
      schedule: { type: "daily", time: "10:00", weekdays: [1] },
    });
    const proposed = await service.propose({
      botId: "bot-a",
      threadId: "thread-a",
      proposal: { action: "run_now", routineId: routine.id },
    });

    expect(proposed.detail).not.toContain(secret);
    expect(proposed.title).not.toContain(nameSecret);
    expect(proposed.summary).not.toContain(nameSecret);
    expect(proposed.detail).not.toContain(nameSecret);
    expect(proposed.detail).toContain("redacted");
    expect(JSON.stringify(store.messagesFor("thread-a")[0]!.card)).not.toContain(secret);
    expect(JSON.stringify(store.messagesFor("thread-a")[0]!.card)).not.toContain(nameSecret);
  });

  it("rejects ambiguous, invalid, and stale one-time schedules", async () => {
    const { service, clock } = harness();
    const proposal = (at: string) =>
      service.propose({
        botId: "bot-a",
        threadId: "thread-a",
        proposal: createProposal({ schedule: { type: "once", at } }),
      });

    await expect(proposal("2026-08-29T09:00:00")).rejects.toThrow(/explicit timezone offset/);
    await expect(proposal("not-a-date")).rejects.toThrow(/explicit timezone offset/);
    await expect(proposal("2026-02-30T09:00:00Z")).rejects.toThrow(/valid RFC3339/);
    await expect(proposal(new Date(clock.now - 1).toISOString())).rejects.toThrow(/future/);
    await expect(
      service.propose({
        botId: "bot-a",
        threadId: "thread-a",
        proposal: createProposal({ durationMinutes: 4 }),
      }),
    ).rejects.toThrow("durationMinutes must be a whole number from 5 to 240");
    await expect(
      service.propose({
        botId: "bot-a",
        threadId: "thread-a",
        proposal: createProposal({ timeoutMinutes: 4 }),
      }),
    ).rejects.toThrow("timeoutMinutes must be a whole number from 5 to 1440");
    await expect(
      service.propose({
        botId: "bot-a",
        threadId: "thread-a",
        proposal: malformedProposal({
          action: "create",
          routine: {
            name: "Morning brief",
            instructions: "Do it",
            schedule: { type: "weekly", time: "09:00", weekdays: ["monday"] },
            surprise: true,
          },
        }),
      }),
    ).rejects.toThrow(/Unrecognized key.*surprise/);
    await expect(
      service.propose({
        botId: "bot-a",
        threadId: "thread-a",
        proposal: malformedProposal({
          action: "create",
          routine: {
            name: "Morning brief",
            instructions: "Do it",
            schedule: { type: "weekly", time: "09:00", weekdays: ["monday"], timezone: "UTC" },
          },
        }),
      }),
    ).rejects.toThrow(/Unrecognized key.*timezone/);
    await expect(
      service.propose({
        botId: "bot-a",
        threadId: "thread-a",
        proposal: createProposal({ name: `${"n".repeat(64)} token=abcdefgh` }),
      }),
    ).rejects.toThrow(/80 characters or fewer after credentials are removed/);
    const secretPrefix = "token=abcdefgh ";
    const secretAtLimit = `${secretPrefix}${"x".repeat(20_000 - secretPrefix.length)}`;
    await expect(
      service.propose({
        botId: "bot-a",
        threadId: "thread-a",
        proposal: createProposal({ instructions: secretAtLimit }),
      }),
    ).rejects.toThrow(/20,000 characters or fewer after credentials are removed/);
  });

  it("normalizes interval schedules with an optional cadence anchor", async () => {
    const now = Date.parse("2026-08-28T10:00:00Z");
    const { service, store, routines, clock } = harness(now);
    const proposed = await service.propose({
      botId: "bot-a",
      threadId: "thread-a",
      proposal: createProposal({
        schedule: {
          type: "interval",
          everyMinutes: 15,
          anchorAt: "2026-08-28T10:07:00Z",
          weekdays: ["monday", "friday"],
          window: { start: "09:00", end: "17:00" },
          endsAt: "2026-09-30T18:00:00Z",
        },
      }),
    });

    expect(proposed.summary).toContain("Every 15 minutes");
    expect(proposed.summary).toContain("Monday, Friday");
    expect(proposed.summary).toContain("during 9:00–17:00 India time");
    expect(proposed.summary).toContain("Sep 30, 2026");
    expect(proposed.summary).toContain("default run limit (3 hours of work)");
    expect(store.messagesFor("thread-a")[0]?.card?.routineRequest?.operation).toMatchObject({
      action: "create",
      routine: {
        schedule: {
          type: "interval",
          everyMinutes: 15,
          anchorAt: Date.parse("2026-08-28T10:07:00Z"),
          weekdays: [1, 5],
          window: { start: "09:00", end: "17:00" },
          endsAt: Date.parse("2026-09-30T18:00:00Z"),
        },
      },
    });

    expect(service.resolve({
      botId: "bot-a",
      threadId: "thread-a",
      requestId: proposed.requestId,
      behavior: "allow",
    })).toMatchObject({ claimed: true, state: "applied" });
    const restricted = routines.listRoutines().find((routine) => routine.sourceThreadId === "thread-a")!;
    expect(restricted.schedule).toMatchObject({
      type: "interval",
      anchorAt: Date.parse("2026-08-28T10:07:00Z"),
      weekdays: [1, 5],
      window: { start: "09:00", end: "17:00" },
      endsAt: Date.parse("2026-09-30T18:00:00Z"),
    });

    const clearProposal = await service.propose({
      botId: "bot-a",
      threadId: "thread-a",
      proposal: {
        action: "update",
        routineId: restricted.id,
        changes: {
          schedule: {
            type: "interval",
            everyMinutes: 15,
            weekdays: null,
            window: null,
            endsAt: null,
          },
        },
      },
    });
    expect(store.messagesFor("thread-a")[1]?.card?.routineRequest?.operation).toMatchObject({
      action: "update",
      changes: {
        schedule: { type: "interval", everyMinutes: 15, weekdays: null, window: null, endsAt: null },
      },
    });
    expect(service.resolve({
      botId: "bot-a",
      threadId: "thread-a",
      requestId: clearProposal.requestId,
      behavior: "allow",
    })).toMatchObject({ claimed: true, state: "applied" });
    const cleared = routines.listRoutines().find((routine) => routine.id === restricted.id)!;
    expect(cleared.schedule).toEqual({
      type: "interval",
      everyMinutes: 15,
      anchorAt: Date.parse("2026-08-28T10:07:00Z"),
    });

    const withoutAnchor = await service.propose({
      botId: "bot-a",
      threadId: "thread-b",
      proposal: createProposal({ schedule: { type: "interval", everyMinutes: 5 } }),
    });
    expect(withoutAnchor.nextRunAt).toBeNull();
    expect(withoutAnchor.detail).toContain("One interval after confirmation");
    expect(store.messagesFor("thread-b")[0]?.card?.routineRequest?.operation).toMatchObject({
      action: "create",
      routine: { schedule: { type: "interval", everyMinutes: 5 } },
    });
    const deferred = store.messagesFor("thread-b")[0]?.card?.routineRequest?.operation;
    if (deferred?.action !== "create") throw new Error("Expected a create operation");
    expect(deferred.routine.schedule).not.toHaveProperty("anchorAt");

    const restrictedWithoutAnchor = await service.propose({
      botId: "bot-a",
      threadId: "thread-c",
      proposal: createProposal({
        schedule: {
          type: "interval",
          everyMinutes: 15,
          weekdays: ["friday"],
          window: { start: "16:00", end: "17:00" },
        },
      }),
    });
    expect(restrictedWithoutAnchor.nextRunAt).toBeNull();
    expect(restrictedWithoutAnchor.summary).toContain(
      "cadence starting at confirmation; first run is the next allowed time",
    );
    expect(restrictedWithoutAnchor.summary).toContain("Friday (India time)");
    expect(restrictedWithoutAnchor.summary).toContain("16:00–17:00 India time");
    expect(restrictedWithoutAnchor.detail).toContain("Next allowed time after confirmation (India time)");
    expect(restrictedWithoutAnchor.detail).not.toContain("One interval after confirmation");

    clock.now = now + 7 * 60_000;
    expect(service.resolve({
      botId: "bot-a",
      threadId: "thread-b",
      requestId: withoutAnchor.requestId,
      behavior: "allow",
    })).toMatchObject({ claimed: true, state: "applied" });
    expect(routines.listRoutines().find((routine) => routine.sourceThreadId === "thread-b")).toMatchObject({
      schedule: { type: "interval", everyMinutes: 5, anchorAt: clock.now },
      nextRunAt: clock.now + 5 * 60_000,
    });

    await expect(service.propose({
      botId: "bot-a",
      threadId: "thread-c",
      proposal: createProposal({ schedule: { type: "interval", everyMinutes: 4 } }),
    })).rejects.toThrow(/5 to 1440/);
    await expect(service.propose({
      botId: "bot-a",
      threadId: "thread-c",
      proposal: createProposal({
        schedule: { type: "interval", everyMinutes: 5, anchorAt: "1969-12-31T23:59:59Z" },
      }),
    })).rejects.toThrow(/valid interval start time/);
  });

  it("rejects a cadence-only update when preserved restrictions make the merged interval invalid", async () => {
    const now = Date.parse("2026-08-28T10:00:00Z");
    const { service, store, routines } = harness(now);
    const routine = routines.create({
      botId: "bot-a",
      name: "Narrow check",
      prompt: "Check during a narrow window.",
      schedule: {
        type: "interval",
        everyMinutes: 5,
        anchorAt: now,
        window: { start: "09:00", end: "09:10" },
      },
    });

    await expect(service.propose({
      botId: "bot-a",
      threadId: "thread-a",
      proposal: {
        action: "update",
        routineId: routine.id,
        changes: { schedule: { type: "interval", everyMinutes: 15 } },
      },
    })).rejects.toThrow(/at least as long as the cadence/);
    expect(store.messagesFor("thread-a")).toHaveLength(0);
    expect(routines.listRoutines().find((candidate) => candidate.id === routine.id)?.schedule).toMatchObject({
      everyMinutes: 5,
      window: { start: "09:00", end: "09:10" },
    });
  });

  it("refuses a cloud routine before creating a card when cloud execution is not ready", async () => {
    const { service, store } = harness(undefined, async () => ({
      ready: false,
      reason: "Connect or provision a cloud computer first.",
    }));

    await expect(service.propose({
      botId: "bot-a",
      threadId: "thread-a",
      proposal: createProposal({ runOn: "cloud" }),
    })).rejects.toThrow(/Connect or provision/);
    expect(store.messagesFor("thread-a")).toHaveLength(0);
  });

  it("checks the executing bot for own, teammate and existing cloud routines", async () => {
    const checked: string[] = [];
    const { service, routines } = harness(undefined, async botId => {
      checked.push(botId);
      return { ready: botId === "bot-a", reason: "Target model unavailable" };
    });
    await service.propose({ botId: "bot-a", threadId: "thread-a", proposal: createProposal({ runOn: "cloud" }) });
    const peerProposal = createProposal({ runOn: "cloud" });
    if (peerProposal.action !== "create") throw new Error("Expected create");
    await expect(service.propose({ botId: "bot-a", threadId: "thread-a", proposal: {
      ...peerProposal, forBot: { botId: "bot-b", name: "Peer" },
    } })).rejects.toThrow("Target model unavailable");
    const routine = routines.create({ botId: "bot-a", name: "Owned cloud", prompt: "Work",
      runOn: "cloud", enabled: false, schedule: { type: "daily", time: "10:00", weekdays: [1] } });
    await service.propose({ botId: "bot-a", threadId: "thread-a", proposal: { action: "run_now", routineId: routine.id } });
    expect(checked).toEqual(["bot-a", "bot-b", "bot-a"]);
  });

  it("checks effective cloud destinations while allowing safe moves away and non-running actions", async () => {
    let checks = 0;
    const { service, routines, store } = harness(undefined, async () => {
      checks += 1;
      return { ready: false, reason: "Cloud is offline" };
    });
    const routine = routines.create({
      botId: "bot-a",
      name: "Cloud routine",
      prompt: "Use the cloud computer",
      runOn: "cloud",
      enabled: false,
      schedule: { type: "daily", time: "10:00", weekdays: [1] },
    });

    await expect(service.propose({
      botId: "bot-a",
      threadId: "thread-a",
      proposal: { action: "update", routineId: routine.id, changes: { name: "Still cloud" } },
    })).rejects.toThrow(/Cloud is offline/);
    expect(checks).toBe(1);

    await service.propose({
      botId: "bot-a",
      threadId: "thread-a",
      proposal: { action: "update", routineId: routine.id, changes: { runOn: "maus" } },
    });
    await service.propose({
      botId: "bot-a",
      threadId: "thread-a",
      proposal: { action: "pause", routineId: routine.id },
    });
    await service.propose({
      botId: "bot-a",
      threadId: "thread-a",
      proposal: { action: "delete", routineId: routine.id },
    });
    expect(checks).toBe(1);
    expect(store.messagesFor("thread-a")).toHaveLength(3);
  });

  it("does not persist a stale card when a routine changes during cloud readiness", async () => {
    let mutateDuringCheck = () => {};
    const { service, routines, store } = harness(undefined, async () => {
      mutateDuringCheck();
      return { ready: true };
    });
    const routine = routines.create({
      botId: "bot-a",
      name: "Cloud routine",
      prompt: "Original instructions",
      runOn: "cloud",
      schedule: { type: "daily", time: "10:00", weekdays: [1] },
    });
    mutateDuringCheck = () => {
      routines.update(routine.id, { prompt: "Changed while checking Cloud" });
    };

    await expect(service.propose({
      botId: "bot-a",
      threadId: "thread-a",
      proposal: { action: "run_now", routineId: routine.id },
    })).rejects.toThrow(/changed after this confirmation card/);
    expect(store.messagesFor("thread-a")).toHaveLength(0);
  });

  it("revalidates conversation ownership after an asynchronous cloud check", async () => {
    let finishCloudCheck!: (value: { ready: boolean }) => void;
    const cloudCheck = new Promise<{ ready: boolean }>((resolve) => {
      finishCloudCheck = resolve;
    });
    let ownsConversation = true;
    const { service, store } = harness(
      undefined,
      () => cloudCheck,
      () => ownsConversation
        ? { ok: true }
        : { ok: false, status: 403, error: "source conversation does not belong to sender" },
    );

    const proposal = service.propose({
      botId: "bot-a",
      threadId: "thread-a",
      proposal: createProposal({ runOn: "cloud" }),
    });
    ownsConversation = false;
    finishCloudCheck({ ready: true });

    await expect(proposal).rejects.toMatchObject({ status: 403 });
    expect(store.messagesFor("thread-a")).toHaveLength(0);
  });

  it("denies without changing the scheduler and claims duplicate answers", async () => {
    const { service, routines, store } = harness();
    const proposal = await service.propose({ botId: "bot-a", threadId: "thread-a", proposal: createProposal() });

    expect(service.resolve({
      botId: "bot-a",
      threadId: "thread-a",
      requestId: proposal.requestId,
      behavior: "answer",
    })).toMatchObject({ claimed: true, state: "invalid" });
    expect(store.messagesFor("thread-a")[0]!.card!.answered).toBeUndefined();

    expect(service.resolve({
      botId: "bot-a",
      threadId: "thread-a",
      requestId: proposal.requestId,
      behavior: "deny",
    })).toEqual({ claimed: true, state: "denied" });
    expect(routines.listRoutines()).toHaveLength(0);
    expect(service.resolve({
      botId: "bot-a",
      threadId: "thread-a",
      requestId: proposal.requestId,
      behavior: "allow",
    })).toEqual({ claimed: true, state: "already_settled", behavior: "deny" });
    expect(service.resolve({
      botId: "bot-a",
      threadId: "thread-a",
      requestId: "provider-request",
      behavior: "allow",
    })).toEqual({ claimed: false, state: "not_found" });
  });

  it("creates only after confirmation, pins ownership, and is durable-idempotent", async () => {
    const { service, routines, store, clock } = harness();
    const proposal = await service.propose({
      botId: "bot-a",
      threadId: "thread-a",
      proposal: createProposal({ durationMinutes: 5, timeoutMinutes: 15 }),
    });

    // A crash after routines.json was atomically written but before the transcript card settled.
    const message = store.messagesFor("thread-a")[0]!;
    const card = message.card!;
    const committed = routines.create({
      botId: "bot-a",
      name: "Morning brief",
      prompt: "Summarize the overnight support queue.",
      runOn: "maus",
      enabled: true,
      schedule: { type: "daily", time: "09:00", weekdays: [1, 3] },
      durationMinutes: 5,
      timeoutMinutes: 15,
    }, {
      requestId: proposal.requestId,
      messageId: message.id,
      botId: "bot-a",
      threadId: "thread-a",
      action: "create",
      fingerprintVersion: 1,
      fingerprint: cardFingerprint(card, message.id),
    });
    const receipt = routines.routineRequestReceipt(proposal.requestId);
    expect(receipt?.resultId).toBe(committed.id);
    clock.now += 60_000;

    const first = service.resolve({
      botId: "bot-a",
      threadId: "thread-a",
      requestId: proposal.requestId,
      behavior: "allow",
    });
    expect(first).toMatchObject({ claimed: true, state: "applied", action: "create" });
    if (first.state !== "applied") throw new Error("Expected the routine to be applied");
    expect(routines.listRoutines()).toMatchObject([{
      botId: "bot-a",
      name: "Morning brief",
      enabled: true,
      durationMinutes: 5,
      timeoutMinutes: 15,
      sourceThreadId: "thread-a",
    }]);
    expect(routines.routineRequestReceipt(proposal.requestId)).toBeNull();
    expect(store.messagesFor("thread-a")[0]!.card).toMatchObject({
      held: undefined,
      routineRequest: { appliedAt: receipt?.appliedAt },
    });

    const second = service.resolve({
      botId: "bot-a",
      threadId: "thread-a",
      requestId: proposal.requestId,
      behavior: "allow",
    });
    expect(second).toMatchObject({ claimed: true, state: "already_settled", behavior: "allow" });
    expect(routines.listRoutines()).toHaveLength(1);

    expect(service.resolve({
      botId: "bot-b",
      threadId: "thread-a",
      requestId: proposal.requestId,
      behavior: "allow",
    })).toMatchObject({ claimed: true, state: "invalid", status: 403 });
  });

  it("applies update, pause, resume, run-now, and delete only to the owning bot", async () => {
    const { service, routines, store } = harness();
    const routine = routines.create({
      botId: "bot-a",
      name: "Old name",
      prompt: "Old instructions",
      schedule: { type: "daily", time: "10:00", weekdays: [1] },
      durationMinutes: 30,
    });

    await expect(service.propose({
      botId: "bot-b",
      threadId: "thread-b",
      proposal: { action: "pause", routineId: routine.id },
    })).rejects.toThrow(RoutineRequestError);

    const apply = async (proposal: RoutineProposalInput) => {
      const card = await service.propose({ botId: "bot-a", threadId: "thread-a", proposal });
      const result = service.resolve({
        botId: "bot-a",
        threadId: "thread-a",
        requestId: card.requestId,
        behavior: "allow",
      });
      expect(result.state).toBe("applied");
      return { card, result };
    };

    await apply({
      action: "update",
      routineId: routine.id,
      changes: {
        name: "New name",
        instructions: "New instructions",
        durationMinutes: 45,
        timeoutMinutes: 10,
      },
    });
    expect(routines.listRoutines()[0]).toMatchObject({
      name: "New name",
      prompt: "New instructions",
      durationMinutes: 45,
      timeoutMinutes: 10,
    });

    await apply({ action: "update", routineId: routine.id, changes: { timeoutMinutes: null } });
    expect(routines.listRoutines()[0]).not.toHaveProperty("timeoutMinutes");

    await apply({ action: "pause", routineId: routine.id });
    expect(routines.listRoutines()[0]!.enabled).toBe(false);
    await apply({ action: "resume", routineId: routine.id });
    expect(routines.listRoutines()[0]!.enabled).toBe(true);

    const runNow = await service.propose({
      botId: "bot-a",
      threadId: "thread-a",
      proposal: { action: "run_now", routineId: routine.id },
    });
    const runMessage = store.messagesFor("thread-a").find(
      (message) => message.card?.requestId === runNow.requestId,
    )!;
    const runCard = runMessage.card!;
    routines.runNow(routine.id, {
      requestId: runNow.requestId,
      messageId: runMessage.id,
      botId: "bot-a",
      threadId: "thread-a",
      action: "run_now",
      fingerprintVersion: 1,
      fingerprint: cardFingerprint(runCard, runMessage.id),
    });
    expect(service.resolve({
      botId: "bot-a",
      threadId: "thread-a",
      requestId: runNow.requestId,
      behavior: "allow",
    })).toMatchObject({ claimed: true, state: "applied" });
    expect(routines.listRuns()).toHaveLength(1);
    expect(routines.routineRequestReceipt(runNow.requestId)).toBeNull();
    expect(service.resolve({
      botId: "bot-a",
      threadId: "thread-a",
      requestId: runNow.requestId,
      behavior: "allow",
    })).toMatchObject({ claimed: true, state: "already_settled" });
    expect(routines.listRuns()).toHaveLength(1);

    await apply({ action: "delete", routineId: routine.id });
    expect(routines.listRoutines()).toHaveLength(0);
  });

  it("captures and enforces the routine revision for every manage confirmation", async () => {
    const { service, routines, store } = harness();
    const routine = routines.create({
      botId: "bot-a",
      name: "Mutable routine",
      prompt: "Original instructions",
      schedule: { type: "daily", time: "10:00", weekdays: [1] },
    });
    const proposed = await service.propose({
      botId: "bot-a",
      threadId: "thread-a",
      proposal: { action: "pause", routineId: routine.id },
    });
    expect(store.messagesFor("thread-a")[0]!.card?.routineRequest?.operation).toMatchObject({
      action: "pause",
      expectedUpdatedAt: routine.updatedAt,
    });

    const changed = routines.update(routine.id, { name: "Changed elsewhere" })!;
    expect(changed.updatedAt).toBeGreaterThan(routine.updatedAt);
    expect(service.resolve({
      botId: "bot-a",
      threadId: "thread-a",
      requestId: proposed.requestId,
      behavior: "allow",
    })).toMatchObject({ claimed: true, state: "invalid", status: 409 });
    expect(routines.listRoutines()[0]).toMatchObject({ name: "Changed elsewhere", enabled: true });
    const dead = store.messagesFor("thread-a")[0]!.card!;
    expect(dead.held).toMatch(/changed after this confirmation card/);
    expect(dead.expired).toBe(true);
    expect(dead.options).toEqual([]);
  });

  it("keeps a pending manage confirmation valid across recurring scheduler progress", async () => {
    const { service, routines, clock } = harness();
    const anchorAt = clock.now + 5 * 60_000;
    const routine = routines.create({
      botId: "bot-a",
      name: "Frequent check",
      prompt: "Check the queue",
      schedule: { type: "interval", everyMinutes: 5, anchorAt },
    });
    const proposed = await service.propose({
      botId: "bot-a",
      threadId: "thread-a",
      proposal: { action: "update", routineId: routine.id, changes: { name: "Frequent review" } },
    });

    clock.now = anchorAt;
    await routines.tick();
    expect(routines.listRoutines()[0]).toMatchObject({
      updatedAt: routine.updatedAt,
      nextRunAt: anchorAt + 5 * 60_000,
    });
    expect(service.resolve({
      botId: "bot-a",
      threadId: "thread-a",
      requestId: proposed.requestId,
      behavior: "allow",
    })).toMatchObject({ claimed: true, state: "applied" });
    expect(routines.listRoutines()[0]).toMatchObject({ name: "Frequent review" });
  });

  it("invalidates a pending confirmation when a one-time routine auto-disables", async () => {
    const { service, routines, clock } = harness();
    const scheduledAt = clock.now + 5 * 60_000;
    const routine = routines.create({
      botId: "bot-a",
      name: "One-time check",
      prompt: "Check once",
      schedule: { type: "once", at: scheduledAt },
    });
    const proposed = await service.propose({
      botId: "bot-a",
      threadId: "thread-a",
      proposal: { action: "update", routineId: routine.id, changes: { name: "Renamed check" } },
    });

    clock.now = scheduledAt;
    await routines.tick();
    expect(routines.listRoutines()[0]).toMatchObject({ enabled: false, nextRunAt: null });
    expect(routines.listRoutines()[0]!.updatedAt).toBeGreaterThan(routine.updatedAt);
    expect(service.resolve({
      botId: "bot-a",
      threadId: "thread-a",
      requestId: proposed.requestId,
      behavior: "allow",
    })).toMatchObject({ claimed: true, state: "invalid", status: 409 });
  });

  it("settles manage cards whose requested mutation already committed before a crash", async () => {
    const { service, routines, store } = harness();
    const routine = routines.create({
      botId: "bot-a",
      name: "Before",
      prompt: "Original instructions",
      schedule: { type: "daily", time: "10:00", weekdays: [1] },
    });
    const update = await service.propose({
      botId: "bot-a",
      threadId: "thread-a",
      proposal: { action: "update", routineId: routine.id, changes: { name: "After" } },
    });

    // A crash after routines.json was atomically written but before the transcript card settled.
    const updateMessage = store.messagesFor("thread-a")[0]!;
    const updateCard = updateMessage.card!;
    const committed = routines.update(routine.id, { name: "After" }, {
      requestId: update.requestId,
      messageId: updateMessage.id,
      botId: "bot-a",
      threadId: "thread-a",
      action: "update",
      fingerprintVersion: 1,
      fingerprint: cardFingerprint(updateCard, updateMessage.id),
    })!;
    expect(service.resolve({
      botId: "bot-a",
      threadId: "thread-a",
      requestId: update.requestId,
      behavior: "allow",
    })).toMatchObject({ claimed: true, state: "applied", resultId: routine.id });
    expect(routines.listRoutines()[0]!.updatedAt).toBe(committed.updatedAt);
    expect(store.messagesFor("thread-a")[0]!.card?.answered).toBe("allow");
    expect(routines.routineRequestReceipt(update.requestId)).toBeNull();

    const deletion = await service.propose({
      botId: "bot-a",
      threadId: "thread-a",
      proposal: { action: "delete", routineId: routine.id },
    });
    const deleteMessage = store.messagesFor("thread-a")[1]!;
    const deleteCard = deleteMessage.card!;
    routines.remove(routine.id, {
      requestId: deletion.requestId,
      messageId: deleteMessage.id,
      botId: "bot-a",
      threadId: "thread-a",
      action: "delete",
      fingerprintVersion: 1,
      fingerprint: cardFingerprint(deleteCard, deleteMessage.id),
    });
    expect(service.resolve({
      botId: "bot-a",
      threadId: "thread-a",
      requestId: deletion.requestId,
      behavior: "allow",
    })).toMatchObject({ claimed: true, state: "applied", resultId: routine.id });
    expect(store.messagesFor("thread-a")[1]!.card?.answered).toBe("allow");
    expect(routines.routineRequestReceipt(deletion.requestId)).toBeNull();
  });

  it("never mistakes an unrelated matching state for the card's committed operation", async () => {
    const { service, routines, store } = harness();
    const routine = routines.create({
      botId: "bot-a",
      name: "Before",
      prompt: "Safe instructions",
      schedule: { type: "daily", time: "10:00", weekdays: [1] },
    });
    const proposal = await service.propose({
      botId: "bot-a",
      threadId: "thread-a",
      proposal: { action: "update", routineId: routine.id, changes: { name: "Reviewed" } },
    });

    routines.update(routine.id, { name: "Reviewed", prompt: "Unrelated changed instructions" });
    expect(service.resolve({
      botId: "bot-a",
      threadId: "thread-a",
      requestId: proposal.requestId,
      behavior: "allow",
    })).toMatchObject({ claimed: true, state: "invalid", status: 409 });
    expect(store.messagesFor("thread-a")[0]!.card?.answered).toBeUndefined();
  });

  it("rejects a malformed persisted action instead of falling through to delete", async () => {
    const { service, routines, store } = harness();
    const routine = routines.create({
      botId: "bot-a",
      name: "Keep me",
      prompt: "Never delete on malformed input",
      schedule: { type: "daily", time: "10:00", weekdays: [1] },
    });
    const proposed = await service.propose({
      botId: "bot-a",
      threadId: "thread-a",
      proposal: { action: "delete", routineId: routine.id },
    });
    const message = store.messagesFor("thread-a")[0]!;
    const card = message.card!;
    Object.assign(card.routineRequest!.operation, { action: "destroy" });

    expect(service.resolve({
      botId: "bot-a",
      threadId: "thread-a",
      requestId: proposed.requestId,
      behavior: "allow",
    })).toMatchObject({ claimed: true, state: "invalid", status: 400 });
    expect(routines.listRoutines()).toMatchObject([{ id: routine.id, name: "Keep me" }]);
    expect(card.answered).toBeUndefined();

    expect(service.resolve({
      botId: "bot-a",
      threadId: "thread-a",
      requestId: proposed.requestId,
      behavior: "deny",
    })).toEqual({ claimed: true, state: "denied" });
    expect(store.messagesFor("thread-a")[0]!.card?.answered).toBe("deny");
  });

  it("reports an already-committed malformed card as applied instead of cancelled", async () => {
    const { service, routines, store } = harness();
    const routine = routines.create({
      botId: "bot-a",
      name: "Before",
      prompt: "Keep the result truthful",
      schedule: { type: "daily", time: "10:00", weekdays: [1] },
    });
    const proposed = await service.propose({
      botId: "bot-a",
      threadId: "thread-a",
      proposal: { action: "update", routineId: routine.id, changes: { name: "After" } },
    });
    const message = store.messagesFor("thread-a")[0]!;
    const card = message.card!;
    routines.update(routine.id, { name: "After" }, {
      requestId: proposed.requestId,
      messageId: message.id,
      botId: "bot-a",
      threadId: "thread-a",
      action: "update",
      fingerprintVersion: 1,
      fingerprint: cardFingerprint(card, message.id),
    });
    Object.assign(card.routineRequest!.operation, { action: "future_schema_action" });

    expect(service.resolve({
      botId: "bot-a",
      threadId: "thread-a",
      requestId: proposed.requestId,
      behavior: "deny",
    })).toMatchObject({ claimed: true, state: "applied", action: "update", resultId: routine.id });
    expect(store.messagesFor("thread-a")[0]!.card?.answered).toBe("allow");
    expect(routines.listRoutines()[0]!.name).toBe("After");
    expect(routines.routineRequestReceipt(proposed.requestId)).toBeNull();
  });

  it("lets Cancel close a semantically corrupted card when no action committed", async () => {
    const { service, routines, store } = harness();
    const proposed = await service.propose({
      botId: "bot-a",
      threadId: "thread-a",
      proposal: createProposal(),
    });
    const card = store.messagesFor("thread-a")[0]!.card!;
    card.routineRequest!.requestId = "nested-wrong-id";

    expect(service.resolve({
      botId: "bot-a",
      threadId: "thread-a",
      requestId: proposed.requestId,
      behavior: "deny",
    })).toEqual({ claimed: true, state: "denied" });
    expect(store.messagesFor("thread-a")[0]!.card?.answered).toBe("deny");
    expect(routines.listRoutines()).toHaveLength(0);
  });

  it("shows no next run when an update leaves a paused routine paused", async () => {
    const { service, routines, store } = harness();
    const routine = routines.create({
      botId: "bot-a",
      name: "Paused routine",
      prompt: "Stay paused",
      enabled: false,
      schedule: { type: "daily", time: "10:00", weekdays: [1] },
    });
    const proposed = await service.propose({
      botId: "bot-a",
      threadId: "thread-a",
      proposal: { action: "update", routineId: routine.id, changes: { name: "Still paused" } },
    });

    expect(proposed.nextRunAt).toBeNull();
    expect(proposed.summary).toContain("Remains paused");
    const card = store.messagesFor("thread-a")[0]!.card!;
    expect(card.subtitle).toContain("Action: Update routine");
    expect(card.subtitle).toContain("Name: Still paused");
    expect(card.subtitle).toContain("Next run: None — this routine remains paused");
    expect(card.subtitle).toContain("Instructions:\nStay paused");
  });

  it("refuses a one-time update that became stale while awaiting confirmation", async () => {
    const { service, routines, clock, store } = harness();
    const routine = routines.create({
      botId: "bot-a",
      name: "One time",
      prompt: "Do it",
      schedule: { type: "daily", time: "10:00", weekdays: [1] },
    });
    const scheduledAt = clock.now + 60_000;
    const proposal = await service.propose({
      botId: "bot-a",
      threadId: "thread-a",
      proposal: {
        action: "update",
        routineId: routine.id,
        changes: { schedule: { type: "once", at: new Date(scheduledAt).toISOString() } },
      },
    });
    clock.now = scheduledAt + 1;

    expect(service.resolve({
      botId: "bot-a",
      threadId: "thread-a",
      requestId: proposal.requestId,
      behavior: "allow",
    })).toMatchObject({ claimed: true, state: "invalid", status: 409 });
    expect(routines.listRoutines()[0]!.schedule.type).toBe("daily");
    expect(store.messagesFor("thread-a")[0]!.card).toMatchObject({ expired: true, held: expect.stringMatching(/now in the past/) });
  });

  it("never decides an expired routine card, even when its expiry condition reverses", async () => {
    const { service, routines, store, clock } = harness();
    const routine = routines.create({
      botId: "bot-a",
      name: "One time",
      prompt: "Do it",
      schedule: { type: "daily", time: "10:00", weekdays: [1] },
    });
    const scheduledAt = clock.now + 60_000;
    const proposal = await service.propose({
      botId: "bot-a",
      threadId: "thread-a",
      proposal: {
        action: "update",
        routineId: routine.id,
        changes: { schedule: { type: "once", at: new Date(scheduledAt).toISOString() } },
      },
    });
    clock.now = scheduledAt + 1;
    expect(service.resolve({ botId: "bot-a", threadId: "thread-a", requestId: proposal.requestId, behavior: "allow" }))
      .toMatchObject({ claimed: true, state: "invalid", status: 409 });
    expect(store.messagesFor("thread-a")[0]!.card).toMatchObject({ expired: true });

    clock.now = scheduledAt - 60_000;
    const expired = "This routine request expired before it was confirmed. Ask for a fresh proposal.";
    expect(service.resolve({ botId: "bot-a", threadId: "thread-a", requestId: proposal.requestId, behavior: "allow" }))
      .toEqual({ claimed: true, state: "invalid", error: expired, status: 409 });
    expect(service.resolve({ botId: "bot-a", threadId: "thread-a", requestId: proposal.requestId, behavior: "deny" }))
      .toEqual({ claimed: true, state: "invalid", error: expired, status: 409 });
    expect(routines.listRoutines()[0]!.schedule.type).toBe("daily");
    const card = store.messagesFor("thread-a")[0]!.card!;
    expect(card).toMatchObject({ expired: true, options: [] });
    expect(card.answered).toBeUndefined();
  });

  it("never resumes a one-time routine with no future occurrence", async () => {
    const { service, routines, clock } = harness();
    const future = clock.now + 60_000;
    const routine = routines.create({
      botId: "bot-a",
      name: "One time",
      prompt: "Do it",
      enabled: false,
      schedule: { type: "once", at: future },
    });
    const proposal = await service.propose({
      botId: "bot-a",
      threadId: "thread-a",
      proposal: { action: "resume", routineId: routine.id },
    });
    clock.now = future + 1;
    expect(service.resolve({
      botId: "bot-a",
      threadId: "thread-a",
      requestId: proposal.requestId,
      behavior: "allow",
    })).toMatchObject({ claimed: true, state: "invalid", status: 409 });
    expect(routines.listRoutines()[0]).toMatchObject({ enabled: false, nextRunAt: null });

    await expect(service.propose({
      botId: "bot-a",
      threadId: "thread-a",
      proposal: { action: "resume", routineId: routine.id },
    })).rejects.toThrow(/new future time/);
  });

  it("explains an ended interval accurately when a resume card becomes stale", async () => {
    const { service, routines, clock, store } = harness();
    const end = clock.now + 5 * 60_000;
    const routine = routines.create({
      botId: "bot-a",
      name: "Limited interval",
      prompt: "Do it while the interval is active.",
      enabled: false,
      schedule: {
        type: "interval",
        everyMinutes: 5,
        anchorAt: clock.now,
        endsAt: end,
      },
    });
    const proposal = await service.propose({
      botId: "bot-a",
      threadId: "thread-a",
      proposal: { action: "resume", routineId: routine.id },
    });
    clock.now = end + 1;

    expect(service.resolve({
      botId: "bot-a",
      threadId: "thread-a",
      requestId: proposal.requestId,
      behavior: "allow",
    })).toMatchObject({ claimed: true, state: "invalid", status: 409 });
    expect(store.messagesFor("thread-a")[0]!.card?.held).toMatch(/interval routine has no future runs/i);
    expect(store.messagesFor("thread-a")[0]!.card?.held).toMatch(/later end time|remove the end restriction/i);
    expect(store.messagesFor("thread-a")[0]!.card?.held).not.toMatch(/one-time/i);

    await expect(service.propose({
      botId: "bot-a",
      threadId: "thread-a",
      proposal: { action: "resume", routineId: routine.id },
    })).rejects.toThrow(/interval routine has no future runs/i);
  });
});

describe("cross-bot routine targeting", () => {
  function targetedHarness(validateTarget?: (proposerBotId: string, target: { botId: string; name: string }) => string | null) {
    const clock = { now: Date.parse("2026-08-28T10:00:00Z") };
    const dir = mkdtempSync(join(tmpdir(), "omb-routine-target-"));
    tempDirs.push(dir);
    const routines = new RoutineManager({
      file: join(dir, "routines.json"),
      now: () => clock.now,
      botState: () => "busy",
      createTask: () => null,
      startTurn: async () => {},
    });
    const store = new MemoryStore();
    const service = new RoutineRequestService({
      store,
      routines,
      now: () => clock.now,
      timeZone: () => "Asia/Kolkata",
      validateTarget,
    });
    return { routines, service, store };
  }

  const forOps = { forBot: { botId: "bot-b", name: "Ops" } };

  it("binds the confirmed routine to the named target bot, not the proposer", async () => {
    const { routines, service, store } = targetedHarness();
    const proposed = await service.propose({
      botId: "bot-a",
      threadId: "thread-a",
      proposal: { ...createProposal(), ...forOps },
    });
    const card = store.messagesFor("thread-a")[0]?.card;
    expect(card?.title).toContain("for @Ops");
    expect(card?.subtitle).toContain("AI and permissions");
    expect(card?.routineRequest?.operation).toMatchObject({ action: "create", forBot: forOps.forBot });

    const result = service.resolve({
      botId: "bot-a",
      threadId: "thread-a",
      requestId: proposed.requestId,
      behavior: "allow",
    });
    expect(result).toMatchObject({ claimed: true, state: "applied", action: "create" });
    const created = routines.listRoutines();
    expect(created).toHaveLength(1);
    expect(created[0].botId).toBe("bot-b");
  });

  it("still schedules for the proposer when no target is named", async () => {
    const { routines, service } = targetedHarness();
    const proposed = await service.propose({ botId: "bot-a", threadId: "thread-a", proposal: createProposal() });
    service.resolve({ botId: "bot-a", threadId: "thread-a", requestId: proposed.requestId, behavior: "allow" });
    expect(routines.listRoutines()[0]?.botId).toBe("bot-a");
  });

  it("refuses at propose time when the target fails authorization", async () => {
    const { service } = targetedHarness(() => "@Ops belongs to a different section");
    await expect(service.propose({
      botId: "bot-a",
      threadId: "thread-a",
      proposal: { ...createProposal(), ...forOps },
    })).rejects.toMatchObject({ message: "@Ops belongs to a different section", status: 403 });
  });

  it("re-checks the target at confirm time — a deleted bot refuses without creating anything", async () => {
    let gone = false;
    const { routines, service, store } = targetedHarness(() => (gone ? "@Ops no longer exists, so this routine cannot be scheduled for it" : null));
    const proposed = await service.propose({
      botId: "bot-a",
      threadId: "thread-a",
      proposal: { ...createProposal(), ...forOps },
    });
    gone = true;
    const result = service.resolve({
      botId: "bot-a",
      threadId: "thread-a",
      requestId: proposed.requestId,
      behavior: "allow",
    });
    expect(result).toMatchObject({ claimed: true, state: "invalid", status: 404 });
    expect(routines.listRoutines()).toHaveLength(0);
    expect(store.messagesFor("thread-a")[0]?.card).toMatchObject({ expired: true, held: expect.stringMatching(/no longer exists/) });
  });

  it("manages the named bot's routine, not the proposer's", async () => {
    const { routines, service, store } = targetedHarness();
    const peerRoutine = routines.create({
      botId: forOps.forBot.botId,
      name: "Ops digest",
      prompt: "Summarize the section's operations.",
      schedule: { type: "daily", time: "09:00", weekdays: [1] },
    });
    const ownRoutine = routines.create({
      botId: "bot-a",
      name: "Own digest",
      prompt: "Summarize my own work.",
      schedule: { type: "daily", time: "10:00", weekdays: [2] },
    });
    const proposed = await service.propose({
      botId: "bot-a",
      threadId: "thread-a",
      proposal: { action: "pause", routineId: peerRoutine.id, forBot: forOps.forBot },
    });
    const card = store.messagesFor("thread-a")[0]?.card;
    expect(card?.title).toContain("for @Ops");
    expect(card?.routineRequest?.operation).toMatchObject({ action: "pause", forBot: forOps.forBot });
    expect(service.resolve({
      botId: "bot-a",
      threadId: "thread-a",
      requestId: proposed.requestId,
      behavior: "allow",
    })).toMatchObject({ claimed: true, state: "applied", action: "pause" });
    expect(routines.listRoutines().find((routine) => routine.id === peerRoutine.id))
      .toMatchObject({ botId: forOps.forBot.botId, enabled: false });
    expect(routines.listRoutines().find((routine) => routine.id === ownRoutine.id)?.enabled).toBe(true);

    const updated = await service.propose({
      botId: "bot-a",
      threadId: "thread-a",
      proposal: {
        action: "update",
        routineId: peerRoutine.id,
        changes: { name: "Renamed ops digest" },
        forBot: forOps.forBot,
      },
    });
    expect(service.resolve({
      botId: "bot-a",
      threadId: "thread-a",
      requestId: updated.requestId,
      behavior: "allow",
    })).toMatchObject({ claimed: true, state: "applied", action: "update", resultId: peerRoutine.id });
    expect(routines.listRoutines().find((routine) => routine.id === peerRoutine.id)?.name)
      .toBe("Renamed ops digest");
  });

  it("scopes a targeted action's routine lookup to the named bot", async () => {
    const { routines, service } = targetedHarness();
    const ownRoutine = routines.create({
      botId: "bot-a",
      name: "Own digest",
      prompt: "Summarize my own work.",
      schedule: { type: "daily", time: "10:00", weekdays: [2] },
    });
    await expect(service.propose({
      botId: "bot-a",
      threadId: "thread-a",
      proposal: { action: "pause", routineId: ownRoutine.id, forBot: forOps.forBot },
    })).rejects.toMatchObject({ status: 404 });
  });

  it("refuses a targeted manage action at propose time when the target fails authorization", async () => {
    const { routines, service, store } = targetedHarness(() => "@Ops belongs to a different section");
    const peerRoutine = routines.create({
      botId: forOps.forBot.botId,
      name: "Ops digest",
      prompt: "Summarize the section's operations.",
      schedule: { type: "daily", time: "09:00", weekdays: [1] },
    });
    await expect(service.propose({
      botId: "bot-a",
      threadId: "thread-a",
      proposal: { action: "delete", routineId: peerRoutine.id, forBot: forOps.forBot },
    })).rejects.toMatchObject({ message: "@Ops belongs to a different section", status: 403 });
    expect(store.messagesFor("thread-a")).toHaveLength(0);
    expect(routines.listRoutines()).toHaveLength(1);
  });

  it("re-checks a targeted manage action at confirm time without touching the routine", async () => {
    let reachable = true;
    const { routines, service, store } = targetedHarness(() => (reachable ? null : "@Ops is no longer in this section"));
    const peerRoutine = routines.create({
      botId: forOps.forBot.botId,
      name: "Ops digest",
      prompt: "Summarize the section's operations.",
      schedule: { type: "daily", time: "09:00", weekdays: [1] },
    });
    const proposed = await service.propose({
      botId: "bot-a",
      threadId: "thread-a",
      proposal: { action: "pause", routineId: peerRoutine.id, forBot: forOps.forBot },
    });
    reachable = false;
    const result = service.resolve({
      botId: "bot-a",
      threadId: "thread-a",
      requestId: proposed.requestId,
      behavior: "allow",
    });
    expect(result).toMatchObject({ claimed: true, state: "invalid", status: 404 });
    expect(routines.listRoutines().find((routine) => routine.id === peerRoutine.id)?.enabled).toBe(true);
    expect(store.messagesFor("thread-a")[0]?.card)
      .toMatchObject({ expired: true, held: expect.stringMatching(/no longer in this section/) });
  });

  it("expires a targeted manage action when the target's routine changes under it", async () => {
    const { routines, service } = targetedHarness();
    const peerRoutine = routines.create({
      botId: forOps.forBot.botId,
      name: "Ops digest",
      prompt: "Summarize the section's operations.",
      schedule: { type: "daily", time: "09:00", weekdays: [1] },
    });
    const proposed = await service.propose({
      botId: "bot-a",
      threadId: "thread-a",
      proposal: { action: "pause", routineId: peerRoutine.id, forBot: forOps.forBot },
    });
    routines.update(peerRoutine.id, { name: "Renamed under the card" });
    const result = service.resolve({
      botId: "bot-a",
      threadId: "thread-a",
      requestId: proposed.requestId,
      behavior: "allow",
    });
    expect(result).toMatchObject({ claimed: true, state: "invalid", status: 409 });
    expect(routines.listRoutines().find((routine) => routine.id === peerRoutine.id)).toMatchObject({ enabled: true });
  });
});

describe("consequenceLine", () => {
  it("uses singular wording for one run a day and one day a week", () => {
    expect(consequenceLine({ type: "interval", everyMinutes: 1440 })).toBe(
      "Will run about once a day; each run starts a fresh session.",
    );
    expect(consequenceLine({ type: "daily", time: "09:00", weekdays: [1] })).toBe(
      "Will run one day a week; each run starts a fresh session.",
    );
    expect(consequenceLine({ type: "daily", time: "09:00", weekdays: [1, 3] })).toBe(
      "Will run 2 days a week; each run starts a fresh session.",
    );
    expect(consequenceLine({ type: "once", at: 0 })).toBe("Will run once; that run starts a fresh session.");
  });

  it("says a one-time run continues the conversation when it keeps one", () => {
    expect(consequenceLine({ type: "once", at: 0 }, false, true)).toBe(
      "Will run once; each run continues the previous run's conversation.",
    );
  });
});

describe("a bot's own routine changes", () => {
  const rule: DirectApplyCheck = (botId, threadId, targetBotId) => directApply({
    fullAccess: threadId === "full-thread", botId, targetBotId, blocked: threadId === "guest-thread",
  });
  const own = () => harness(undefined, undefined, undefined, rule);
  const openCards = (store: { messagesFor(threadId: string): RoutineRequestMessage[] }, threadId: string) =>
    store.messagesFor(threadId).filter((message) => message.card && !message.card.answered && !message.card.dismissed);
  const undo = (service: RoutineRequestService, requestId: string, threadId = "ask-thread") =>
    service.undo({ botId: "bot-a", threadId, requestId });

  it("creates, updates, pauses, resumes and deletes its own routine at Ask with no open card", async () => {
    const { service, routines, store } = own();
    const submit = (proposal: RoutineProposalInput) => service.submit({ botId: "bot-a", threadId: "ask-thread", proposal });
    const created = await submit(createProposal());
    expect(created).toMatchObject({ state: "applied", appliedBy: "self", result: { action: "create" } });
    const routineId = created.result!.resultId;
    expect(await submit({ action: "update", routineId, changes: { name: "Renamed brief" } })).toMatchObject({ state: "applied", appliedBy: "self" });
    expect(routines.listRoutines()[0]?.name).toBe("Renamed brief");
    expect(await submit({ action: "pause", routineId })).toMatchObject({ state: "applied" });
    expect(await submit({ action: "resume", routineId })).toMatchObject({ state: "applied" });
    expect(await submit({ action: "delete", routineId })).toMatchObject({ state: "applied" });
    expect(routines.listRoutines()).toHaveLength(0);
    expect(openCards(store, "ask-thread")).toHaveLength(0);
    const cards = store.messagesFor("ask-thread").map((message) => message.card!);
    expect(cards).toHaveLength(5);
    expect(cards.every((card) => card.autoApplied && card.answered === "allow" && card.options.length === 0)).toBe(true);
    expect(cards[0]!.routineRequest?.undo).toMatchObject({ name: "Morning brief", schedule: { type: "daily" } });
    expect(cards[1]!.routineRequest?.undo).toMatchObject({ name: "Renamed brief", before: { name: "Morning brief" } });
  });

  it("applies another bot's routine at Ask, and in a guest-driven turn, with no card left open", async () => {
    const { service, routines, store } = own();
    const proposal = createProposal();
    if (proposal.action !== "create") throw new Error("Expected create");
    expect(await service.submit({ botId: "bot-a", threadId: "ask-thread", proposal: { ...proposal, forBot: { botId: "bot-b", name: "Peer" } } }))
      .toMatchObject({ state: "applied", result: { action: "create" } });
    expect(await service.submit({ botId: "bot-a", threadId: "guest-thread", proposal: createProposal({ instructions: "A guest's request." }) }))
      .toMatchObject({ state: "applied" });
    expect(routines.listRoutines().map((routine) => routine.botId).sort()).toEqual(["bot-a", "bot-b"]);
    expect(openCards(store, "ask-thread")).toHaveLength(0);
    expect(openCards(store, "guest-thread")).toHaveLength(0);
    const peers = routines.create({ botId: "bot-b", name: "Peer digest", prompt: "Digest.", schedule: { type: "daily", time: "09:00", weekdays: [1] } });
    expect(await service.submit({ botId: "bot-a", threadId: "ask-thread", proposal: { action: "pause", routineId: peers.id, forBot: { botId: "bot-b", name: "Peer" } } }))
      .toMatchObject({ state: "applied" });
    expect(routines.listRoutines().find((routine) => routine.id === peers.id)?.enabled).toBe(false);
  });

  it("has no cap: a bot's 21st enabled routine and a resume past 20 apply like any other", async () => {
    const { service, routines, store } = own();
    const daily = { type: "daily" as const, time: "09:00", weekdays: [1] };
    for (let index = 0; index < 20; index += 1) routines.create({ botId: "bot-a", name: `Own ${index}`, prompt: `Own ${index}.`, schedule: daily });
    const paused = routines.create({ botId: "bot-a", name: "Paused", prompt: "Paused task.", enabled: false, schedule: daily });
    expect(await service.submit({ botId: "bot-a", threadId: "ask-thread", proposal: createProposal({ instructions: "The 21st." }) }))
      .toMatchObject({ state: "applied", appliedBy: "self" });
    expect(await service.submit({ botId: "bot-a", threadId: "ask-thread", proposal: { action: "resume", routineId: paused.id } }))
      .toMatchObject({ state: "applied" });
    expect(routines.listRoutines().filter((routine) => routine.enabled)).toHaveLength(22);
    expect(openCards(store, "ask-thread")).toHaveLength(0);
  });

  it("never asks the open-card budget, since no change leaves a card open", async () => {
    const canPersist = vi.fn((_botId: string, _threadId: string, opensCard: boolean) =>
      opensCard ? { ok: false as const, status: 429, error: "confirm or cancel an existing proposal first" } : { ok: true as const });
    const { service, routines } = harness(undefined, undefined, canPersist, rule);
    for (let index = 0; index < 20; index += 1) {
      routines.create({ botId: "bot-a", name: `Routine ${index}`, prompt: `Task ${index}.`, schedule: { type: "daily", time: "09:00", weekdays: [1] } });
    }
    expect(await service.submit({ botId: "bot-a", threadId: "ask-thread", proposal: createProposal({ instructions: "Past twenty." }) }))
      .toMatchObject({ state: "applied" });
    expect(canPersist.mock.calls.every(([, , opensCard]) => opensCard === false)).toBe(true);
  });

  it("logs a self-applied routine as the bot's own even if receipt settlement fails", async () => {
    const { service, store } = own();
    const created = await service.submit({ botId: "bot-a", threadId: "ask-thread", proposal: createProposal() });
    vi.spyOn(store, "patchMessage").mockImplementation(() => { throw new Error("receipt write failed"); });
    const run = await service.submit({ botId: "bot-a", threadId: "ask-thread", proposal: { action: "run_now", routineId: created.result!.resultId } });
    expect(run).toMatchObject({ state: "applied", appliedBy: "self", result: { settlementPending: true } });
  });

  it("undoes run on startup: an update switches it back off, a delete restores it", async () => {
    const { service, routines } = own();
    const submit = (proposal: RoutineProposalInput) => service.submit({ botId: "bot-a", threadId: "ask-thread", proposal });
    const routineId = (await submit(createProposal())).result!.resultId;
    const switchedOn = await submit({ action: "update", routineId, changes: { runOnStartup: true } });
    expect(routines.listRoutines()[0]?.runOnStartup).toBe(true);
    expect(undo(service, switchedOn.requestId)).toMatchObject({ state: "undone", action: "update" });
    expect(routines.listRoutines()[0]?.runOnStartup).toBeUndefined();

    const marked = (await submit(createProposal({ instructions: "Start with the app.", runOnStartup: true }))).result!.resultId;
    const deleted = await submit({ action: "delete", routineId: marked });
    expect(undo(service, deleted.requestId)).toMatchObject({ state: "undone", action: "delete" });
    expect(routines.listRoutines().find((routine) => routine.prompt === "Start with the app.")?.runOnStartup).toBe(true);
  });

  it.each([
    ["pause", false], ["pause", true], ["resume", false], ["resume", true],
  ] as const)("restores the previous enabled state after %s from %s", async (action, enabled) => {
    const { service, routines, clock } = own();
    const saved = routines.create({ botId: "bot-a", name: "Status fixture", prompt: "Check the queue.", enabled,
      schedule: { type: "daily", time: "09:00", weekdays: [1] } });
    clock.now += 1_000;
    const applied = await service.submit({ botId: "bot-a", threadId: "ask-thread", proposal: { action, routineId: saved.id } });
    expect(routines.listRoutines()[0]?.enabled).toBe(action === "resume");
    expect(undo(service, applied.requestId)).toMatchObject({ state: "undone" });
    expect(routines.listRoutines()[0]?.enabled).toBe(enabled);
  });

  it.each(["pause", "resume"] as const)("undoes an unchanged %s without disclosing instructions or losing attachments", async (action) => {
    const { service, routines, store, clock } = own();
    const enabled = action === "resume";
    const prompt = "Use token=fixture-private-value.";
    const attachments = [{ id: "context", name: "Context", path: "/fixture/context.txt", kind: "file" as const, size: 20 }];
    const saved = routines.create({ botId: "bot-a", name: "Private status fixture", prompt, enabled, attachments,
      schedule: { type: "daily", time: "09:00", weekdays: [1] } });
    clock.now += 1_000;
    const applied = await service.submit({ botId: "bot-a", threadId: "ask-thread", proposal: { action, routineId: saved.id } });
    const receipt = store.messagesFor("ask-thread")[0]!.card!;
    expect(JSON.stringify(receipt)).not.toContain("fixture-private-value");
    expect(undo(service, applied.requestId)).toMatchObject({ state: "undone" });
    expect(routines.listRoutines()[0]).toMatchObject({ enabled, prompt, attachments });
  });

  it.each(["pause", "resume"] as const)("still undoes a legacy %s receipt without a before snapshot", async (action) => {
    const { service, routines, store, clock } = own();
    const enabled = action === "pause";
    const saved = routines.create({ botId: "bot-a", name: "Legacy status fixture", prompt: "Check the queue.", enabled,
      schedule: { type: "daily", time: "09:00", weekdays: [1] } });
    clock.now += 1_000;
    const applied = await service.submit({ botId: "bot-a", threadId: "ask-thread", proposal: { action, routineId: saved.id } });
    delete store.messagesFor("ask-thread")[0]!.card!.routineRequest!.undo!.before;
    expect(undo(service, applied.requestId)).toMatchObject({ state: "undone" });
    expect(routines.listRoutines()[0]?.enabled).toBe(enabled);
  });

  it.each([
    ["pause", "name"], ["resume", "name"], ["pause", "prompt"], ["resume", "prompt"],
  ] as const)("keeps %s Undo valid when redacting a maximum-length %s", async (action, field) => {
    const { service, routines, store, clock } = own();
    const name = field === "name" ? `${"x".repeat(65)} token=12345678` : "Status fixture";
    const prompt = field === "prompt" ? `${"x".repeat(19_985)} token=12345678` : "Check the queue.";
    const enabled = action === "resume";
    const saved = routines.create({ botId: "bot-a", name, prompt, enabled,
      schedule: { type: "daily", time: "09:00", weekdays: [1] } });
    clock.now += 1_000;
    const applied = await service.submit({ botId: "bot-a", threadId: "ask-thread", proposal: { action, routineId: saved.id } });
    const receipt = JSON.parse(JSON.stringify(store.messagesFor("ask-thread")[0]!.card!.routineRequest));
    expect(routineRequestCardDataSchema.safeParse(receipt).success).toBe(true);
    expect(JSON.stringify(receipt)).not.toContain("12345678");
    expect(receipt.undo.before.enabled).toBe(enabled);
    expect(undo(service, applied.requestId)).toMatchObject({ state: "undone" });
    expect(routines.listRoutines()[0]).toMatchObject({ name, prompt, enabled });
  });

  it.each(["pause", "resume"] as const)("restores %s state without changing a fractional once timestamp", async (action) => {
    const { service, routines, store, clock } = own();
    const enabled = action === "resume";
    const schedule = { type: "once" as const, at: clock.now + 60_000.5 };
    const saved = routines.create({ botId: "bot-a", name: "Fractional time", prompt: "Check the queue.", enabled, schedule });
    clock.now += 1_000;
    const applied = await service.submit({ botId: "bot-a", threadId: "ask-thread", proposal: { action, routineId: saved.id } });
    const receipt = JSON.parse(JSON.stringify(store.messagesFor("ask-thread")[0]!.card!.routineRequest));
    expect(routineRequestCardDataSchema.safeParse(receipt).success).toBe(true);
    expect(receipt.undo.before.enabled).toBe(enabled);
    expect(undo(service, applied.requestId)).toMatchObject({ state: "undone" });
    expect(routines.listRoutines()[0]).toMatchObject({ enabled, schedule });
  });

  it("undoes each kind of change once, and refuses a run or a stale change", async () => {
    const { service, routines, store, clock } = own();
    const submit = (proposal: RoutineProposalInput) => service.submit({ botId: "bot-a", threadId: "ask-thread", proposal });
    const created = await submit(createProposal());
    const routineId = created.result!.resultId;

    const updated = await submit({ action: "update", routineId, changes: { name: "Renamed", schedule: { type: "interval", everyMinutes: 60 } } });
    expect(undo(service, updated.requestId)).toMatchObject({ state: "undone", action: "update", routineId });
    expect(routines.listRoutines()[0]).toMatchObject({ name: "Morning brief", schedule: { type: "daily", time: "09:00", weekdays: [1, 3] } });
    expect(undo(service, updated.requestId)).toMatchObject({ state: "already_undone" });

    const paused = await submit({ action: "pause", routineId });
    expect(undo(service, paused.requestId)).toMatchObject({ state: "undone" });
    expect(routines.listRoutines()[0]?.enabled).toBe(true);
    const pausedAgain = await submit({ action: "pause", routineId });
    const resumed = await submit({ action: "resume", routineId });
    expect(undo(service, resumed.requestId)).toMatchObject({ state: "undone" });
    expect(routines.listRoutines()[0]?.enabled).toBe(false);
    expect(undo(service, pausedAgain.requestId)).toMatchObject({ state: "invalid", stale: true, error: "Changed since, so it can't be undone here." });
    await submit({ action: "resume", routineId });

    const run = await submit({ action: "run_now", routineId });
    expect(run).toMatchObject({ state: "applied", appliedBy: "self", result: { action: "run_now" } });
    expect(openCards(store, "ask-thread")).toHaveLength(0);
    expect(routines.listRuns()).toHaveLength(1);
    expect(undo(service, run.requestId)).toMatchObject({ state: "invalid", status: 409 });

    const stale = await submit({ action: "update", routineId, changes: { name: "Bot's name" } });
    clock.now += 1_000;
    routines.update(routineId, { name: "Person's name" });
    expect(undo(service, stale.requestId)).toMatchObject({ state: "invalid", stale: true });
    expect(routines.listRoutines()[0]?.name).toBe("Person's name");
    expect(store.messagesFor("ask-thread").find((message) => message.card?.requestId === stale.requestId)?.card?.undone).toBeUndefined();

    const deleted = await submit({ action: "delete", routineId });
    expect(routines.listRoutines()).toHaveLength(0);
    const restored = undo(service, deleted.requestId);
    expect(restored).toMatchObject({ state: "undone", action: "delete", restoredId: expect.any(String) });
    expect(routines.listRoutines()).toEqual([expect.objectContaining({ name: "Person's name", prompt: "Summarize the overnight support queue.", botId: "bot-a", enabled: true })]);

    expect(undo(service, created.requestId)).toMatchObject({ state: "invalid", stale: true });
    expect(routines.listRoutines()).toHaveLength(1);
    const second = await submit(createProposal({ instructions: "A second routine." }));
    expect(undo(service, second.requestId)).toMatchObject({ state: "undone" });
    expect(routines.listRoutines().some((routine) => routine.id === second.result!.resultId)).toBe(false);
    expect(store.messagesFor("ask-thread").find((message) => message.card?.requestId === second.requestId)?.card).toMatchObject({ undone: true });
  });

  it("counts a room goal the bot leads as its own", async () => {
    const { service, routines } = own();
    const goal = routines.create({ botId: "bot-a", target: "room-goal", groupId: "room-a", name: "Room goal", prompt: "Plan the week.", schedule: { type: "daily", time: "09:00", weekdays: [1] } });
    const paused = await service.submit({ botId: "bot-a", threadId: "ask-thread", proposal: { action: "pause", routineId: goal.id } });
    expect(paused).toMatchObject({ state: "applied", appliedBy: "self" });
    const deleted = await service.submit({ botId: "bot-a", threadId: "ask-thread", proposal: { action: "delete", routineId: goal.id } });
    expect(undo(service, deleted.requestId)).toMatchObject({ state: "undone" });
    expect(routines.listRoutines()).toEqual([expect.objectContaining({ target: "room-goal", groupId: "room-a", enabled: false, name: "Room goal" })]);
  });

  it("does not undo a change a person confirmed, or from another conversation", async () => {
    const { service } = own();
    const proposed = await service.propose({ botId: "bot-a", threadId: "ask-thread", proposal: createProposal() });
    service.resolve({ botId: "bot-a", threadId: "ask-thread", requestId: proposed.requestId, behavior: "allow" });
    expect(undo(service, proposed.requestId)).toMatchObject({ state: "invalid", status: 409 });
    const applied = await service.submit({ botId: "bot-a", threadId: "ask-thread", proposal: createProposal({ instructions: "Another." }) });
    expect(service.undo({ botId: "bot-b", threadId: "ask-thread", requestId: applied.requestId })).toMatchObject({ state: "invalid", status: 403 });
    expect(undo(service, "missing")).toEqual({ claimed: false });
  });
});