Cotton code
396 lines · 33.0 KB · TypeScriptRaw
import { beforeAll, describe, expect, it } from "vitest";import { ACTS } from "../src/acts.ts";import { derivedId } from "../src/mcp/context.ts";import { answer, changeKeys, loggedOnly, http, KIT_MANIFESTS, mint, PERSONAL_TABLES, personalObject, put, refusal, tool } from "./personal.ts";/** An instant `seconds` after an hour ago, in the spelling the hooks send (`date -u +%Y-%m-%dT%H:%M:%SZ`). */const BASE = Math.floor(Date.now() / 1000) * 1000 - 3_600_000;const at = (seconds: number): string => new Date(BASE + seconds * 1000).toISOString().replace(/\.\d{3}Z$/, "Z");const iso = (seconds: number): string => new Date(BASE + seconds * 1000).toISOString();const PROJECT = { slug: "widgets", name: "Widgets", repos: ["https://git.example.test/acme/widgets"], status: "active" };async function project(slug: string, data: Record<string, unknown> = PROJECT): Promise<string> {  const ids = await put(slug, [{ ref: "p", table: "project", data }]);  return ids.p!;}const SESSION_KEYS = ["id", "tool", "externalId", "machine", "deviceId", "account", "project", "repoUrl", "branch", "startedAt", "lastActiveAt", "endedAt", "title", "model", "summary", "shipped", "turnCount", "promptCount", "transcriptRef", "state", "stateAt", "waitingKind", "waitingRef", "lastLine", "hostOwned", "prompt", "requestedDeviceId", "chosenBy", "holdReason", "error", "todoId", "todoDatabase", "kind", "parentSessionId", "tasksDone", "tasksTotal"];const GET_KEYS = ["id", "tool", "externalId", "machine", "deviceId", "account", "project", "repoUrl", "branch", "cwd", "title", "model", "prompt", "summary", "state", "stateAt", "waitingKind", "lastLine", "holdReason", "error", "todoId", "todoDatabase", "startedAt", "lastActiveAt", "endedAt", "hostOwned", "kind", "parentSessionId", "prompts", "tasksDone", "tasksTotal", "tasks"];type Session = Record<string, unknown> & { prompts: { seq: number; ts: string; role: string; text: string }[]; tasks: { seq: number; text: string; state: string }[] };/** RULE (owner, 25 Oct 2026): the session hooks log to the personal object exactly as they logged to the Rust server, unchanged except for URL and token. */describe("log_session, as the Claude Code hooks send it", () => {  const SLUG = "ses-log";  let owner = "";  let credential = "";  let projectId = "";  const sid = "4f7c2a10-hook-replay";  let rowId = "";  beforeAll(async () => {    ({ owner, credential } = await personalObject(SLUG));    projectId = await project(SLUG);    rowId = derivedId("cotton_sessions", ["claude-code", sid]);  });  it("takes the SessionStart call, derives the row id from (tool, externalId) and resolves the project from the remote", async () => {    const start = await answer(SLUG, owner, "log_session", {      tool: "claude-code",      externalId: sid,      machine: "mac-a",      lastActiveAt: at(0),      startedAt: at(0),      turnCount: 0,      repoUrl: "git@git.example.test:acme/widgets.git",      branch: "main",      cwd: "/work/widgets",      title: "mac-a · widgets",      model: "claude-test-model",      transcriptRef: "box:mac-a:projects/widgets/abc.jsonl",    });    expect(Object.keys(start)).toEqual(["sessionId", "promptCount", "inserted", ...changeKeys()]);    expect(start).toEqual({ sessionId: rowId, promptCount: 0, inserted: 0, ...loggedOnly() });    const s = await answer<Session>(SLUG, owner, "get_session", { sessionId: rowId });    expect(Object.keys(s)).toEqual(GET_KEYS);    expect(s).toMatchObject({ tool: "claude-code", externalId: sid, machine: "mac-a", project: "widgets", repoUrl: "git.example.test/acme/widgets", branch: "main", cwd: "/work/widgets", title: "mac-a · widgets", model: "claude-test-model", startedAt: iso(0), lastActiveAt: iso(0), endedAt: null, hostOwned: false, kind: "thread", prompts: [], tasks: [], tasksDone: 0, tasksTotal: 0 });  });  it("takes the Stop hook's turns, keeps the first title, and a resend is a no-op", async () => {    const turns = [      { seq: 0, ts: at(10), role: "user", text: "add the widget  list" },      { seq: 1, ts: at(20), role: "assistant", text: "Done — the list is in." },      { seq: 3, ts: at(30), role: "user", text: "   " },    ];    const log = { tool: "claude-code", externalId: sid, machine: "mac-a", lastActiveAt: at(30), repoUrl: "https://git.example.test/acme/widgets", branch: "main", cwd: "/work/widgets", titleIfEmpty: "add the widget list", model: "claude-test-model", prompts: turns, transcriptRef: "box:mac-a:projects/widgets/abc.jsonl" };    expect(await answer(SLUG, owner, "log_session", log)).toEqual({ sessionId: rowId, promptCount: 2, inserted: 2, ...loggedOnly(3) });    expect(await answer(SLUG, owner, "log_session", { ...log, lastActiveAt: at(31) })).toEqual({ sessionId: rowId, promptCount: 2, inserted: 0, ...loggedOnly() });    const s = await answer<Session>(SLUG, owner, "get_session", { sessionId: rowId });    expect(s.title).toBe("mac-a · widgets");    expect(s.prompts).toEqual([      { seq: 0, ts: iso(10), role: "user", text: "add the widget  list" },      { seq: 1, ts: iso(20), role: "assistant", text: "Done — the list is in." },    ]);    const listed = await answer<{ sessions: Record<string, unknown>[] }>(SLUG, owner, "list_sessions", {});    expect(listed.sessions[0]).toMatchObject({ id: rowId, turnCount: 2, promptCount: 2 });  });  it("takes the TodoWrite hook's list whole, and the next list replaces it", async () => {    // The hook says `status`; the tool reads `state`, as the Rust tool did — so every task reads open.    const sent = await answer(SLUG, owner, "log_session", { tool: "claude-code", externalId: sid, machine: "mac-a", lastActiveAt: at(40), tasks: [{ seq: 0, text: "write the list", status: "done" }, { seq: 2, text: "test it", status: "active" }] });    expect(sent).toEqual({ sessionId: rowId, promptCount: 2, inserted: 0, tasksDone: 0, tasksTotal: 2, ...loggedOnly(3) });    const stated = await answer(SLUG, owner, "log_session", { tool: "claude-code", externalId: sid, machine: "mac-a", lastActiveAt: at(41), tasks: [{ seq: 0, text: "write the list", state: "done" }, { seq: 0, text: "a second telling", state: "open" }, { seq: 1, text: "", state: "open" }, { seq: 2, text: "test it", state: "bogus" }, "junk", { seq: -1, text: "below zero" }] });    expect(stated).toMatchObject({ tasksDone: 1, tasksTotal: 2 });    let s = await answer<Session>(SLUG, owner, "get_session", { sessionId: rowId });    expect(s.tasks).toEqual([{ seq: 0, text: "write the list", state: "done" }, { seq: 2, text: "test it", state: "open" }]);    await answer(SLUG, owner, "log_session", { tool: "claude-code", externalId: sid, machine: "mac-a", lastActiveAt: at(42), tasks: [{ seq: 0, text: "write the list", state: "done" }] });    s = await answer<Session>(SLUG, owner, "get_session", { sessionId: rowId });    expect(s.tasks).toEqual([{ seq: 0, text: "write the list", state: "done" }]);    // Not a list says nothing; an empty list clears.    await answer(SLUG, owner, "log_session", { tool: "claude-code", externalId: sid, machine: "mac-a", lastActiveAt: at(43), tasks: "nope" });    expect((await answer<Session>(SLUG, owner, "get_session", { sessionId: rowId })).tasksTotal).toBe(1);    expect(await answer(SLUG, owner, "log_session", { tool: "claude-code", externalId: sid, machine: "mac-a", lastActiveAt: at(44), tasks: [] })).toMatchObject({ tasksDone: 0, tasksTotal: 0 });    expect((await answer<Session>(SLUG, owner, "get_session", { sessionId: rowId })).tasks).toEqual([]);  });  // Needs the store to revive a tombstone: a task's id is derived from (session, seq), so a list that shrinks and grows again re-creates a deleted id.  it("brings a dropped task back when the list grows again", async () => {    await answer(SLUG, owner, "log_session", { tool: "claude-code", externalId: sid, machine: "mac-a", lastActiveAt: at(45), tasks: [{ seq: 0, text: "write the list", state: "open" }] });    expect((await answer<Session>(SLUG, owner, "get_session", { sessionId: rowId })).tasksTotal).toBe(1);  });  it("takes the SessionEnd call, and a resumed session's later turn clears the end", async () => {    await answer(SLUG, owner, "log_session", { tool: "claude-code", externalId: sid, machine: "mac-a", lastActiveAt: at(50), endedAt: at(50) });    expect((await answer<Session>(SLUG, owner, "get_session", { sessionId: rowId })).endedAt).toBe(iso(50));    // A late hook at the end itself leaves it ended.    await answer(SLUG, owner, "log_session", { tool: "claude-code", externalId: sid, machine: "mac-a", lastActiveAt: at(50) });    expect((await answer<Session>(SLUG, owner, "get_session", { sessionId: rowId })).endedAt).toBe(iso(50));    await answer(SLUG, owner, "log_session", { tool: "claude-code", externalId: sid, machine: "mac-a", lastActiveAt: at(60), titleIfEmpty: "mac-a · widgets · resumed" });    const s = await answer<Session>(SLUG, owner, "get_session", { sessionId: rowId });    expect(s).toMatchObject({ endedAt: null, lastActiveAt: iso(60), title: "mac-a · widgets" });  });  it("redacts before it clips, and the recap's PR and commit links are what it shipped", async () => {    const token = `ctn_${"x".repeat(30)}`;    await answer(SLUG, owner, "log_session", {      tool: "claude-code",      externalId: sid,      machine: "mac-a",      lastActiveAt: at(70),      title: `rename ${"t".repeat(200)}`,      summary: `shipped https://github.com/acme/widgets/pull/12 and https://github.com/acme/widgets/commit/abc1234, then https://github.com/acme/widgets/pull/12 again. Token ${token}.`,      prompts: [{ seq: 5, ts: at(70), text: `my key is Bearer abcdefgh12345678 and ${token}` }],    });    const listed = await answer<{ sessions: Record<string, unknown>[] }>(SLUG, owner, "list_sessions", {});    const row = listed.sessions[0]!;    expect(row.shipped).toEqual(["https://github.com/acme/widgets/pull/12", "https://github.com/acme/widgets/commit/abc1234"]);    expect(row.summary).toContain("[redacted:cotton-token]");    expect(row.summary).not.toContain(token);    expect((row.title as string).length).toBe(140);    const s = await answer<Session>(SLUG, owner, "get_session", { sessionId: rowId });    expect(s.prompts.at(-1)).toEqual({ seq: 5, ts: iso(70), role: "user", text: "my key is Bearer [redacted:bearer] and [redacted:cotton-token]" });  });  it("refuses with the Rust sentences, and only for what it must", async () => {    const base = { tool: "claude-code", externalId: sid, machine: "mac-a", lastActiveAt: at(80) };    const cases: [Record<string, unknown>, string][] = [      [{ ...base, tool: "cursor" }, "tool must be one of claude-code, codex, kimi, gemini, opencode, other"],      [{ ...base, externalId: "  " }, "externalId is required — the tool's own session id"],      [{ ...base, machine: undefined }, "machine is required — this machine's hostname"],      [{ ...base, lastActiveAt: "yesterday-ish" }, "lastActiveAt must be an ISO-8601 timestamp"],      [{ ...base, startedAt: "soon" }, "startedAt must be an ISO-8601 timestamp"],      [{ ...base, endedAt: "never" }, "endedAt must be an ISO-8601 timestamp"],      [{ ...base, turnCount: -1 }, "turnCount must be a non-negative integer"],      [{ ...base, turnCount: 1.5 }, "turnCount must be a non-negative integer"],      [{ ...base, prompts: "x" }, "prompts must be an array"],      [{ ...base, prompts: [7] }, "each prompt must be { seq, ts, text }"],      [{ ...base, prompts: [{ ts: at(1), text: "a" }] }, "prompt.seq must be a non-negative integer"],      [{ ...base, prompts: [{ seq: 1, ts: "then", text: "a" }] }, "prompt.ts must be an ISO-8601 timestamp"],      [{ ...base, prompts: [{ seq: 1, ts: at(1), text: 3 }] }, "prompt.text must be a string"],      [{ ...base, prompts: [{ seq: 1, ts: at(1), text: "a", role: "system" }] }, "prompt.role must be one of user, assistant"],      [{ ...base, sessionId: rowId.slice(0, 8) }, `no such session: ${rowId.slice(0, 8)} — sessionId is a session's full row id, never a prefix`],      [{ ...base, project: "nope" }, 'unknown project "nope" — projects are: widgets'],    ];    for (const [args, sentence] of cases) expect(await refusal(SLUG, owner, "log_session", args)).toBe(sentence);    // A blank sessionId is an absent variable spelled out by a hook.    expect(await answer(SLUG, owner, "log_session", { ...base, sessionId: "" })).toMatchObject({ sessionId: rowId });  });  it("files a session on the one active project listing the remote, on none when two do, and an explicit slug moves it", async () => {    await put(SLUG, [{ table: "project", data: { slug: "widgets-fork", name: "Fork", repos: ["git.example.test/acme/forked"], status: "active" } }]);    const a = await answer<{ sessionId: string }>(SLUG, owner, "log_session", { tool: "codex", externalId: "codex-1", machine: "mac-d", lastActiveAt: at(90), repoUrl: "ssh://git@git.example.test/acme/forked.git" });    expect((await answer<Session>(SLUG, owner, "get_session", { sessionId: a.sessionId })).project).toBe("widgets-fork");    await answer(SLUG, owner, "log_session", { tool: "codex", externalId: "codex-1", machine: "mac-d", lastActiveAt: at(91), project: "widgets" });    expect((await answer<Session>(SLUG, owner, "get_session", { sessionId: a.sessionId })).project).toBe("widgets");    // The repo no longer moves it: the owner's reassignment outranks the repo.    await answer(SLUG, owner, "log_session", { tool: "codex", externalId: "codex-1", machine: "mac-d", lastActiveAt: at(92), repoUrl: "git.example.test/acme/forked" });    expect((await answer<Session>(SLUG, owner, "get_session", { sessionId: a.sessionId })).project).toBe("widgets");    await put(SLUG, [{ table: "project", data: { slug: "widgets-two", name: "Two", repos: ["https://git.example.test/acme/forked/"], status: "active" } }]);    const b = await answer<{ sessionId: string }>(SLUG, owner, "log_session", { tool: "codex", externalId: "codex-2", machine: "mac-d", lastActiveAt: at(93), repoUrl: "git.example.test/acme/forked" });    expect((await answer<Session>(SLUG, owner, "get_session", { sessionId: b.sessionId })).project).toBeNull();    void projectId;  });  it("folds an adopted twin into the hosted row the hook names", async () => {    const hosted = "0b6e4a9c-1111-4222-8333-444455556666";    await put(SLUG, [{ verb: "put", table: "session", id: hosted, data: { tool: "claude-code", machine: "mac-a", last_active_at: iso(100), host_owned: true, state: "running" } }]);    const twin = await answer<{ sessionId: string }>(SLUG, owner, "log_session", { tool: "claude-code", externalId: "twin-1", machine: "mac-a", lastActiveAt: at(101), titleIfEmpty: "the twin's title", prompts: [{ seq: 0, ts: at(101), text: "first words" }, { seq: 1, ts: at(102), role: "assistant", text: "reply" }] });    expect(twin.sessionId).not.toBe(hosted);    const folded = await answer(SLUG, owner, "log_session", { tool: "claude-code", externalId: "twin-1", machine: "mac-a", lastActiveAt: at(103), sessionId: hosted, prompts: [{ seq: 1, ts: at(102), role: "assistant", text: "reply" }, { seq: 2, ts: at(103), text: "more" }] });    expect(folded).toEqual({ sessionId: hosted, promptCount: 3, inserted: 1, ...loggedOnly(7) });    const into = await answer<Session>(SLUG, owner, "get_session", { sessionId: hosted });    expect(into).toMatchObject({ externalId: "twin-1", hostOwned: true, title: "the twin's title", state: "running" });    expect(into.prompts.map((p) => [p.seq, p.text])).toEqual([[0, "first words"], [1, "reply"], [2, "more"]]);    const gone = await answer<Session>(SLUG, owner, "get_session", { sessionId: twin.sessionId });    expect(gone).toMatchObject({ externalId: null, state: "withdrawn", error: `folded into the session it was: ${hosted}`, prompts: [] });    expect(gone.endedAt).not.toBeNull();  });  it("does not write a phone message the Mac typed back as a second turn", async () => {    const id = derivedId("cotton_sessions", ["claude-code", "echo-1"]);    await answer(SLUG, owner, "log_session", { tool: "claude-code", externalId: "echo-1", machine: "mac-a", lastActiveAt: at(200), prompts: [{ seq: 0, ts: at(200), text: "hello" }] });    await put(SLUG, [{ verb: "put", table: "session_message", id: "7d1c0c4e-0000-4000-8000-000000000001", created_at: iso(205), data: { to_kind: "session", to_session: id, from_kind: "owner", kind: "instruction", body: "run the\r\ntests  ", status: "claimed" } }]);    const r = await answer(SLUG, owner, "log_session", { tool: "claude-code", externalId: "echo-1", machine: "mac-a", lastActiveAt: at(210), prompts: [{ seq: 1, ts: at(210), text: "run the tests" }, { seq: 2, ts: at(211), role: "assistant", text: "ran them" }, { seq: 3, ts: at(212), text: "run the tests" }] });    // The first typed copy is the message's echo; the second is the owner saying it again.    expect(r).toEqual({ sessionId: id, promptCount: 3, inserted: 2, ...loggedOnly(3) });    const s = await answer<Session>(SLUG, owner, "get_session", { sessionId: id });    expect(s.prompts.map((p) => p.seq)).toEqual([0, 2, 3]);  });  it("makes one row when two hooks of a new session arrive at once", async () => {    const call = (seq: number) => answer(SLUG, owner, "log_session", { tool: "codex", externalId: "race-1", machine: "mac-a", lastActiveAt: at(250 + seq), prompts: [{ seq, ts: at(250 + seq), text: `turn ${seq}` }] });    const [a, b] = await Promise.all([call(0), call(1)]);    expect(a.sessionId).toBe(b.sessionId);    const s = await answer<Session>(SLUG, owner, "get_session", { sessionId: a.sessionId as string });    expect(s.prompts.map((p) => p.seq)).toEqual([0, 1]);  });  it("is a write a lane token may make for its session, while the lane still writes nothing else", async () => {    const lane = await mint(SLUG, credential, "lane widgets", ["read", "lane:widgets"], 7);    const logged = await answer(SLUG, lane, "log_session", { tool: "claude-code", externalId: "lane-1", machine: "mac-a", lastActiveAt: at(300), prompts: [{ seq: 0, ts: at(300), text: "lane work" }] });    expect(logged).toEqual({ sessionId: derivedId("cotton_sessions", ["claude-code", "lane-1"]), promptCount: 1, inserted: 1, ...loggedOnly(2) });    expect(await refusal(SLUG, lane, "create_todo", { title: "not a lane's" })).toBe("this is lane widgets's token: it reads, and writes only its session log — `create_todo` is not log_session");    expect(await answer(SLUG, lane, "get_session", { sessionId: logged.sessionId as string })).toMatchObject({ externalId: "lane-1" });  });});describe("list_sessions and get_session", () => {  const SLUG = "ses-list";  let owner = "";  const ids: string[] = [];  beforeAll(async () => {    ({ owner } = await personalObject(SLUG));    await project(SLUG);    await put(SLUG, [{ table: "project", data: { slug: "old", name: "Old", repos: ["git.example.test/acme/old"], status: "archived" } }]);    const sessions = [      { tool: "claude-code", externalId: "s1", machine: "mac-a", lastActiveAt: at(10), repoUrl: "git.example.test/acme/widgets", prompts: [{ seq: 0, ts: at(10), text: "Fix the stand-up timer, then ship it." }] },      { tool: "claude-code", externalId: "s2", machine: "mac-d", lastActiveAt: at(20), prompts: [{ seq: 0, ts: at(20), text: "Write the Café menu loader" }, { seq: 1, ts: at(21), role: "assistant", text: "The café menu loader is written." }] },      { tool: "codex", externalId: "s3", machine: "mac-a", lastActiveAt: at(30), project: "widgets", prompts: [{ seq: 0, ts: at(30), text: "nothing to see" }] },      { tool: "codex", externalId: "s4", machine: "mac-a", lastActiveAt: at(30) },    ];    for (const s of sessions) ids.push(((await answer(SLUG, owner, "log_session", s)) as { sessionId: string }).sessionId);  });  it("lists newest first with every key in the Rust order, filtered by project, none, machine and since", async () => {    const all = await answer<{ sessions: Record<string, unknown>[] }>(SLUG, owner, "list_sessions", {});    const tie = [ids[2]!, ids[3]!].sort().reverse();    expect(all.sessions.map((s) => s.id)).toEqual([...tie, ids[1], ids[0]]);    expect(Object.keys(all.sessions[0]!)).toEqual(SESSION_KEYS);    expect(Object.keys(all)).toEqual(["sessions"]);    expect((await answer<{ sessions: { id: string }[] }>(SLUG, owner, "list_sessions", { project: "widgets" })).sessions.map((s) => s.id).sort()).toEqual([ids[0], ids[2]].sort());    expect((await answer<{ sessions: { id: string }[] }>(SLUG, owner, "list_sessions", { project: "none" })).sessions.map((s) => s.id).sort()).toEqual([ids[1], ids[3]].sort());    expect((await answer<{ sessions: unknown[] }>(SLUG, owner, "list_sessions", { project: "old" })).sessions).toEqual([]);    expect((await answer<{ sessions: { id: string }[] }>(SLUG, owner, "list_sessions", { machine: "mac-d" })).sessions.map((s) => s.id)).toEqual([ids[1]]);    expect((await answer<{ sessions: unknown[] }>(SLUG, owner, "list_sessions", { since: at(20) })).sessions).toHaveLength(3);    expect((await answer<{ sessions: unknown[] }>(SLUG, owner, "list_sessions", { kind: "conversation" })).sessions).toEqual([]);  });  it("pages by a cursor that is its own handle", async () => {    const first = await answer<{ sessions: { id: string }[]; nextCursor?: string }>(SLUG, owner, "list_sessions", { limit: 3 });    expect(Object.keys(first)).toEqual(["sessions", "nextCursor"]);    const second = await answer<{ sessions: { id: string }[]; nextCursor?: string }>(SLUG, owner, "list_sessions", { limit: 3, cursor: first.nextCursor });    expect(second.sessions.map((s) => s.id)).toEqual([ids[0]]);    expect(second.nextCursor).toBeUndefined();    const decoded = JSON.parse(atob(first.nextCursor!.replace(/-/g, "+").replace(/_/g, "/"))) as Record<string, unknown>;    expect(Object.keys(decoded)).toEqual(["v", "key", "id"]);    expect(decoded).toEqual({ v: 1, key: iso(20), id: ids[1] });  });  it("finds sessions by what was said, with the hits", async () => {    const found = await answer<{ sessions: { id: string; hits: { seq: number; snippet: string }[] }[] }>(SLUG, owner, "list_sessions", { q: "cafe menu" });    expect(found.sessions.map((s) => s.id)).toEqual([ids[1]]);    expect(found.sessions[0]!.hits.map((h) => h.seq).sort()).toEqual([0, 1]);    expect(found.sessions[0]!.hits.find((h) => h.seq === 0)!.snippet).toBe("Write the Café menu loader");    const standup = await answer<{ sessions: { id: string; hits: { snippet: string }[] }[] }>(SLUG, owner, "list_sessions", { q: "stand-up" });    expect(standup.sessions.map((s) => s.id)).toEqual([ids[0]]);    expect(await answer(SLUG, owner, "list_sessions", { q: "zebra" })).toEqual({ sessions: [] });    expect(await answer(SLUG, owner, "list_sessions", { q: '"*"' })).toEqual({ sessions: [] });  });  it("refuses with the Rust sentences", async () => {    expect(await refusal(SLUG, owner, "list_sessions", { since: "last week" })).toBe("since must be an ISO 8601 timestamp");    expect(await refusal(SLUG, owner, "list_sessions", { cursor: "not-a-cursor!" })).toBe("cursor is not one list_sessions handed out — pass nextCursor from the previous page exactly as it came, or drop it to start the list again");    expect(await refusal(SLUG, owner, "list_sessions", { cursor: btoa(JSON.stringify({ v: 2, key: "a", id: "b" })).replace(/=+$/, "") })).toContain("cursor is not one list_sessions handed out");    expect(await refusal(SLUG, owner, "list_sessions", { kind: "chat" })).toBe("kind is one of conversation, thread — not `chat`");    expect(await refusal(SLUG, owner, "list_sessions", { project: "nope" })).toBe('unknown project "nope" — projects are: widgets');    expect(await refusal(SLUG, owner, "get_session", {})).toBe("sessionId is required — the id list_sessions answers with");    expect(await refusal(SLUG, owner, "get_session", { sessionId: "missing" })).toBe("no session with id missing");  });});/** RULE (owner, 15 Nov 2026): the session inbox is retired. Its four tools and the owner's send act are gone, list_sessions has no live filter, and session_message takes no new row; the rows an object already holds stay and are read as before. */describe("the session inbox, retired", () => {  const SLUG = "ses-retired";  let owner = "";  let sessionId = "";  const held = "7d1c0c4e-0000-4000-8000-0000000000aa";  beforeAll(async () => {    ({ owner } = await personalObject(SLUG));    sessionId = ((await answer(SLUG, owner, "log_session", { tool: "claude-code", externalId: "old-1", machine: "mac-a", lastActiveAt: at(0), prompts: [{ seq: 0, ts: at(0), text: "hello" }] })) as { sessionId: string }).sessionId;    await put(SLUG, [{ verb: "put", table: "session_message", id: held, created_at: iso(5), data: { to_kind: "session", to_session: sessionId, from_kind: "owner", kind: "instruction", body: "an old line", status: "done" } }]);  });  it("lists none of the inbox tools and answers none of them", async () => {    const listed = await http<{ result: { tools: { name: string }[] } }>(SLUG, "POST", "/mcp", { jsonrpc: "2.0", id: 1, method: "tools/list" }, { authorization: `Bearer ${owner}` });    const names = listed.body.result.tools.map((t) => t.name);    expect(names).toEqual(expect.arrayContaining(["log_session", "list_sessions", "get_session"]));    for (const gone of ["send_to_session", "poll_session_inbox", "get_session_message", "update_session_message"]) {      expect(names).not.toContain(gone);      const r = await tool(SLUG, owner, gone, { session: { tool: "claude-code", externalId: "old-1" } });      expect(r.isError, gone).toBe(true);    }    expect(Object.keys(ACTS)).not.toContain("send_to_session");    const act = await http<{ code: string }>(SLUG, "POST", "/v1/act", { act: "send_to_session", args: { to: sessionId, body: "carry on" } }, { authorization: `Bearer ${owner}` });    expect([act.status, act.body.code]).toEqual([400, "unknown_act"]);  });  it("writes no new session_message, by create_record or by the direct create act", async () => {    const sentence = "session_message is retired: the rows it holds are kept, and no new one is written";    const data = { to_kind: "session", to_session: sessionId, from_kind: "owner", kind: "instruction", body: "a new line" };    expect(await refusal(SLUG, owner, "create_record", { table: "session_message", data })).toBe(sentence);    const direct = await http<{ code: string; message: string }>(SLUG, "POST", "/v1/act", { act: "create", args: { table: "session_message", data } }, { authorization: `Bearer ${owner}` });    expect([direct.status, direct.body.code, direct.body.message]).toEqual([403, "retired_table", sentence]);  });  it("keeps the rows it holds, and a logged turn is still saved and listed", async () => {    const kept = await answer<{ records: { id: string }[] }>(SLUG, owner, "list_records", { table: "session_message" });    expect(kept.records.map((r) => r.id)).toEqual([held]);    await answer(SLUG, owner, "log_session", { tool: "claude-code", externalId: "old-1", machine: "mac-a", lastActiveAt: at(20), prompts: [{ seq: 1, ts: at(20), role: "assistant", text: "hello back" }] });    const s = await answer<Session>(SLUG, owner, "get_session", { sessionId });    expect(s.prompts.map((p) => [p.seq, p.text])).toEqual([[0, "hello"], [1, "hello back"]]);    const listed = await answer<{ sessions: Record<string, unknown>[] }>(SLUG, owner, "list_sessions", {});    expect(listed.sessions.map((r) => r.id)).toEqual([sessionId]);    expect(Object.keys(listed.sessions[0]!)).toEqual(SESSION_KEYS);  });});describe("list_devices", () => {  const SLUG = "ses-dev";  let owner = "";  beforeAll(async () => {    ({ owner } = await personalObject(SLUG));    const now = Date.now();    const ago = (minutes: number): string => new Date(now - minutes * 60_000).toISOString();    await put(SLUG, [      { verb: "put", table: "device", id: "aaaaaaaa-0000-4000-8000-000000000001", data: { device_id: "key-mac-a", name: "Mac (mac-a)", platform: "mac", approved_at: ago(600), sampled_at: ago(1), cpu_count: 12, agents: JSON.stringify({ "developer-id": "Acme Test Ltd" }), account_ids: JSON.stringify({ anthropic: "acct-one" }), repos: JSON.stringify({ widgets: "main" }), schema_version: 7, ai_holds: JSON.stringify({ held_until: "2026-10-16T12:30:00Z", reason: "anthropic_credits" }) } },      { verb: "put", table: "device", id: "aaaaaaaa-0000-4000-8000-000000000002", data: { device_id: "key-phone", name: "Phone", platform: "ios", approved_at: ago(300) } },      { verb: "put", table: "device", id: "aaaaaaaa-0000-4000-8000-000000000003", data: { device_id: "key-old", name: "Old Mac", platform: "mac", approved_at: ago(900), revoked_at: ago(100), revoked_reason: "sold" } },    ]);  });  it("lists every approval newest first, with every key in the Rust order", async () => {    const all = await answer<{ devices: Record<string, unknown>[] }>(SLUG, owner, "list_devices", {});    expect(all.devices.map((d) => d.deviceId)).toEqual(["key-phone", "key-mac-a", "key-old"]);    const macA = all.devices[1]!;    expect(Object.keys(macA)).toEqual(["id", "deviceId", "name", "platform", "appVersion", "pushAuthorization", "publishesRelayIdentity", "approvedAt", "approvedBy", "revokedAt", "revokedBy", "revokedReason", "cpuCount", "memTotalGb", "memFreePct", "load1", "diskFreeGb", "sessionsRunning", "sessionsCap", "buildLockHeld", "memCommittedGb", "memBudgetGb", "sessionPeakGb", "sessionPeakSamples", "servingRank", "schemaVersion", "copyAsOf", "agents", "capabilities", "accountIds", "repos", "hostVersion", "sampledAt", "chip", "osVersion", "diskTotalGb", "updateHold", "scope", "runnerOrderedAt", "runnerConfirmedAt", "runnerProblem", "aiHolds", "aiSpend", "aiDayCapUsd", "reportedState", "apps"]);    expect(macA).toMatchObject({ name: "Mac (mac-a)", cpuCount: 12, memTotalGb: null, schemaVersion: 7, capabilities: ["signer"], accountIds: { anthropic: "acct-one" }, repos: { widgets: "main" }, publishesRelayIdentity: false, aiHolds: { held_until: "2026-10-16T12:30:00Z", reason: "anthropic_credits" }, reportedState: null });    expect(all.devices[0]).toMatchObject({ agents: {}, capabilities: [], repos: null, accountIds: {} });    const live = await answer<{ devices: { deviceId: string }[] }>(SLUG, owner, "list_devices", { includeRevoked: false });    expect(live.devices.map((d) => d.deviceId)).toEqual(["key-phone", "key-mac-a"]);    expect(await refusal(SLUG, owner, "list_devices", { includeRevoked: "no" })).toBe("includeRevoked must be true or false");  });  it("serves no list_agent_accounts: it went with the AI-account tables (OPEN TABLES, owner, 24 Nov 2026)", async () => {    const listed = await http<{ result: { tools: { name: string }[] } }>(SLUG, "POST", "/mcp", { jsonrpc: "2.0", id: 1, method: "tools/list" }, { authorization: `Bearer ${owner}` });    expect(listed.body.result.tools.map((t) => t.name)).not.toContain("list_agent_accounts");  });});describe("the session tools behind the scope words", () => {  it("is listed to a writer and not to a reader", async () => {    const SLUG = "ses-scope";    const { credential } = await personalObject(SLUG);    const reader = await mint(SLUG, credential, "reader", ["read"]);    const listed = await http<{ result: { tools: { name: string }[] } }>(SLUG, "POST", "/mcp", { jsonrpc: "2.0", id: 1, method: "tools/list" }, { authorization: `Bearer ${reader}` });    const names = listed.body.result.tools.map((t) => t.name);    expect(names).toEqual(expect.arrayContaining(["list_sessions", "get_session", "list_devices"]));    expect(names).not.toContain("log_session");    const r = await tool(SLUG, reader, "log_session", { tool: "claude-code", externalId: "x", machine: "m", lastActiveAt: at(0) });    expect(r).toEqual({ content: [{ type: "text", text: 'this token does not have "write" access. Ask the owner to reconnect with write enabled.' }], isError: true });  });});/** RULE (owner, 27 Oct 2026): agent sessions are conversations and live in Messages beside WhatsApp, SMS and Instagram; Coding sessions is no tool of its own. The session inbox is retired (Nov 2026): the session's conversation reads its old messages as history and offers no input, and the Worker has no send act. */describe("agents inside Messages", () => {  it("lists the channels and the Agents view, and the session's conversation reads session_message", () => {    const messages = KIT_MANIFESTS.find((t) => t.id === "messages")!;    const views = messages.views as { id: string; read: { table: string; where?: Record<string, unknown> }; sort?: unknown }[];    expect(views.map((v) => v.id)).toEqual(expect.arrayContaining(["whatsapp", "sms", "instagram", "agents"]));    for (const channel of ["whatsapp", "sms", "instagram"]) expect(views.find((v) => v.id === channel)!.read).toEqual({ table: "thread", where: { channels: channel }, empty: { line: `empty_views.messages.${channel}`, table: true } });    expect(views.find((v) => v.id === "agents")).toMatchObject({ read: { table: "session" }, sort: { column: "active_at", descending: true } });    expect(messages.tables).toContain("session");    expect(KIT_MANIFESTS.map((t) => t.id)).not.toContain("sessions");    const session = PERSONAL_TABLES.find((t) => t.id === "session")!;    const conversation = session.conversation as Record<string, unknown>;    expect(conversation.table).toBe("session_message");    expect(conversation.send).toBeUndefined();    expect(conversation.sends).toBeUndefined();    expect(conversation.can_send).toBe(false);    expect(conversation.placeholder).toBeUndefined();  });});