diff --git a/apps/connector/package.json b/apps/connector/package.json index 97c2a1ae4..5fd7987a5 100644 --- a/apps/connector/package.json +++ b/apps/connector/package.json @@ -1,7 +1,7 @@ { "name": "@chopin/connector", "private": true, - "version": "0.0.39", + "version": "0.0.40", "type": "module", "scripts": { "build": "bun scripts/build-connector.ts", diff --git a/apps/connector/src/main.ts b/apps/connector/src/main.ts index f50b5176b..76a2b3686 100644 --- a/apps/connector/src/main.ts +++ b/apps/connector/src/main.ts @@ -28,7 +28,7 @@ import { } from "./machine"; import { createOutput } from "./output"; import { permissionMemory } from "./permission"; -import { commandWords, dispatchedPlanners, servePlanners } from "./planner"; +import { commandWords, dispatchedPlanners, forgetPlannerDocument, servePlanners } from "./planner"; import { plannerSpares } from "./planner-spare"; import { launchGate } from "./launch-gate"; import { PLANNER_DISK_SWEEP_MS, sweepPlannerDisks } from "./planner-disks"; @@ -818,6 +818,22 @@ export async function connect(args: string[], injected: Injected = {}) { server: url, output, ask: documents => forgettablePlanners(url, machine, documents, abort.signal), + ...plannerCommand.length + ? { + beforeForget: ({ document, slot }) => + forgetPlannerDocument({ + url, + document, + slot, + command: plannerCommand, + sandbox, + env, + ...(agentStore ? { agentStore } : {}), + output, + signal: backends.signal, + }), + } + : {}, }).catch(() => {}); // The Planners Chopin asks for, of documents this machine's owner chose it for. let dispatched = plannerCommand.length diff --git a/apps/connector/src/nvx.ts b/apps/connector/src/nvx.ts index 0ce6a8723..bebbccd51 100644 --- a/apps/connector/src/nvx.ts +++ b/apps/connector/src/nvx.ts @@ -8,20 +8,20 @@ import { join, posix, win32 } from "node:path"; * only, several a day, so the pin moves only with a `chopin` release that was tested on it. */ export const NVX_RELEASE = { - version: "0.1.0-dev.c753e7b4c288", - tag: "v0.1.0-dev.c753e7b4c288", + version: "0.1.0-dev.30bf7f09e59a", + tag: "v0.1.0-dev.30bf7f09e59a", packages: { "linux-kvm": { file: "nvx-0.1.0-linux-kvm.tar.gz", - sha256: "5f646bac060b2b6d7d447f9d8b274b0ce4e4c45c98bc4f81fa20759082192da9", + sha256: "64d7372790ee53cde628e7c6f76afba737b4cef7f7308582ae9864184afab145", }, "linux-mshv": { file: "nvx-0.1.0-linux-mshv.tar.gz", - sha256: "7ee04b2a4115ac6bc94be8ff263e4d7f8dea9845e2de124bc289e48376e1b8de", + sha256: "72d026350aedcc195e3a82ccaa7efeb822d335fd6a4a55df7ecf4fc98d8902ed", }, "windows-whp": { file: "nvx-0.1.0-windows-whp.zip", - sha256: "b2b185ddb2e00fb24810dbb8da5e0c36f36c1fc3d237cf0cec1b5a8724e4851f", + sha256: "45347c1c95256939c2ab798178fb9ac3628c9f5b976d65e646d8113c573f8e32", }, }, } as const; diff --git a/apps/connector/src/planner-disks.test.ts b/apps/connector/src/planner-disks.test.ts index 99ec0e595..60166809f 100644 --- a/apps/connector/src/planner-disks.test.ts +++ b/apps/connector/src/planner-disks.test.ts @@ -1,9 +1,15 @@ import { afterAll, expect, test } from "bun:test"; -import { existsSync } from "node:fs"; -import { mkdir, mkdtemp, rm, utimes, writeFile } from "node:fs/promises"; +import { existsSync, mkdirSync, writeFileSync } from "node:fs"; +import { mkdir, mkdtemp, readFile, rm, utimes, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; +import { MACHINE_STORE_ADAPTER } from "@chopin/protocol/machine-store"; +import { AgentStore, storeAdapter } from "./machine-store"; +import { vmSpec } from "./nvx"; +import { forgetPlannerDocument } from "./planner"; import { forgetResetDisk, holdDisk, stampPlannerReset, sweepPlannerDisks } from "./planner-disks"; +import type { Launch } from "./sandbox"; +import { hostSandbox } from "./testing/host-sandbox"; let scratch = await mkdtemp(join(tmpdir(), "chopin-planner-disks-")); afterAll(() => rm(scratch, { recursive: true, force: true })); @@ -215,3 +221,249 @@ test("a disk made before a writer last reset its Planner goes, at a sweep or bef expect(await forgetResetDisk(fresh.slot(D(4)), undefined, item)).toBe(false); expect(fresh.kept(D(4))).toEqual([true, true, true]); }); + +const STORE_LOGIN = { + url: + "postgresql://m_0b5e6f0e7a7b4c1d9e1f2a3b4c5d6e7f@db.example.com:5432/m_0b5e6f0e7a7b4c1d9e1f2a3b4c5d6e7f?sslmode=verify-full", + password: "fake-store-password-0123456789", +}; + +async function fakeAgentStore(directory: string) { + let adapter = await storeAdapter(directory, async root => { + let dir = join(root, "node_modules", ...MACHINE_STORE_ADAPTER.split("/")); + mkdirSync(dir, { recursive: true }); + writeFileSync(join(dir, "package.json"), JSON.stringify({ version: "0.10.8" })); + }); + return new AgentStore(STORE_LOGIN, adapter); +} + +test("beforeForget runs only for forgotten documents, never for reset, age, unpair or another server", async () => { + let it = await machine([D(1), D(2), D(3), D(4)], { [D(4)]: B }); + let now = Date.now(); + await utimes(`${it.slot(D(3))}.disk`, new Date(now - 31 * DAY), new Date(now - 31 * DAY)); + let seen: string[] = []; + let removed = await sweepPlannerDisks({ + directory: it.directory, + server: A, + now, + ask: async () => ({ forget: [D(1)], reset: [D(2)] }), + beforeForget: async ({ document, slot }) => { + // The sweep holds the disk lock and the slot's agent folder still exists. + expect(existsSync(`${slot}.disk.held`)).toBe(true); + expect(existsSync(`${slot}.agent`)).toBe(true); + seen.push(document); + }, + }); + expect(removed.sort()).toEqual([D(1), D(2), D(3)]); + expect(seen).toEqual([D(1)]); + + // Unpair (`everything`) never runs beforeForget either. + let unpaired = await machine([D(5)]); + let unpairedSeen: string[] = []; + expect( + await sweepPlannerDisks({ + directory: unpaired.directory, + server: A, + everything: "unpaired", + beforeForget: async ({ document }) => { + unpairedSeen.push(document); + }, + }), + ).toEqual([D(5)]); + expect(unpairedSeen).toEqual([]); +}); + +test("forgetPlannerDocument runs the Planner command with CHOPIN_FORGOTTEN_DOCUMENT and store state, no credentials, and valid microVM spec", async () => { + let it = await machine([D(1)]); + let store = await fakeAgentStore(it.directory); + let record = join(scratch, "forget-record.json"); + let script = join(scratch, "forget-planner.mjs"); + await writeFile( + script, + `import { existsSync, readFileSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +let atomic = process.env.ATOMIC_CODING_AGENT_DIR; +let settings = atomic && existsSync(join(atomic, "settings.json")) + ? JSON.parse(readFileSync(join(atomic, "settings.json"), "utf8")) + : null; +writeFileSync(${JSON.stringify(record)}, JSON.stringify({ + cwd: process.cwd(), + doc: process.env.CHOPIN_FORGOTTEN_DOCUMENT, + url: process.env.CHOPIN_URL, + ai: process.env.CHOPIN_AI, + atomic, + custom: process.env.CUSTOM_SETTING, + settingsUrl: settings?.storage?.options?.url ?? null, + passwordExists: !!(atomic && existsSync(join(atomic, "storage-password"))), + slotLocked: existsSync(${JSON.stringify(`${it.slot(D(1))}.disk.held`)}), + forbidden: Object.keys(process.env).filter(name => + [ + "CHOPIN_DOCUMENT", + "CHOPIN_PLANNER_TOKEN", + "CHOPIN_PLANNER_TOKEN_FILE", + "CHOPIN_MCP_TOKEN_FILE", + "CHOPIN_GITHUB_TOKEN", + "CHOPIN_GITHUB_TOKEN_FILE", + "CHOPIN_GITHUB_TOKEN_EXPIRES_AT", + "CHOPIN_CHECKOUT", + "CHOPIN_WORKTREE", + "CHOPIN_PLANNER_SPARE", + "GITHUB_TOKEN", + "GH_TOKEN", + ].includes(name) + ), +})); +`, + ); + let launches: Launch[] = []; + let baseSandbox = hostSandbox(); + let sandbox = { + ...baseSandbox, + spawn(launch: Launch) { + launches.push(launch); + return baseSandbox.spawn(launch); + }, + }; + let lines: string[] = []; + let output = { + say: (...text: string[]) => lines.push(text.join(" ")), + style: { dim: (text: string) => text }, + } as unknown as Parameters[0]["output"]; + let removed = await sweepPlannerDisks({ + directory: it.directory, + server: A, + output, + ask: async () => ({ forget: [D(1)], reset: [] }), + beforeForget: ({ document, slot }) => + forgetPlannerDocument({ + url: A, + document, + slot, + command: [process.execPath, script], + sandbox, + env: { + CUSTOM_SETTING: "kept-value", + GITHUB_TOKEN: "ghp_should_not_pass", + CHOPIN_PLANNER_TOKEN: "chopin_p_should_not_pass", + }, + agentStore: store, + output, + }), + }); + expect(removed).toEqual([D(1)]); + expect(it.kept(D(1))).toEqual([false, false, false]); + expect(lines.some(line => line.includes("Couldn't let the Planner"))).toBe(false); + expect(lines.some(line => line.includes("Removed the disk"))).toBe(true); + + let seen = JSON.parse(await readFile(record, "utf8")); + expect(seen.doc).toBe(D(1)); + expect(seen.url).toBe(A); + expect(seen.ai).toBe("chopin"); + expect(seen.cwd).toBe(`${it.slot(D(1))}.agent`); + expect(seen.atomic).toBe(join(`${it.slot(D(1))}.agent`, "atomic")); + expect(seen.custom).toBe("kept-value"); + expect(seen.settingsUrl).toBe(STORE_LOGIN.url); + expect(seen.passwordExists).toBe(true); + expect(seen.slotLocked).toBe(true); + expect(seen.forbidden).toEqual([]); + + // The same Launch compiles into a valid microVM spec with no repository, disk or checkout. + expect(launches).toHaveLength(1); + let spec = vmSpec(launches[0]!, { + base: it.directory, + platform: "linux", + proxyPort: 9000, + image: { + layer: { path: "/tmp/layer.erofs", uuid: "00000000-0000-4000-8000-000000000000" }, + path: ["/opt/chopin/agent/bin"], + environment: {}, + user: "1000:1000", + }, + }); + expect(spec.disk).toBeUndefined(); + expect(spec.environment.CHOPIN_FORGOTTEN_DOCUMENT).toBe(D(1)); + expect(spec.shares.some(share => share.host === `${it.slot(D(1))}.agent` && share.mode === "rw")) + .toBe(true); +}); + +test("a failing or timed-out cleanup logs one dimmed line, redacts secrets, and still removes the disk", async () => { + let it = await machine([D(1), D(2)]); + let store = await fakeAgentStore(it.directory); + let failScript = join(scratch, "forget-fail.mjs"); + await writeFile( + failScript, + `console.error("store error with " + ${JSON.stringify(STORE_LOGIN.password)}); +process.exit(2); +`, + ); + let slowScript = join(scratch, "forget-slow.mjs"); + await writeFile(slowScript, "setTimeout(() => {}, 60_000);\n"); + let sandbox = hostSandbox(); + let dimmed: string[] = []; + let lines: string[] = []; + let output = { + say: (...text: string[]) => lines.push(text.join(" ")), + style: { + dim: (text: string) => { + dimmed.push(text); + return text; + }, + }, + } as unknown as Parameters[0]["output"]; + + let removed = await sweepPlannerDisks({ + directory: it.directory, + server: A, + output, + ask: async () => ({ forget: [D(1), D(2)], reset: [] }), + beforeForget: ({ document, slot }) => + forgetPlannerDocument({ + url: A, + document, + slot, + command: [process.execPath, document === D(1) ? failScript : slowScript], + sandbox, + agentStore: store, + output, + timeoutMs: 250, + }), + }); + expect(removed.sort()).toEqual([D(1), D(2)]); + expect(it.kept(D(1))).toEqual([false, false, false]); + expect(it.kept(D(2))).toEqual([false, false, false]); + + let failLine = lines.find(line => line.includes(`Couldn't let the Planner of ${D(1)} clean up:`)); + expect(failLine).toBeDefined(); + expect(failLine).toContain("exit 2"); + expect(failLine).not.toContain("\n"); + expect(failLine).not.toContain(STORE_LOGIN.password); + expect(dimmed).toContain(failLine!); + + let timeoutLine = lines.find(line => + line.includes(`Couldn't let the Planner of ${D(2)} clean up:`) + ); + expect(timeoutLine).toBeDefined(); + expect(timeoutLine).toContain("timed out"); + expect(timeoutLine).not.toContain("\n"); + expect(dimmed).toContain(timeoutLine!); +}); + +test("forgetPlannerDocument skips when no Planner command is configured", async () => { + let it = await machine([D(1)]); + let spawned = false; + let sandbox = { + ...hostSandbox(), + spawn() { + spawned = true; + throw new Error("should not spawn"); + }, + }; + await forgetPlannerDocument({ + url: A, + document: D(1), + slot: it.slot(D(1)), + command: [], + sandbox, + }); + expect(spawned).toBe(false); +}); diff --git a/apps/connector/src/planner-disks.ts b/apps/connector/src/planner-disks.ts index 763f6325f..1579bff09 100644 --- a/apps/connector/src/planner-disks.ts +++ b/apps/connector/src/planner-disks.ts @@ -128,6 +128,12 @@ export async function sweepPlannerDisks(options: { server: string; output?: Output; ask?: ForgetAsk; + /** + * Runs once before removing the slot of a document Chopin says is archived or gone (`forget`, + * never `reset`, age or `everything`), while the sweep holds its disk lock and its agent folder + * still exists. Errors never stop the disk's removal. + */ + beforeForget?: (item: { document: string; repository: string; slot: string }) => Promise; now?: number; days?: number; everything?: string; @@ -173,7 +179,18 @@ export async function sweepPlannerDisks(options: { let used = (await stat(item.path).catch(() => undefined))?.mtimeMs ?? now; if (used >= oldest) continue; } - await removePlannerSlot(item.path.slice(0, -".disk".length)); + let slot = item.path.slice(0, -".disk".length); + if ( + !options.everything && item.server === options.server && forget.has(item.document) + && options.beforeForget + ) { + await options.beforeForget({ + document: item.document, + repository: item.repository, + slot, + }).catch(() => {}); + } + await removePlannerSlot(slot); } finally { sweeping.delete(path); await rm(path, { force: true }); diff --git a/apps/connector/src/planner.ts b/apps/connector/src/planner.ts index a7d849164..6001ebcba 100644 --- a/apps/connector/src/planner.ts +++ b/apps/connector/src/planner.ts @@ -1199,6 +1199,139 @@ export function plannerGuest( }; } +/** Reads the first non-empty line from `stream` (capped) until the stream closes. */ +function firstOutputLine(stream: NodeJS.ReadableStream, set: (line: string) => void) { + return new Promise(resolve => { + let buffered = ""; + stream.setEncoding("utf8"); + stream.on("data", (chunk: string) => { + if (buffered.length > 8_192) return; + buffered += chunk; + let line = buffered.split(/\r?\n/).map(item => item.trim()).find(Boolean); + if (line) set(line.slice(0, 500)); + }); + stream.once("end", () => resolve()); + stream.once("close", () => resolve()); + stream.once("error", () => resolve()); + }); +} + +/** How long a Planner command is given to clean up after a forgotten document. */ +export const FORGET_TIMEOUT_MS = 2 * 60_000; + +/** + * Runs the machine's Planner command once for a document Chopin no longer has, before its slot is + * removed, so the Planner can clean up what it kept for the document outside the disk (for example + * sessions in the machine's agent store). Gets `CHOPIN_FORGOTTEN_DOCUMENT`, `CHOPIN_URL`, the + * Planner's private agent state in `slot` with `agentStore` when present, and the machine's + * sandbox/microVM, with no Chopin credential, GitHub token, checkout or worktree. Bounded by + * `timeoutMs`; never throws, logging one dimmed line on failure. + */ +export async function forgetPlannerDocument(options: { + url: string; + document: string; + slot: string; + command: string[]; + sandbox: Sandbox; + env?: Record; + agentStore?: AgentStore; + output?: Output; + signal?: AbortSignal; + timeoutMs?: number; +}): Promise { + if (!options.command.length) return; + let secrets = [ + ...Object.values(options.env ?? {}), + ...options.agentStore ? [options.agentStore.login.password] : [], + ]; + let fail = (detail: string) => { + let line = redacted(detail, secrets).replace(/\s+/g, " ").trim(); + options.output?.say( + options.output.style.dim( + `… Couldn't let the Planner of ${options.document} clean up: ${line}`, + ), + ); + }; + let home = agentFolder(options.slot); + let inherited = plannerEnvironment( + true, + options.slot, + options.env, + options.agentStore, + options.output, + ); + let env: Record = Object.fromEntries( + Object.entries(withoutSpare(inherited)).filter(([name]) => + name === "CHOPIN_AI" || !name.toUpperCase().startsWith("CHOPIN_") + ), + ); + env.CHOPIN_URL = options.url; + env.CHOPIN_FORGOTTEN_DOCUMENT = options.document; + let child; + try { + child = spawnIn(options.sandbox, { + command: options.command, + cwd: home, + env, + stdin: "ignore", + own: [home], + agentHome: home, + }); + } catch (error) { + fail(error instanceof Error ? error.message : String(error)); + return; + } + let firstStderr: string | undefined; + let firstStdout: string | undefined; + let drained = Promise.all([ + firstOutputLine(child.stderr, line => firstStderr ??= line), + firstOutputLine(child.stdout, line => firstStdout ??= line), + ]); + let exited = new Promise<{ ok: boolean; how: string }>(resolve => { + child.once("error", error => resolve({ ok: false, how: error.message })); + child.once("exit", (code, signal) => + resolve( + code === 0 && !signal + ? { ok: true, how: "exit 0" } + : { ok: false, how: signal ? `signal ${signal}` : `exit ${code}` }, + )); + }); + let timeoutMs = options.timeoutMs ?? FORGET_TIMEOUT_MS; + let timedOut = false; + let aborted = false; + let timer: ReturnType | undefined; + let stop!: () => void; + let onAbort = () => { + aborted = true; + stop(); + }; + let stopped = new Promise(resolve => { + stop = () => resolve(undefined); + timer = setTimeout(() => { + timedOut = true; + stop(); + }, timeoutMs); + timer.unref?.(); + if (options.signal?.aborted) onAbort(); + else options.signal?.addEventListener("abort", onAbort, { once: true }); + }); + let outcome = await Promise.race([exited, stopped]); + clearTimeout(timer); + options.signal?.removeEventListener("abort", onAbort); + if (outcome === undefined || process.platform !== "win32") await stopBackend(child); + outcome ??= await exited; + await Promise.race([drained, new Promise(resolve => setTimeout(resolve, 500))]); + if (outcome.ok && !timedOut && !aborted) return; + let detail = timedOut + ? `timed out after ${Math.round(timeoutMs / 1_000)}s` + : aborted + ? "stopped" + : firstStderr || firstStdout + ? `${outcome.how}: ${firstStderr ?? firstStdout}` + : outcome.how; + fail(detail); +} + /** `env` without `CHOPIN_PLANNER_SPARE`: a cold launch is never offered spare mode. */ function withoutSpare(env: Record): Record { let { CHOPIN_PLANNER_SPARE: _spare, ...rest } = env; diff --git a/bun.lock b/bun.lock index eb3f028ca..a818d8f60 100644 --- a/bun.lock +++ b/bun.lock @@ -21,7 +21,7 @@ }, "apps/connector": { "name": "@chopin/connector", - "version": "0.0.39", + "version": "0.0.40", "dependencies": { "@agentclientprotocol/sdk": "1.6.0", "@chopin/experiment": "workspace:*", diff --git a/docs/agent-connection.md b/docs/agent-connection.md index 0cc5a29c2..ab03bfbb0 100644 --- a/docs/agent-connection.md +++ b/docs/agent-connection.md @@ -1579,6 +1579,27 @@ credential's `reset` names when; a disk from before goes before the next launch) no Planner has run on it for 30 days, or when the machine is unpaired or revoked; commits never pushed go with it. +### Forgotten-document cleanup + +When the connector removes a Planner's disk because Chopin says its document is archived +or gone (never for a Planner reset, 30-day age, or unpair/revocation) and +`--planner-command` is configured, it runs that command once before removing the slot +while holding the disk lock, so the Planner can clean up state it kept for the document +outside the disk (for example sessions in the machine's agent store). + +- **Environment**: `CHOPIN_FORGOTTEN_DOCUMENT=`, `CHOPIN_URL`, `CHOPIN_AI=chopin`, + the slot's agent state directories (`ATOMIC_CODING_AGENT_DIR`, etc., with the machine's + agent store settings written there when present), and the connector's `--env` values. + No Chopin credential (`CHOPIN_PLANNER_TOKEN*`, `CHOPIN_MCP_TOKEN_FILE`), no GitHub + token (`CHOPIN_GITHUB_TOKEN*`, `GITHUB_TOKEN`, `GH_TOKEN`), no `CHOPIN_DOCUMENT`, no + checkout or worktree (`CHOPIN_CHECKOUT`, `CHOPIN_WORKTREE`), and no agent connection. +- **Sandbox**: runs in the machine's microVM from the Planner's image with the slot's + agent folder mounted writable as its working directory and `HOME`, and no repository or + disk mounted. +- **Bounds**: at most 2 minutes; a non-zero exit, error, or timeout logs one dimmed line + (`Couldn't let the Planner of clean up: …`) and never stops the disk's + removal. On exit 0, only the usual disk-removal line is logged. + The connector renews the Planner credential in `CHOPIN_PLANNER_TOKEN_FILE` 5 minutes before it expires, for as long as the backend runs and Chopin still lets the machine run the document, and tries again if it cannot reach Chopin, keeping the file it has. It diff --git a/docs/chopin-cli.md b/docs/chopin-cli.md index 013ee4fb3..0f4c4de1d 100644 --- a/docs/chopin-cli.md +++ b/docs/chopin-cli.md @@ -1060,8 +1060,13 @@ What this changes for you: once a Planner Chopin stopped asking for has exited, as when its document is deleted), when someone resets the document's Planner in Chopin (as it next starts here, or at the next hourly check), when no Planner has run on it for 30 days, or when this machine is unpaired or - revoked, never while a microVM runs on it. Its unpushed commits go with it, and the - connector says so. + revoked, never while a microVM runs on it. When Chopin says the document is archived or + gone and `--planner-command` is set, the connector first runs that command once in a + microVM with `CHOPIN_FORGOTTEN_DOCUMENT=` (at most 2 minutes, with the + slot's agent folder and machine store login and no credentials or checkout) so the + Planner can clean up state it kept outside the disk; any failure is logged dimmed and + never stops the disk's removal. Its unpushed commits go with it, and the connector says + so. - **Your checkout over the share is slow to walk.** Reading a whole large checkout from a microVM is much slower than on your machine, so a Planner reads it for what is uncommitted and does its own work in its clone.