Skip to content

Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.

feat(scripts): add manual Windows Room acceptance journey and run evidence check

shoudi zheng9d88173e0b75
diff --git a/docs/desktop-release.md b/docs/desktop-release.md
index 546fa747..4dba73ae 100644
--- a/docs/desktop-release.md
+++ b/docs/desktop-release.md
@@ -125,6 +125,57 @@ gh release upload native-deps <archive> --repo simplexai-labs/linger
`SHA256SUMS.txt`. A test release is removed with its tag:
`gh release delete desktop-v0.16.36-rc.1 --repo simplexai-labs/linger --cleanup-tag`.
+### Physical Windows acceptance
+
+This is a manual verification flow for real Windows machines; it does not run
+in CI and does not gate releases. Use a digest-verified Windows Setup
+candidate on a clean, ordinary-user desktop with working mouse and keyboard,
+free disk, default Defender, and access from Windows to the configured external
+model endpoint. Pre-stage the Setup; do not build on the test laptop. Codex CLI
+and CC Switch are not prerequisites.
+
+1. Install through the actual Setup UI and complete Quick Install in Pi mode
+ with the configured external model. Record signing/SmartScreen and setup
+ independently. Confirm the Computer is online and its Pi catalog and
+ workspace grant are ready.
+2. Run one unique Room journey using
+ [`room-journey.mjs`](../scripts/acceptance/room-journey.mjs).
+ An aborted Run is a failure as soon as TeamHub persists it for the test
+ message. Success requires a completed Run, its persisted reply linked to
+ that Run with the matching SHA-256 digest, exact new file bytes, and the
+ successful write and terminal events for that Run.
+ Quit and reopen the installed Desktop, then verify that the configuration,
+ Room reply, and file persist.
+3. Test the real graphical uninstaller independently of the Room outcome.
+ Record the app payload, per-user uninstall and startup registrations,
+ shortcuts, process identities, listeners, and retained data checksums
+ before and after. Exit code zero alone does not prove cleanup; report
+ remaining payload, running processes or listeners, and any retry
+ separately from the first attempt.
+
+Keep fault injection and recovery matrices on disposable environments;
+label Windows ARM and native Windows x64 evidence separately. Record build,
+transfer, setup, operator wait, Room terminal detection, reopen, and uninstall
+times separately to show where the next optimization belongs.
+
+For the Room helper, set `LINGER_ACCEPTANCE_BASE_URL` (loopback),
+`LINGER_ACCEPTANCE_OWNER_FILE` (private local owner JSON), and
+`LINGER_ACCEPTANCE_COMPUTER_ID`; use `LINGER_ACCEPTANCE_MODEL` to select a
+specific catalog entry and `LINGER_ACCEPTANCE_TIMEOUT_SECONDS` to override the
+180-second budget. For one-command verification on the isolated host, set
+`LINGER_ACCEPTANCE_CONTEXT_VIEWS` to the daemon's `context-views` directory and
+`LINGER_ACCEPTANCE_AGENT_LOG_ROOT` to the Agent Service's log directory
+containing `agents/`. Alternatively set an exact
+`LINGER_ACCEPTANCE_WORKSPACE` and `LINGER_ACCEPTANCE_AGENT_LOG`. Paths for
+evidence are absolute. Invoke `node scripts/acceptance/room-journey.mjs`.
+Across hosts, `room_observed` means only the Run and persisted reply were
+linked; verify the file bytes and Agent logs separately with
+[`local-runner-message-evidence.mjs`](../scripts/local-runner-message-evidence.mjs)
+(`node scripts/local-runner-message-evidence.mjs --run-evidence` with
+`LINGER_ACCEPTANCE_FILE`, `LINGER_ACCEPTANCE_EXPECTED` or
+`LINGER_ACCEPTANCE_EXPECTED_SHA256`, `LINGER_ACCEPTANCE_AGENT_LOG`, and
+`LINGER_ACCEPTANCE_RUN_ID`).
+
## Release Files
| File | Contents |
diff --git a/scripts/acceptance/room-journey.mjs b/scripts/acceptance/room-journey.mjs
new file mode 100644
index 00000000..0cc7c095
--- /dev/null
+++ b/scripts/acceptance/room-journey.mjs
@@ -0,0 +1,333 @@
+import { randomBytes, randomUUID } from "node:crypto";
+import { readFile, readdir } from "node:fs/promises";
+import { isAbsolute, join } from "node:path";
+import { setTimeout as delay } from "node:timers/promises";
+import { pathToFileURL } from "node:url";
+import {
+ sha256Hex,
+ verifyLocalRunEvidence,
+} from "../local-runner-message-evidence.mjs";
+
+function required(name) {
+ const value = process.env[name]?.trim();
+ if (!value) throw new Error(`${name} is required`);
+ return value;
+}
+
+export async function observeRoom({
+ get,
+ roomID,
+ messageID,
+ agentID,
+ expectedReplySha256,
+ verify,
+ signal,
+ wait = () => delay(1000, undefined, { signal }),
+}) {
+ const room = `/v0/rooms/${encodeURIComponent(roomID)}`;
+ const runs = async (id) => {
+ const page = await get(
+ `${room}/runtime-presentation-runs?message_id=${encodeURIComponent(id)}`,
+ signal,
+ );
+ return page.items.filter(
+ (item) => item.room_id === roomID && item.agent?.id === agentID,
+ );
+ };
+ for (;;) {
+ signal.throwIfAborted();
+ const observed = await runs(messageID);
+ const aborted = observed.find((item) => item.status === "aborted");
+ if (aborted) return { outcome: "aborted", runID: aborted.run_id };
+ const completed = observed.filter((item) => item.status === "completed");
+ if (completed.length) {
+ const page = await get(`${room}/messages`, signal);
+ for (const reply of page.items) {
+ if (reply.author?.id !== agentID) continue;
+ if (
+ expectedReplySha256 &&
+ (typeof reply.raw_message !== "string" ||
+ sha256Hex(reply.raw_message.trim()) !== expectedReplySha256)
+ )
+ continue;
+ const linked = await runs(reply.id);
+ for (const { run_id: runID } of completed) {
+ if (
+ !linked.some(
+ (item) => item.run_id === runID && item.status === "completed",
+ )
+ )
+ continue;
+ if (!verify)
+ return { outcome: "room_observed", runID, replyID: reply.id };
+ if (await verify(runID, signal))
+ return { outcome: "verified", runID, replyID: reply.id };
+ }
+ }
+ }
+ await wait();
+ }
+}
+
+async function main() {
+ const base = new URL(required("LINGER_ACCEPTANCE_BASE_URL"));
+ if (
+ !["http:", "https:"].includes(base.protocol) ||
+ !["127.0.0.1", "localhost", "[::1]"].includes(base.hostname) ||
+ base.username ||
+ base.password ||
+ base.pathname !== "/" ||
+ base.search ||
+ base.hash
+ )
+ throw new Error("The test server must be a loopback HTTP(S) origin");
+ const timeoutSeconds = Number(
+ process.env.LINGER_ACCEPTANCE_TIMEOUT_SECONDS ?? 180,
+ );
+ if (
+ !Number.isInteger(timeoutSeconds) ||
+ timeoutSeconds < 10 ||
+ timeoutSeconds > 600
+ )
+ throw new Error(
+ "LINGER_ACCEPTANCE_TIMEOUT_SECONDS must be an integer from 10 to 600",
+ );
+ const computerID = required("LINGER_ACCEPTANCE_COMPUTER_ID");
+ const ownerText = await readFile(
+ required("LINGER_ACCEPTANCE_OWNER_FILE"),
+ "utf8",
+ );
+ let owner;
+ try {
+ owner = JSON.parse(ownerText);
+ } catch {
+ throw new Error("Owner file is not valid JSON");
+ }
+ if (
+ typeof owner?.owner_email !== "string" ||
+ typeof owner.owner_password !== "string"
+ )
+ throw new Error("Owner file does not contain local owner credentials");
+ const workspace = process.env.LINGER_ACCEPTANCE_WORKSPACE?.trim();
+ const views = process.env.LINGER_ACCEPTANCE_CONTEXT_VIEWS?.trim();
+ const log = process.env.LINGER_ACCEPTANCE_AGENT_LOG?.trim();
+ const logRoot = process.env.LINGER_ACCEPTANCE_AGENT_LOG_ROOT?.trim();
+ if (
+ (workspace && views) ||
+ (log && logRoot) ||
+ Boolean(workspace || views) !== Boolean(log || logRoot) ||
+ [workspace, views, log, logRoot].some(
+ (entry) => entry && !isAbsolute(entry),
+ )
+ )
+ throw new Error(
+ "Provide one absolute workspace or context-views path and one absolute Agent log or log-root path",
+ );
+
+ async function request(route, body, cookie, signal) {
+ const requestTimeout = AbortSignal.timeout(15_000);
+ const response = await fetch(base.origin + route, {
+ method: body === undefined ? "GET" : "POST",
+ headers: {
+ ...(cookie ? { cookie } : {}),
+ ...(body === undefined
+ ? {}
+ : {
+ "content-type": "application/json",
+ "Idempotency-Key": randomUUID(),
+ }),
+ },
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
+ redirect: "error",
+ signal: signal
+ ? AbortSignal.any([signal, requestTimeout])
+ : requestTimeout,
+ });
+ if (!response.ok)
+ throw new Error(
+ `HTTP ${response.status} from ${route.replace(/\/v0\/rooms\/[^/]+/, "/v0/rooms/{room}")}`,
+ );
+ return response;
+ }
+
+ const login = await request("/v0/auth/login", {
+ identifier: owner.owner_email,
+ password: owner.owner_password,
+ });
+ const cookie = login.headers
+ .getSetCookie()
+ .map((value) => value.split(";")[0])
+ .join("; ");
+ if (!cookie) throw new Error("Login returned no session cookie");
+ const { identity } = await login.json();
+ const actor = identity?.actors?.find((item) => item.tenant_id);
+ if (!actor) throw new Error("Login returned no tenant actor");
+ const tenant = encodeURIComponent(actor.tenant_id);
+ const get = async (route, signal) =>
+ (await request(route, undefined, cookie, signal)).json();
+ const post = async (route, body) =>
+ (await request(route, body, cookie)).json();
+ const inventory = await get(`/v0/tenants/${tenant}/local-computers`);
+ const computer = inventory.items?.find(
+ (item) => item.computer_id === computerID,
+ );
+ if (!computer || computer.status !== "online")
+ throw new Error("Selected Computer is not online");
+ const pi = computer.runtimes?.find(
+ (runtime) => runtime.type === "pi" && runtime.status === "ready",
+ );
+ if (!pi?.models?.length)
+ throw new Error("Selected Computer has no ready Pi model");
+ const requestedModel = process.env.LINGER_ACCEPTANCE_MODEL?.trim();
+ const model = requestedModel
+ ? pi.models.find((entry) => entry.id === requestedModel)
+ : (pi.models.find((entry) => entry.is_default) ?? pi.models[0]);
+ if (!model)
+ throw new Error("Requested model is absent from the Computer catalog");
+ const grant = computer.workspace_grants?.find(
+ (entry) => entry.mode === "workspace-write",
+ );
+ if (!grant)
+ throw new Error("Selected Computer has no writable workspace grant");
+
+ const suffix = randomBytes(8).toString("hex");
+ const filename = `linger-acceptance-${suffix}.txt`;
+ const marker = `LINGER_ACCEPTANCE_${suffix.toUpperCase()}`;
+ const reply = `LINGER_REPLY_${suffix.toUpperCase()}`;
+ const expectedFileSha256 = sha256Hex(marker);
+ const expectedReplySha256 = sha256Hex(reply);
+ const name = `Linger Acceptance ${suffix}`;
+ const agent = await post(`/v0/tenants/${tenant}/agents`, {
+ name,
+ instructions:
+ "Complete the user request using the provided tools. Report the result concisely.",
+ runtime: {
+ model: model.id,
+ placement: {
+ type: "local",
+ computer_id: computerID,
+ runtime_type: "pi",
+ workspace_grant_id: grant.grant_id,
+ },
+ },
+ });
+ const agentID = agent.actor.id;
+ const managementID = agent.agent_management_id;
+ if (logRoot && !/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(managementID ?? ""))
+ throw new Error("Agent creation did not return a valid management ID");
+ const agentLog =
+ log ?? (logRoot && join(logRoot, "agents", managementID, "events.ndjson"));
+ const verify =
+ agentLog &&
+ (async (runID, signal) => {
+ if (workspace)
+ return verifyLocalRunEvidence({
+ file: join(workspace, filename),
+ expected: marker,
+ log: agentLog,
+ runId: runID,
+ signal,
+ });
+ const entries = await readdir(views, { withFileTypes: true });
+ for (const entry of entries) {
+ signal.throwIfAborted();
+ if (!entry.isDirectory() || !/^[0-9a-f]{32}$/.test(entry.name))
+ continue;
+ const file = join(views, entry.name, "workspace", filename);
+ if (
+ await verifyLocalRunEvidence({
+ file,
+ expected: marker,
+ log: agentLog,
+ runId: runID,
+ signal,
+ })
+ )
+ return true;
+ }
+ return false;
+ });
+ const room = await post(`/v0/tenants/${tenant}/direct-rooms`, {
+ peer_actor_id: agentID,
+ });
+ const mention = `@${name}`;
+ const text = `Use your write tool to create ${filename} in the current workspace with exactly ${marker} as its complete content. Then send a Room reply whose entire content is exactly ${reply} and nothing else.`;
+ const message = await post(
+ `/v0/rooms/${encodeURIComponent(room.id)}/messages`,
+ {
+ raw_message: `${mention} ${text}`,
+ segments: [
+ {
+ type: "reference",
+ content: mention,
+ target: agentID,
+ target_type: "agent",
+ },
+ { type: "text", content: ` ${text}` },
+ ],
+ },
+ );
+ const ids = {
+ computer_id: computerID,
+ agent_id: agentID,
+ room_id: room.id,
+ message_id: message.id,
+ };
+ console.log(
+ JSON.stringify({
+ phase: "sent",
+ ...ids,
+ model: model.id,
+ filename,
+ expected_file_content: marker,
+ expected_file_sha256: expectedFileSha256,
+ expected_reply: reply,
+ expected_reply_sha256: expectedReplySha256,
+ }),
+ );
+ const sentAt = performance.now();
+ const signal = AbortSignal.timeout(timeoutSeconds * 1000);
+ const result = await observeRoom({
+ get,
+ roomID: room.id,
+ messageID: message.id,
+ agentID,
+ expectedReplySha256,
+ signal,
+ verify,
+ }).catch((error) => {
+ if (signal.aborted) {
+ console.log(
+ JSON.stringify({
+ phase: "timed_out",
+ ...ids,
+ elapsed_ms: Math.round(performance.now() - sentAt),
+ }),
+ );
+ throw new Error(
+ `Room evidence incomplete after ${timeoutSeconds} seconds`,
+ );
+ }
+ throw error;
+ });
+ console.log(
+ JSON.stringify({
+ phase: result.outcome,
+ ...ids,
+ run_id: result.runID,
+ reply_id: result.replyID,
+ elapsed_ms: Math.round(performance.now() - sentAt),
+ }),
+ );
+ if (result.outcome === "aborted") process.exitCode = 1;
+}
+
+if (
+ process.argv[1] &&
+ import.meta.url === pathToFileURL(process.argv[1]).href
+) {
+ main().catch((error) => {
+ console.error(`Acceptance journey failed: ${error.message}`);
+ process.exitCode = 1;
+ });
+}
diff --git a/scripts/local-runner-message-evidence.mjs b/scripts/local-runner-message-evidence.mjs
index e54a68a0..d0f37756 100644
--- a/scripts/local-runner-message-evidence.mjs
+++ b/scripts/local-runner-message-evidence.mjs
@@ -1,6 +1,8 @@
import { createHash } from "node:crypto";
-import { readFileSync } from "node:fs";
+import { createReadStream, readFileSync } from "node:fs";
+import { lstat, readFile } from "node:fs/promises";
import path from "node:path";
+import { createInterface } from "node:readline";
import { fileURLToPath } from "node:url";
export class LocalMessageEvidenceError extends Error {
@@ -10,6 +12,74 @@ export class LocalMessageEvidenceError extends Error {
}
}
+export function sha256Hex(value) {
+ return createHash("sha256").update(value).digest("hex");
+}
+
+export async function verifyLocalRunEvidence({
+ file,
+ expected,
+ expectedSha256,
+ log,
+ runId,
+ signal,
+}) {
+ if (
+ !nonEmptyString(file) ||
+ !nonEmptyString(log) ||
+ !nonEmptyString(runId) ||
+ (expected === undefined &&
+ !/^[a-f0-9]{64}$/.test(String(expectedSha256 ?? "")))
+ )
+ fail("INVALID_INPUT");
+ try {
+ const fileInfo = await lstat(file);
+ if (!fileInfo.isFile() || fileInfo.isSymbolicLink())
+ fail("INVALID_ARTIFACT_FILE");
+ const content = await readFile(file, { signal });
+ if (expected !== undefined) {
+ const marker = Buffer.from(expected);
+ if (fileInfo.size !== marker.length || !content.equals(marker))
+ return false;
+ } else if (sha256Hex(content) !== expectedSha256) {
+ return false;
+ }
+ let successfulWrite = false;
+ let succeeded = false;
+ const stream = createReadStream(log, { encoding: "utf8", signal });
+ const lines = createInterface({ input: stream, crlfDelay: Infinity });
+ try {
+ for await (const line of lines) {
+ let event;
+ try {
+ event = JSON.parse(line);
+ } catch {
+ continue;
+ }
+ if ((event?.runId ?? event?.run_id) !== runId) continue;
+ if (
+ event.event === "agent.tool_call" &&
+ event.tool_name === "write" &&
+ event.is_error === false
+ )
+ successfulWrite = true;
+ if (
+ event.event === "local_run.terminal_persisted" &&
+ event.resultCode === "succeeded"
+ )
+ succeeded = true;
+ if (successfulWrite && succeeded) return true;
+ }
+ } finally {
+ stream.destroy();
+ }
+ return false;
+ } catch (error) {
+ if (error?.code === "ENOENT") return false;
+ throw error;
+ }
+}
+
export function assertLocalMessageEvidence({ report, runtime, expected }) {
if (
!Array.isArray(report) ||
@@ -36,9 +106,7 @@ export function assertLocalMessageEvidence({ report, runtime, expected }) {
operation.run_id !== expected.runId
)
fail("RUNTIME_NOT_SUCCEEDED");
- const finalDigest = createHash("sha256")
- .update(expected.finalText)
- .digest("hex");
+ const finalDigest = sha256Hex(expected.finalText);
const publications = report.filter(
(row) => row?.type === "agent.messages.published",
);
@@ -89,35 +157,71 @@ const fail = (code) => {
throw new LocalMessageEvidenceError(code);
};
+async function runCli() {
+ if (process.argv[2] === "--run-evidence") {
+ const file = process.env.LINGER_ACCEPTANCE_FILE?.trim();
+ const expected = process.env.LINGER_ACCEPTANCE_EXPECTED?.trim();
+ const expectedSha256 =
+ process.env.LINGER_ACCEPTANCE_EXPECTED_SHA256?.trim();
+ const log = process.env.LINGER_ACCEPTANCE_AGENT_LOG?.trim();
+ const runId = process.env.LINGER_ACCEPTANCE_RUN_ID?.trim();
+ if (!file || !log || !path.isAbsolute(file) || !path.isAbsolute(log))
+ fail("INVALID_INPUT");
+ const hasMarker = /^LINGER_ACCEPTANCE_[A-F0-9]{16}$/.test(expected ?? "");
+ const hasDigest = /^[a-f0-9]{64}$/.test(expectedSha256 ?? "");
+ if (!runId || (!hasMarker && !hasDigest)) fail("INVALID_INPUT");
+ const verified = await verifyLocalRunEvidence({
+ file,
+ expected: hasMarker ? expected : undefined,
+ expectedSha256: hasMarker ? undefined : expectedSha256,
+ log,
+ runId,
+ signal: AbortSignal.timeout(15_000),
+ });
+ if (!verified) fail("RUN_EVIDENCE_INCOMPLETE");
+ process.stdout.write(
+ `${JSON.stringify({
+ result: "verified",
+ run_id: runId,
+ file_sha256: hasMarker ? sha256Hex(expected) : expectedSha256,
+ file_content: "exact",
+ successful_write: true,
+ terminal_succeeded: true,
+ })}\n`,
+ );
+ return;
+ }
+
+ const [
+ reportPath,
+ runtimePath,
+ agentId,
+ roomId,
+ runId,
+ operationId,
+ finalText,
+ ] = process.argv.slice(2);
+ const report = readFileSync(reportPath, "utf8")
+ .split("\n")
+ .filter((line) => line.trim())
+ .map((line) => JSON.parse(line));
+ const runtime = JSON.parse(readFileSync(runtimePath, "utf8"));
+ const proof = assertLocalMessageEvidence({
+ report,
+ runtime,
+ expected: { agentId, roomId, runId, operationId, finalText },
+ });
+ process.stdout.write(`${JSON.stringify(proof)}\n`);
+}
+
if (
process.argv[1] &&
path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)
) {
- try {
- const [
- reportPath,
- runtimePath,
- agentId,
- roomId,
- runId,
- operationId,
- finalText,
- ] = process.argv.slice(2);
- const report = readFileSync(reportPath, "utf8")
- .split("\n")
- .filter((line) => line.trim())
- .map((line) => JSON.parse(line));
- const runtime = JSON.parse(readFileSync(runtimePath, "utf8"));
- const proof = assertLocalMessageEvidence({
- report,
- runtime,
- expected: { agentId, roomId, runId, operationId, finalText },
- });
- process.stdout.write(`${JSON.stringify(proof)}\n`);
- } catch (error) {
+ runCli().catch((error) => {
const code =
error instanceof LocalMessageEvidenceError ? error.code : "INVALID_INPUT";
process.stderr.write(`Local message evidence failed: ${code}\n`);
process.exitCode = 1;
- }
+ });
}
diff --git a/scripts/windows-room-acceptance.test.ts b/scripts/windows-room-acceptance.test.ts
new file mode 100644
index 00000000..7a7d00c5
--- /dev/null
+++ b/scripts/windows-room-acceptance.test.ts
@@ -0,0 +1,289 @@
+import { execFile } from "node:child_process";
+import { mkdtemp, rm, symlink, writeFile } from "node:fs/promises";
+import { createServer } from "node:http";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { promisify } from "node:util";
+import { expect, it, vi } from "vitest";
+import { observeRoom } from "./acceptance/room-journey.mjs";
+import {
+ sha256Hex,
+ verifyLocalRunEvidence,
+} from "./local-runner-message-evidence.mjs";
+
+const route = "/v0/rooms/room";
+const sourceRuns = `${route}/runtime-presentation-runs?message_id=source`;
+const replyRuns = `${route}/runtime-presentation-runs?message_id=reply`;
+const run = { run_id: "run", room_id: "room", agent: { id: "agent" } };
+const completed = { ...run, status: "completed" };
+const replyMarker = "LINGER_REPLY_0123456789ABCDEF";
+const replyDigest = sha256Hex(replyMarker);
+const reply = {
+ id: "reply",
+ raw_message: replyMarker,
+ author: { id: "agent" },
+};
+
+function observe(
+ pages: Record<string, unknown[]>,
+ verify = vi.fn().mockResolvedValue(true),
+) {
+ const get = vi.fn(async (url: string, _signal: AbortSignal) => ({
+ items: pages[url]?.shift() ?? [],
+ }));
+ let time = 0;
+ const result = observeRoom({
+ get,
+ roomID: "room",
+ messageID: "source",
+ agentID: "agent",
+ expectedReplySha256: replyDigest,
+ verify,
+ signal: new AbortController().signal,
+ wait: async () => {
+ if (++time === 4) throw new Error("deadline");
+ },
+ });
+ return { get, verify, result };
+}
+
+it("returns a persisted abort immediately without querying replies", async () => {
+ const { get, verify, result } = observe({
+ [sourceRuns]: [[{ ...run, status: "aborted" }]],
+ });
+ await expect(result).resolves.toEqual({ outcome: "aborted", runID: "run" });
+ expect(get.mock.calls).toEqual([[sourceRuns, expect.any(AbortSignal)]]);
+ expect(verify).not.toHaveBeenCalled();
+});
+
+it("ignores active and unrelated runs, then waits for linked evidence", async () => {
+ const verify = vi.fn().mockResolvedValueOnce(false).mockResolvedValue(true);
+ const { get, result } = observe(
+ {
+ [sourceRuns]: [
+ [
+ { ...run, status: "active", replied: true },
+ { ...run, status: "aborted", room_id: "other" },
+ { ...run, status: "aborted", agent: { id: "other" } },
+ ],
+ [completed],
+ [completed],
+ ],
+ [`${route}/messages`]: [[reply], [reply]],
+ [replyRuns]: [[completed], [completed]],
+ },
+ verify,
+ );
+ await expect(result).resolves.toEqual({
+ outcome: "verified",
+ runID: "run",
+ replyID: "reply",
+ });
+ expect(get.mock.calls.map(([url]) => url)).toEqual([
+ sourceRuns,
+ sourceRuns,
+ `${route}/messages`,
+ replyRuns,
+ sourceRuns,
+ `${route}/messages`,
+ replyRuns,
+ ]);
+ expect(verify).toHaveBeenCalledTimes(2);
+});
+
+it("does not accept a reply from a different run or digest", async () => {
+ const wrongRun = observe({
+ [sourceRuns]: [[completed]],
+ [`${route}/messages`]: [[reply]],
+ [replyRuns]: [[{ ...completed, run_id: "other" }]],
+ });
+ await expect(wrongRun.result).rejects.toThrow("deadline");
+ expect(wrongRun.verify).not.toHaveBeenCalled();
+
+ const wrongDigest = observe({
+ [sourceRuns]: [[completed]],
+ [`${route}/messages`]: [[{ ...reply, raw_message: "other-digest" }]],
+ [replyRuns]: [[completed]],
+ });
+ await expect(wrongDigest.result).rejects.toThrow("deadline");
+ expect(wrongDigest.verify).not.toHaveBeenCalled();
+});
+
+it("exits nonzero with the matching IDs before waiting for a reply", async () => {
+ const root = await mkdtemp(join(tmpdir(), "acceptance-room-"));
+ const requests: string[] = [];
+ const payloads = new Map<string, object>([
+ ["/v0/auth/login", { identity: { actors: [{ tenant_id: "tenant" }] } }],
+ [
+ "/v0/tenants/tenant/local-computers",
+ {
+ items: [
+ {
+ computer_id: "computer",
+ status: "online",
+ runtimes: [
+ { type: "pi", status: "ready", models: [{ id: "model" }] },
+ ],
+ workspace_grants: [{ mode: "workspace-write", grant_id: "grant" }],
+ },
+ ],
+ },
+ ],
+ [
+ "/v0/tenants/tenant/agents",
+ { actor: { id: "agent" }, agent_management_id: "agent-management" },
+ ],
+ ["/v0/tenants/tenant/direct-rooms", { id: "room" }],
+ [`${route}/messages`, { id: "source" }],
+ [sourceRuns, { items: [{ ...run, status: "aborted" }] }],
+ ]);
+ const server = createServer((request, response) => {
+ const url = request.url ?? "";
+ requests.push(url);
+ if (url === "/v0/auth/login")
+ response.setHeader("Set-Cookie", "fixture=yes");
+ response.setHeader("Content-Type", "application/json");
+ response.end(JSON.stringify(payloads.get(url)));
+ });
+ try {
+ await new Promise<void>((resolve, reject) => {
+ server.once("error", reject);
+ server.listen(0, "127.0.0.1", resolve);
+ });
+ const address = server.address();
+ if (!address || typeof address === "string")
+ throw new Error("No fixture port");
+ const owner = join(root, "owner.json");
+ await writeFile(
+ owner,
+ '{"owner_email":"[email protected]","owner_password":"fixture-only"}',
+ { mode: 0o600 },
+ );
+ const entry = fileURLToPath(
+ new URL("./acceptance/room-journey.mjs", import.meta.url),
+ );
+ try {
+ await promisify(execFile)(process.execPath, [entry], {
+ timeout: 5_000,
+ env: {
+ ...Object.fromEntries(
+ Object.entries(process.env).filter(
+ ([key]) => !key.startsWith("LINGER_ACCEPTANCE_"),
+ ),
+ ),
+ LINGER_ACCEPTANCE_BASE_URL: `http://127.0.0.1:${address.port}`,
+ LINGER_ACCEPTANCE_OWNER_FILE: owner,
+ LINGER_ACCEPTANCE_COMPUTER_ID: "computer",
+ LINGER_ACCEPTANCE_CONTEXT_VIEWS: join(root, "context-views"),
+ LINGER_ACCEPTANCE_AGENT_LOG_ROOT: join(root, "logs"),
+ LINGER_ACCEPTANCE_TIMEOUT_SECONDS: "10",
+ },
+ });
+ throw new Error("Unexpected successful exit");
+ } catch (error) {
+ const result = error as { code: unknown; stdout: string };
+ expect(result.code).toBe(1);
+ const terminal = JSON.parse(result.stdout.trim().split("\n").at(-1)!);
+ expect(terminal).toMatchObject({
+ phase: "aborted",
+ room_id: "room",
+ message_id: "source",
+ agent_id: "agent",
+ run_id: "run",
+ });
+ }
+ expect(requests).toEqual([...payloads.keys()]);
+ } finally {
+ server.closeAllConnections();
+ await new Promise<void>((resolve) => server.close(() => resolve()));
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+it("requires exact bytes, regular files, and both events from the same run", async () => {
+ const root = await mkdtemp(join(tmpdir(), "acceptance-evidence-"));
+ try {
+ const marker = "LINGER_ACCEPTANCE_0123456789ABCDEF";
+ const file = join(root, "marker.txt");
+ const link = join(root, "marker-link.txt");
+ const log = join(root, "events.ndjson");
+ const write = {
+ event: "agent.tool_call",
+ tool_name: "write",
+ is_error: false,
+ };
+ const terminal = {
+ event: "local_run.terminal_persisted",
+ resultCode: "succeeded",
+ };
+ const verify = () =>
+ verifyLocalRunEvidence({ file, expected: marker, log, runId: "run" });
+ await expect(verify()).resolves.toBe(false);
+ await writeFile(file, marker);
+ await expect(verify()).resolves.toBe(false);
+ await writeFile(
+ log,
+ `${JSON.stringify({ ...write, runId: "run" })}\n${JSON.stringify({ ...terminal, runId: "other" })}\n`,
+ );
+ await expect(verify()).resolves.toBe(false);
+ await writeFile(
+ log,
+ `${JSON.stringify({ ...write, runId: "run" })}\n${JSON.stringify({ ...terminal, runId: "run" })}\n`,
+ );
+ await expect(verify()).resolves.toBe(true);
+ await expect(
+ verifyLocalRunEvidence({
+ file,
+ expectedSha256: sha256Hex(marker),
+ log,
+ runId: "run",
+ }),
+ ).resolves.toBe(true);
+
+ const cli = fileURLToPath(
+ new URL("./local-runner-message-evidence.mjs", import.meta.url),
+ );
+ const { stdout } = await promisify(execFile)(
+ process.execPath,
+ [cli, "--run-evidence"],
+ {
+ timeout: 5_000,
+ env: {
+ ...Object.fromEntries(
+ Object.entries(process.env).filter(
+ ([key]) => !key.startsWith("LINGER_ACCEPTANCE_"),
+ ),
+ ),
+ LINGER_ACCEPTANCE_FILE: file,
+ LINGER_ACCEPTANCE_EXPECTED: marker,
+ LINGER_ACCEPTANCE_AGENT_LOG: log,
+ LINGER_ACCEPTANCE_RUN_ID: "run",
+ },
+ },
+ );
+ expect(JSON.parse(stdout)).toEqual({
+ result: "verified",
+ run_id: "run",
+ file_sha256: sha256Hex(marker),
+ file_content: "exact",
+ successful_write: true,
+ terminal_succeeded: true,
+ });
+
+ await symlink(file, link);
+ await expect(
+ verifyLocalRunEvidence({
+ file: link,
+ expected: marker,
+ log,
+ runId: "run",
+ }),
+ ).rejects.toThrow("INVALID_ARTIFACT_FILE");
+
+ await writeFile(file, `${marker}\r\n`);
+ await expect(verify()).resolves.toBe(false);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});