Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Compact now: use the engine's in-place compaction when the next message would carry on the same session
laijsg10033e984bbac
diff --git a/docs/verification/context-compaction.md b/docs/verification/context-compaction.mdindex db42c87cda..6f75be563b 100644--- a/docs/verification/context-compaction.md+++ b/docs/verification/context-compaction.md@@ -9,7 +9,17 @@ session, and shows the engine's compaction as a note in the chat when theengine reports it (Claude Code's `compact_boundary`, Codex's`contextCompaction` item). **Compact now** asks the engine first: for ClaudeCode that is its own `/compact` on a fork of the session, as for a warm-summary below, and the conversation moves to that fork.+summary below, and the conversation moves to that fork. For Codex it is+`thread/compact/start` on the app-server the last turn left running, in place:+the conversation stays on its thread, nothing is resent and no summary is+written. It runs only on that kept process (it never starts one), and only when+the conversation's next message would carry on the same thread, as it would+after the same checks a message makes before it reuses the process (the same+Codex account, config.toml and CLI, the thread's provider). The usage Codex+reports for it is recorded; when it sends no usage notification the row has no+tokens and no cost (a fallback, not an estimate), and the context+reading from before it is dropped (the meter shows nothing until the next turn+reports one). With `context.compactAt` set, Compact now on Codex folds instead.OpenMausBot's own fold (below) is what compacts in every other case:@@ -25,7 +35,8 @@ OpenMausBot's own fold (below) is what compacts in every other case:- `context.compactAt` set in config.json: the fold runs there for everyengine, as it did before engines were left to compact themselves;- Compact now when the engine cannot run its own (no session open or parked,- a Claude Code too old to fork, Codex).+ a Claude Code too old to fork, a Codex whose app-server was closed, whose+ next message would not carry on its thread, or with `context.compactAt` set).```shpnpm exec vitest run server/host/conversation-compaction.test.ts server/context-compaction.e2e.test.tsdiff --git a/scripts/control-omb.ts b/scripts/control-omb.tsindex 00a10f97b0..0596e6e40d 100644--- a/scripts/control-omb.ts+++ b/scripts/control-omb.ts@@ -349,6 +349,7 @@ export async function launchVerificationServer(} } : {}),...(extraProviders.includes("codex") ? { codex: {driver: "codex", displayName: "Verification Codex", config: { cli: fileURLToPath(new URL("../server/testing/fake-codex-app-server.ts", import.meta.url)) },+ environment: Object.fromEntries(Object.entries(parentEnv).filter(([key, value]) => key.startsWith("FAKE_CODEX_") && value)),} } : {}),...(extraProviders.includes("cline") ? { cline: {driver: "clineAgent", displayName: "Verification Cline",diff --git a/server/context-compaction.e2e.test.ts b/server/context-compaction.e2e.test.tsindex d7199ec662..971ffee11a 100644--- a/server/context-compaction.e2e.test.ts+++ b/server/context-compaction.e2e.test.ts@@ -1,5 +1,6 @@-import { spawn, type ChildProcess } from "node:child_process";-import { closeSync, existsSync, openSync, readFileSync, writeFileSync } from "node:fs";+import { execFileSync, spawn, type ChildProcess } from "node:child_process";+import { closeSync, existsSync, mkdirSync, mkdtempSync, openSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";import { join } from "node:path";import { fileURLToPath } from "node:url";import { expect, it } from "vitest";@@ -7,6 +8,8 @@ import { launchVerificationServer, runControlOmb, verificationServerEnvironmentimport { request } from "../scripts/mcp-server.ts";import { waitForExit } from "./testing/cleanup.ts";import { readRegistry } from "./testing/registry.ts";+import { withoutTurnClock } from "./testing/turn-clock-text.ts";+import { readUsage } from "./usage-ledger.ts";async function fixture(test: (f: Awaited<ReturnType<typeof setup>>) => Promise<void>, hang = false, fakeEnv: NodeJS.ProcessEnv = {}) {const f = await setup(hang, fakeEnv);@@ -246,3 +249,272 @@ it.each([expect(f.task().resumeCursors.claude === session).toBe(compactions === 0);expect(String(f.turns().at(-1).prompt.message.content).includes("Earlier conversation summary")).toBe(compactions === 1);}, false, { FAKE_CLAUDE_CONTEXT_TOKENS: String(tokens) }), 90_000);++async function codexFixture(test: (f: Awaited<ReturnType<typeof codexSetup>>) => Promise<void>, fakeEnv: NodeJS.ProcessEnv = {}) {+ const f = await codexSetup(fakeEnv);+ try { await test(f); } finally { await f.close(); }+}++async function codexSetup(fakeEnv: NodeJS.ProcessEnv) {+ const scratch = mkdtempSync(join(tmpdir(), "omb-codex-compact-e2e-"));+ const callLog = join(scratch, "codex-calls.ndjson");+ const env = { ...process.env, FAKE_CODEX_MODE: "happy", FAKE_CODEX_CALL_LOG: callLog, FAKE_CODEX_THREAD_IDS: "distinct", FAKE_CODEX_CONTEXT_TOKENS: "1000,1000,270000",+ FAKE_CODEX_CONTEXT_TOKENS_AFTER_COMPACT: "40000", FAKE_CLAUDE_VERSION: "2.1.270", FAKE_CODEX_COMPACT_HOLD_FILE: join(scratch, "compact-hold"), ...fakeEnv };+ const session = await launchVerificationServer(env, undefined, undefined, undefined, undefined, undefined, ["codex"])+ .catch((error) => { rmSync(scratch, { recursive: true, force: true }); throw error; });+ let ready = false;+ try {+ mkdirSync(join(session.info.dataDir, ".codex"));+ const authenticate = (account: string) => writeFileSync(join(session.info.dataDir, ".codex", "auth.json"), JSON.stringify({ auth_mode: "chatgpt", tokens: { account_id: account, access_token: "fixture" } }));+ authenticate("account-1");+ const evidence: unknown[] = [];+ const api = async (path: string, body?: unknown, method = "POST") => {+ const sent = { path, method: body === undefined ? "GET" : method, body };+ try {+ const result = await request(path, body === undefined ? {} : { method, body: JSON.stringify(body) }, session.info.url) as any;+ evidence.push({ ...sent, result });+ return result;+ } catch (error) {+ evidence.push({ ...sent, refused: String((error as Error).message) });+ throw error;+ }+ };+ const cli = async (...args: string[]) => {+ try {+ const result = await runControlOmb(args, { env: { OPENMAUSBOT_URL: session.info.url } }) as any;+ evidence.push({ command: args, result });+ return result;+ } catch (error) {+ evidence.push({ command: args, failed: String((error as Error).message) });+ throw error;+ }+ };+ const holdCompaction = () => writeFileSync(join(scratch, "compact-hold"), "");+ const releaseCompaction = () => rmSync(join(scratch, "compact-hold"), { force: true });+ const bot = (await cli("new-bot", "--name", "Codex context probe")).bot;+ const thread: string = bot.activeTaskId;+ const codex = (await cli("models")).instances.find((item: any) => item.instanceId === "codex");+ const select = (selection: Record<string, unknown>) => api(`/api/bots/${bot.id}/tasks/${thread}`, { modelSelection: selection, requireAvailableModel: true }, "PATCH");+ const model = codex.models.options[0].id as string;+ await select({ instanceId: "codex", model });+ const messages = async () => (await api(`/api/threads/${thread}/messages`)).messages as any[];+ const task = () => readRegistry(session.info.dataDir).bots.find((b: any) => b.id === bot.id).tasks.find((t: any) => t.threadId === thread);+ const idle = () => expect.poll(async () => (await api("/api/bots?messages=0")).bots+ .find((b: any) => b.id === bot.id).tasks.find((t: any) => t.threadId === thread).busy, { timeout: 15_000 }).toBe(false);+ const send = async (text: string) => {+ await cli("send", "--bot", bot.id, "--task", thread, "--text", text);+ expect((await cli("wait", "--bot", bot.id, "--task", thread, "--timeout", "30")).status).toBe("settled");+ };+ const calls = (method?: string): Array<{ pid: number; method: string; params: any }> =>+ (existsSync(callLog) ? readFileSync(callLog, "utf8").trim().split("\n").filter(Boolean).map(line => JSON.parse(line)) : []).filter(call => !method || call.method === method);+ const turnTexts = () => calls("turn/start").map(call => ({ pid: call.pid, thread: call.params.threadId as string,+ text: withoutTurnClock(call.params.input.map((part: any) => part.text ?? "").join("\n")) }));+ const folds = async () => (await messages()).filter(m => m.kind === "compaction" && m.compaction);+ const engineRows = async () => (await messages()).filter(m => m.kind === "compaction" && m.engineCompaction);+ const cursor = () => task().resumeCursors.codex as string;+ const longConversation = async () => {+ for (const text of ["FIRST historical request", "SECOND keep recent", "THIRD correction"]) await send(text);+ await expect.poll(() => task().usage?.context).toMatchObject({ tokens: 270_000, window: 272_000 });+ await expect.poll(() => cursor()).toMatch(/^codex-thread-/);+ expect(await folds()).toHaveLength(0);+ };+ const compact = async () => { await api(`/api/bots/${bot.id}/compact`, { threadId: thread }); await idle(); };+ const usageRows = () => readUsage(session.info.dataDir, { from: new Date(Date.now() - 3_600_000), to: new Date(Date.now() + 3_600_000) })+ .filter(row => row.threadId === thread && row.botId === bot.id).sort((a, b) => a.at.localeCompare(b.at));+ ready = true;+ return { session, api, cli, bot, thread, select, model, messages, task, idle, send, calls, turnTexts, folds, engineRows, cursor, longConversation, compact, authenticate, scratch, usageRows, holdCompaction, releaseCompaction,+ close: async () => {+ try {+ try {+ evidence.push({ commit: execFileSync("git", ["rev-parse", "HEAD"], { encoding: "utf8" }).trim(),+ final: { messages: await messages().catch(() => null), task: task(), usage: usageRows(), fakeCodexCalls: calls() } });+ } finally {+ writeFileSync(`${session.info.logPath}.context.json`, JSON.stringify(evidence, null, 2), { mode: 0o600 });+ console.info(`Codex compaction evidence: ${session.info.logPath}.context.json`);+ }+ } finally {+ try { await session.close(); } finally { rmSync(scratch, { recursive: true, force: true }); }+ }+ } };+ } finally { if (!ready) { try { await session.close(); } finally { rmSync(scratch, { recursive: true, force: true }); } } }+}++const sameThreadAfterCompaction = async (f: Awaited<ReturnType<typeof codexSetup>>) => {+ await expect.poll(() => f.cursor()).toMatch(/^codex-thread-/);+ const session = f.cursor();+ const turns = f.turnTexts();+ expect(turns).toHaveLength(3);+ const pid = turns[0]!.pid;+ expect(new Set(turns.map(turn => turn.pid))).toEqual(new Set([pid]));+ await expect.poll(() => f.task().handedMessages?.codex?.session).toBe(session);+ const ledger = JSON.stringify(f.task().handedMessages);+ await f.compact();+ expect(f.calls("thread/compact/start")).toEqual([{ pid, method: "thread/compact/start", params: { threadId: session } }]);+ expect(await f.folds()).toHaveLength(0);+ const rows = await f.engineRows();+ expect(rows).toHaveLength(1);+ expect(rows[0]).toMatchObject({ kind: "compaction", engineCompaction: true });+ expect(rows[0].compaction).toBeUndefined();+ await expect.poll(() => f.task().usage.context).toBeUndefined();+ expect(f.task().lastContextModel).toBeUndefined();+ expect(f.cursor()).toBe(session);+ expect(JSON.stringify(f.task().handedMessages)).toBe(ledger);+ await expect.poll(() => f.usageRows().length).toBe(4);+ expect(f.usageRows()[3]).toMatchObject({ instanceId: "codex", driverKind: "codex", input: 0, output: 0, costUsd: null });+ const listed = (await f.api("/api/bots?messages=0")).bots.find((b: any) => b.id === f.bot.id).tasks.find((t: any) => t.threadId === f.thread);+ expect(listed.usage?.context).toBeUndefined();+ await f.send("FOURTH after compaction");+ const next = f.turnTexts().at(-1)!;+ expect(f.calls("thread/start")).toHaveLength(1);+ expect(next).toEqual({ pid, thread: session, text: "FOURTH after compaction" });+ expect(await f.folds()).toHaveLength(0);+ expect(f.cursor()).toBe(session);+ await expect.poll(() => f.task().usage.context).toMatchObject({ tokens: 40_000 });+};++const foldedToNewThread = async (f: Awaited<ReturnType<typeof codexSetup>>, oldSession: string, requests = 0) => {+ expect(f.calls("thread/compact/start")).toHaveLength(requests);+ const record = (await f.folds()).at(-1);+ expect(record.compaction.by).toBe("person");+ await f.send("FOURTH after the fold");+ expect(f.calls("thread/start")).toHaveLength(2);+ const next = f.turnTexts().at(-1)!;+ expect(next.thread).not.toBe(oldSession);+ await expect.poll(() => f.cursor()).toBe(next.thread);+ expect(next.text).toContain("Earlier conversation summary");+};++it("Compact now compacts a Codex conversation in place on its kept process: the next message goes on in the same thread, with nothing resent and nothing folded", () => codexFixture(async f => {+ await f.longConversation();+ await sameThreadAfterCompaction(f);+}), 90_000);++it("books the usage Codex reports for a compaction, and the next turn still counts its own", () => codexFixture(async f => {+ await f.longConversation();+ await f.compact();+ await expect.poll(() => f.usageRows().length).toBe(4);+ expect(f.usageRows()[3]).toMatchObject({ instanceId: "codex", input: 50, output: 5, cachedInput: 20 });+ await f.send("FOURTH after compaction");+ await expect.poll(() => f.usageRows().length).toBe(5);+ expect(f.usageRows()[4]).toMatchObject({ input: 7, output: 3, cachedInput: 4 });+}, { FAKE_CODEX_COMPACT_USAGE: JSON.stringify({ inputTokens: 50, outputTokens: 5, cachedInputTokens: 20 }) }), 90_000);++it("folds, as before engines compacted themselves, when the person set where to fold", () => codexFixture(async f => {+ await f.api("/api/config", { context: { compactAt: 0.5 } }, "PATCH");+ await f.longConversation();+ const session = f.cursor();+ await f.compact();+ await foldedToNewThread(f, session);+}), 90_000);++it("folds, as it always did, when the process the last turn left is gone", () => codexFixture(async f => {+ await f.longConversation();+ const session = f.cursor();+ const { pid } = f.turnTexts().at(-1)!;+ process.kill(pid, "SIGKILL");+ await expect.poll(() => {+ const log = join(f.session.info.dataDir, "native", `${f.thread}.ndjson`);+ return existsSync(log) && readFileSync(log, "utf8").includes("exited while idle");+ }).toBe(true);+ await f.compact();+ await foldedToNewThread(f, session);+}), 90_000);++it("folds the branch the person is on, and sends the other thread nothing, after switching to another branch", () => codexFixture(async f => {+ await f.longConversation();+ const session = f.cursor();+ const earlier = (await f.messages()).filter(m => m.role === "bot" && m.kind === "text")[0];+ await f.api(`/api/bots/${f.bot.id}/active-branch`, { threadId: f.thread, messageId: earlier.id });+ await f.compact();+ await foldedToNewThread(f, session);+}), 90_000);++it("folds, rather than report a compaction the next message would not use, when the thread moves to the bot's own folder", () => codexFixture(async f => {+ await f.longConversation();+ const session = f.cursor();+ const project = mkdtempSync(join(f.scratch, "project-"));+ await f.api(`/api/bots/${f.bot.id}`, { cwd: project }, "PATCH");+ await f.compact();+ await foldedToNewThread(f, session);+}), 90_000);++it("folds when the effort the thread holds is set back to the default, which would make the next message start over", () => codexFixture(async f => {+ await f.select({ instanceId: "codex", model: f.model, effort: "high" });+ await f.longConversation();+ const session = f.cursor();+ await f.select({ instanceId: "codex", model: f.model });+ await f.compact();+ await foldedToNewThread(f, session);+}), 90_000);++it("folds when the account was signed into another one since the last turn, and never sends the old process the request", () => codexFixture(async f => {+ await f.longConversation();+ const session = f.cursor();+ f.authenticate("account-2");+ await f.compact();+ await foldedToNewThread(f, session);+}), 90_000);++it("folds when Codex does not compact", () => codexFixture(async f => {+ await f.longConversation();+ const session = f.cursor();+ await f.compact();+ await foldedToNewThread(f, session, 1);+}, { FAKE_CODEX_COMPACT: "error" }), 90_000);++it("books a compaction Codex sends no usage notification for as a row of no tokens and no cost", () => codexFixture(async f => {+ await f.longConversation();+ await f.compact();+ await expect.poll(() => f.usageRows().length).toBe(4);+ expect(f.usageRows()[3]).toMatchObject({ instanceId: "codex", input: 0, output: 0, costUsd: null });+ await f.send("FOURTH after compaction");+ await expect.poll(() => f.usageRows().length).toBe(5);+ expect(f.usageRows()[4]).toMatchObject({ input: 7, output: 3, cachedInput: 4 });+}, { FAKE_CODEX_COMPACT_NO_USAGE: "1" }), 90_000);++it("writes nothing, and folds nothing, when the effort the thread holds was set back to the default while Codex compacted", () => codexFixture(async f => {+ await f.select({ instanceId: "codex", model: f.model, effort: "high" });+ await f.longConversation();+ const session = f.cursor();+ f.holdCompaction();+ await f.api(`/api/bots/${f.bot.id}/compact`, { threadId: f.thread });+ await expect.poll(() => f.calls("thread/compact/start").length).toBe(1);+ await f.select({ instanceId: "codex", model: f.model });+ f.releaseCompaction();+ await f.idle();+ expect(f.calls("thread/compact/start")).toHaveLength(1);+ expect(await f.engineRows()).toHaveLength(0);+ expect(await f.folds()).toHaveLength(0);+ expect(f.task().usage.context).toMatchObject({ tokens: 270_000 });+ expect(f.cursor()).toBe(session);+ await expect.poll(() => f.usageRows().length).toBe(4);+}), 90_000);++it("lets a second click do nothing while the first runs, and again once it is done", () => codexFixture(async f => {+ await f.longConversation();+ f.holdCompaction();+ await f.api(`/api/bots/${f.bot.id}/compact`, { threadId: f.thread });+ await expect.poll(() => f.calls("thread/compact/start").length).toBe(1);+ await expect(f.api(`/api/bots/${f.bot.id}/compact`, { threadId: f.thread })).rejects.toThrow(/already working/);+ f.releaseCompaction();+ await f.idle();+ await f.compact();+ expect(f.calls("thread/compact/start")).toHaveLength(1);+ expect(await f.engineRows()).toHaveLength(1);+ expect(await f.folds()).toHaveLength(0);+}), 90_000);++it("leaves the first turn of another engine after a Codex compaction to replay the conversation as it always does", () => codexFixture(async f => {+ await f.longConversation();+ await f.compact();+ expect(await f.engineRows()).toHaveLength(1);+ const claude = (await f.cli("models")).instances.find((item: any) => item.instanceId === "claude");+ await f.select({ instanceId: "claude", model: claude.models.options[0].id });+ await f.send("FIFTH asked of Claude");+ const prompt = String(JSON.parse(readFileSync(f.session.fixtureDumpPath, "utf8")).prompt.message.content);+ expect(prompt).toContain("FIRST historical request");+ expect(prompt).toContain("THIRD correction");+ expect(prompt).toContain("FIFTH asked of Claude");+ expect(prompt).not.toContain("Earlier conversation summary");+ expect(await f.folds()).toHaveLength(0);+}), 90_000);diff --git a/server/fresh-start.e2e.test.ts b/server/fresh-start.e2e.test.tsindex 27b2aac327..6de9032a4e 100644--- a/server/fresh-start.e2e.test.ts+++ b/server/fresh-start.e2e.test.ts@@ -39,7 +39,7 @@ async function setup(extraEnv: NodeJS.ProcessEnv) {it("sends the provider nothing from before the divider, while a warm session and the turn before it stay untouched", async () => {// The reply state keeps the scripted replies in order across the new process, so "OLD" only ever marks the turns before the divider.const dir = mkdtempSync(join(tmpdir(), "omb-fresh-start-"));- const f = await setup({ FAKE_CLAUDE_REPLIES: JSON.stringify(["OLD_BETA_REPLY", "OLD_DELTA_REPLY", "after one", "after two", "after three"]), FAKE_CLAUDE_REPLY_STATE: join(dir, "replies") });+ const f = await setup({ FAKE_CLAUDE_REPLIES: JSON.stringify(["OLD_BETA_REPLY", "OLD_DELTA_REPLY", "after one", "after two", "after three"]), FAKE_CLAUDE_REPLY_STATE: join(dir, "replies"), FAKE_CODEX_COMPACT: "unsupported" });try {const first = await f.send("OLD_SECRET_ALPHA remember this");expect(first.prompt).toBe("OLD_SECRET_ALPHA remember this");diff --git a/server/helper-model.e2e.test.ts b/server/helper-model.e2e.test.tsindex 873d839dd8..50eb60b825 100644--- a/server/helper-model.e2e.test.ts+++ b/server/helper-model.e2e.test.ts@@ -54,7 +54,7 @@ async function boot(extraConfig: Record<string, unknown>) {writeFileSync(join(home, ".openmausbot", "config.json"), JSON.stringify({instances: {claude: { driver: "claudeAgent", config: { cli: fake("fake-claude-cli.ts"), permissionMode: "bypassPermissions" } },- codex: { driver: "codex", config: { cli: fake("fake-codex-app-server.ts") } },+ codex: { driver: "codex", environment: { FAKE_CODEX_COMPACT: "unsupported" }, config: { cli: fake("fake-codex-app-server.ts") } },pi: { driver: "piAgent", environment: { FAKE_PI_MODE: "tooluse" }, config: { cli: fake("fake-pi-cli.ts"), fullAuto: true } },},memory: { captureQuietMs: 1_000 },diff --git a/server/host/conversation-compaction.test.ts b/server/host/conversation-compaction.test.tsindex e60adefc91..eeb1d2d2b4 100644--- a/server/host/conversation-compaction.test.ts+++ b/server/host/conversation-compaction.test.ts@@ -70,27 +70,35 @@ describe("claudeCompactionDisabled", () => {describe("compactConversation", () => {const bot = { id: "bot" } as BotRecord;const thread = "thread";- function setup(options: { tokens: number; nativeCompaction?: boolean; engineCompactionOn?: boolean; engineCompact?: boolean; compactAt?: number;- generateText?: ConversationCompactionDeps["generateText"]; claimIsCurrent?: () => boolean }) {+ function setup(options: { tokens: number; nativeCompaction?: boolean; engineCompactionOn?: boolean; engineCompact?: boolean | "stale"; compactAt?: number;+ generateText?: ConversationCompactionDeps["generateText"]; claimIsCurrent?: () => boolean; resumes?: boolean; applied?: string }) {const messages: Message[] = ["one", "two", "three", "four"].flatMap((word, index) => [{ id: `u${index}`, role: "user", kind: "text", text: `ask ${word}`, at: index * 2 } as Message,{ id: `b${index}`, role: "bot", kind: "text", text: `answer ${word}`, at: index * 2 + 1 } as Message,]);const asked: string[] = [];+ const checks: Array<{ model: string; compactAtSet: boolean; resumes: boolean; current: boolean; selection: { instanceId: string; model: string | null } | undefined }> = [];const summarizing: boolean[] = [];+ const patches: Array<Record<string, unknown>> = [];const deps: ConversationCompactionDeps = {store: {- taskByThread: () => ({ lastContextModel: "engine:model", usage: { context: { tokens: options.tokens, window: 200_000 } }, resumeCursors: {} }) as never,+ taskByThread: () => ({ lastContextModel: "engine:model", usage: { context: { tokens: options.tokens, window: 200_000 } }, resumeCursors: {}, appliedCompactionId: options.applied }) as never,activePath: () => messages,- patchTask: () => undefined as never,+ patchTask: (_botId: string, _threadId: string, patch: Record<string, unknown>) => { patches.push(patch); return undefined as never; },appendMessage: (_threadId: string, message: Partial<Message>) => { const made = { id: `m${messages.length}`, ...message } as Message; messages.push(made); return made; },} as never,context: () => (options.compactAt === undefined ? undefined : { compactAt: options.compactAt }),directContext: (_bot, _thread, all) => all.filter((m) => m.kind === "text").map((m) => ({ id: m.id, role: m.role === "user" ? "user" as const : "assistant" as const, text: m.text ?? "" })),- latestCompaction: () => undefined,+ latestCompaction: () => (options.applied ? { id: options.applied } : undefined) as never,nativeCompactTokens: () => 200_000,engineCompactionOn: () => options.engineCompactionOn ?? true,- engineCompact: async (target) => { asked.push(target.instanceId); return options.engineCompact ?? false; },+ engineCompact: async (target, _signal, check) => {+ asked.push(target.instanceId);+ checks.push({ model: check.model, compactAtSet: check.compactAtSet, resumes: check.resumes("session-1"), current: check.current(), selection: check.selectionNow() });+ return options.engineCompact === "stale" ? "stale" : options.engineCompact ? "done" : "skipped";+ },+ resumesSession: () => options.resumes ?? true,+ currentSelection: () => ({ instanceId: "engine", model: "model" }),generateText: options.generateText ?? (() => undefined),claimIsCurrent: options.claimIsCurrent ?? (() => true),controllers: new Map(),@@ -101,7 +109,7 @@ describe("compactConversation", () => {const instance = { instanceId: "engine", driverKind: "claudeAgent", adapter: { capabilities: { nativeCompaction: options.nativeCompaction ?? true } } };const run = (manual: boolean) => createConversationCompaction(deps)({ bot, threadId: thread, generation: "g", instance, model: "model", excludedIds: new Set(), manual });const folds = () => messages.filter((m) => m.kind === "compaction");- return { run, folds, asked, deps, summarizing };+ return { run, folds, asked, checks, deps, summarizing, patches };}it("writes no fold before a turn at 164k on an engine that compacts itself, and one on an engine that does not", async () => {@@ -146,6 +154,43 @@ describe("compactConversation", () => {expect(fed.asked).toEqual([]);expect(fed.folds()).toHaveLength(1);});+ it("asks the engine with what its compaction is checked against, and folds nothing when the engine compacted but the conversation moved on", async () => {+ const stale = setup({ tokens: 50_000, engineCompact: "stale", resumes: false });+ await stale.run(true);+ expect(stale.asked).toEqual(["engine"]);+ expect(stale.checks).toEqual([{ model: "model", compactAtSet: false, resumes: false, current: true, selection: { instanceId: "engine", model: "model" } }]);+ expect(stale.folds()).toHaveLength(0);+ expect(stale.summarizing).toEqual([]);+ const gone = setup({ tokens: 50_000, engineCompact: "stale", claimIsCurrent: () => false });+ await gone.run(true);+ expect(gone.folds()).toHaveLength(0);+ expect(gone.checks[0]).toMatchObject({ current: false });+ const set = setup({ tokens: 50_000, compactAt: 3_000, engineCompact: "stale" });+ await set.run(true);+ expect(set.checks[0]).toMatchObject({ compactAtSet: true });+ });++ describe("the floor an applied fold leaves", () => {+ const applied = { applied: "rec" };++ it("is written for an automatic check as it always was", async () => {+ const auto = setup({ tokens: 50_000, ...applied });+ await auto.run(false);+ expect(auto.patches).toEqual([{ contextFloor: 50_000 }]);+ });++ it("is written for Compact now only once it goes on to fold, not when the engine compacted or the conversation moved on", async () => {+ for (const engineCompact of [true, "stale"] as const) {+ const engine = setup({ tokens: 50_000, engineCompact, ...applied });+ await engine.run(true);+ expect(engine.patches).toEqual([]);+ }+ const folded = setup({ tokens: 50_000, ...applied });+ await folded.run(true);+ expect(folded.patches).toEqual([{ contextFloor: 50_000 }]);+ });+ });+it("says it is summarizing while a summary someone waits on is written, and clears it on every way out", async () => {const written = setup({ tokens: 50_000 });await written.run(true);diff --git a/server/host/conversation-compaction.ts b/server/host/conversation-compaction.tsindex 1ac7b6ba99..92e24e8b2a 100644--- a/server/host/conversation-compaction.ts+++ b/server/host/conversation-compaction.ts@@ -2,6 +2,7 @@ import { draftSummary, foldPoint } from "../compaction-summary.ts";import { compactBudget, compactionReading, contextWindowFor, shouldCompact } from "../context-budget.ts";import { MAX_SUMMARY_BYTES, selectReplay } from "../context-rebuild.ts";import type { ModelCatalog } from "../contracts.ts";+import type { EngineCompactCheck, EngineCompactOutcome } from "./warm-summary-host.ts";import type { ContextMessage } from "../delta-context.ts";import { sinceFreshStart } from "../fresh-start.ts";import type { BotRecord, Message, Store } from "../store.ts";@@ -56,8 +57,12 @@ export interface ConversationCompactionDeps {nativeCompactTokens(instance: CompactionInstance, model: string): number | undefined;/** False for an engine whose own compaction is switched off in its environment. */engineCompactionOn(instance: CompactionInstance): boolean;- /** The engine's own compaction of this conversation's session, asked for by the person; false when it has none to offer now. */- engineCompact(target: { botId: string; threadId: string; instanceId: string }, signal: AbortSignal): Promise<boolean>;+ /** The engine's own compaction of this conversation's session, asked for by the person; `skipped` when it has none to offer now. */+ engineCompact(target: { botId: string; threadId: string; instanceId: string }, signal: AbortSignal, check: EngineCompactCheck): Promise<EngineCompactOutcome>;+ /** Whether the conversation's next turn carries on `session`, by the decision that turn makes before it dispatches. */+ resumesSession(input: CompactConversationInput, session: string): boolean;+ /** The engine instance and model the conversation's next turn would run on now. */+ currentSelection(botId: string, threadId: string): { instanceId: string; model: string | null } | undefined;generateText(botId: string, instance: CompactionInstance): ((prompt: string, options?: { signal?: AbortSignal }) => Promise<string>) | undefined;claimIsCurrent(botId: string, generation: string, threadId: string): boolean;controllers: Map<string, { generation: string; controller: AbortController }>;@@ -90,10 +95,11 @@ export function createConversationCompaction(deps: ConversationCompactionDeps) {const measurement = compactionReading(instance.adapter.capabilities, task.lastContextModel === `${instance.instanceId}:${model}` && !task.rewound ? task.usage?.context : undefined);const window = contextWindowFor(model, instance.models, measurement?.window);const bytes = history.reduce((n, entry) => n + Buffer.byteLength(entry.text), 0);- let floor = task.contextFloor;+ let floor = task.contextFloor, seededFloor = false;if (record && record.id === task.appliedCompactionId && floor === undefined && measurement?.tokens) {floor = measurement.tokens;- store.patchTask(bot.id, threadId, { contextFloor: floor });+ seededFloor = true;+ if (!manual) store.patchTask(bot.id, threadId, { contextFloor: floor });}const engineCompacts = instance.adapter.capabilities.nativeCompaction === true && deps.engineCompactionOn(instance);if (!manual && !foldDue({ engineCompacts, configuredCompactAt: settings?.compactAt, contextTokens: measurement?.tokens, estimatedBytes: bytes,@@ -112,8 +118,13 @@ export function createConversationCompaction(deps: ConversationCompactionDeps) {// Someone waits on this summary (not an idle one): the status line says so until every way out below, in the finally.let shown = false;try {- if (manual && engineCompacts && await deps.engineCompact({ botId: bot.id, threadId, instanceId: instance.instanceId }, controller.signal)) return;+ const engine = manual && engineCompacts ? await deps.engineCompact({ botId: bot.id, threadId, instanceId: instance.instanceId }, controller.signal, {+ model, compactAtSet: positive(settings?.compactAt), resumes: (session) => deps.resumesSession(input, session), selectionNow: () => deps.currentSelection(bot.id, threadId),+ current: () => deps.claimIsCurrent(bot.id, generation, threadId),+ }) : "skipped";controller.signal.throwIfAborted();+ if (engine !== "skipped") return;+ if (seededFloor && manual) store.patchTask(bot.id, threadId, { contextFloor: floor });if (!idle && deps.summarizing) { shown = true; deps.summarizing(threadId, true); }const summary = await draftSummary(fold.folded, { signal: controller.signal, generateText: deps.generateText(bot.id, instance) });if (!idle && !deps.claimIsCurrent(bot.id, generation, threadId)) throw deps.cancelled("context summarization stopped");diff --git a/server/host/resume-check.test.ts b/server/host/resume-check.test.tsnew file mode 100644index 0000000000..3dcade83a4--- /dev/null+++ b/server/host/resume-check.test.ts@@ -0,0 +1,130 @@+import { describe, expect, it } from "vitest";++import type { ContextMessage, HandedState } from "../delta-context.ts";+import type { BotRecord, Message, TaskRecord } from "../store.ts";+import type { CompactConversationInput } from "./conversation-compaction.ts";+import { createResumeCheck } from "./resume-check.ts";++const messages: Message[] = ["ask one", "answer one", "ask two", "answer two"].map((text, index) =>+ ({ id: `m${index}`, at: index, role: index % 2 ? "bot" : "user", kind: "text", text }) as Message);+const handedAll = (extra: Partial<HandedState> = {}): HandedState => ({ session: "session-1", config: "config", through: "m3", ids: [], ...extra });++function setup(task: Partial<TaskRecord> = {}, options: { record?: Record<string, unknown>; folder?: string; strict?: boolean; keep?: string[]; rules?: string; selection?: Record<string, unknown> } = {}) {+ const bot = { id: "b1", name: "Bot", soul: "soul", modelSelection: options.selection ?? { instanceId: "claude", model: "model" } } as unknown as BotRecord;+ const live = { threadId: "t1", resumeCursors: { claude: "session-1" }, lastInstanceId: "claude", handedMessages: { claude: handedAll() }, ...task } as unknown as TaskRecord;+ const check = createResumeCheck({+ store: { taskByThread: () => live, activePath: () => messages } as never,+ directContext: (_bot, _thread, all): ContextMessage[] => all.map((m) => ({ id: m.id, role: m.role === "user" ? "user" : "assistant", text: m.text ?? "", ...(options.keep?.includes(m.id) ? { keep: true } : {}) })),+ latestCompaction: () => options.record as never,+ context: () => undefined,+ everyBotRules: () => options.rules,+ sectionPrompt: () => "",+ folderToFollow: () => options.folder,+ externalMarker: (id) => id?.startsWith("__external__") ? id : undefined,+ strictResume: () => options.strict ?? true,+ currentBot: () => bot,+ });+ const input = (over: Partial<CompactConversationInput> = {}) => ({ bot, threadId: "t1",+ instance: { instanceId: bot.modelSelection.instanceId, driverKind: bot.modelSelection.instanceId === "codex" ? "codex" : "claudeAgent" }, model: "model", excludedIds: new Set<string>(), manual: true, generation: "g", ...over }) as unknown as CompactConversationInput;+ return { live, bot, check, input, resumes: (over: Partial<CompactConversationInput> = {}, session = "session-1") => check.nextTurnResumes(input(over), session) };+}++describe("whether the next turn carries on a session", () => {+ it("does when every message was delivered to it", () => {+ expect(setup().resumes()).toBe(true);+ });++ it("is about the session the conversation holds, and no other", () => {+ expect(setup().resumes({}, "another")).toBe(false);+ expect(setup({ resumeCursors: {} }).resumes()).toBe(false);+ });++ it("does not after a rewind, or after an update from outside every engine", () => {+ expect(setup({ rewound: true }).resumes()).toBe(false);+ expect(setup({ lastInstanceId: "__external__:1" }).resumes()).toBe(false);+ });++ it("does not for an engine that was not the last one to answer, nor a conversation whose engine has no cursor of its own", () => {+ expect(setup({ lastInstanceId: "codex" }).resumes()).toBe(false);+ expect(setup({ lastInstanceId: "codex", resumeCursors: { claude: "session-1", codex: "x" } }).resumes()).toBe(false);+ });++ it("does for an older conversation with no last engine recorded and one cursor, as the turn itself does", () => {+ expect(setup({ lastInstanceId: undefined }).resumes()).toBe(true);+ expect(setup({ lastInstanceId: undefined, resumeCursors: { claude: "session-1", codex: "x" } }).resumes()).toBe(false);+ });++ it("does not when the thread follows its bot into another folder", () => {+ expect(setup({}, { folder: "/work" }).resumes()).toBe(false);+ });++ it("does not for a summary record whose anchors are on this branch and which was not applied yet, and does for one already applied", () => {+ const record = { id: "m4", firstKeptId: "m2", foldedThroughId: "m1", summary: "summary", by: "person", tokensBefore: 1 };+ const withRecord = [...messages, { id: "m4", at: 4, role: "bot", kind: "compaction", compaction: record } as Message];+ const unapplied = setup({}, { record });+ unapplied.live.resumeCursors = { claude: "session-1" };+ const check = createResumeCheck({+ store: { taskByThread: () => unapplied.live, activePath: () => withRecord } as never,+ directContext: (_bot, _thread, all) => all.map((m) => ({ id: m.id, role: m.role === "user" ? "user" as const : "assistant" as const, text: m.kind === "compaction" ? "" : m.text ?? "" })),+ latestCompaction: () => record as never, context: () => undefined, everyBotRules: () => undefined, sectionPrompt: () => "", folderToFollow: () => undefined, externalMarker: () => undefined, strictResume: () => true, currentBot: () => unapplied.bot,+ });+ expect(check.nextTurnResumes(unapplied.input(), "session-1")).toBe(false);+ unapplied.live.appliedCompactionId = "m4";+ expect(check.nextTurnResumes(unapplied.input(), "session-1")).toBe(true);+ });++ it("does for a summary record from another branch, as a turn resumes there", () => {+ const stale = { id: "m9", firstKeptId: "m2", foldedThroughId: "abandoned", summary: "obsolete", by: "harness", tokensBefore: 1 };+ expect(setup({}, { record: stale }).resumes()).toBe(true);+ });++ it("does not when the delivery ledger cannot say what the session holds, and does when it can", () => {+ expect(setup({ handedMessages: { claude: handedAll({ session: "other" }) } }).resumes()).toBe(false);+ expect(setup({ handedMessages: { claude: handedAll({ through: "gone" }) } }).resumes()).toBe(false);+ expect(setup({ handedMessages: {} }).resumes()).toBe(true);+ expect(setup({ handedMessages: { claude: handedAll({ through: "m1" }) } }).resumes()).toBe(true);+ });++ it("does not for a Codex thread that holds an effort the next turn would clear", () => {+ const codex = { lastInstanceId: "codex", resumeCursors: { codex: "session-1" }, handedMessages: { codex: handedAll({ effort: "high" }) } };+ expect(setup(codex, { selection: { instanceId: "codex", model: "model" } }).resumes()).toBe(false);+ expect(setup(codex, { selection: { instanceId: "codex", model: "model", effort: "high" } }).resumes()).toBe(true);+ });++ it("asks about the selection as it is now, not as it was when the compaction began", () => {+ const codex = { lastInstanceId: "codex", resumeCursors: { codex: "session-1" }, handedMessages: { codex: handedAll({ effort: "high" }) } };+ const f = setup(codex, { selection: { instanceId: "codex", model: "model", effort: "high" } });+ const began = f.input();+ expect(f.check.nextTurnResumes(began, "session-1")).toBe(true);+ f.bot.modelSelection = { instanceId: "codex", model: "model" };+ expect(f.check.nextTurnResumes(began, "session-1")).toBe(false);+ f.bot.modelSelection = { instanceId: "claude", model: "model" };+ expect(f.check.nextTurnResumes(began, "session-1")).toBe(false);+ });++ it("does not when a teammate's result the session has not seen changed the configuration it keeps", () => {+ const unseen = { handedMessages: { claude: handedAll({ through: "m1", config: "old" }) } };+ expect(setup(unseen, { keep: ["m3"] }).resumes()).toBe(false);+ expect(setup({ handedMessages: { claude: handedAll({ through: "m1", config: setup().check.sessionConfigFor({ id: "b1", name: "Bot" } as BotRecord, "claudeAgent", "model", undefined)("soul") }) } }, { keep: ["m3"] }).resumes()).toBe(true);+ expect(setup(unseen).resumes()).toBe(true);+ });++ it("is never true for a task that is gone", () => {+ const { check, input } = setup();+ const gone = createResumeCheck({ store: { taskByThread: () => undefined, activePath: () => messages } as never, directContext: () => [], latestCompaction: () => undefined, context: () => undefined,+ everyBotRules: () => undefined, sectionPrompt: () => "", folderToFollow: () => undefined, externalMarker: () => undefined, strictResume: () => true, currentBot: () => input().bot });+ expect(gone.nextTurnResumes(input(), "session-1")).toBe(false);+ expect(check.nextTurnResumes(input(), "session-1")).toBe(true);+ });++ it("hashes what a resumed session keeps from its launch, the model and effort only for Codex", () => {+ const { check } = setup({}, { rules: "be brief" });+ const bot = { id: "b1", name: "Bot" } as BotRecord;+ const claude = (model: string, effort?: string) => check.sessionConfigFor(bot, "claudeAgent", model, effort)("soul");+ expect(claude("a")).toBe(claude("b", "high"));+ const codex = (model: string, effort?: string) => check.sessionConfigFor(bot, "codex", model, effort)("soul");+ expect(codex("a")).not.toBe(codex("b"));+ expect(codex("a")).not.toBe(codex("a", "high"));+ expect(claude("a")).not.toBe(setup().check.sessionConfigFor(bot, "claudeAgent", "a", undefined)("soul"));+ });+});diff --git a/server/host/resume-check.ts b/server/host/resume-check.tsindex e8bd4e37ac..9172de06ad 100644--- a/server/host/resume-check.ts+++ b/server/host/resume-check.ts@@ -1,16 +1,24 @@import { createHash } from "node:crypto";import { DEFAULT_REBUILD_BYTES, replayToolCalls, selectReplay } from "../context-rebuild.ts";import type { ContextMessage } from "../delta-context.ts";-import type { BotRecord, Message } from "../store.ts";+import { sinceFreshStart } from "../fresh-start.ts";+import { resumePlan } from "../resume-plan.ts";+import type { BotRecord, Message, Store, TaskRecord } from "../store.ts";+import type { CompactConversationInput } from "./conversation-compaction.ts";type Compaction = NonNullable<Parameters<typeof selectReplay>[1]>["compaction"];export interface ResumeCheckDeps {+ store: Pick<Store, "taskByThread" | "activePath">;directContext(bot: BotRecord, threadId: string, messages: Message[]): ContextMessage[];latestCompaction(messages: readonly Message[]): Compaction;context(): { rebuildBytes?: number; replayToolHistory?: boolean } | undefined;everyBotRules(): string | undefined;sectionPrompt(section: string | undefined): string;+ folderToFollow(bot: BotRecord, threadId: string, task: TaskRecord, driverKind: string): string | undefined;+ externalMarker(lastInstanceId: string | undefined): string | undefined;+ strictResume(instanceId: string): boolean;+ currentBot(botId: string, threadId: string): BotRecord | null;}export function createResumeCheck(deps: ResumeCheckDeps) {@@ -29,5 +37,18 @@ export function createResumeCheck(deps: ResumeCheckDeps) {return (soul: string | undefined): string => createHash("sha256").update(JSON.stringify([...persistentConfig, soul])).digest("hex").slice(0, 16);};- return { replayInputs, sessionConfigFor };+ const nextTurnResumes = (input: CompactConversationInput, session: string): boolean => {+ const { threadId, instance } = input;+ const bot = deps.currentBot(input.bot.id, threadId);+ const task = deps.store.taskByThread(input.bot.id, threadId);+ if (!bot || !task || bot.modelSelection.instanceId !== instance.instanceId) return false;+ const { model, effort } = bot.modelSelection;+ const { context, replayable, record, selection } = replayInputs(bot, threadId, sinceFreshStart(deps.store.activePath(threadId)), input.excludedIds);+ const plan = resumePlan({ task, instanceId: instance.instanceId, strictResume: deps.strictResume(instance.instanceId), compacted: selection.compacted, recordId: record?.id,+ folderChanged: deps.folderToFollow(bot, threadId, task, instance.driverKind) !== undefined, contextOrder: context.map((m) => m.id), replayable,+ externalMarker: deps.externalMarker(task.lastInstanceId), coordinationResumed: false, effort });+ return plan.cursor === session && plan.resumes(sessionConfigFor(bot, instance.driverKind, model, effort)(bot.soul));+ };++ return { replayInputs, sessionConfigFor, nextTurnResumes };}diff --git a/server/host/warm-summary-host.test.ts b/server/host/warm-summary-host.test.tsindex 811812c57d..60d9aebe75 100644--- a/server/host/warm-summary-host.test.ts+++ b/server/host/warm-summary-host.test.ts@@ -1,13 +1,13 @@import { describe, expect, it, vi } from "vitest";-import type { IdleCompactResult } from "../contracts.ts";+import type { EngineCompactResult, IdleCompactResult } from "../contracts.ts";import type { HandedState } from "../delta-context.ts";import type { Message } from "../store.ts";import { createJobSlots } from "../job-slots.ts";import { WARM_SUMMARY_GIVE_UP_MS, WARM_SUMMARY_IDLE_MS, WARM_SUMMARY_NOW_MS, WARM_SUMMARY_RETRY_MS, WARM_SUMMARY_SOON_MS } from "../warm-summary.ts";import { addServerLinePacks } from "../server-lines.ts";import { autoCompactWindow } from "../drivers/claude.ts";-import { COMPACTION_STARTED_LINE, createWarmSummaryHost, keptAfterSummary, PRESENCE_HOLD_MS, summaryInstructions, type WarmSummaryHostDeps } from "./warm-summary-host.ts";+import { COMPACTION_STARTED_LINE, createWarmSummaryHost, keptAfterSummary, PRESENCE_HOLD_MS, summaryInstructions, type EngineCompactCheck, type WarmSummaryHostDeps } from "./warm-summary-host.ts";let at = 0;const line = (role: "user" | "bot", text: string, extra: Partial<Message> = {}): Message =>@@ -46,12 +46,13 @@ describe("what a summary keeps", () => {});/** A host over an in-memory conversation with a Claude-like engine. */-function setup(overrides: Partial<WarmSummaryHostDeps> = {}, options: { tokens?: number; native?: boolean; room?: boolean; onCompact?: () => void } = {}) {+function setup(overrides: Partial<WarmSummaryHostDeps> = {}, options: { tokens?: number; native?: boolean; room?: boolean; onCompact?: () => void; inPlace?: (threadId: string, input: { botId?: string; session: string; model?: string | null; selectionNow?: () => { instanceId: string; model: string | null } | undefined; signal?: AbortSignal }) => Promise<EngineCompactResult> } = {}) {let now = 5_000_000;const timers: Array<{ at: number; fn: () => void; cancelled: boolean }> = [];const messages: Message[] = [line("user", "build the page"), line("bot", "built it"), line("user", "make the title bold"),line("bot", "done, it is bold now"), line("user", "and the subtitle?"), line("bot", "the subtitle is bold too")];- const task = { threadId: "t1", resumeCursors: { claude: "live-session" } as Record<string, unknown>, lastInstanceId: "claude",+ const task = { threadId: "t1", resumeCursors: { claude: "live-session" } as Record<string, unknown>, lastInstanceId: "claude", lastContextModel: "claude:m" as string | undefined,+ usage: { input: 10, output: 5, turns: 1, costUsd: null, context: { tokens: 270_000, window: 272_000 } as { tokens: number; window: number } | undefined },handedMessages: { claude: { session: "live-session", config: "cfg", ids: [] } } as Record<string, HandedState> };const appended: Message[] = [];const store = {@@ -62,11 +63,13 @@ function setup(overrides: Partial<WarmSummaryHostDeps> = {}, options: { tokens?:appendMessage: (_threadId: string, message: Partial<Message>) => { appended.push(message as Message); return message; },setResumeCursor: (_botId: string, instanceId: string, cursor: unknown) => { task.resumeCursors[instanceId] = cursor; },setHandedMessages: (_botId: string, _threadId: string, instanceId: string, state: HandedState) => { task.handedMessages[instanceId] = state; },+ patchTask: (_botId: string, _threadId: string, patch: Record<string, unknown>) => Object.assign(task, patch),};const compactCalls: Array<{ threadId: string; instructions: string; session?: string }> = [];let compactResult: IdleCompactResult = { ok: true, session: "fork-session", sessionBefore: "live-session", input: 4, cacheRead: 150_000, cacheWrite: 40, output: 2_400, costUsd: 0.2, model: "claude-opus-5-5" };const holds: Array<{ threadId: string; until: number | null }> = [];const adapter = {+ ...(options.inPlace ? { compactSession: vi.fn(options.inPlace) } : {}),cacheKeepWarm: {...(options.native === false ? {} : { compact: vi.fn(async (threadId: string, input: { instructions: string; session?: string }) => {compactCalls.push({ threadId, ...input });@@ -77,6 +80,7 @@ function setup(overrides: Partial<WarmSummaryHostDeps> = {}, options: { tokens?:},};const book = vi.fn();+ const bookEngineCompact = vi.fn();const fold = vi.fn(async () => true);const deps: WarmSummaryHostDeps = {store: store as unknown as WarmSummaryHostDeps["store"],@@ -91,6 +95,7 @@ function setup(overrides: Partial<WarmSummaryHostDeps> = {}, options: { tokens?:routines: () => ({ listRoutines: () => [], listRuns: () => [] }),fold,book,+ bookEngineCompact,keepWarmUntil: () => undefined,now: () => now,after: (ms, fn) => {@@ -115,7 +120,7 @@ function setup(overrides: Partial<WarmSummaryHostDeps> = {}, options: { tokens?:for (let i = 0; i < 5; i++) await new Promise((resolve) => setImmediate(resolve));};const finishTurn = () => host.turnCompleted({ threadId: "t1", botId: "b1", instanceId: "claude" }, { ok: true, contextTokens: options.tokens ?? 150_000 });- return { host, task, messages, appended, compactCalls, holds, book, fold, advance, finishTurn,+ return { host, task, messages, appended, compactCalls, holds, book, bookEngineCompact, adapter, fold, advance, finishTurn,setCompactResult: (result: IdleCompactResult) => { compactResult = result; }, now: () => now };}@@ -364,3 +369,136 @@ describe("warm summaries for a Claude conversation", () => {expect(g.holds).toEqual([{ threadId: "t1", until: g.now() + PRESENCE_HOLD_MS }]);});});++describe("Compact now", () => {+ const target = { threadId: "t1", botId: "b1", instanceId: "claude" };+ const check = (overrides: Partial<EngineCompactCheck> = {}): EngineCompactCheck => ({ model: "m", compactAtSet: false, resumes: () => true, selectionNow: () => ({ instanceId: "claude", model: "m" }), current: () => true, ...overrides });+ const ok = (usage: { input: number; output: number; cachedInput: number } | null = null): EngineCompactResult => ({ ok: true, usage, model: null });++ it("compacts in place: the cursor and the delivery ledger stay, the session and its engine are remembered, and one engine row is written", async () => {+ const f = setup({}, { inPlace: async () => ok({ input: 90, output: 10, cachedInput: 30 }) });+ const ledger = f.task.handedMessages.claude;+ const signal = new AbortController().signal;+ await expect(f.host.compactNow(target, signal, check())).resolves.toBe("done");+ expect(f.adapter.compactSession).toHaveBeenCalledWith("t1", { botId: "b1", session: "live-session", model: "m", selectionNow: expect.any(Function), signal });+ expect(f.adapter.compactSession!.mock.calls[0]![1].selectionNow!()).toEqual({ instanceId: "claude", model: "m" });+ expect(f.task.resumeCursors.claude).toBe("live-session");+ expect(f.task.handedMessages.claude).toBe(ledger);+ expect(f.task.lastContextModel).toBeUndefined();+ expect(f.task.usage).toEqual({ input: 10, output: 5, turns: 1, costUsd: null, context: undefined });+ expect(f.appended).toEqual([{ role: "bot", kind: "compaction", engineCompaction: true }]);+ expect(f.bookEngineCompact).toHaveBeenCalledWith(target, { ok: true, usage: { input: 90, output: 10, cachedInput: 30 }, model: "m" });+ expect(f.compactCalls).toEqual([]);+ expect(f.book).not.toHaveBeenCalled();+ });++ it("leaves the conversation to the fold when the person set where it folds, for an engine that compacts in place", async () => {+ const f = setup({}, { inPlace: async () => ok() });+ await expect(f.host.compactNow(target, new AbortController().signal, check({ compactAtSet: true }))).resolves.toBe("skipped");+ expect(f.adapter.compactSession).not.toHaveBeenCalled();+ const claude = setup();+ await expect(claude.host.compactNow(target, new AbortController().signal, check({ compactAtSet: true }))).resolves.toBe("done");+ expect(claude.compactCalls).toHaveLength(1);+ });++ it("hands the usage the engine did not report on as no usage, for the caller to book as unreported", async () => {+ const f = setup({}, { inPlace: async () => ok(null) });+ await expect(f.host.compactNow(target, new AbortController().signal, check())).resolves.toBe("done");+ expect(f.bookEngineCompact).toHaveBeenCalledWith(target, expect.objectContaining({ usage: null }));+ });++ it("leaves the conversation as it was, and folds, when the engine did nothing", async () => {+ const f = setup({}, { inPlace: async () => ({ ok: false, reason: "no kept process" }) });+ await expect(f.host.compactNow(target, new AbortController().signal, check())).resolves.toBe("skipped");+ expect(f.appended).toEqual([]);+ expect(f.bookEngineCompact).not.toHaveBeenCalled();+ expect(f.task.lastContextModel).toBe("claude:m");+ expect(f.task.usage.context).toEqual({ tokens: 270_000, window: 272_000 });+ });++ it("never asks the engine when the next turn would not carry on this session", async () => {+ const f = setup({}, { inPlace: async () => ok() });+ await expect(f.host.compactNow(target, new AbortController().signal, check({ resumes: () => false }))).resolves.toBe("skipped");+ expect(f.adapter.compactSession).not.toHaveBeenCalled();+ const claude = setup();+ await expect(claude.host.compactNow(target, new AbortController().signal, check({ resumes: () => false }))).resolves.toBe("skipped");+ expect(claude.compactCalls).toEqual([]);+ expect(claude.book).not.toHaveBeenCalled();+ });++ it("asks the decision about the session the conversation holds", async () => {+ const asked: string[] = [];+ const f = setup({}, { inPlace: async () => ok() });+ await f.host.compactNow(target, new AbortController().signal, check({ resumes: (session) => { asked.push(session); return true; } }));+ expect(asked).toEqual(["live-session", "live-session"]);+ });++ it.each([+ ["the cursor moved", (f: ReturnType<typeof setup>) => async () => { f.task.resumeCursors.claude = "another"; return ok({ input: 5, output: 1, cachedInput: 0 }); }, check()],+ ["the turn lost the conversation", () => async () => ok({ input: 5, output: 1, cachedInput: 0 }), check({ current: () => false })],+ ["the next turn no longer carries on", () => async () => ok({ input: 5, output: 1, cachedInput: 0 }), check({ resumes: (() => { let calls = 0; return () => ++calls === 1; })() })],+ ])("is stale when the engine compacted but %s: usage is booked, nothing else is written", async (_why, inPlace, checked) => {+ const holder: { f?: ReturnType<typeof setup> } = {};+ const f = setup({}, { inPlace: () => inPlace(holder.f!)() });+ holder.f = f;+ await expect(f.host.compactNow(target, new AbortController().signal, checked)).resolves.toBe("stale");+ expect(f.bookEngineCompact).toHaveBeenCalledTimes(1);+ expect(f.appended).toEqual([]);+ expect(f.task.lastContextModel).toBe("claude:m");+ expect(f.task.usage.context).toEqual({ tokens: 270_000, window: 272_000 });+ expect(f.fold).not.toHaveBeenCalled();+ });++ it.each([+ ["model", { instanceId: "claude", model: "another::model" }],+ ["engine instance, with a model of the same name", { instanceId: "another", model: "m" }],+ ["selection, gone", undefined],+ ])("is stale when the %s the next turn would run on changed while the engine compacted, whatever the session decision says", async (_what, now) => {+ const f = setup({}, { inPlace: async () => ok({ input: 5, output: 1, cachedInput: 0 }) });+ await expect(f.host.compactNow(target, new AbortController().signal, check({ selectionNow: () => now }))).resolves.toBe("stale");+ expect(f.bookEngineCompact).toHaveBeenCalledTimes(1);+ expect(f.appended).toEqual([]);+ expect(f.task.lastContextModel).toBe("claude:m");+ expect(f.task.usage.context).toEqual({ tokens: 270_000, window: 272_000 });+ expect(f.fold).not.toHaveBeenCalled();+ });++ it("is stale when it was stopped while the engine compacted", async () => {+ const stop = new AbortController();+ const f = setup({}, { inPlace: async () => { stop.abort(); return ok(); } });+ await expect(f.host.compactNow(target, stop.signal, check())).resolves.toBe("stale");+ expect(f.appended).toEqual([]);+ });++ it("still runs Claude Code's compaction on a fork for an engine without an in-place one, and moves its ledger to the fork", async () => {+ const f = setup();+ await expect(f.host.compactNow(target, new AbortController().signal, check())).resolves.toBe("done");+ expect(f.compactCalls).toHaveLength(1);+ expect(f.task.resumeCursors.claude).toBe("fork-session");+ expect(f.task.handedMessages.claude).toMatchObject({ session: "fork-session" });+ expect(f.book).toHaveBeenCalledTimes(1);+ expect(f.task.lastContextModel).toBe("claude:m");+ expect(f.task.usage.context).toEqual({ tokens: 270_000, window: 272_000 });+ const same = setup();+ same.setCompactResult({ ok: true, session: "live-session", sessionBefore: "live-session", input: 1, cacheRead: 1, cacheWrite: 1, output: 1, costUsd: null, model: null });+ await expect(same.host.compactNow(target, new AbortController().signal, check())).resolves.toBe("done");+ expect(same.task.handedMessages.claude).toMatchObject({ session: "live-session", ids: [] });+ const failed = setup();+ failed.setCompactResult({ ok: false, reason: "busy" });+ await expect(failed.host.compactNow(target, new AbortController().signal, check())).resolves.toBe("skipped");+ });++ it("falls back for an engine with no session of its own", async () => {+ const f = setup({}, { native: false });+ f.task.resumeCursors = {};+ await expect(f.host.compactNow(target, new AbortController().signal, check())).resolves.toBe("skipped");+ });++ it("leaves the idle plan of an engine that only compacts in place on OpenMausBot's own fold", async () => {+ const f = setup({}, { native: false, inPlace: async () => ok() });+ f.finishTurn();+ await f.advance(WARM_SUMMARY_IDLE_MS);+ expect(f.fold).toHaveBeenCalledWith(target, expect.any(AbortSignal));+ expect(f.adapter.compactSession).not.toHaveBeenCalled();+ });+});diff --git a/server/host/warm-summary-host.ts b/server/host/warm-summary-host.tsindex 7062be61c9..fcea00602f 100644--- a/server/host/warm-summary-host.ts+++ b/server/host/warm-summary-host.ts@@ -10,7 +10,7 @@//// The person sees it the way they see compaction today: one activity line for Claude Code's summary, the summary note for// OpenMausBot's fold.-import type { IdleCompactResult } from "../contracts.ts";+import type { EngineCompactResult, IdleCompactResult } from "../contracts.ts";import { isContextMessage, type HandedState } from "../delta-context.ts";import { sinceFreshStart } from "../fresh-start.ts";import { backgroundTextSlots, type JobSlots } from "../job-slots.ts";@@ -40,11 +40,30 @@ export const PRESENCE_HOLD_MS = 10 * 60_000;type CompactFn = (threadId: string, options: { instructions: string; session?: string; signal?: AbortSignal }) => Promise<IdleCompactResult>;+/** What an engine's compaction asked for by the person is checked against, before it and once it is done. */+export interface EngineCompactCheck {+ /** The model selection the conversation's next turn runs on. */+ model: string;+ /** The person set `context.compactAt`: an engine that compacts in place leaves compacting to the fold. */+ compactAtSet: boolean;+ /** Whether the next turn would carry on `session` rather than rebuild from the transcript. */+ resumes(session: string): boolean;+ /** The engine instance and model the next turn would run on now. */+ selectionNow(): { instanceId: string; model: string | null } | undefined;+ /** The turn that holds the conversation for this compaction still does. */+ current(): boolean;+}++/** `skipped`: the engine did nothing or failed, and the caller folds. `done`: the session is compacted. `stale`: the engine+ * compacted, but the conversation moved on while it did, so nothing is written and nothing folds. */+export type EngineCompactOutcome = "skipped" | "done" | "stale";+export interface WarmSummaryHostDeps {/** How many background engine jobs run at once, across bots (job-slots.ts). */slots?: JobSlots;- store: Pick<Store, "taskByThread" | "botByThread" | "groupByThread" | "activePath" | "appendMessage" | "setResumeCursor" | "setHandedMessages">;- instance(instanceId: string): { adapter: { cacheKeepWarm?: { compact?: CompactFn; hold(threadId: string, until: number | null): boolean } } } | null | undefined;+ store: Pick<Store, "taskByThread" | "botByThread" | "groupByThread" | "activePath" | "appendMessage" | "setResumeCursor" | "setHandedMessages" | "patchTask">;+ instance(instanceId: string): { adapter: { cacheKeepWarm?: { compact?: CompactFn; hold(threadId: string, until: number | null): boolean };+ compactSession?(threadId: string, options: { botId?: string; session: string; model?: string | null; selectionNow?: EngineCompactCheck["selectionNow"]; signal?: AbortSignal }): Promise<EngineCompactResult> } } | null | undefined;/** Off with `context.autoCompact: false` or OMB_WARM_SUMMARY=0. */enabled(): boolean;/** Where the engine summarizes by itself, in tokens (Claude Code's --autocompact); undefined when OpenMausBot set none. */@@ -61,6 +80,8 @@ export interface WarmSummaryHostDeps {fold(target: WarmSummaryTarget, signal: AbortSignal): Promise<boolean>;/** The summary call's usage, booked like a keep-warm ping. */book(target: WarmSummaryTarget, result: Extract<IdleCompactResult, { ok: true }>): void;+ /** An engine's in-place compaction's usage; with none reported, a row whose tokens are marked unreported. */+ bookEngineCompact(target: WarmSummaryTarget, result: Extract<EngineCompactResult, { ok: true }>): void;/** Until when keep-warm already holds this conversation's process. */keepWarmUntil(threadId: string): number | undefined;/** The language the conversation's person reads its lines in (server/server-lines.ts); undefined reads as English. */@@ -126,6 +147,26 @@ export function createWarmSummaryHost(deps: WarmSummaryHostDeps) {return { ok: true };};+ const compactInPlace = async (target: WarmSummaryTarget, session: string, check: EngineCompactCheck, signal: AbortSignal): Promise<EngineCompactOutcome> => {+ const { threadId, botId, instanceId } = target;+ const result = await deps.instance(instanceId)!.adapter.compactSession!(threadId, { botId, session, model: check.model, selectionNow: check.selectionNow, signal });+ if (!result.ok) {+ deps.log?.(`compact now ${threadId}: not by the engine (${result.reason})`);+ return "skipped";+ }+ deps.bookEngineCompact(target, { ...result, model: result.model ?? check.model });+ const now = check.selectionNow();+ if (store.taskByThread(botId, threadId)?.resumeCursors[instanceId] !== session || !check.current() || signal.aborted || now?.instanceId !== instanceId || now.model !== check.model || !check.resumes(session)) {+ deps.log?.(`compact now ${threadId}: the engine compacted, but the conversation moved on meanwhile`);+ return "stale";+ }+ const task = store.taskByThread(botId, threadId);+ store.patchTask(botId, threadId, { lastContextModel: undefined, ...(task?.usage ? { usage: { ...task.usage, context: undefined } } : {}) });+ store.appendMessage(threadId, { role: "bot", kind: "compaction", engineCompaction: true });+ deps.log?.(`compact now ${threadId}: compacted in place by the engine`);+ return "done";+ };+const warm = createWarmSummary({now,timeScale: Number(process.env.OMB_WARM_SUMMARY_TIME_SCALE) || 1,@@ -174,12 +215,25 @@ export function createWarmSummaryHost(deps: WarmSummaryHostDeps) {return {...warm,/** The person asked for a summary now: the engine's own compaction of the conversation's session, where the engine has- * one to run outside a turn. False leaves the conversation as it was. */- async compactNow(target: WarmSummaryTarget, signal: AbortSignal): Promise<boolean> {+ * one to run outside a turn, and only on a session the conversation's next turn would carry on. `skipped` leaves the+ * conversation as it was. */+ async compactNow(target: WarmSummaryTarget, signal: AbortSignal, check: EngineCompactCheck): Promise<EngineCompactOutcome> {warm.forget(target.threadId);+ const session = store.taskByThread(target.botId, target.threadId)?.resumeCursors[target.instanceId];+ if (typeof session === "string" && !check.resumes(session)) {+ deps.log?.(`compact now ${target.threadId}: not by the engine (the next turn would not carry on its session)`);+ return "skipped";+ }+ if (typeof session === "string" && deps.instance(target.instanceId)?.adapter.compactSession) {+ if (check.compactAtSet) {+ deps.log?.(`compact now ${target.threadId}: not by the engine (context.compactAt is set, so the fold compacts)`);+ return "skipped";+ }+ return compactInPlace(target, session, check, signal);+ }const outcome = await native(target, { signal, awaited: () => true }, true);if (!outcome.ok) deps.log?.(`compact now ${target.threadId}: not by the engine (${outcome.reason})`);- return outcome.ok;+ return outcome.ok ? "done" : "skipped";},/** The person has the conversation in front of them (opened it, or is active in the app with it open). */sawThread(threadId: string): void {diff --git a/server/index.ts b/server/index.tsindex caaedb681b..2a80178d45 100644--- a/server/index.ts+++ b/server/index.ts@@ -998,6 +998,9 @@ function routineOpener(routineId: string): string {}/** Its turns run in Ask, confined to a private folder, and nothing in it reaches the owner's turns. */+function keepsPrivateFolder(threadId: string, guestConfined = cloudGuestDriven(threadId) || botApiThread(threadId)): boolean {+ return guestConfined || cloudGuestOpened(threadId);+}function cloudGuestOpened(threadId: string): boolean {return Boolean(CLOUD_HOME) && cloudThreadStarters(threadId).some((person) => person !== undefined && !cloudOwnerPerson(person));}@@ -5140,6 +5143,11 @@ function bookForkUsage({ threadId, botId, instanceId }: KeepWarmTarget, result:model: result.model ?? store.taskByThread(bot.id, threadId)?.modelSelection?.model ?? bot.modelSelection.model,input: result.input + result.cacheRead + result.cacheWrite, output: result.output, cachedInput: result.cacheRead, costUsd: result.costUsd, trigger: { kind: "bot", botId: bot.id } });}+function bookEngineCompactUsage({ threadId, botId, instanceId }: KeepWarmTarget, { usage, model }: { usage: { input: number; output: number; cachedInput: number } | null; model: string | null }) {+ const bot = store.bot(botId), instance = registry.get(instanceId);+ if (bot && instance) bookTurnUsage({ botId: bot.id, botName: bot.name, threadId, instanceId, driverKind: instance.driverKind, costUsd: null, trigger: turnTriggers.get(threadId) ?? { kind: "owner" },+ model: model ?? store.taskByThread(bot.id, threadId)?.modelSelection?.model ?? bot.modelSelection.model, input: usage?.input ?? 0, output: usage?.output ?? 0, ...(usage ? { cachedInput: usage.cachedInput } : {}) }, usage !== null);+}const cacheKeepWarm = createCacheKeepWarm({now: () => Date.now(),after: (ms, fn) => {@@ -5181,7 +5189,7 @@ cacheKeepWarmStatus = (threadId) => cacheKeepWarm.status(threadId);const warmSummaries = createWarmSummaryHost({ store, instance: (id) => registry.get(id), queued: hasQueuedSteeredMessages, coordinator, waits: () => botWaits, routines: () => routines,enabled: () => cfg.context?.autoCompact !== false && process.env.OMB_WARM_SUMMARY !== "0" && spendState(cfg, DATA_DIR)?.exceeded !== true, memoryShort: () => engineMemory.headroom() < 0.3,nativeCompactAt: ({ botId, threadId, instanceId }) => { const instance = registry.get(instanceId), measured = store.taskByThread(botId, threadId)?.lastContextModel, at = instance ? nativeCompactTokens(instance, measured?.startsWith(`${instanceId}:`) ? measured.slice(instanceId.length + 1) : botForThread(botId, threadId)?.modelSelection.model) : undefined; return at && Number.isFinite(at) ? at : undefined; },- busy: (botId, threadId) => threadBusy(botId, threadId) || botHasActiveTurn(botId), keepWarmUntil: (threadId) => cacheKeepWarm.status(threadId)?.until, book: bookForkUsage, log: (line) => console.info(line), language: threadLanguage,+ busy: (botId, threadId) => threadBusy(botId, threadId) || botHasActiveTurn(botId), keepWarmUntil: (threadId) => cacheKeepWarm.status(threadId)?.until, book: bookForkUsage, bookEngineCompact: bookEngineCompactUsage, log: (line) => console.info(line), language: threadLanguage,fold: async ({ botId, threadId, instanceId }, idle) => { const bot = store.projectBotForTask(botId, threadId), model = store.taskByThread(botId, threadId)?.lastContextModel, instance = registry.get(instanceId), before = latestCompaction(store.activePath(threadId))?.id;if (bot && instance && model?.startsWith(`${instanceId}:`)) await compactConversation({ bot, threadId, generation: `idle:${randomUUID()}`, instance, model: model.slice(instanceId.length + 1), excludedIds: new Set(), manual: false, idle });return latestCompaction(store.activePath(threadId))?.id !== before; } });@@ -6965,12 +6973,16 @@ function peerReplayText(m: Message, name: string, text: string): string {}const { lineLabels, personPrompt, routineRunNote } = createLineLabels({ sharedChat: (threadId) => sharedMembership() && !store.groupByThread(threadId) && audienceMember(teamHost.audienceOf(threadId)) === null, userName: userNameFor, teamRole: (key) => (teamOwners.people?.list() ?? []).find((one) => personKey({ id: "", email: one.email }) === key)?.role, routineName: (threadId) => { const run = routines?.runForThread(threadId); return routines?.listRoutines().find((one) => one.id === run?.routineId)?.name; } });-const { replayInputs, sessionConfigFor } = createResumeCheck({ directContext, latestCompaction, context: () => cfg.context, everyBotRules: () => cfg.everyBotRules, sectionPrompt: sectionContextSystemPrompt });+const { replayInputs, sessionConfigFor, nextTurnResumes } = createResumeCheck({ store, directContext, latestCompaction, context: () => cfg.context, everyBotRules: () => cfg.everyBotRules, sectionPrompt: sectionContextSystemPrompt,+ folderToFollow: (bot, threadId, task, driverKind) => folderToFollow(bot, threadId, task.cwd, { worksInFolders: supportsWorkspaceFiles(driverKind), keepsPrivateFolder: keepsPrivateFolder(threadId) }),+ externalMarker: (lastInstanceId) => isExternalContextMarker(lastInstanceId) ? lastInstanceId : undefined, strictResume: (instanceId) => registry.get(instanceId)?.adapter.capabilities.strictResume === true, currentBot: (botId, threadId) => store.projectBotForTask(botId, threadId) });const compactConversation = createConversationCompaction({store, context: () => cfg.context, directContext, latestCompaction,nativeCompactTokens: (instance, model) => nativeCompactTokens(instance, model),engineCompactionOn: (instance) => instance.driverKind !== "claudeAgent" || !claudeCompactionDisabled({ ...process.env, ...cfg.instances?.[instance.instanceId]?.environment }),- engineCompact: (target, signal) => warmSummaries.compactNow(target, signal),+ engineCompact: (target, signal, check) => warmSummaries.compactNow(target, signal, check),+ resumesSession: (input, session) => nextTurnResumes(input, session),+ currentSelection: (botId, threadId) => store.projectBotForTask(botId, threadId)?.modelSelection,generateText: (botId, instance) => sideJobs.text("compaction", botId, { instance: instance as NonNullable<ReturnType<typeof registry.get>> })?.generateText,claimIsCurrent: (botId, generation, threadId) => directTurnClaimIsCurrent(botId, generation, threadId),controllers: compactionControllers, cancelled: (reason) => new DirectTurnSetupCancelled(reason), idleFraction: HARNESS_IDLE_FRACTION, summarizing: (threadId, active) => bus.publish({ ...waitEventBase(threadId), type: "context.summarizing", active }),@@ -7710,7 +7722,7 @@ async function beginTurn(const contextOrder = context.map(m => m.id);const transcript = selection.transcript.map(({ role, text }) => ({ role, text }));// Engines keep a session in the folder it started in, so a thread that follows its bot to the bot's working folder starts a new one there.- const followed = folderToFollow(bot, threadId, task.cwd, { worksInFolders: supportsWorkspaceFiles(instance.driverKind), keepsPrivateFolder: guestConfined || cloudGuestOpened(threadId) });+ const followed = folderToFollow(bot, threadId, task.cwd, { worksInFolders: supportsWorkspaceFiles(instance.driverKind), keepsPrivateFolder: keepsPrivateFolder(threadId, guestConfined) });const strictResume = instance.adapter.capabilities.strictResume === true;const externalContextMarker = isExternalContextMarker(task.lastInstanceId) ? task.lastInstanceId : undefined;const resuming = resumePlan({ task, instanceId, strictResume, compacted: selection.compacted, recordId: record?.id, folderChanged: followed !== undefined,