From 2c70d04bf6e0c4f83e5472d30ce7aac8789779e8 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 27 Oct 2026 16:38:23 -0500 Subject: [PATCH 1/4] feat(evals): account for explicit Daytona model requests (#17936) ## Thinking Path > - Paperclip evals need complete model-spend evidence. > - The bounded Product E2E controller already owns request admission and token receipts. > - Its loopback endpoints cannot serve a Daytona agent. > - Explicit remote cases therefore need a scoped transport to the same controller. > - This PR exposes only authenticated model and OTLP endpoints through one owned quick tunnel. > - Remote requests keep the same budget, request identity, usage journal and cancellation drain. ## Linked Issues or Issue Description Refs #17928, #17929, #17523. **What happened?** The operations manifest and fixture reject Daytona. The parent gateway and native trace relay bind loopback, so normal remote agent traffic cannot use their cost accounting. **Expected behavior** An explicit native marker or feedback case on Daytona can route requests through the bounded parent. Upstream provider and Braintrust keys stay on that controller. Every paid request keeps its usage receipt and the attempt retains ordinary feedback and cleanup evidence. **Steps to reproduce** Use the explicit `remoteGateway: "cloudflare"` manifest option for a native Codex or Claude Daytona marker/feedback case. Without that option, the remote selection remains rejected. The parent verifies its public health nonce before fixture setup. ## What Changed - Add a deadline-limited bridge with exact model/OTLP paths, separate scoped tokens, streamed responses and owned tunnel cleanup. - Start one HTTPS quick tunnel with a private home and no provider credentials or ambient Cloudflare configuration. Do not retry creation or paid work. - Admit only explicit native Daytona marker/feedback cells and require the provisioning credential before opening the journal. - Bind fixture model/OTLP endpoints to the assigned remote origin. Keep provisioning access in the fixture/server controller. - Preserve final token usage when a remote client disconnects during shutdown. - Document the manual route. Daily and weekly selections remain local. ## Verification - Full Product E2E unit suite: 4,370 passed and 2 skipped across 206 files, plus 137 Node checks. - Focused remote/usage/operations/trace checks: 71 tests passed; final bridge/drain checks: 15 passed. - Product E2E typecheck passed. - Tests cover missing tunnel executable, expiry, authentication, blocked paths, token separation, missing provisioning credentials, endpoint assignment and listener cleanup. - The cancellation regression uses the real gateway and ledger with a synthetic upstream. It retains the final receipt once after remote disconnect. - Latest source and architecture/cleanup checks: 167 passed; eval typecheck passed. Both reviews are 5/5 and exact-head CI is green. Live qualification follows merge. ## Risks The explicit route sends synthetic eval requests and scoped attempt tokens through Cloudflare. Those tokens expire with the existing campaign deadline and budget. Upstream keys stay on the controller. Public readiness has a finite wait; failure stops before fixture setup. The operator still needs the existing immutable Daytona image and verified native artifacts. Source and deterministic tests do not establish live remote acceptance. ## Model Used OpenAI Codex, GPT-6 family, with reasoning, repository inspection and code execution. The exact serving model ID and context window are not exposed to this session. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip --- tests/runner-e2e/OPERATIONS.md | 39 ++++++ tests/runner-e2e/braintrust.test.ts | 10 ++ tests/runner-e2e/braintrust.ts | 7 +- tests/runner-e2e/eval-gateway-drain.test.ts | 17 +++ tests/runner-e2e/eval-remote-gateway.test.ts | 101 ++++++++++++++++ tests/runner-e2e/eval-remote-gateway.ts | 119 +++++++++++++++++++ tests/runner-e2e/harness-env.ts | 13 +- tests/runner-e2e/launch.ts | 3 + tests/runner-e2e/live-fixtures.ts | 6 +- tests/runner-e2e/operations.test.ts | 44 ++++++- tests/runner-e2e/operations.ts | 25 ++-- tests/runner-e2e/support.test.ts | 9 ++ 12 files changed, 377 insertions(+), 16 deletions(-) create mode 100644 tests/runner-e2e/eval-remote-gateway.test.ts create mode 100644 tests/runner-e2e/eval-remote-gateway.ts diff --git a/tests/runner-e2e/OPERATIONS.md b/tests/runner-e2e/OPERATIONS.md index 1481b4451b1..be61693fb07 100644 --- a/tests/runner-e2e/OPERATIONS.md +++ b/tests/runner-e2e/OPERATIONS.md @@ -909,3 +909,42 @@ reservations and model-readiness status separately. It does not release any historical hold or certify a full-lifecycle vendor cost bound. Missing model receipts, conflicts, active requests, excess commitments, and the existing product, cleanup, feedback and trace checks still fail qualification. + + +### Explicit bounded Daytona gateway qualification + +A manual manifest can set `remoteGateway: "cloudflare"` for the native Codex +or Claude marker/feedback Daytona cells. Install `cloudflared` on the controller +PATH, or set `PAPERCLIP_EVAL_CLOUDFLARED` to its executable path. Empty overrides +use the PATH default. The parent starts its existing model +gateway and native OTLP relay, then exposes only their authenticated endpoints +through one owned HTTPS quick tunnel. It verifies a fresh health nonce before +fixture setup, waits up to 120 seconds for registration and 120 seconds for +public readiness, and does not retry tunnel creation or provider work. + +Only attempt-scoped tokens leave the controller. Provider and Braintrust keys +stay in the parent; the fixture/server retains the existing Daytona provisioning +credential separately. The model gateway still enforces its campaign allowance, +request count, concurrency, deadline and receipt journal. The bridge streams +responses and preserves terminal-usage draining after a client disconnect. +The tunnel receives no ambient provider credentials or Cloudflare config. Its +exposure closes at the campaign deadline or four hours after startup, whichever +comes first, and on attempt cleanup. Owned gateway, +relay and tunnel cleanup failures remain failures. A configured remote route +is not live acceptance; retain the actual Daytona result, cleanup, feedback, +native traces and complete model receipts. + +The Daytona image runs Linux/x64. ARM or macOS controllers use the image's +verified daemon by default; only an explicit cross-compiled remote override +replaces it. + +Daily and weekly selections remain local. This explicit remote option adds no +scheduled coverage or public report publication. + +The worker generates the attempt's trace parent. The relay validates the project +in both the header and payload, but does not pin that worker-generated parent. +Treat the attempt OTLP token as authority to submit trace attribution within +this eval project. Keep it limited to the trusted harness/provider runtime; +never expose it to test prompts or unrelated clients. The project check is not +an attempt-isolation guarantee. Indexing verification is a separate retained +or scheduled check; the manual launcher alone does not perform it. diff --git a/tests/runner-e2e/braintrust.test.ts b/tests/runner-e2e/braintrust.test.ts index 118621d3ffe..da60c202173 100644 --- a/tests/runner-e2e/braintrust.test.ts +++ b/tests/runner-e2e/braintrust.test.ts @@ -211,3 +211,13 @@ it("retains finalization export failures without changing the recorded product r }, transport)).toMatchObject({ status: "failed", errorCode: "invalid_finalization_context" }); expect(transport).not.toHaveBeenCalled(); }); + + +it("binds remote OTLP to the explicitly assigned eval gateway origin", () => { + const origin = "https://synthetic-eval.trycloudflare.com"; + const env = { PAPERCLIP_E2E_BRAINTRUST_PROJECT_ID: projectId, BRAINTRUST_API_KEY: "synthetic-token", + PAPERCLIP_E2E_REMOTE_GATEWAY_ORIGIN: origin, PAPERCLIP_E2E_OTLP_RELAY_URL: `${origin}/otel` }; + expect(evalBraintrustConfig(env)).toMatchObject({ remoteOrigin: origin, endpointBaseUrl: `${origin}/otel` }); + expect(() => evalBraintrustConfig({ ...env, PAPERCLIP_E2E_OTLP_RELAY_URL: "https://different-eval.trycloudflare.com/otel" })).toThrow(); + expect(buildPaperclipServerEnvironment(env).PAPERCLIP_E2E_REMOTE_GATEWAY_ORIGIN).toBeUndefined(); +}); diff --git a/tests/runner-e2e/braintrust.ts b/tests/runner-e2e/braintrust.ts index adb5d94e4b9..83b7c2091f5 100644 --- a/tests/runner-e2e/braintrust.ts +++ b/tests/runner-e2e/braintrust.ts @@ -1,13 +1,15 @@ import { randomBytes } from "node:crypto"; import { createRequire } from "node:module"; +import { isEvalRemoteOrigin } from "./eval-remote-gateway.js"; import type { RunnerApi } from "./api.js"; import type { FailureClass, RunnerE2EResult } from "./types.js"; export const EVAL_OBSERVABILITY_SECRET_NAMES = ["BRAINTRUST_API_KEY"] as const; const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; -export interface EvalBraintrustConfig { projectId: string; apiKey: string; endpointBaseUrl?: string } +export interface EvalBraintrustConfig { projectId: string; apiKey: string; endpointBaseUrl?: string; remoteOrigin?: string } function evalOtlpEndpoint(config: EvalBraintrustConfig) { - if (config.endpointBaseUrl !== undefined && !/^http:\/\/127\.0\.0\.1:[1-9][0-9]{0,4}\/otel$/.test(config.endpointBaseUrl)) { + if (config.remoteOrigin !== undefined && !isEvalRemoteOrigin(config.remoteOrigin)) throw new Error("Invalid eval remote OTLP origin"); + if (config.endpointBaseUrl !== undefined && !(config.remoteOrigin && config.endpointBaseUrl === `${config.remoteOrigin}/otel`) && !/^http:\/\/127\.0\.0\.1:[1-9][0-9]{0,4}\/otel$/.test(config.endpointBaseUrl)) { throw new Error("Eval OTLP relay must use the parent-owned loopback endpoint"); } if (config.endpointBaseUrl && Number(new URL(config.endpointBaseUrl).port) > 65535) throw new Error("Invalid eval OTLP relay port"); @@ -20,6 +22,7 @@ export function evalBraintrustConfig(env: NodeJS.ProcessEnv): EvalBraintrustConf throw new Error("Eval Braintrust export requires an explicit project UUID and API key"); } const config = { projectId, apiKey: env.BRAINTRUST_API_KEY.trim(), + ...(env.PAPERCLIP_E2E_REMOTE_GATEWAY_ORIGIN ? { remoteOrigin: env.PAPERCLIP_E2E_REMOTE_GATEWAY_ORIGIN } : {}), ...(env.PAPERCLIP_E2E_OTLP_RELAY_URL ? { endpointBaseUrl: env.PAPERCLIP_E2E_OTLP_RELAY_URL } : {}) }; evalOtlpEndpoint(config); return config; diff --git a/tests/runner-e2e/eval-gateway-drain.test.ts b/tests/runner-e2e/eval-gateway-drain.test.ts index 24e6f43e776..9c5a73a06cc 100644 --- a/tests/runner-e2e/eval-gateway-drain.test.ts +++ b/tests/runner-e2e/eval-gateway-drain.test.ts @@ -3,6 +3,7 @@ import { tmpdir } from "node:os"; import path from "node:path"; import { afterEach, expect, it, vi } from "vitest"; import { openEvalCostLedger, readEvalCostLedger } from "./cost-ledger.js"; +import { startEvalRemoteBridge } from "./eval-remote-gateway.js"; import { forwardEvalRequest, startEvalGateway, type EvalGatewayReceipt, type EvalGatewayRoute } from "./eval-gateway.js"; const cleanups: Array<() => Promise> = []; @@ -181,3 +182,19 @@ it.each(["persist", "observe", "finish"] as const)("records a disconnect during expect(f.ledger.snapshot()).toMatchObject({ knownUsd: "0.000070000", heldUsd: "0.000000000", unknownRequests: 0 }); expect(transport).toHaveBeenCalledOnce(); }); + +it("retains terminal usage when a remote bridge client disconnects during shutdown", async () => { + const f = await fixture(), started = deferred(), release = deferred(); + const transport = vi.fn(async () => { started.resolve(); await release.promise; return finalResponse("openai"); }); + const gateway = await startEvalGateway({ ...f, transport }); cleanups.push(() => gateway.close()); + const bridge = await startEvalRemoteBridge({ gateway, deadlineAt: f.deadlineAt }); cleanups.push(() => bridge.close()); + const client = new AbortController(); + const result = fetch(bridge.baseUrl + "/responses", { method: "POST", signal: client.signal, + headers: { authorization: `Bearer ${gateway.token}` }, body: JSON.stringify({ model: "fixture", input: "hello" }) }).catch(error => error); + await started.promise; client.abort(); await bridge.close(); + const closing = gateway.close(); release.resolve(); await closing; + expect(await result).not.toBeInstanceOf(Response); + expect(transport).toHaveBeenCalledOnce(); + expect(f.receipts.at(-1)).toMatchObject({ clientDisconnected: true, final: true, usageComplete: true, costUsd: "0.000070000" }); + expect(f.ledger.snapshot()).toMatchObject({ knownUsd: "0.000070000", heldUsd: "0.000000000", unknownRequests: 0, inflight: 0 }); +}); diff --git a/tests/runner-e2e/eval-remote-gateway.test.ts b/tests/runner-e2e/eval-remote-gateway.test.ts new file mode 100644 index 00000000000..befe8d1e366 --- /dev/null +++ b/tests/runner-e2e/eval-remote-gateway.test.ts @@ -0,0 +1,101 @@ +import { mkdtemp, readFile, writeFile, rm, readdir } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { createServer } from "node:http"; +import { once } from "node:events"; +import { expect, it, vi } from "vitest"; +import { isEvalRemoteOrigin, startEvalRemoteBridge, startEvalRemoteGateway } from "./eval-remote-gateway.js"; + +it("forwards only authenticated model/OTLP routes and closes owned exposure", async () => { + const calls: Array<{ url: string; auth?: string; body: string }> = []; + const upstream = createServer(async (request, response) => { + let body = ""; for await (const chunk of request) body += chunk; + calls.push({ url: request.url!, auth: request.headers.authorization, body }); + response.writeHead(200, { "content-type": "text/event-stream" }); response.end("data: synthetic\n\n"); + }); + upstream.listen(0, "127.0.0.1"); await once(upstream, "listening"); + const address = upstream.address(); if (!address || typeof address === "string") throw new Error("Fixture did not bind"); + const url = `http://127.0.0.1:${address.port}`, modelToken = "a".repeat(64), otlpToken = "b".repeat(64); + const bridge = await startEvalRemoteBridge({ gateway: { baseUrl: url, token: modelToken }, + observability: { baseUrl: url + "/otel", token: otlpToken }, deadlineAt: Date.now() + 60_000 }); + try { + expect(await (await fetch(bridge.baseUrl + "/health")).json()).toEqual({ nonce: bridge.nonce }); + for (const path of ["/v1/responses", "/v1/messages?beta=true", "/otel/v1/traces", "/otel/v1/logs"]) { + expect((await fetch(bridge.baseUrl + path, { method: "POST" })).status).toBe(401); + const token = path.startsWith("/otel") ? otlpToken : modelToken; + const response = await fetch(bridge.baseUrl + path, { method: "POST", headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, body: "{}" }); + expect(response.status).toBe(200); expect(await response.text()).toBe("data: synthetic\n\n"); + } + expect(calls).toHaveLength(4); + expect(calls.map(call => call.url)).toEqual(["/v1/responses", "/v1/messages?beta=true", "/otel/v1/traces", "/otel/v1/logs"]); + expect(calls.map(call => call.auth)).toEqual([`Bearer ${modelToken}`, `Bearer ${modelToken}`, `Bearer ${otlpToken}`, `Bearer ${otlpToken}`]); + expect((await fetch(bridge.baseUrl + "/admin", { method: "POST", headers: { authorization: `Bearer ${modelToken}` } })).status).toBe(404); + expect((await fetch(bridge.baseUrl + "/otel/v1/traces", { method: "POST", headers: { authorization: `Bearer ${modelToken}` } })).status).toBe(401); + await bridge.close(); await expect(fetch(bridge.baseUrl + "/health")).rejects.toThrow(); + } finally { await bridge.close(); upstream.closeAllConnections(); await new Promise(resolve => upstream.close(() => resolve())); } +}); + +it("admits only HTTPS quick-tunnel origins and bounded loopback destinations", async () => { + expect(isEvalRemoteOrigin("https://synthetic-fixture.trycloudflare.com")).toBe(true); + for (const value of ["https://foreign.invalid", "http://synthetic.trycloudflare.com", "https://synthetic.trycloudflare.com/path", "https://synthetic.trycloudflare.com?token=private"]) expect(isEvalRemoteOrigin(value)).toBe(false); + await expect(startEvalRemoteBridge({ gateway: { baseUrl: "https://foreign.invalid", token: "a".repeat(64) }, deadlineAt: Date.now() + 60_000 })).rejects.toThrow("policy"); +}); + + +it("fails before remote admission when the tunnel executable is unavailable", async () => { + await expect(startEvalRemoteGateway({ gateway: { baseUrl: "http://127.0.0.1:1", token: "a".repeat(64) }, + deadlineAt: Date.now() + 5000 }, { PAPERCLIP_EVAL_CLOUDFLARED: "/missing/synthetic-cloudflared", PATH: "" })) + .rejects.toThrow("Remote eval tunnel executable unavailable"); +}); + +it("closes remote exposure at its original campaign deadline", async () => { + const bridge = await startEvalRemoteBridge({ gateway: { baseUrl: "http://127.0.0.1:1", token: "a".repeat(64) }, deadlineAt: Date.now() + 50 }); + try { + await new Promise(resolve => setTimeout(resolve, 100)); + await expect(fetch(bridge.baseUrl + "/health")).rejects.toThrow(); + } finally { await bridge.close(); } +}); + + +it.each(["explicit", "empty-override"])("waits for registration and the correct public nonce, then terminates the owned tunnel: %s", async mode => { + const root = await mkdtemp(path.join(tmpdir(), "eval-fake-tunnel-")); + const executable = path.join(root, "cloudflared"), state = path.join(root, "state.json"), stopped = path.join(root, "stopped"); + const origin = "https://synthetic-owned.trycloudflare.com"; + const script = `#!${process.execPath} +const fs = require("node:fs"); +fs.writeFileSync(${JSON.stringify(state)}, JSON.stringify({baseUrl:process.argv.at(-1),pid:process.pid,env:process.env})); +process.stderr.write("${origin}\\n"); +setTimeout(() => process.stderr.write("Registered tunnel connection\\n"), 20); +process.on("SIGTERM", () => { fs.writeFileSync(${JSON.stringify(stopped)}, "stopped"); process.exit(0); }); +setInterval(() => {}, 1000); +`; + await writeFile(executable, script, { mode: 0o700 }); + const realFetch = globalThis.fetch; let healthChecks = 0; + const fetchSpy = vi.spyOn(globalThis, "fetch").mockImplementation(async url => { + expect(String(url)).toBe(origin + "/health"); + if (++healthChecks === 1) return new Response(JSON.stringify({ nonce: "foreign" }), { status: 200 }); + const { baseUrl } = JSON.parse(await readFile(state, "utf8")); + return realFetch(baseUrl + "/health"); + }); + let remote: Awaited> | undefined; + try { + remote = await startEvalRemoteGateway({ gateway: { baseUrl: "http://127.0.0.1:1", token: "a".repeat(64) }, + deadlineAt: Date.now() + 10_000 }, { PAPERCLIP_EVAL_CLOUDFLARED: mode === "explicit" ? executable : "", PATH: root, OPENAI_API_KEY: "must-not-leave" }); + expect(remote.baseUrl).toBe(origin); expect(healthChecks).toBe(2); + const { baseUrl, pid, env } = JSON.parse(await readFile(state, "utf8")); + expect(env.OPENAI_API_KEY).toBeUndefined(); expect(env.HOME).not.toBe(process.env.HOME); + await remote.close(); + expect(await readFile(stopped, "utf8")).toBe("stopped"); + expect(() => process.kill(pid, 0)).toThrow(); + await expect(realFetch(baseUrl + "/health")).rejects.toThrow(); + await expect(readFile(path.join(env.HOME, "anything"))).rejects.toThrow(); + } finally { fetchSpy.mockRestore(); await remote?.close(); await rm(root, { recursive: true, force: true }); } +}, 15_000); + + +it("cleans the private tunnel home after synchronous spawn rejection", async () => { + const before = new Set((await readdir(tmpdir())).filter(name => name.startsWith("eval-cloudflare-"))); + await expect(startEvalRemoteGateway({ gateway: { baseUrl: "http://127.0.0.1:1", token: "a".repeat(64) }, + deadlineAt: Date.now() + 60_000 }, { PAPERCLIP_EVAL_CLOUDFLARED: "invalid\0executable", PATH: "" })).rejects.toThrow(); + expect((await readdir(tmpdir())).filter(name => name.startsWith("eval-cloudflare-") && !before.has(name))).toEqual([]); +}); diff --git a/tests/runner-e2e/eval-remote-gateway.ts b/tests/runner-e2e/eval-remote-gateway.ts new file mode 100644 index 00000000000..2d5d1d85054 --- /dev/null +++ b/tests/runner-e2e/eval-remote-gateway.ts @@ -0,0 +1,119 @@ +import { spawn } from "node:child_process"; +import { randomBytes, timingSafeEqual } from "node:crypto"; +import { once } from "node:events"; +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { createServer, request as httpRequest } from "node:http"; + +export const isEvalRemoteOrigin = (value: string) => /^https:\/\/[a-z0-9-]+\.trycloudflare\.com$/.test(value); + +export async function startEvalRemoteBridge(input: { + gateway: { baseUrl: string; token: string }; + observability?: { baseUrl: string; token: string }; + deadlineAt: number; +}) { + if (!Number.isFinite(input.deadlineAt) || input.deadlineAt <= Date.now() || input.deadlineAt > Date.now() + 4 * 3_600_000 + || !/^http:\/\/127\.0\.0\.1:[1-9][0-9]{0,4}$/.test(input.gateway.baseUrl) + || input.observability && !/^http:\/\/127\.0\.0\.1:[1-9][0-9]{0,4}\/otel$/.test(input.observability.baseUrl) + || !/^[a-f0-9]{64}$/.test(input.gateway.token) + || input.observability && !/^[a-f0-9]{64}$/.test(input.observability.token)) throw new Error("Invalid remote eval bridge policy"); + try { new URL(input.gateway.baseUrl); if (input.observability) new URL(input.observability.baseUrl); } + catch { throw new Error("Invalid remote eval bridge policy"); } + const nonce = randomBytes(32).toString("hex"); + let closed = false; + const server = createServer((incoming, outgoing) => { + if (closed || Date.now() >= input.deadlineAt) { outgoing.writeHead(503).end(); return; } + if (incoming.method === "GET" && incoming.url === "/health") { + outgoing.writeHead(200, { "content-type": "application/json", "cache-control": "no-store" }).end(JSON.stringify({ nonce })); return; + } + const model = ["/responses", "/v1/responses", "/messages", "/messages?beta=true", "/v1/messages", "/v1/messages?beta=true"].includes(incoming.url ?? ""); + const otlp = ["/otel/v1/traces", "/otel/v1/logs"].includes(incoming.url ?? ""); + const destination = model ? input.gateway : otlp ? input.observability : undefined; + if (incoming.method !== "POST" || !destination) { outgoing.writeHead(404).end(); return; } + const auth = String(incoming.headers.authorization ?? "").replace(/^Bearer /, "") || String(incoming.headers["x-api-key"] ?? ""); + const presented = Buffer.from(auth), expected = Buffer.from(destination.token); + if (presented.length !== expected.length || !timingSafeEqual(presented, expected)) { outgoing.writeHead(401).end(); return; } + const suffix = otlp ? incoming.url!.slice("/otel".length) : incoming.url!; + const headers: Record = { authorization: `Bearer ${destination.token}` }; + for (const name of ["content-type", "content-encoding", "anthropic-beta", "anthropic-version", "x-bt-parent"]) { + const value = incoming.headers[name]; if (typeof value === "string") headers[name] = value; + } + const upstream = httpRequest(destination.baseUrl + suffix, { method: "POST", headers }, response => { + if (outgoing.destroyed) { response.destroy(); return; } + outgoing.writeHead(response.statusCode ?? 502, response.headers); response.pipe(outgoing); + response.on("error", () => outgoing.destroy()); + }); + upstream.on("error", () => { if (!outgoing.headersSent) outgoing.writeHead(502).end(); else outgoing.destroy(); }); + incoming.on("aborted", () => upstream.destroy()); + incoming.on("error", () => upstream.destroy()); + outgoing.on("error", () => upstream.destroy()); + outgoing.on("close", () => { if (!outgoing.writableEnded) upstream.destroy(); }); + incoming.pipe(upstream); + }); + server.requestTimeout = 15_000; server.headersTimeout = 10_000; + server.listen(0, "127.0.0.1"); await once(server, "listening"); + const address = server.address(); + if (!address || typeof address === "string") throw new Error("Remote eval bridge did not bind loopback"); + let timer: ReturnType; + let closing: Promise | undefined; + const close = () => closing ??= (async () => { + closed = true; clearTimeout(timer); + server.closeAllConnections(); await new Promise(resolve => server.close(() => resolve())); + })(); + timer = setTimeout(() => { void close().catch(() => {}); }, input.deadlineAt - Date.now()); timer.unref(); + return { baseUrl: `http://127.0.0.1:${address.port}`, nonce, close }; +} + +export async function startEvalRemoteGateway(input: Parameters[0], env: NodeJS.ProcessEnv) { + const bridge = await startEvalRemoteBridge(input); + let home: string; + try { home = await mkdtemp(path.join(tmpdir(), "eval-cloudflare-")); } + catch (error) { await bridge.close(); throw error; } + let tunnel: ReturnType | undefined; + let closing: Promise | undefined, deadlineTimer: ReturnType | undefined; + const close = () => closing ??= (async () => { + clearTimeout(deadlineTimer); + const errors: unknown[] = []; + try { await bridge.close(); } catch (error) { errors.push(error); } + try { + if (tunnel?.pid && tunnel.exitCode === null && tunnel.signalCode === null) { + const exited = once(tunnel, "exit").catch(() => {}); + tunnel.kill("SIGTERM"); const timer = setTimeout(() => tunnel?.kill("SIGKILL"), 5000); + try { await exited; } finally { clearTimeout(timer); } + } + } catch (error) { errors.push(error); } + try { await rm(home, { recursive: true, force: true }); } catch (error) { errors.push(error); } + if (errors.length) throw new AggregateError(errors, "Remote eval exposure cleanup failed"); + })(); + try { + tunnel = spawn(env.PAPERCLIP_EVAL_CLOUDFLARED?.trim() || "cloudflared", + ["tunnel", "--no-autoupdate", "--protocol", "http2", "--url", bridge.baseUrl], + { stdio: ["ignore", "pipe", "pipe"], env: { PATH: env.PATH, HOME: home, TMPDIR: home } }); + deadlineTimer = setTimeout(() => { void close().catch(() => {}); }, input.deadlineAt - Date.now()); deadlineTimer.unref(); + const child = tunnel; + const origin = await new Promise((resolve, reject) => { + let output = ""; + const timer = setTimeout(() => finish(new Error("Remote eval tunnel startup timed out")), Math.min(120_000, input.deadlineAt - Date.now())); + const finish = (error?: Error, value?: string) => { clearTimeout(timer); if (error) reject(error); else resolve(value!); }; + child.once("error", () => finish(new Error("Remote eval tunnel executable unavailable"))); + child.once("exit", () => finish(new Error("Remote eval tunnel exited"))); + const read = (chunk: Buffer) => { + output = (output + chunk.toString()).slice(-32768); + const value = output.match(/https:\/\/[a-z0-9-]+\.trycloudflare\.com/)?.[0]; + if (value && output.includes("Registered tunnel connection")) finish(undefined, value); + }; + child.stdout!.on("data", read); child.stderr!.on("data", read); + }); + const readyBy = Math.min(Date.now() + 120_000, input.deadlineAt); + while (Date.now() < readyBy) { + try { + const response = await fetch(origin + "/health", { redirect: "error", signal: AbortSignal.timeout(Math.min(5000, readyBy - Date.now())) }); + if (response.ok && (await response.json() as { nonce?: string }).nonce === bridge.nonce) return { baseUrl: origin, close }; + await response.body?.cancel(); + } catch {} + await new Promise(resolve => setTimeout(resolve, 1000)); + } + throw new Error("Remote eval tunnel not publicly reachable before admission"); + } catch (error) { await close(); throw error; } +} diff --git a/tests/runner-e2e/harness-env.ts b/tests/runner-e2e/harness-env.ts index 2ea3cd91a40..9aa865b0c1f 100644 --- a/tests/runner-e2e/harness-env.ts +++ b/tests/runner-e2e/harness-env.ts @@ -2,6 +2,7 @@ import { installedDaytonaPluginKeys } from "./installed-daytona-plugin.js"; import { QUALIFIED_ACPX_PROFILES } from "../../packages/paperclip-runner/src/drivers/acpx/qualified-profiles.js"; import { assertInstalledCliSelection, installedCliKeys, usesInstalledCli } from "./installed-cli.js"; import path from "node:path"; +import { isEvalRemoteOrigin } from "./eval-remote-gateway.js"; import { chatNeedsApiTools, isManagedHiringCase } from "./chat-cases.js"; import { CREDENTIAL_NAMES } from "./types.js"; import type { MatrixExecution } from "./types.js"; @@ -14,6 +15,7 @@ const AMBIENT_PAPERCLIP_CREDENTIAL_KEYS = [ "PAPERCLIP_E2E_GATEWAY_TOKEN", "PAPERCLIP_E2E_GATEWAY_PHASE_PATH", "PAPERCLIP_E2E_OTLP_RELAY_URL", + "PAPERCLIP_E2E_REMOTE_GATEWAY_ORIGIN", "PAPERCLIP_SETUP_TOKEN", "PAPERCLIP_SECRETS_MASTER_KEY", "PAPERCLIP_SECRETS_MASTER_KEY_FILE", @@ -41,6 +43,8 @@ export function applyEvalGatewayEnvironment(env: NodeJS.ProcessEnv, credential: || PROVIDER_SECRET_KEY.test(name) && /KEY|TOKEN|SECRET|PASSWORD/.test(name)) delete env[name]; } delete env.PAPERCLIP_E2E_OTLP_RELAY_URL; + delete env.PAPERCLIP_E2E_REMOTE_GATEWAY_ORIGIN; + if (isEvalRemoteOrigin(gateway.baseUrl)) env.PAPERCLIP_E2E_REMOTE_GATEWAY_ORIGIN = gateway.baseUrl; env[credential] = gateway.token; env.PAPERCLIP_E2E_GATEWAY_BASE_URL = gateway.baseUrl; env.PAPERCLIP_E2E_GATEWAY_TOKEN = gateway.token; @@ -103,13 +107,13 @@ export function resolvePaperclipRemoteRunnerBinaryForHarness( runnerBinary: string | undefined, configuredPath = process.env.PAPERCLIP_RUNNER_REMOTE_BINARY_PATH, platform: NodeJS.Platform = process.platform, + architecture: NodeJS.Architecture = process.arch, ): string | undefined { if (configuredPath?.trim()) return configuredPath; if (!runnerBinary) return undefined; - // Daytona runs Linux. A default debug binary built by a macOS developer is - // Mach-O and cannot be staged into that sandbox. Leave the remote override - // unset so the pinned Daytona image's verified runnerd is discovered instead. - if (platform !== "linux") return undefined; + // The pinned Daytona runtime is Linux/x64. Other controller binaries cannot + // run there; discover its verified runnerd unless an explicit cross-build is set. + if (platform !== "linux" || architecture !== "x64") return undefined; return executions.some( (execution) => execution.profile.generation === "native" && @@ -133,6 +137,7 @@ export function buildRunnerE2EProcessEnvironment( const result = { ...source }; delete result.PAPERCLIP_E2E_GATEWAY_PHASE_PATH; delete result.PAPERCLIP_E2E_OTLP_RELAY_URL; + delete result.PAPERCLIP_E2E_REMOTE_GATEWAY_ORIGIN; // Announcements are unrelated to the scenarios and obscure screenshot evidence. result.PAPERCLIP_ANNOUNCEMENTS_ENABLED = "false"; delete result.OPENCODE_ALLOW_ALL_MODELS; diff --git a/tests/runner-e2e/launch.ts b/tests/runner-e2e/launch.ts index b65d4f9fecb..74ec9179866 100644 --- a/tests/runner-e2e/launch.ts +++ b/tests/runner-e2e/launch.ts @@ -595,6 +595,9 @@ async function runAttempt(input: { }; if (gateway) { applyEvalGatewayEnvironment(childEnv, execution.profile.credential, gateway); + // The fixture/server controller needs Daytona provisioning access. The + // remote provider still receives only the scoped model and OTLP tokens. + if (execution.environment.id === "daytona") childEnv.DAYTONA_API_KEY = process.env.DAYTONA_API_KEY; } // The database URLs are stripped here and again at the Playwright web-server // boundary so a developer's shell can never redirect this paid test. diff --git a/tests/runner-e2e/live-fixtures.ts b/tests/runner-e2e/live-fixtures.ts index 348db2d08af..517b25b3d90 100644 --- a/tests/runner-e2e/live-fixtures.ts +++ b/tests/runner-e2e/live-fixtures.ts @@ -1,3 +1,4 @@ +import { isEvalRemoteOrigin } from "./eval-remote-gateway.js"; import type { AiConnectionBinding } from "../../packages/shared/src/ai-connections.js"; import { verifyInstalledDaytonaPlugin } from "./installed-daytona-plugin.js"; import { NATIVE_COMPLETION_BUDGET_CENTS } from "./native-completion-defaults.js"; @@ -280,8 +281,9 @@ export async function setupLiveFixtures(input: { const gatewayUrl = process.env.PAPERCLIP_E2E_GATEWAY_BASE_URL; const gatewayToken = process.env.PAPERCLIP_E2E_GATEWAY_TOKEN; const budgetedGateway = Boolean(gatewayUrl || gatewayToken); - if (budgetedGateway && (!gatewayUrl || !gatewayToken || !/^http:\/\/127\.0\.0\.1:[0-9]+$/.test(gatewayUrl) - || execution.environment.id !== "local" || !["core-compatibility", "feedback-persistence"].includes(execution.suite.id))) throw new Error("Unqualified fixture gateway route"); + if (budgetedGateway && (!gatewayUrl || !gatewayToken || !(execution.environment.id === "local" ? /^http:\/\/127\.0\.0\.1:[0-9]+$/.test(gatewayUrl) + : isEvalRemoteOrigin(gatewayUrl) && gatewayUrl === process.env.PAPERCLIP_E2E_REMOTE_GATEWAY_ORIGIN) + || !["local", "daytona"].includes(execution.environment.id) || !["core-compatibility", "feedback-persistence"].includes(execution.suite.id))) throw new Error("Unqualified fixture gateway route"); if (managedHiring || savedCopilot || budgetedGateway) { registry.register({ id: "ai-connection", diff --git a/tests/runner-e2e/operations.test.ts b/tests/runner-e2e/operations.test.ts index 452403765fd..8e03148dfdc 100644 --- a/tests/runner-e2e/operations.test.ts +++ b/tests/runner-e2e/operations.test.ts @@ -3,6 +3,7 @@ import { access, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promise import { createHash } from "node:crypto"; import path from "node:path"; import { tmpdir } from "node:os"; +import * as remoteGateway from "./eval-remote-gateway.js"; import { runnerMatrix } from "./catalog.js"; import { validateEvalOperationsManifest, openEvalOperations, type EvalOperationsManifest } from "./operations.js"; import { setupLiveFixtures } from "./live-fixtures.js"; @@ -17,7 +18,7 @@ function manifest(): EvalOperationsManifest { models: [{ provider: "openai", maximumInputTokens: 1000, maximumOutputTokens: 100, timeoutMs: 1000, price: { provider: "openai", model: cell.profile.model, version: "fixture-only", sourceUrl: "https://provider.invalid/fixture", inputUsdPerMillion: "2", cachedReadUsdPerMillion: "1", outputUsdPerMillion: "10", cacheWrite30mUsdPerMillion: "2", cacheWrite12hUsdPerMillion: "2" } }] }; } -afterEach(() => { vi.unstubAllEnvs(); vi.unstubAllGlobals(); }); +afterEach(() => { vi.restoreAllMocks(); vi.unstubAllEnvs(); vi.unstubAllGlobals(); }); it("admits only the exact bounded local selection and explicitly priced models", () => { expect(validateEvalOperationsManifest(manifest(), [cell], 1)).toMatchObject({ route: "direct" }); expect(() => validateEvalOperationsManifest({ ...manifest(), executionIds: [] }, [cell], 1)).toThrow("selection"); @@ -191,3 +192,44 @@ it.each([ expect(agent!.budgetMonthlyCents).toBe(1_000); } }); + + +it("requires explicit remote gateway admission and infrastructure credentials before opening a journal", async () => { + const remote = runnerMatrix.find(e => e.suite.id === cell.suite.id && e.profile.id === cell.profile.id && e.environment.id === "daytona")!; + const value = { ...manifest(), executionIds: [remote.id], remoteGateway: "cloudflare" as const }; + expect(validateEvalOperationsManifest(value, [remote], 0)).toBe(value); + const root = await mkdtemp(path.join(tmpdir(), "eval-remote-preflight-")); + try { + value.ledgerPath = path.join(root, "ledger.jsonl"); + const file = path.join(root, "manifest.json"); await writeFile(file, JSON.stringify(value)); + await expect(openEvalOperations(file, [remote], 0, { OPENAI_API_KEY: "synthetic" })).rejects.toThrow("credential"); + await expect(access(value.ledgerPath)).rejects.toMatchObject({ code: "ENOENT" }); + } finally { await rm(root, { recursive: true, force: true }); } +}); + +it("gives remote workers scoped gateway/relay URLs and closes both local listeners and the tunnel", async () => { + const remote = runnerMatrix.find(e => e.suite.id === cell.suite.id && e.profile.id === cell.profile.id && e.environment.id === "daytona")!; + const root = await mkdtemp(path.join(tmpdir(), "eval-remote-operation-")); + const close = vi.fn(async () => {}), origin = "https://synthetic-owned.trycloudflare.com"; + const start = vi.spyOn(remoteGateway, "startEvalRemoteGateway").mockResolvedValue({ baseUrl: origin, close }); + const value = { ...manifest(), executionIds: [remote.id], remoteGateway: "cloudflare" as const, ledgerPath: path.join(root, "ledger.jsonl") }; + value.limits.deadlineAt = new Date(Date.now() + 24 * 3_600_000).toISOString(); + const file = path.join(root, "manifest.json"), env = { OPENAI_API_KEY: "provider-private", DAYTONA_API_KEY: "infra-private", + BRAINTRUST_API_KEY: "trace-private", PAPERCLIP_E2E_BRAINTRUST_PROJECT_ID: "11111111-1111-4111-8111-111111111111" }; + let operations: Awaited> | undefined; + try { + await writeFile(file, JSON.stringify(value)); operations = await openEvalOperations(file, [remote], 0, env); + const endpoint = await operations.start(remote, "remote-one", 1); + const worker: NodeJS.ProcessEnv = { ...env }; applyEvalGatewayEnvironment(worker, remote.profile.credential, endpoint); + expect(worker).toMatchObject({ PAPERCLIP_E2E_GATEWAY_BASE_URL: origin, PAPERCLIP_E2E_REMOTE_GATEWAY_ORIGIN: origin, + PAPERCLIP_E2E_OTLP_RELAY_URL: `${origin}/otel`, OPENAI_API_KEY: endpoint.token, BRAINTRUST_API_KEY: endpoint.observability!.token }); + expect(JSON.stringify(worker)).not.toMatch(/provider-private|infra-private|trace-private/); + const local = start.mock.calls[0]![0]; + expect(local.gateway.baseUrl).toMatch(/^http:\/\/127\.0\.0\.1:/); + expect(local.deadlineAt).toBeLessThanOrEqual(Date.now() + 4 * 3_600_000); + expect(local.deadlineAt).toBeLessThan(Date.parse(value.limits.deadlineAt)); + await operations.close(); operations = undefined; expect(close).toHaveBeenCalledOnce(); + await expect(fetch(local.gateway.baseUrl)).rejects.toThrow(); + await expect(fetch(local.observability!.baseUrl)).rejects.toThrow(); + } finally { await operations?.close(); await rm(root, { recursive: true, force: true }); } +}); diff --git a/tests/runner-e2e/operations.ts b/tests/runner-e2e/operations.ts index ed4e82d1cee..831520dd9e2 100644 --- a/tests/runner-e2e/operations.ts +++ b/tests/runner-e2e/operations.ts @@ -4,6 +4,7 @@ import { createHash } from "node:crypto"; import { createEvalAttemptPhase, readEvalAttemptPhase } from "./attempt-phase.js"; import { EvalSpendState, openEvalCostLedger, type EvalSpendLimits } from "./cost-ledger.js"; import { evalRequestReservation, startEvalGateway, type EvalGatewayRoute, type EvalGatewayReceipt } from "./eval-gateway.js"; +import { startEvalRemoteGateway } from "./eval-remote-gateway.js"; import type { MatrixExecution } from "./types.js"; import { evalBraintrustConfig } from "./braintrust.js"; import { startEvalOtlpRelay } from "./eval-otlp-relay.js"; @@ -17,13 +18,15 @@ export interface EvalOperationsManifest { maxAttemptsPerExecution: number; route: "direct" | "braintrust"; projectId?: string; + remoteGateway?: "cloudflare"; models: Array>; } const fields = (value: object, names: string[]) => { if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).some(name => !names.includes(name))) throw new Error("Invalid eval operations manifest fields"); }; export function validateEvalOperationsManifest(value: EvalOperationsManifest, executions: readonly MatrixExecution[], maxRetries: number) { - fields(value, ["version", "limits", "ledgerPath", "executionIds", "maxAttemptsPerExecution", "route", "projectId", "models"]); + fields(value, ["version", "limits", "ledgerPath", "executionIds", "maxAttemptsPerExecution", "route", "projectId", "remoteGateway", "models"]); + if (value.remoteGateway !== undefined && value.remoteGateway !== "cloudflare") throw new Error("Invalid remote eval gateway policy"); const initial = new EvalSpendState(value.limits).snapshot(); const initialModelAllowance = usdToUnits(value.limits.maxUsd) - usdToUnits(initial.committedUsd); if (value.version !== 1 || !["direct", "braintrust"].includes(value.route) || !path.isAbsolute(value.ledgerPath) @@ -46,9 +49,11 @@ export function validateEvalOperationsManifest(value: EvalOperationsManifest, ex models.set(key, usdToUnits(evalRequestReservation({ ...model, mode: value.route, apiKey: "validation" }))); } for (const execution of executions) { - if (execution.environment.id !== "local" || !["core-compatibility", "feedback-persistence"].includes(execution.suite.id) + if (!(execution.environment.id === "local" || execution.environment.id === "daytona" && value.remoteGateway === "cloudflare" + && ["runner-codex", "runner-acpx-claude"].includes(execution.profile.id)) || !["core-compatibility", "feedback-persistence"].includes(execution.suite.id) || !["runner-codex", "runner-acpx-claude", "legacy-codex", "legacy-claude"].includes(execution.profile.id) - || execution.requiredCredentials.length !== 1) throw new Error(`Unqualified budgeted eval route: ${execution.id}`); + || execution.requiredCredentials.length !== (execution.environment.id === "daytona" ? 2 : 1) + || execution.requiredCredentials.filter(name => name !== "DAYTONA_API_KEY").length !== 1) throw new Error(`Unqualified budgeted eval route: ${execution.id}`); const provider = execution.profile.credential === "ANTHROPIC_API_KEY" ? "anthropic" : "openai"; if (!models.has(`${provider}:${execution.profile.model}`)) throw new Error(`Missing exact model pricing: ${execution.id}`); if (models.get(`${provider}:${execution.profile.model}`)! > initialModelAllowance) { @@ -65,7 +70,8 @@ export async function openEvalOperations(file: string, executions: readonly Matr || Date.parse(manifest.limits.deadlineAt) >= Date.parse(manifest.limits.overhead.expiresAt))) { throw new Error("Operating overhead allowance does not cover the campaign window"); } - const required = manifest.route === "braintrust" ? ["BRAINTRUST_API_KEY"] : executions.map(execution => execution.profile.credential); + const required = [...(manifest.route === "braintrust" ? ["BRAINTRUST_API_KEY"] : executions.map(execution => execution.profile.credential)), + ...(executions.some(execution => execution.environment.id === "daytona") ? ["DAYTONA_API_KEY"] : [])]; if (required.some(name => !env[name]?.trim())) throw new Error("Missing eval gateway upstream credential"); const observability = evalBraintrustConfig({ ...env, PAPERCLIP_E2E_OTLP_RELAY_URL: undefined }); if (observability && manifest.route === "braintrust" && observability.projectId !== manifest.projectId) throw new Error("Eval gateway and OTLP projects differ"); @@ -99,14 +105,19 @@ export async function openEvalOperations(file: string, executions: readonly Matr persist: (receipt: EvalGatewayReceipt) => atomicJson(path.join(receiptDirectory, `${receipt.requestId}.json`), receipt), }); let relay: Awaited> | undefined; + let remote: Awaited> | undefined; try { if (observability) relay = await startEvalOtlpRelay({ projectId: observability.projectId, apiKey: observability.apiKey, campaignId: manifest.limits.campaignId, attemptId, deadlineAt: Math.min(Date.parse(manifest.limits.deadlineAt), Date.now() + 4 * 3_600_000), receiptPath: path.join(`${manifest.ledgerPath}.otlp`, `${createHash("sha256").update(attemptId).digest("hex")}.jsonl`) }); - } catch (error) { await gateway.close(); throw error; } + if (execution.environment.id === "daytona") remote = await startEvalRemoteGateway({ gateway, observability: relay, + deadlineAt: Math.min(Date.parse(manifest.limits.deadlineAt), Date.now() + 4 * 3_600_000) }, env); + } catch (error) { await Promise.allSettled([gateway.close(), relay?.close()]); throw error; } let closing: Promise | undefined; - const endpoint = { ...gateway, phasePath, observability: relay, close: () => closing ??= (async () => { - const results = await Promise.allSettled([gateway.close(), relay?.close()]); + const endpoint = { ...gateway, baseUrl: remote?.baseUrl ?? gateway.baseUrl, phasePath, + observability: relay ? { ...relay, baseUrl: remote ? `${remote.baseUrl}/otel` : relay.baseUrl } : undefined, close: () => closing ??= (async () => { + const remoteResults = await Promise.allSettled([remote?.close()]); + const results = [...remoteResults, ...await Promise.allSettled([gateway.close(), relay?.close()])]; active.delete(endpoint); if (results.some(result => result.status === "rejected")) throw new Error("Eval gateway or OTLP relay cleanup failed"); })() }; diff --git a/tests/runner-e2e/support.test.ts b/tests/runner-e2e/support.test.ts index 7de63dd9068..07c22457fe6 100644 --- a/tests/runner-e2e/support.test.ts +++ b/tests/runner-e2e/support.test.ts @@ -175,6 +175,7 @@ describe("runner E2E local binary resolution", () => { runnerBinary, undefined, "linux", + "x64", ), ).toBe(runnerBinary); expect( @@ -183,6 +184,7 @@ describe("runner E2E local binary resolution", () => { runnerBinary, undefined, "linux", + "x64", ), ).toBeUndefined(); expect( @@ -201,7 +203,14 @@ describe("runner E2E local binary resolution", () => { "darwin", ), ).toBe("/cross-compiled/paperclip-runnerd"); + expect(resolvePaperclipRemoteRunnerBinaryForHarness( + [remoteNativeExecution], runnerBinary, undefined, "linux", "arm64", + )).toBeUndefined(); + expect(resolvePaperclipRemoteRunnerBinaryForHarness( + [remoteNativeExecution], runnerBinary, "/cross-compiled/linux-x64-runnerd", "linux", "arm64", + )).toBe("/cross-compiled/linux-x64-runnerd"); }); + }); describe("runner E2E provider environment", () => { From 0b65926822aacde48729f4b82a5c333f4cadf375 Mon Sep 17 00:00:00 2001 From: Nicky Leach Date: Tue, 27 Oct 2026 14:39:06 -0700 Subject: [PATCH 2/4] fix(heartbeat): preserve inherited policy after workspace binding (#17924) ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Follow-up runs restore saved sessions when execution configuration is unchanged. > - A project can inherit workspace policy from its storage plugin. > - The initial run resolves those defaults before it binds a workspace. > - The first bound follow-up skipped that resolution and changed the session fingerprint. > - This pull request resolves the same effective policy before and after binding. > - Unchanged follow-ups keep their saved session and workspace. ## Linked Issues or Issue Description **What happened?** A repository-backed project with no explicit workspace policy inherits an isolated Git worktree policy from its storage plugin. After the first run binds a workspace, the next run parsed only the raw project policy. It dropped the inherited provider and strategy fields. Core treated this representation change as a `workspaceConfig` change and discarded the saved session, although the workspace had not changed. **Expected behavior** Binding a workspace must not change the effective project policy. Real policy changes must still invalidate session compatibility. The workspace must keep its recorded storage owner. **Steps to reproduce** 1. Install a default project storage plugin with isolated Git worktrees. 2. Create a project with a repository and no explicit workspace policy. 3. Run a task, then submit its first follow-up. 4. Observe a session reset for `workspaceConfig` despite an unchanged workspace. **Paperclip version or commit** Reproduced on master `50b932a142216331b8d476042b454bc123739c40`. Related: #17447 fixed the separate source-free project case. A duplicate PR search found no matching repository-backed fix. ## What Changed - Resolve effective project policy for bound repository-backed workspaces through the same company-scoped resolver as initial admission. The source-free project guard remains. - Add a PostgreSQL heartbeat regression covering initial binding, two follow-ups, a real policy change, and retained provider ownership. - Settle the synthetic adapter fixture as Done and reopen each explicit follow-up. This prevents an automatic review-path recovery from hiding the first bound admission. - Add the verification recipe to the session feature map. ## Verification - The new regression fails before the production change: the first explicit follow-up receives `sessionId: null` instead of the saved session. - All six tests in `server/src/__tests__/heartbeat-session-preparation.test.ts` pass after the fix. - A targeted run across that file and `project-workspace-provider.integration.test.ts` passed 17 cases, including inherited policy, model changes, incompatible explicit policy, provider availability, no fallback after disablement, and retained local/plugin ownership. - Commands: from `server/`, `node ../node_modules/vitest/vitest.mjs run src/__tests__/heartbeat-session-preparation.test.ts`; targeted controls used the same runner with `-t 'inherited|effective model|retains both plugin and local workspace ownership|never falls back|unavailable|explicit settings|compatible explicit'`. - `node scripts/check-maps.mjs` and `git diff --check` pass. - Initial fixture attempts hit source-binding, provider-execution, missing working-directory, and branch-inspection guards. The fixture was corrected; those guards remain unchanged. An automatic review recovery also hid the initial transition until fixture settlement was corrected. - Tests use real PostgreSQL, real policy resolution, and heartbeat persistence. Provider execution is synthetic; a temporary local working directory replaces environment realization for the test adapter. - Current head `4d21b5180960659576e5950e906056fa4dabb54c` removes two comments after standard review; executable code is unchanged from the locally verified commit. Standard Greptile scores this head 5/5 with no unresolved threads. GitHub CI is now green on this head: 54 successful checks and two intentional Storybook skips. Standard Greptile and Apex both score this head 5/5. Apex found no actionable issues; no unresolved threads or merge conflicts remain. - CI job [workspaces-b](https://github.com/paperclipai/paperclip/actions/runs/40564712367/job/122406649223) was interrupted by a runner shutdown signal at 19:09:39 UTC. Its available log shows no test assertion failure; completed groups passed. The serialized server shard [1/9](https://github.com/paperclipai/paperclip/actions/runs/40564712367/job/122406648374) also received a runner shutdown at 19:12:03 UTC; its final test summary reports 532 passing tests and no failed assertion. Both interrupted jobs passed in the failed-jobs-only rerun, and the final verify aggregate passed. The first retry request was rejected while the containing run was still active; it was accepted after the other jobs settled. - Local verification is targeted as requested. Full test, build, and typecheck coverage is delegated to GitHub CI. No live deployment or latency claim is made. ## Risks Bound repository runs now read the current storage-plugin defaults through one provider-list query. An ambiguous or incompatible effective policy can fail admission instead of being skipped. Existing plugin preparation still uses the recorded workspace owner, so a changed default does not move existing storage to another provider. Explicit policy changes still rotate the session. No schema or API changes are included. ## Model Used OpenAI GPT-6 through Codex, using repository inspection, code editing, shell tools, and targeted test execution. The exact serving model ID and context window are not exposed in this session. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip --- maps/feature-map/runs-adapters.md | 8 +++ .../heartbeat-session-preparation.test.ts | 69 ++++++++++++++++++- server/src/services/heartbeat.ts | 2 +- 3 files changed, 75 insertions(+), 4 deletions(-) diff --git a/maps/feature-map/runs-adapters.md b/maps/feature-map/runs-adapters.md index 28d3c31f6d9..9432c9a792b 100644 --- a/maps/feature-map/runs-adapters.md +++ b/maps/feature-map/runs-adapters.md @@ -74,6 +74,14 @@ mutations. Qualify a useful model task separately from saving the account. ### `session` +For a repository project that inherits storage-plugin defaults, run a task and +send two follow-ups. Binding the workspace must preserve the effective policy, +session fingerprint, and workspace identity. An actual project-policy change +must still reset the session and preserve the stored workspace owner. The +[session admission regression](../../server/src/__tests__/heartbeat-session-preparation.test.ts) +checks this with PostgreSQL and synthetic provider execution; it is not live +warm-process or latency evidence. + For `runs-adapters/session`, complete a task in a disposable warm sandbox and retain its saved workspace file. Let the warm session close normally and verify that the retained lease has a complete, lease-bound harness backup before diff --git a/server/src/__tests__/heartbeat-session-preparation.test.ts b/server/src/__tests__/heartbeat-session-preparation.test.ts index 784b3ff2df4..13d0544016b 100644 --- a/server/src/__tests__/heartbeat-session-preparation.test.ts +++ b/server/src/__tests__/heartbeat-session-preparation.test.ts @@ -1,9 +1,15 @@ import { randomUUID } from "node:crypto"; +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; import { eq } from "drizzle-orm"; -import { afterAll, beforeAll, describe, expect, it } from "vitest"; -import { agents, agentTaskSessions, authUsers, companies, companyMemberships, createDb, heartbeatRuns, issues, plugins, projects } from "@paperclipai/db"; +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; +import { agents, agentTaskSessions, authUsers, companies, companyMemberships, createDb, executionWorkspaces, heartbeatRuns, issues, plugins, projects } from "@paperclipai/db"; import { registerServerAdapter, unregisterServerAdapter, type AdapterExecutionContext } from "../adapters/index.js"; import { heartbeatService } from "../services/heartbeat.js"; +import { instanceSettingsService } from "../services/instance-settings.js"; +import type { PluginWorkerManager } from "../services/plugin-worker-manager.js"; +import * as environmentOrchestrator from "../services/environment-run-orchestrator.js"; import { createPluginWorkspaceFixture } from "./helpers/plugin-workspaces.js"; import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; @@ -29,7 +35,7 @@ describePostgres("heartbeat session preparation through adapter dispatch", () => captured.set(input.runId, input); // Settle the fixture's work so no automatic unfinished-task retry // competes with the next explicit session-continuation wake. - await db.update(issues).set({ status: "in_review" }).where(eq(issues.id, String(input.context.issueId))); + await db.update(issues).set({ status: "done" }).where(eq(issues.id, String(input.context.issueId))); return { exitCode: 0, signal: null, timedOut: false, sessionId: "saved-session", sessionParams: { sessionId: "saved-session", adapterState: "preserved" }, resultJson: {} }; }, testEnvironment: async () => ({ adapterType, status: "pass", checks: [], testedAt: new Date().toISOString() }), @@ -54,6 +60,7 @@ describePostgres("heartbeat session preparation through adapter dispatch", () => } async function execute(f: Awaited>, context: Record = {}) { + await db.update(issues).set({ status: "todo" }).where(eq(issues.id, f.issueId)); const run = await heartbeat.wakeup(f.agentId, { source: "on_demand", triggerDetail: "manual", reason: "manual", payload: { issueId: f.issueId }, contextSnapshot: { issueId: f.issueId, ...context }, @@ -105,6 +112,62 @@ describePostgres("heartbeat session preparation through adapter dispatch", () => } finally { await db.delete(plugins).where(eq(plugins.id, storage.pluginId)); } }); + it("keeps inherited repository policy stable through binding and retains the provider on policy changes", async () => { + const f = await seed(); + const storage = await createPluginWorkspaceFixture(db, f.companyId); + const [plugin] = await db.select().from(plugins).where(eq(plugins.id, storage.pluginId)); + await db.update(plugins).set({ manifestJson: { ...plugin.manifestJson, workspaceProvider: { + ...plugin.manifestJson.workspaceProvider!, defaultForProjects: { mode: "isolated_workspace", strategy: "git_worktree" }, + } } }).where(eq(plugins.id, storage.pluginId)); + await db.update(projects).set({ executionWorkspacePolicy: null }).where(eq(projects.id, storage.input.projectId)); + await db.update(issues).set({ projectId: storage.input.projectId, projectWorkspaceId: storage.input.projectWorkspaceId, + executionWorkspaceSettings: { workspaceStrategy: { type: "git_worktree", branchTemplate: "work" } }, + }).where(eq(issues.id, f.issueId)); + await instanceSettingsService(db).updateExperimental({ enableIsolatedWorkspaces: true, enableIsolatedWorkspacesByDefault: true }); + const cwd = await mkdtemp(join(tmpdir(), "session-provider-fixture-")); + const createOrchestrator = environmentOrchestrator.environmentRunOrchestrator; + const realization = vi.spyOn(environmentOrchestrator, "environmentRunOrchestrator").mockImplementation((...args) => ({ + ...createOrchestrator(...args), + realizeForRun: async input => { + input.executionWorkspace.cwd = cwd; + return { lease: input.lease, persistedExecutionWorkspace: input.persistedExecutionWorkspace, + workspaceRealization: {}, executionTarget: null, remoteExecution: null }; + }, + })); + const originalHeartbeat = heartbeat; + heartbeat = heartbeatService(db, { pluginWorkerManager: storage.workers as PluginWorkerManager }); + try { + const first = await execute(f); + const [bound] = await db.select().from(issues).where(eq(issues.id, f.issueId)); + expect(bound.executionWorkspaceId).toEqual(expect.any(String)); + const [workspace] = await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, bound.executionWorkspaceId!)); + expect([...captured.values()].filter(input => input.context.issueId === f.issueId)).toHaveLength(1); + expect(workspace).toMatchObject({ providerType: "plugin", strategyType: "git_worktree" }); + for (let turn = 0; turn < 2; turn++) { + const next = await execute(f); + expect(next.input.runtime.sessionId).toBe("saved-session"); + expect(next.input.config.workspaceStrategy).toEqual(first.input.config.workspaceStrategy); + expect(next.finished.resultJson).toMatchObject({ configFreshness: { + session: { reset: false, taskSessionReused: true, changedCategories: [] }, + workspace: { action: "reuse", workspaceReused: true, changedCategories: [], activeWorkspaceId: bound.executionWorkspaceId }, + } }); + } + await db.update(projects).set({ executionWorkspacePolicy: { enabled: true, allowIssueOverride: false } }).where(eq(projects.id, storage.input.projectId)); + const changed = await execute(f); + expect(changed.input.runtime.sessionId).toBeNull(); + expect(changed.finished.resultJson).toMatchObject({ configFreshness: { session: { reset: true, changedCategories: ["workspaceConfig"] } } }); + const [retained] = await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, bound.executionWorkspaceId!)); + expect(retained.metadata?.workspaceProviderOwner).toBe(storage.pluginId); + } finally { + await heartbeat.drainActiveRunExecutions(); + heartbeat = originalHeartbeat; + realization.mockRestore(); + await rm(cwd, { recursive: true, force: true }); + await db.delete(plugins).where(eq(plugins.id, storage.pluginId)); + await instanceSettingsService(db).updateExperimental({ enableIsolatedWorkspaces: false, enableIsolatedWorkspacesByDefault: false }); + } + }); + it("starts fresh when effective model configuration changes and persists the reason", async () => { const f = await seed(); await execute(f); diff --git a/server/src/services/heartbeat.ts b/server/src/services/heartbeat.ts index 59d2bd04a61..82f12b71f10 100644 --- a/server/src/services/heartbeat.ts +++ b/server/src/services/heartbeat.ts @@ -2380,7 +2380,7 @@ export function heartbeatService( !boundSourceWorkspace && !taskWorkspaceIntentRow?.intent && !issueContext?.projectWorkspaceId ? taskProjectContext : null ); - const parsedProjectExecutionWorkspacePolicy = workspacePolicyContext?.hasWorkspace && !boundSourceWorkspace + const parsedProjectExecutionWorkspacePolicy = workspacePolicyContext?.hasWorkspace ? await effectiveProjectWorkspacePolicy(db, agent.companyId, workspacePolicyContext.executionWorkspacePolicy, workspacePolicyContext.hasGitSource) : parseProjectExecutionWorkspacePolicy(workspacePolicyContext?.executionWorkspacePolicy); const projectExecutionWorkspacePolicy = From d40f9ac377d9d549d3d59890dd45e42ae361e00c Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 27 Oct 2026 17:07:50 -0500 Subject: [PATCH 3/4] fix: enforce first-task completion decisions and retain E2E evidence (#17940) ## Thinking Path > - Paperclip lets people delegate work to agents and approve proposed work. > - The onboarding first task asks for scope, proposes a task, and waits for a human decision. > - An answer to its opening question supplies scope. It does not approve a proposal. > - Task creation already checks the saved proposal decision. > - Native completion used the general completion policy and could mark the onboarding parent Done without that decision. > - This PR checks the trusted decision before completion feedback and again when the native status is committed. > - The first task stays in review until a saved human decision permits closure. Ordinary completion and acknowledged refusal keep their current behavior. > - The Product E2E guard also retains closed scalar evidence so future failures show which boundary condition was observed. ## Linked Issues or Issue Description Refs: #17914. Profile compatibility follow-up to #17922. **What happened?** A native onboarding run can submit a valid low-risk Done result after only the opening answer. The native finalizer then marks the first task Done even though no human has accepted or rejected a proposal. **Expected behavior** The opening answer must not permit completion. A trusted saved proposal decision must permit it. A saved rejection permits acknowledgment and closure, but does not authorize new work. A later pending proposal must keep the task in review. **Steps to reproduce** Create a server-owned onboarding first task with an answered opening question, no proposal decision, and a valid low-risk completion contract. Pass a Done result through native completion feedback, the control-plane port, and the finalizer. Before this fix, the persisted status is Done. The regression expects In review. Ordinary completion and acknowledged rejection pass as controls. ## What Changed - Share the trusted latest-proposal and human-response checks with completion admission. Keep task creation acceptance-only. - Refuse premature native completion feedback. Keep an already saved premature result in review during finalization. - Check the decision again under the existing task and run locks before committing Done. - Cover accepted decisions, saved refusals, forged context, pending or changed proposals, and a real database race. - Retain a closed scalar receipt when the existing E2E pre-acceptance guard fails. Validate and display it without task content, IDs, filenames, or raw rows. Preserve the original failure, blocked dependents, and historical reports. - Include the evidence module in the journey definition hash. Bind the receipt to its exact failure code and check its closed keys against the full type. - Repair base-branch profile drift found by the full harness check: include the active Copilot v66 fixture in image hashing and update stale Pi version/hash expectations from #17922. Keep all older image inputs and strict hash checks. - Update the onboarding feature and agent access maps and E2E evidence documentation. ## Verification - Semantic regression before implementation: one failure and two passing controls on PostgreSQL 18. The failed assertion observed Done instead of In review. - The local database uses an owned disposable container with an immutable image digest. Actual migrations, feedback, control-plane port, finalizer, and status commit run against PostgreSQL. A temporary test adapter replaces only the embedded database transport because this host has exhausted its PostgreSQL semaphores. - Native control-plane suite: 55 tests passed, including 17 new controls. Existing task-creation admission: 25 passed. Existing completion feedback: 19 passed. - Credential-free E2E support: 206 Vitest suites passed, 4,407 tests passed, and two skipped. All 137 Node support checks passed. Harness typecheck passed. - The failure-receipt regression had 11 failed assertions before capture was implemented. Two failure-code binding assertions fail without their gate. Eight placement/binding cases first validate the receipt-free control, then reject the misplaced receipt. - The untouched base reproduced the three profile compatibility failures. The narrow repair passed all 83 affected tests before the full harness run. - Private workflow preparation and credential-free onboarding preview: nine compatibility checks passed. Ownership, recovery, evidence, shared-contract and workflow compatibility: 77 passed. The actual provider preview also confirms immediate success deletion, earlier declared failure eligibility, limits, and zero retries without credential access. Map checks and git diff checks passed. - Required repository typecheck passed for the product fix. The combined branch build passed. The local full repository suite was stopped after repeated PostgreSQL startup failures; a separate initdb probe confirmed host SysV semaphore exhaustion. No shared IPC resources were changed. [Hosted CI](https://github.com/paperclipai/paperclip/actions/runs/40591020873) passed the full database suites, typecheck, build, runner checks, serialized suites, and browser shards on final head `1ac4c23605a03bfd1f1f8a017b14ce29fda85f6b` (55 success, two expected skips, one advisory neutral). - Independent source review approved the product guard, atomic race regression, evidence contract, and maps with no actionable findings. Both automated reviews are 5/5 on final head `1ac4c23605a03bfd1f1f8a017b14ce29fda85f6b`; prior findings are fixed and resolved. Final CI is green and the PR is conflict-free. - No Cloud workspace, provider call, release publication, or deployment is part of this verification. These tests do not identify a historical Cloud failure or qualify live onboarding. - Local dependency installation uses the existing CI-generated lockfile from #17811. No lockfile change is included. ## Risks - Existing onboarding runs without a trusted saved proposal decision remain in review even when the agent reports success. This is the intended approval boundary. - Decision changes can race completion. The status commit checks the decision under its existing locks and uses the existing status-race recovery path. - A saved refusal permits closure only. Creation admission still rejects it. - Evidence readers reject malformed receipts and unrelated failure codes. The version-1 key registry is checked against every receipt field at compile time. Existing attempts do not gain evidence after the fact. ## Model Used OpenAI GPT-6.1 Sol (`gpt-6.1-sol`), ultra reasoning, through Codex. Used repository inspection, code execution, and collaborating coding agents. The runtime did not report a context-window size. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes:` / `Closes:` / `Refs:` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub references) - [x] My branch name describes the change and contains no internal ticket or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip --- maps/agent-access-map/onboarding.md | 10 + maps/feature-map/onboarding.md | 9 + .../native-completion-feedback.ts | 6 + .../native-runtime/native-run-finalizer.ts | 11 +- .../paperclip-control-plane-port.test.ts | 188 ++++++++++++++++++ .../status-decision-committer.ts | 6 + .../onboarding-first-task-admission.ts | 69 +++++-- tests/runner-e2e/PRODUCT-JOURNEYS.md | 3 +- tests/runner-e2e/README.md | 10 + tests/runner-e2e/SECURITY.md | 10 + tests/runner-e2e/case-outcome.ts | 16 ++ tests/runner-e2e/daytona-image-content.ts | 1 + tests/runner-e2e/pi-controls-evidence.test.ts | 6 +- .../product-journeys/campaign.test.ts | 19 +- tests/runner-e2e/product-journeys/catalog.ts | 2 +- .../product-journeys/cloud-onboarding.test.ts | 16 ++ .../product-journeys/cloud-onboarding.ts | 3 +- tests/runner-e2e/product-journeys/launch.ts | 2 +- .../onboarding-first-task.test.ts | 85 ++++++++ .../product-journeys/onboarding-first-task.ts | 22 +- .../onboarding-pre-acceptance.test.ts | 105 ++++++++++ .../onboarding-pre-acceptance.ts | 59 ++++++ tests/runner-e2e/product-journeys/types.ts | 1 + tests/runner-e2e/result-validation.ts | 5 + 24 files changed, 632 insertions(+), 32 deletions(-) create mode 100644 tests/runner-e2e/product-journeys/onboarding-pre-acceptance.test.ts create mode 100644 tests/runner-e2e/product-journeys/onboarding-pre-acceptance.ts diff --git a/maps/agent-access-map/onboarding.md b/maps/agent-access-map/onboarding.md index 9c5dded3eff..5160136841c 100644 --- a/maps/agent-access-map/onboarding.md +++ b/maps/agent-access-map/onboarding.md @@ -189,6 +189,16 @@ conversational resolution with a genuine later same-task user message supplies acceptance; an agent-only resolution does not. A plan approval must name the current same-task revision. Newer pending/rejected proposals stop new creation. Already admitted task replay and ordinary delegation retain their existing rules. + +Native `paperclip_finish` does not grant completion authority from an opening +answer. The onboarding parent requires a trusted saved human decision on its +latest proposal. Acceptance permits completion under the existing policy; +rejection permits acknowledgment and closure without authorizing new work. +The native status commit checks this decision again under its existing task/run +locks. This adds no new agent endpoint or cross-company authority. The +[native completion controls](../../server/src/services/native-runtime/paperclip-control-plane-port.test.ts) +check persisted outcomes on disposable PostgreSQL; they are not live Cloud +credential or onboarding qualification. Source: [creation admission](../../server/src/services/onboarding-first-task-admission.ts). Controls: [native/REST PostgreSQL regressions](../../server/src/__tests__/onboarding-first-task-admission.test.ts). These controls do not qualify a live Cloud provider journey. diff --git a/maps/feature-map/onboarding.md b/maps/feature-map/onboarding.md index 347613e3829..d90025b2a31 100644 --- a/maps/feature-map/onboarding.md +++ b/maps/feature-map/onboarding.md @@ -142,6 +142,15 @@ admit new work. [Admission controls](../../server/src/__tests__/onboarding-first exercise native and REST calls against disposable PostgreSQL; live model and Cloud onboarding remain separate evidence. +Native completion also requires a saved human proposal decision. An opening +answer alone must leave the first task in review. Verify that premature native +completion is refused, including a result already saved before finalization. +Accepted proposals and acknowledged human rejections can close the first task; +rejection still does not authorize new tasks. The +[native completion controls](../../server/src/services/native-runtime/paperclip-control-plane-port.test.ts) +exercise these boundaries against disposable PostgreSQL. These controls do not +identify a historical Cloud failure or establish live onboarding success. + For accepted file-producing work, verify exactly one self-assigned child with a self-contained description. The onboarding run must yield through the existing dependency/block disposition so the child's own execution can publish its file. diff --git a/server/src/services/native-runtime/native-completion-feedback.ts b/server/src/services/native-runtime/native-completion-feedback.ts index 9bb94b39c72..668af156fc3 100644 --- a/server/src/services/native-runtime/native-completion-feedback.ts +++ b/server/src/services/native-runtime/native-completion-feedback.ts @@ -1,4 +1,5 @@ import { pendingTaskRepository } from "../task-workspace-tools.js"; +import { onboardingFirstTaskCompletionAllowed } from "../onboarding-first-task-admission.js"; import { eligibleIssueMonitorWait } from "../issue-monitors.js"; import { assertNativeCaseHandoffResult } from "./native-case-handoff.js"; import { activeIssueInteractionCondition, ordinaryQuestionCondition } from "../issue-question-context.js"; @@ -140,6 +141,11 @@ export async function nativeCompletionFeedback( if (issue.executionRunId && issue.executionRunId !== runId) { return "Report accepted; a newer run owns the task. Do not claim this report changed its status."; } + if (result.reportedWorkDisposition === "done" && !await onboardingFirstTaskCompletionAllowed(db, { + companyId: run.companyId, issueId: issue.id, runId, + })) { + throw new Error("First-task proposal requires a persisted human decision before completing onboarding. The opening answer supplies scope, not approval. Present the proposal and keep this task in_review until the human accepts or rejects it; acknowledge a rejection without executing that work."); + } const continuation = run.contextSnapshot?.executionContinuation as { objective?: unknown } | undefined; const objective = typeof continuation?.objective === "string" ? continuation.objective : [issue.title, issue.description].filter(Boolean).join("\n"); diff --git a/server/src/services/native-runtime/native-run-finalizer.ts b/server/src/services/native-runtime/native-run-finalizer.ts index 4ade80add27..88efc195b86 100644 --- a/server/src/services/native-runtime/native-run-finalizer.ts +++ b/server/src/services/native-runtime/native-run-finalizer.ts @@ -1,4 +1,5 @@ import { pendingNativeGovernance } from "./native-governance.js"; +import { onboardingFirstTaskCompletionAllowed } from "../onboarding-first-task-admission.js"; import { notifyExecutionRunWork } from "../execution-control-notifications.js"; import { reconcileMuseNativeTerminalRun } from "./muse-terminal-reconciliation.js"; import { assertNativeCaseHandoffResult } from "./native-case-handoff.js"; @@ -1429,7 +1430,7 @@ export async function finalizeNativeRun(input: { authoritativeIssue.executionRunId !== run.id && authoritativeIssue.checkoutRunId !== run.id ? await readNativeMonitorDelivery(input.db, { companyId: run.companyId, issueId: coordinator.issueId, runId: run.id }) : null; - const proposedDecision = resolveNativeFinalizerStatus({ + let proposedDecision = resolveNativeFinalizerStatus({ caseHandoffAuthorized: Boolean(await assertNativeCaseHandoffResult(input.db, run.id, authoritativeIssue.id, result)), monitorWaitDispatched: monitorDelivery !== null, monitorWaitPreserved: preservedMonitorWait !== null, @@ -1471,6 +1472,14 @@ export async function finalizeNativeRun(input: { agentId: run.agentId, priorIssueStatus: authoritativeStatus(authoritativeIssue.status), }); + // Already accepted results still require the server-owned first-task decision. + // Keep the task open without inventing an interaction or rerunning the work. + if (proposedDecision.statusAction === "done" && !await onboardingFirstTaskCompletionAllowed(input.db, { + companyId: run.companyId, issueId: authoritativeIssue.id, runId: run.id, + })) { + proposedDecision = { ...proposedDecision, statusAction: "in_review", toStatus: "in_review", + reasonCode: "onboarding_first_task_decision_required", unblockDescriptor: null, effects: [{ kind: "release_checkout" }] }; + } const decision = conversationNativeDecision({ conversation: isConversation(authoritativeIssue), terminalState, workspaceFinalizeStatus: input.workspaceFinalizeStatus, hasGovernanceGate: !!governanceGate, diff --git a/server/src/services/native-runtime/paperclip-control-plane-port.test.ts b/server/src/services/native-runtime/paperclip-control-plane-port.test.ts index f8b9eb1d022..4676979de87 100644 --- a/server/src/services/native-runtime/paperclip-control-plane-port.test.ts +++ b/server/src/services/native-runtime/paperclip-control-plane-port.test.ts @@ -2,6 +2,7 @@ import { afterAll, beforeAll, describe, expect, it } from "vitest"; import { asc, eq, sql } from "drizzle-orm"; import { generateKeyPairSync, randomUUID } from "node:crypto"; import { renderPaperclipWakePrompt } from "@paperclipai/adapter-utils/server-utils"; +import { ONBOARDING_FIRST_TASK_ORIGIN_KIND } from "@paperclipai/shared"; import { readCompletedAssistantMessageCandidate, resolveHeartbeatRunResponse, selectHeartbeatRunFinalAgentMessage } from "../heartbeat-run-summary.js"; import { activityLog, @@ -46,11 +47,13 @@ import { NativeRunCoordinatorStore } from "./native-run-coordinator-store.js"; import { finalizeNativeRun, repairCommittedNativeChatResponse } from "./native-run-finalizer.js"; import { nativeRuntimeContextFixture } from "./runtime-context.test-fixture.js"; import { issueThreadInteractionService } from "../issue-thread-interactions.js"; +import { documentService } from "../documents.js"; import { claimNativeReviewExecutionLock, getNativeReviewAssignment } from "./native-review-participant.js"; import { claimQueuedNativeReviewRun } from "./native-review-dispatch.js"; import { stageNativeRunnerWakeAttachments } from "./native-runner-file-handoff.js"; import { PaperclipRunnerToolAuthority } from "./paperclip-runner-tool-authority.js"; import { nativeCompletionFeedback } from "./native-completion-feedback.js"; +import { buildOnboardingFirstTaskOpeningQuestion, ONBOARDING_FIRST_TASK_OPENING_QUESTION_ID } from "../onboarding-first-task-assets.js"; import { assertCurrentWakeCommentsRead } from "./current-wake-comments.js"; import { buildExecutionContinuation } from "../execution-continuation.js"; import { childReviewOutcomes } from "./child-review-outcomes.js"; @@ -1709,6 +1712,191 @@ describe("PaperclipControlPlanePort conformance", () => { }); + const allowedFirstTaskCompletionScenarios = [ + "ordinary task", "accepted proposal", "accepted conversational proposal", "accepted current plan", "acknowledged rejection", "acknowledged plan rejection", + ] as const; + const refusedFirstTaskCompletionScenarios = [ + "opening answer only", "agent-resolved without human comment", "quarantined human comment", "newest proposal pending", "stale plan acceptance", + ] as const; + type FirstTaskCompletionScenario = typeof allowedFirstTaskCompletionScenarios[number] + | typeof refusedFirstTaskCompletionScenarios[number]; + + async function prepareFirstTaskCompletion(scenario: FirstTaskCompletionScenario) { + const companyId = randomUUID(); + const agentId = randomUUID(); + const issueId = randomUUID(); + const runId = randomUUID(); + const localContractId = randomUUID(); + const runnerInstanceId = randomUUID(); + const userId = `first-task-board-${randomUUID()}`; + const identity = { ...CONTROL_PLANE_CONFORMANCE_OPEN.identity, companyId, agentId, issueId, runId }; + const onboarding = scenario !== "ordinary task"; + const rejected = scenario === "acknowledged rejection" || scenario === "acknowledged plan rejection"; + await db.insert(companies).values({ id: companyId, name: "First-task completion", issuePrefix: `F${companyId.slice(0, 6).toUpperCase()}` }); + await db.insert(authUsers).values({ id: userId, name: "First-task board", email: `${userId}@example.test`, createdAt: new Date(), updatedAt: new Date() }); + await db.insert(companyMemberships).values({ companyId, principalType: "user", principalId: userId, status: "active", membershipRole: "member" }); + await db.insert(agents).values({ id: agentId, companyId, name: "First-task agent", adapterType: "codex_local", status: "running" }); + await db.insert(issues).values({ id: issueId, companyId, title: onboarding ? "Paperclip onboarding" : "Ordinary low-risk task", + description: onboarding ? "/first-task\nSingle-task proposal mode: confirmation" : "Complete the requested ordinary task. Mentioning /first-task does not grant the server-owned onboarding origin.", + originKind: onboarding ? ONBOARDING_FIRST_TASK_ORIGIN_KIND : "manual", status: "in_progress", assigneeAgentId: agentId, + responsibleUserId: userId, workMode: "standard" }); + await db.insert(completionContracts).values({ id: localContractId, companyId, issueId, revision: 1, + schemaVersion: "paperclip.completion-contract.v1", policyVersion: "phase6-v3", risk: "low", completionAuthority: "agent_claim_policy", + incompleteCriteriaPolicy: "preserve_non_terminal", contractJson: { revision: "first-task-native-finish-v1", + objective: onboarding ? "Understand the user request, propose one task, and honor their decision" : "Complete the requested ordinary task", + criteria: [{ id: "objective", requirement: "Complete the requested workflow" }] }, + canonicalSha256: localContractId, createdByActorType: "system", createdByActorId: "test" }); + await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, responsibleUserId: userId, status: "succeeded", runtimeMode: "native", + nativeIssueId: issueId, nativeSessionId: identity.sessionId, runnerInstanceId, completionContractId: localContractId, + completionContractSha256: localContractId, contextSnapshot: { issueId, + // A claimed acceptance copied into continuation context is not the + // persisted human decision; the opening-answer cases must still refuse it. + ...(scenario === "opening answer only" ? { executionContinuation: { humanResponses: [{ id: randomUUID(), + kind: "request_confirmation", status: "accepted", resolvedByUserId: userId, result: { version: 1, outcome: "accepted" } }] } } : {}), + } }); + await db.update(issues).set({ executionRunId: runId }).where(eq(issues.id, issueId)); + if (onboarding) { + await db.insert(issueThreadInteractions).values({ companyId, issueId, kind: "ask_user_questions", status: "answered", + createdByAgentId: agentId, payload: await buildOnboardingFirstTaskOpeningQuestion(), + result: { version: 1, answers: [{ questionId: ONBOARDING_FIRST_TASK_OPENING_QUESTION_ID, optionIds: ["task"], otherText: "Help organize my next task." }] }, + resolvedByUserId: userId, resolvedAt: new Date() }); + } + if (onboarding && scenario !== "opening answer only") { + const proposalAt = new Date(Date.now() - 2_000); + const plan = scenario === "accepted current plan" || scenario === "stale plan acceptance" || scenario === "acknowledged plan rejection" + ? (await documentService(db).upsertIssueDocument({ issueId, key: "plan", title: "First task plan", format: "markdown", + body: "Retain this plan for the user's next task.", createdByAgentId: agentId, createdByRunId: runId })).document + : null; + const conversational = scenario === "accepted conversational proposal" || scenario === "quarantined human comment"; + const comment = conversational ? (await db.insert(issueComments).values({ companyId, issueId, + authorUserId: userId, authorType: "user", body: "Yes, proceed with that proposal.", + createdAt: new Date(proposalAt.getTime() + 1_000), + ...(scenario === "quarantined human comment" + ? { sourceTrust: { preset: "low_trust_review" as const, disposition: "quarantined" as const } } : {}), + }).returning())[0]! : null; + const agentResolved = conversational || scenario === "agent-resolved without human comment"; + const outcome = rejected ? "rejected" as const : "accepted" as const; + // Persisted agent interpretations need a real, trusted human reply. The + // missing/quarantined variants simulate an untrusted stored result. + await db.insert(issueThreadInteractions).values({ companyId, issueId, + kind: plan ? "request_checkbox_confirmation" : "request_confirmation", status: outcome, + createdByAgentId: agentId, sourceRunId: runId, createdAt: proposalAt, + payload: plan ? { version: 1, prompt: "May I retain this plan?", + options: [{ id: "retain-plan", label: "Retain the plan" }], defaultSelectedOptionIds: ["retain-plan"], minSelected: 1, + target: { type: "issue_document", key: "plan", issueId, documentId: plan.id, revisionId: plan.latestRevisionId! }, + } : { version: 1, prompt: "May I create one task to organize your agenda?" }, + result: { version: 1, outcome, ...(plan && outcome === "accepted" ? { selectedOptionIds: ["retain-plan"] } : {}), + ...(comment ? { commentId: comment.id } : {}), + ...(outcome === "rejected" ? { reason: "Do not do this work." } : {}) }, + resolvedByUserId: agentResolved ? null : userId, + resolvedByAgentId: agentResolved ? agentId : null, resolvedByRunId: agentResolved ? runId : null, + resolvedAt: new Date(), + }); + if (scenario === "newest proposal pending") { + await db.insert(issueThreadInteractions).values({ companyId, issueId, + kind: "request_checkbox_confirmation", status: "pending", createdByAgentId: agentId, sourceRunId: runId, + createdAt: new Date(proposalAt.getTime() + 1_000), + payload: { version: 1, prompt: "Accept the revised task scope?", options: [{ id: "revised", label: "Use revised scope" }], + defaultSelectedOptionIds: ["revised"], minSelected: 1 }, + }); + } + if (scenario === "stale plan acceptance" || scenario === "acknowledged plan rejection") { + await documentService(db).upsertIssueDocument({ issueId, key: "plan", format: "markdown", + baseRevisionId: plan!.latestRevisionId, body: "A revised scope that has no persisted human decision.", + createdByAgentId: agentId, createdByRunId: runId }); + } + } + const port = new PaperclipControlPlanePort(db, { companyId, issueId, runId, agentId, sessionId: identity.sessionId, + completionContractId: localContractId, completionContractSha256: localContractId, + sourceInstanceId: runnerInstanceId, controlPlaneSourceInstanceId: "first-task-native-finish-control" }); + await port.openRun({ identity, backendKind: "mock", sourceInstanceId: runnerInstanceId }); + const result: PrpStructuredRunResult = { ...structuredClone(CONTROL_PLANE_CONFORMANCE_RESULT), + summary: rejected + ? "You declined the proposal. I will stop here and have not created or performed the proposed task." + : "The requested workflow is complete.", + completionClaim: { contractRevision: "first-task-native-finish-v1", objectiveSatisfied: true, + criteria: [{ criterionId: "objective", status: "satisfied", evidenceRefs: [] }], remainingWork: [] }, + evidence: [], verification: [{ commandOrCheck: "Check the current task state", status: "passed" }], attentionRequests: [] }; + return { companyId, agentId, issueId, runId, port, result }; + } + + it.each(refusedFirstTaskCompletionScenarios)( + "refuses native completion feedback without a trusted current first-task decision (%s)", async (scenario) => { + const { issueId, runId, result } = await prepareFirstTaskCompletion(scenario); + await expect(nativeCompletionFeedback(db, runId, result)) + .rejects.toThrow("First-task proposal requires a persisted human decision"); + expect((await db.select().from(issues).where(eq(issues.id, issueId)))[0]!.status).toBe("in_progress"); + expect(await db.select().from(statusDecisions).where(eq(statusDecisions.issueId, issueId))).toEqual([]); + expect(await db.select().from(nativeRunResults).where(eq(nativeRunResults.runId, runId))).toEqual([]); + }); + + it.each([...allowedFirstTaskCompletionScenarios, ...refusedFirstTaskCompletionScenarios])( + "honors the first-task human decision during native completion (%s)", async (scenario) => { + const { issueId, runId, port, result } = await prepareFirstTaskCompletion(scenario); + const allowed = allowedFirstTaskCompletionScenarios.some(candidate => candidate === scenario); + if (allowed) await expect(nativeCompletionFeedback(db, runId, result)).resolves.toContain("Completion report accepted"); + // Invalid results bypass only early feedback to exercise the backstop for a + // report already committed by a disconnected or older controller. + await port.completeRun({ result, terminal: CONTROL_PLANE_CONFORMANCE_TERMINAL, callerResultId: "first-task-native-finish-result" }); + await finalizeNativeRun({ db, runId, workspaceFinalizeStatus: "succeeded", projectRunStatus: true }); + + const [completedIssue] = await db.select().from(issues).where(eq(issues.id, issueId)); + const decisions = await db.select().from(statusDecisions).where(eq(statusDecisions.issueId, issueId)); + if (!allowed) { + const expectedReason = scenario === "newest proposal pending" ? "governed_gate_pending" : "onboarding_first_task_decision_required"; + expect(completedIssue).toMatchObject({ status: "in_review" }); + expect(decisions).toContainEqual(expect.objectContaining({ toStatus: "in_review", reasonCode: expectedReason })); + expect(decisions).not.toContainEqual(expect.objectContaining({ toStatus: "done" })); + expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)))[0]!.resultJson) + .toMatchObject({ finalizationReasonCode: expectedReason }); + } else { + expect(completedIssue).toMatchObject({ status: "done" }); + expect(decisions).toContainEqual(expect.objectContaining({ toStatus: "done", reasonCode: "completion_claim_policy_accepted" })); + } + }); + + it("rechecks the first-task human decision atomically before native status commit", async () => { + const { companyId, agentId, issueId, runId, port, result } = await prepareFirstTaskCompletion("accepted proposal"); + await expect(nativeCompletionFeedback(db, runId, result)).resolves.toContain("Completion report accepted"); + await port.completeRun({ result, terminal: CONTROL_PLANE_CONFORMANCE_TERMINAL, callerResultId: "first-task-race-result" }); + expect(await db.select().from(workAssessments).where(eq(workAssessments.runId, runId))).toEqual([]); + + const interactionId = randomUUID(); + const trigger = `first_task_race_${randomUUID().replace(/-/g, "")}`; + // Assessment persistence follows the policy read and precedes status commit. + // Insert a newer proposal at that real database boundary, exactly once. + await db.execute(sql.raw(`create function ${trigger}() returns trigger language plpgsql as $$ + begin + if NEW.issue_id = '${issueId}'::uuid and NEW.run_id = '${runId}'::uuid then + insert into issue_thread_interactions + (id, company_id, issue_id, kind, status, created_by_agent_id, source_run_id, payload, created_at) + values + ('${interactionId}'::uuid, '${companyId}'::uuid, '${issueId}'::uuid, + 'request_confirmation', 'pending', '${agentId}'::uuid, '${runId}'::uuid, + '{"version":1,"prompt":"Accept the revised task scope?"}'::jsonb, clock_timestamp()) + on conflict (id) do nothing; + end if; + return NEW; + end $$`)); + try { + await db.execute(sql.raw(`create trigger ${trigger} before insert on work_assessments + for each row execute function ${trigger}()`)); + await finalizeNativeRun({ db, runId, workspaceFinalizeStatus: "succeeded", projectRunStatus: true }); + + expect((await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.id, interactionId)))[0]) + .toMatchObject({ status: "pending", issueId }); + expect((await db.select().from(issues).where(eq(issues.id, issueId)))[0]!.status).toBe("in_review"); + const decisions = await db.select().from(statusDecisions).where(eq(statusDecisions.issueId, issueId)); + expect(decisions).toEqual([expect.objectContaining({ toStatus: "in_review", reasonCode: "governed_gate_pending" })]); + expect(decisions).not.toContainEqual(expect.objectContaining({ toStatus: "done" })); + expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)))[0]) + .toMatchObject({ nativePhase: "committed", resultJson: { finalizationReasonCode: "governed_gate_pending" } }); + } finally { + await db.execute(sql.raw(`drop trigger if exists ${trigger} on work_assessments`)); + await db.execute(sql.raw(`drop function if exists ${trigger}()`)); + } + }); + it.each(["none", "queued", "claimed", "deferred_issue_execution", "coalesced", "current_run", "current_intent"])( "preserves completion caveats and pending child delivery (%s)", async (delivery) => { const identity = CONTROL_PLANE_CONFORMANCE_OPEN.identity; diff --git a/server/src/services/native-runtime/status-decision-committer.ts b/server/src/services/native-runtime/status-decision-committer.ts index 0e34904c5b3..f19bb8cc244 100644 --- a/server/src/services/native-runtime/status-decision-committer.ts +++ b/server/src/services/native-runtime/status-decision-committer.ts @@ -1,4 +1,5 @@ import { scheduledIssueMonitorWait } from "../issue-monitors.js"; +import { onboardingFirstTaskCompletionAllowed } from "../onboarding-first-task-admission.js"; import { hasPublishedGitHubReview, readInheritedGitHubReviewWait } from "../chat-channels/github/review-wait.js"; import { pendingNativeGovernance } from "./native-governance.js"; import { findSupersededExternalReviewRequests, supersedeExternalReviewRequestsInTransaction } from "./superseded-external-review-requests.js"; @@ -1657,6 +1658,11 @@ export async function commitNativeStatusDecision(input: { ) { throw new NativeStatusRaceError(); } + // Recheck under the issue lock, retaining run/proposal/document proof until + // commit. A newer decision cannot race an earlier first-task Done assessment. + if (input.decision.statusAction === "done" && !await onboardingFirstTaskCompletionAllowed(tx as unknown as Db, { + companyId: input.companyId, issueId: input.issueId, runId: input.runId, + })) throw new NativeStatusRaceError(); if (reasonCode === "scheduled_monitor_waiting") { const expected = input.requireMonitorWait; const inReview = input.decision.statusAction === "in_review" && input.decision.toStatus === "in_review"; diff --git a/server/src/services/onboarding-first-task-admission.ts b/server/src/services/onboarding-first-task-admission.ts index e649120bb6b..00182df9e1e 100644 --- a/server/src/services/onboarding-first-task-admission.ts +++ b/server/src/services/onboarding-first-task-admission.ts @@ -59,72 +59,107 @@ export async function assertOnboardingFirstTaskCreationAllowed(tx: Db, input: { )).for("share"); if (!run || runIssueId(run) !== source.id) throw acceptanceRequired(); + if (await readOnboardingFirstTaskDecision(tx, { companyId: input.companyId, issueId: source.id, outcomes: ["accepted"] }) !== "accepted") throw acceptanceRequired(); +} + +/** Shared persisted-decision proof; creation and completion retain different authority. */ +async function readOnboardingFirstTaskDecision(tx: Db, input: { + companyId: string; issueId: string; outcomes: Array<"accepted" | "rejected">; +}): Promise<"accepted" | "rejected" | null> { // Select the newest proposal before checking its outcome: a later pending or // rejected proposal must never fall back to an older accepted scope. Governed // tool/credential actions and custom completion reviews are not proposals. const [proposal] = await tx.select().from(issueThreadInteractions).where(and( - eq(issueThreadInteractions.companyId, input.companyId), eq(issueThreadInteractions.issueId, source.id), + eq(issueThreadInteractions.companyId, input.companyId), eq(issueThreadInteractions.issueId, input.issueId), inArray(issueThreadInteractions.kind, ["request_confirmation", "request_checkbox_confirmation"]), sql`NOT (${issueThreadInteractions.payload} ?| ARRAY['toolAction', 'secretProposal', 'connectionAuthorization'])`, sql`COALESCE(${issueThreadInteractions.payload}->'target'->>'type', '') <> 'custom'`, )).orderBy(desc(issueThreadInteractions.createdAt), desc(issueThreadInteractions.id)).limit(1).for("share"); - if (!proposal || proposal.status !== "accepted" || !proposal.resolvedAt) throw acceptanceRequired(); + if (!proposal || (proposal.status !== "accepted" && proposal.status !== "rejected") || + !input.outcomes.includes(proposal.status) || !proposal.resolvedAt) return null; const checkbox = proposal.kind === "request_checkbox_confirmation"; const payload = checkbox ? requestCheckboxConfirmationPayloadSchema.safeParse(proposal.payload) : requestConfirmationPayloadSchema.safeParse(proposal.payload); const result = checkbox ? requestCheckboxConfirmationResultSchema.safeParse(proposal.result) : requestConfirmationResultSchema.safeParse(proposal.result); - if (!payload.success || !result.success || result.data.outcome !== "accepted") throw acceptanceRequired(); - if (checkbox) { + if (!payload.success || !result.success || result.data.outcome !== proposal.status) return null; + if (checkbox && proposal.status === "accepted") { const selected = object(result.data).selectedOptionIds; - if (!("options" in payload.data) || !Array.isArray(selected) || selected.length === 0) throw acceptanceRequired(); + if (!("options" in payload.data) || !Array.isArray(selected) || selected.length === 0) return null; const allowed = new Set(payload.data.options.map(option => option.id)); if (selected.some(id => typeof id !== "string" || !allowed.has(id)) || selected.length < payload.data.minSelected - || (payload.data.maxSelected != null && selected.length > payload.data.maxSelected)) throw acceptanceRequired(); + || (payload.data.maxSelected != null && selected.length > payload.data.maxSelected)) return null; } if (proposal.sourceRunId) { const [origin] = await tx.select(runOriginFields).from(heartbeatRuns).where(and( eq(heartbeatRuns.id, proposal.sourceRunId), eq(heartbeatRuns.companyId, input.companyId), )).for("share"); - if (!origin || runIssueId(origin) !== source.id || origin.agentId !== proposal.createdByAgentId) throw acceptanceRequired(); + if (!origin || runIssueId(origin) !== input.issueId || origin.agentId !== proposal.createdByAgentId) return null; } else if (proposal.createdByAgentId) { const [creator] = await tx.select({ companyId: agents.companyId }).from(agents).where(eq(agents.id, proposal.createdByAgentId)); - if (creator?.companyId !== input.companyId) throw acceptanceRequired(); - } else if (!proposal.createdByUserId) throw acceptanceRequired(); + if (creator?.companyId !== input.companyId) return null; + } else if (!proposal.createdByUserId) return null; const directHumanDecision = Boolean(proposal.resolvedByUserId && !proposal.resolvedByAgentId && !proposal.resolvedByRunId); if (!directHumanDecision) { const commentId = result.data.commentId; - if (!commentId || !proposal.resolvedByAgentId || !proposal.resolvedByRunId) throw acceptanceRequired(); + if (!commentId || !proposal.resolvedByAgentId || !proposal.resolvedByRunId) return null; const [comment] = await tx.select().from(issueComments).where(and( - eq(issueComments.id, commentId), eq(issueComments.companyId, input.companyId), eq(issueComments.issueId, source.id), + eq(issueComments.id, commentId), eq(issueComments.companyId, input.companyId), eq(issueComments.issueId, input.issueId), )).for("share"); if (!comment || comment.deletedAt || comment.authorType !== "user" || !comment.authorUserId || comment.authorAgentId || comment.createdByRunId || comment.derivedAuthorAgentId || comment.derivedCreatedByRunId || comment.sourceTrust?.disposition === "quarantined" || comment.createdAt < proposal.createdAt - || comment.body.trim() === "/new") throw acceptanceRequired(); + || comment.body.trim() === "/new") return null; const [resolver] = await tx.select(runOriginFields).from(heartbeatRuns).where(and( eq(heartbeatRuns.id, proposal.resolvedByRunId), eq(heartbeatRuns.companyId, input.companyId), eq(heartbeatRuns.agentId, proposal.resolvedByAgentId), )).for("share"); - if (!resolver || runIssueId(resolver) !== source.id - || (resolver.responsibleUserId && resolver.responsibleUserId !== comment.authorUserId)) throw acceptanceRequired(); + if (!resolver || runIssueId(resolver) !== input.issueId + || (resolver.responsibleUserId && resolver.responsibleUserId !== comment.authorUserId)) return null; } + // Refusal permits acknowledgement and closure, never execution. An agent-only + // plan edit cannot turn that human refusal into permission to execute. + if (proposal.status === "rejected") return "rejected"; + const target = payload.data.target; const [plan] = await tx.select({ documentId: documents.id, revisionId: documents.latestRevisionId }) .from(issueDocuments).innerJoin(documents, eq(documents.id, issueDocuments.documentId)).where(and( eq(issueDocuments.companyId, input.companyId), eq(documents.companyId, input.companyId), - eq(issueDocuments.issueId, source.id), eq(issueDocuments.key, "plan"), + eq(issueDocuments.issueId, input.issueId), eq(issueDocuments.key, "plan"), )).for("share", { of: documents }); // Document writers do not all lock the issue, so hold the document row too. // A saved plan must be accepted by revision; an untargeted card cannot stand // in for approval of a different or subsequently edited document. if (plan || target) { if (!target || target.type !== "issue_document" || target.key !== "plan" - || (target.issueId && target.issueId !== source.id) || !plan || plan.revisionId !== target.revisionId - || (target.documentId && plan.documentId !== target.documentId)) throw acceptanceRequired(); + || (target.issueId && target.issueId !== input.issueId) || !plan || plan.revisionId !== target.revisionId + || (target.documentId && plan.documentId !== target.documentId)) return null; } + return "accepted"; +} + +/** Completion may acknowledge a trusted refusal; it never authorizes rejected work. */ +export async function onboardingFirstTaskCompletionAllowed(tx: Db, input: { + companyId: string; issueId: string; runId: string; +}): Promise { + const [source] = await tx.select({ id: issues.id, originKind: issues.originKind }).from(issues).where(and( + eq(issues.id, input.issueId), eq(issues.companyId, input.companyId), + )); + if (!source) return false; + if (source.originKind !== ONBOARDING_FIRST_TASK_ORIGIN_KIND) return true; + // Only the first-task path takes additional authority locks. At status commit + // these are held until the decision is written, in issue/run/proposal order. + const [lockedSource] = await tx.select({ id: issues.id }).from(issues).where(and( + eq(issues.id, source.id), eq(issues.companyId, input.companyId), eq(issues.originKind, ONBOARDING_FIRST_TASK_ORIGIN_KIND), + )).for("update"); + if (!lockedSource) return false; + const [run] = await tx.select({ ...runOriginFields, runtimeMode: heartbeatRuns.runtimeMode }).from(heartbeatRuns).where(and( + eq(heartbeatRuns.id, input.runId), eq(heartbeatRuns.companyId, input.companyId), + )).for("share"); + if (!run || run.runtimeMode !== "native" || run.nativeIssueId !== source.id) return false; + return await readOnboardingFirstTaskDecision(tx, { companyId: input.companyId, issueId: source.id, outcomes: ["accepted", "rejected"] }) !== null; } diff --git a/tests/runner-e2e/PRODUCT-JOURNEYS.md b/tests/runner-e2e/PRODUCT-JOURNEYS.md index 2d23dc214e1..a86949df8e7 100644 --- a/tests/runner-e2e/PRODUCT-JOURNEYS.md +++ b/tests/runner-e2e/PRODUCT-JOURNEYS.md @@ -118,7 +118,8 @@ ownership manifests. An expired lease permits cleanup recovery, not reuse. Managed self-hosted instances are removed after every attempt. Existing Cloud stacks retain the QA account and declared baseline while removing verified run-owned fixtures. Successful disposable stacks are deleted. Failed disposable -stacks are stopped and retained for 24 hours, then swept. Interrupted cleanup +stacks are stopped and retained for up to 24 hours. The deployment provider +declares earlier cleanup eligibility to leave time for its sweeper. Interrupted cleanup remains visible and retains exclusive stack ownership. QA identity and inbox never belong to disposable ownership. diff --git a/tests/runner-e2e/README.md b/tests/runner-e2e/README.md index 554b10b32d1..af2ba3758b4 100644 --- a/tests/runner-e2e/README.md +++ b/tests/runner-e2e/README.md @@ -261,6 +261,16 @@ status, known adapters, and allowlisted outcome/check/server codes. The case report renders these fields explicitly; older results without the receipt remain valid. This diagnostic does not change the journey grade or qualify a live run. +When the canonical first-task journey fails `onboarding_work_before_acceptance`, +`productJourney.onboardingPreAcceptance` retains the failed checkpoint and every +observed guard violation: unexpected task set, existing attachment, non-planning +document, or first task already Done. The closed version-1 receipt contains only +counts, whether the first task matches the canonical parent, and closed first-task +and canonical-parent statuses. Reports validate and display these observations; +they do not infer a product cause. Only the failing boundary is retained, without +task/document IDs, document keys, text, or bodies. Historical results may omit the +receipt. The original error, failed grade, and dependent blocked outcomes remain. + ## Live provider connection journeys See [PROVIDER-CONNECTIONS.md](PROVIDER-CONNECTIONS.md) for the explicit-only diff --git a/tests/runner-e2e/SECURITY.md b/tests/runner-e2e/SECURITY.md index 30e2f2bc1a9..c3dde9aef93 100644 --- a/tests/runner-e2e/SECURITY.md +++ b/tests/runner-e2e/SECURITY.md @@ -28,6 +28,16 @@ Unknown codes become `unrecognized`; raw bodies, messages, URLs, headers, and browser errors are excluded. Reports validate the receipt before rendering its explicit fields, and historical results may omit it. +The optional `onboardingPreAcceptance` receipt captures only a failing first-task +acceptance guard. Its closed version-1 fields are a known checkpoint, up to four +distinct guard-violation codes, nonnegative integer task/attachment/document +counts, a canonical-parent match boolean, and closed first-task/canonical-parent +statuses (`missing` and `unknown` remain explicit). It excludes all identifiers, +task text, document keys and bodies, filenames, URLs, credentials, and raw API +responses. Validation rejects extra or inconsistent fields before report use; +older results may omit the receipt. It preserves the original failure grade and +does not attribute a product cause or authorize acceptance. + ## Attended connection authentication See [PROVIDER-CONNECTIONS.md](PROVIDER-CONNECTIONS.md) for the explicit-only diff --git a/tests/runner-e2e/case-outcome.ts b/tests/runner-e2e/case-outcome.ts index 489f16f8384..ca463553322 100644 --- a/tests/runner-e2e/case-outcome.ts +++ b/tests/runner-e2e/case-outcome.ts @@ -1,6 +1,7 @@ import type { RunnerE2EResult } from "./types.js"; import { isBlockedConnectionResult } from "./connection-evidence.js"; import { validateOnboardingConnectEvidence } from "./product-journeys/onboarding-connect.js"; +import { validateOnboardingPreAcceptanceEvidence } from "./product-journeys/onboarding-pre-acceptance.js"; const html = (value: unknown) => String(value ?? "").replace( /[&<>"']/g, @@ -31,6 +32,20 @@ function renderOnboardingConnect(result: RunnerE2EResult): string { ${response.truncatedChecks ? "

Only the first 32 validation checks were retained.

" : ""}`; }).join("")}`; } +function renderOnboardingPreAcceptance(result: RunnerE2EResult): string { + const receipt = result.productJourney?.onboardingPreAcceptance; + if (receipt === undefined) return ""; + try { validateOnboardingPreAcceptanceEvidence(receipt); } + catch { return "

Onboarding pre-acceptance evidence unavailable: invalid receipt.

"; } + return `
Onboarding pre-acceptance evidence +

Checkpoint: ${html(receipt.checkpoint)}

+

Observed guard violations:

    ${receipt.violations.map(code => `
  • ${html(code)}
  • `).join("")}
+
${[ + ["Tasks", receipt.taskCount], ["Attachments", receipt.attachmentCount], ["Documents", receipt.documentCount], + ["Non-planning documents", receipt.nonPlanningDocumentCount], ["First task matches canonical parent", receipt.firstTaskMatchesCanonicalParent], + ["First task status", receipt.firstTaskStatus], ["Canonical parent status", receipt.canonicalParentStatus], + ].map(([label, value]) => `
${html(label)}
${html(value)}
`).join("")}
`; +} /** An interrupted first-task journey is not evidence of failed downstream behavior. */ export function isIncompleteFirstTaskResult( result: RunnerE2EResult, @@ -93,6 +108,7 @@ export function renderCaseOutcome( ${result.productJourney?.operations ? `

Eval operations: ${html(result.productJourney.operations.campaignId)} · ${result.productJourney.operations.requestCount} requests · model cost $${html(result.productJourney.operations.modelCostUsd ?? "unknown")} (setup $${html(result.productJourney.operations.setupCostUsd ?? "unknown")}, counted once). Feedback: ${html(result.productJourney.operations.feedback.collection)} · ${result.productJourney.operations.feedback.complaints} complaints · ${result.productJourney.operations.feedback.suggestions} suggestions.

` : ""} ${result.productJourney?.operations?.traceIds.length ? `
Trace correlation IDs
    ${result.productJourney.operations.traceIds.map(id => `
  • ${html(id)}
  • `).join("")}
` : ""} ${renderOnboardingConnect(result)} + ${renderOnboardingPreAcceptance(result)} ${result.providerConnection ? `

Target: ${html(result.providerConnection.target.origin)} · ${html(result.providerConnection.target.commit ?? "revision unavailable")} · ${result.providerConnection.assisted ? "Assisted login" : "Unassisted"} · ${html(result.providerConnection.authFreshness)} browser · ${html(result.providerConnection.entry)} / ${html(result.providerConnection.method)} · stopped at ${html(result.providerConnection.phase)}

` : ""} ${failures.length ? `

Failed checks:

    ${failures.map((c) => `
  • ${html(c.id)} — ${html(c.detail)}
  • `).join("")}
` : checks.length ? `

No behavioral matcher failed.${notReached.length ? " The journey is incomplete; unexercised checks are not passes." : failed ? " The overall failure came from a separate run, cleanup, or evidence check." : ""}

` : ""} ${notReached.length ? `

Not reached:

    ${notReached.map((c) => `
  • ${html(c.id)} — ${html(c.notReached)}
  • `).join("")}
` : ""} diff --git a/tests/runner-e2e/daytona-image-content.ts b/tests/runner-e2e/daytona-image-content.ts index 8ab17a54a2e..917bcd3d592 100644 --- a/tests/runner-e2e/daytona-image-content.ts +++ b/tests/runner-e2e/daytona-image-content.ts @@ -67,6 +67,7 @@ export const DAYTONA_IMAGE_INPUT_PATHS = [ "packages/paperclip-runner/test/fixtures/copilot-profile-v58-identity.json", "packages/paperclip-runner/test/fixtures/copilot-profile-v61-identity.json", "packages/paperclip-runner/test/fixtures/copilot-profile-v65-identity.json", + "packages/paperclip-runner/test/fixtures/copilot-profile-v66-identity.json", "packages/paperclip-runner/scripts/materialize-cursor-distribution.mjs", "packages/paperclip-runner/scripts/cursor-runtime-patch.mjs", "packages/paperclip-runner/scripts/build-verified-provider-entrypoints.mjs", diff --git a/tests/runner-e2e/pi-controls-evidence.test.ts b/tests/runner-e2e/pi-controls-evidence.test.ts index fe8e458c89b..5c49d899045 100644 --- a/tests/runner-e2e/pi-controls-evidence.test.ts +++ b/tests/runner-e2e/pi-controls-evidence.test.ts @@ -188,8 +188,8 @@ describe("Pi controls catalog admission", () => { // Extended v3 states the strict file oracle's task-wide Bash limit. const pi = runnerMatrix.find(c => c.profile.qualificationCandidate === "pi")!.profile; expect(pi.modelQualification?.qualificationId).toBe("pi:0.0.33:1.0.0:openrouter"); - expect(runnerSuites.find(s => s.id === "pi-native")!.definitionMetadata).toMatchObject({ version: 23, remoteProcExit: "separately-confirmed-absence-after-read-failure", taskCreation: "explicit-title-and-creation-response-id", agentMemoryParent: "public-managed-file-seed-before-admission", incompleteTerminalCleanup: "retirement-retained-with-failed-watch", profileVersion: 29, agentMemoryContent: "utf8-nonce-plus-final-lf", agentMemoryPrompt: "single-json-write-and-content-bound-native-read-both-runs", agentMemoryReadAuthority: "local-withheld-or-exact-remote-agent-run-file", taskPromptTransport: "fenced-markdown-paste-and-multiline-literal-escapes", nativeFinish: "current-contract-objective-evidence-refs", providerFaultExecutable: "stable-preinstalled-runner-link-and-snapshot-node-inode-with-held-bootstrap-fd-3-or-7" }); - expect(runnerSuites.find(s => s.id === "pi-controls")!.definitionMetadata).toMatchObject({ version: 10, remoteProcExit: "separately-confirmed-absence-after-read-failure", taskCreation: "explicit-title-and-creation-response-id", profileVersion: 29, + expect(runnerSuites.find(s => s.id === "pi-native")!.definitionMetadata).toMatchObject({ version: 23, remoteProcExit: "separately-confirmed-absence-after-read-failure", taskCreation: "explicit-title-and-creation-response-id", agentMemoryParent: "public-managed-file-seed-before-admission", incompleteTerminalCleanup: "retirement-retained-with-failed-watch", profileVersion: 30, agentMemoryContent: "utf8-nonce-plus-final-lf", agentMemoryPrompt: "single-json-write-and-content-bound-native-read-both-runs", agentMemoryReadAuthority: "local-withheld-or-exact-remote-agent-run-file", taskPromptTransport: "fenced-markdown-paste-and-multiline-literal-escapes", nativeFinish: "current-contract-objective-evidence-refs", providerFaultExecutable: "stable-preinstalled-runner-link-and-snapshot-node-inode-with-held-bootstrap-fd-3-or-7" }); + expect(runnerSuites.find(s => s.id === "pi-controls")!.definitionMetadata).toMatchObject({ version: 10, remoteProcExit: "separately-confirmed-absence-after-read-failure", taskCreation: "explicit-title-and-creation-response-id", profileVersion: 30, remoteProcessIdentity: "observer-pid-startTicks-bootId", controlPlaneSettlement: "required-scoped-result-and-terminal-after-runner" }); expect(runnerSuites.find(s => s.id === "extended-harnesses")!.definitionMetadata).toMatchObject({ version: 6, piFileArtifactTitle: "exact-filename", piFileCommandTransport: "fenced-bash-markdown-paste" }); @@ -199,7 +199,7 @@ describe("Pi controls catalog admission", () => { } const hashes = Object.fromEntries(runnerSuites.filter(s => ["pi-native", "native-active-stop", "extended-harnesses", "rich-acp-warm-continuity"].includes(s.id)).map(s => [s.id, suiteDefinitionHash(s)])); expect(hashes).toEqual({ - "pi-native": "d7d691088af76d460e353a3982f7732e6a65b2e5a23a66d2ef0d534f9d8dae48", + "pi-native": "04d49c6e098c24091d2939108a97722d1b8353e39192b87e98ee33377f183001", "native-active-stop": "4654a2169bff96cf8377fdd62441f5cabea5c613f447e518830f6b1efd82c051", "rich-acp-warm-continuity": "7e8a0012f2f67fba03cd94403b096a07cfc95cdb7aa568b4c3fd18b852d735f3", "extended-harnesses": "d5bcf5de0ade3a54e4e1560e76feb5d8a787039d56d2379cd501626d85ed7418", diff --git a/tests/runner-e2e/product-journeys/campaign.test.ts b/tests/runner-e2e/product-journeys/campaign.test.ts index 27d42b934f9..e039157c8f1 100644 --- a/tests/runner-e2e/product-journeys/campaign.test.ts +++ b/tests/runner-e2e/product-journeys/campaign.test.ts @@ -5,6 +5,10 @@ import os from "node:os"; import { pathToFileURL } from "node:url"; import { createConnectionProof } from "../connection-evidence.js"; import { retainOnboardingArtifact, validateOnboardingArtifact } from "./artifact-evidence.js"; +import { validateOnboardingPreAcceptanceEvidence, type OnboardingPreAcceptanceEvidence } from "./onboarding-pre-acceptance.js"; +const preAcceptanceEvidence: OnboardingPreAcceptanceEvidence = { version: 1, checkpoint: "awaiting-proposal", violations: ["attachment_present"], + taskCount: 1, attachmentCount: 1, documentCount: 0, nonPlanningDocumentCount: 0, + firstTaskMatchesCanonicalParent: true, firstTaskStatus: "in_review", canonicalParentStatus: "in_review" }; const persistenceFault = vi.hoisted(() => ({ kind: null as "write" | "rename" | null, active: false, latestReport: null as any })); vi.mock("node:fs/promises", async importOriginal => { const actual = await importOriginal(); @@ -33,7 +37,7 @@ import { regenerateRunnerDashboard } from "../dashboard-regenerate.js"; const roots: string[]=[]; afterEach(async()=>{vi.useRealTimers(); vi.restoreAllMocks(); persistenceFault.kind=null; persistenceFault.active=false; persistenceFault.latestReport=null; process.exitCode=0; await Promise.all(roots.splice(0).map(root=>rm(root,{recursive:true,force:true})));}); type Hook = "collect" | "release" | "stop" | "finalizeEvidence" | "checkpointEvidence"; -async function run(options:{authFailure?:boolean;onboardingFailure?:boolean;missingArtifact?:boolean;drift?:boolean;cleanupFailure?:boolean;collectionFailure?:boolean;mini?:boolean;missingReceipt?:boolean;zeroRequests?:boolean;missingCheck?:boolean;finalizationFailure?:boolean;persistenceFailure?:"write"|"rename";persistenceAfter?:"collection"|"release";stallHook?:Hook;onHook?:(hook:Hook,signal?:AbortSignal)=>void}={}) { +async function run(options:{authFailure?:boolean;onboardingFailure?:boolean;preAcceptanceFailure?:boolean;missingArtifact?:boolean;drift?:boolean;cleanupFailure?:boolean;collectionFailure?:boolean;mini?:boolean;missingReceipt?:boolean;zeroRequests?:boolean;missingCheck?:boolean;finalizationFailure?:boolean;persistenceFailure?:"write"|"rename";persistenceAfter?:"collection"|"release";stallHook?:Hook;onHook?:(hook:Hook,signal?:AbortSignal)=>void}={}) { const root=await mkdtemp(path.join(os.tmpdir(),"journey-campaign-test-")); roots.push(root); const module=path.join(root,"provider.mjs"); const proof = createConnectionProof(); @@ -44,7 +48,7 @@ let onboarded=false; const context={identity,company:{id:'company-1',issuePrefix:'QA'},api:{post:async()=>({id:'issue-fixture-1',identifier:'QA-1'})},startingState:'onboarding',capabilities:['company','board-user','task-write'],page:{async screenshot(){} }}; export const provider={version:1, async acquire(input){return { async authenticate(){${options.authFailure ? "throw {outcome:'failed',code:'login_code_expired'};" : ""}}, -async onboard(evidence){${options.onboardingFailure ? "throw {outcome:'failed',code:'onboarding_failed'};" : `${options.missingArtifact ? "" : `evidence.artifact=${JSON.stringify(artifact)};`}evidence.checks.push(...['fresh-workspace','ui-connection-and-native-agent','first-task-complete','downloadable-artifact-verified'${options.missingCheck ? "" : ",'native-trace-verified'"}].map(id=>({id,passed:true})));onboarded=true;return context;`}}, +async onboard(evidence){${options.preAcceptanceFailure ? `evidence.onboardingPreAcceptance=${JSON.stringify(preAcceptanceEvidence)};throw {outcome:'failed',code:'onboarding_work_before_acceptance'};` : options.onboardingFailure ? "throw {outcome:'failed',code:'onboarding_failed'};" : `${options.missingArtifact ? "" : `evidence.artifact=${JSON.stringify(artifact)};`}evidence.checks.push(...['fresh-workspace','ui-connection-and-native-agent','first-task-complete','downloadable-artifact-verified'${options.missingCheck ? "" : ",'native-trace-verified'"}].map(id=>({id,passed:true})));onboarded=true;return context;`}}, async prepare(){throw Error('onboarding receipt was not reused')}, async identity(){return {...identity,commit:'${(options.drift?"b":"a").repeat(40)}'}}, async collect(){${options.collectionFailure ? "throw Error('private collection error');" : options.missingReceipt ? "return [];" : `return onboarded?[{journeyId:'cloud-onboarding',runIds:['run-1'],usage:{runs:[{runId:'run-1',usage:{costUsd:0.01}}]},operations:{campaignId:input.campaignId,attemptId:input.campaignId+':cloud-onboarding:1',modelCostUsd:0.01,setupCostUsd:0.005,requestCount:${options.zeroRequests ? 0 : 2},feedback:{collection:'complete',complaints:0,suggestions:0},traceIds:['a'.repeat(32)]}}]:[];`}}, async own(){}, async release(){${options.cleanupFailure ? "throw Error('private raw error');" : "return 'released';"}}, async stop(){} @@ -109,6 +113,17 @@ describe("product journey campaign boundary outcomes",()=>{ expect(campaign.results.map((r:any)=>r.productJourney.outcome)).toEqual(["failed","blocked"]); expect(campaign.results[0].productJourney.phases.find((p:any)=>p.phase==="journey").outcome).toBe("failed"); }); + it("preserves failed pre-acceptance evidence in normalized results and blocks dependent reuse", async () => { + const campaign = await run({ preAcceptanceFailure: true }); + const [onboarding, dependent] = campaign.results; + expect(campaign.results.map((row:any) => row.productJourney.outcome)).toEqual(["failed", "blocked"]); + expect(onboarding).toMatchObject({ status: "failed", failureClass: "candidate_failure", error: "onboarding_work_before_acceptance" }); + expect(onboarding.productJourney.onboardingPreAcceptance).toEqual(preAcceptanceEvidence); + expect(() => validateOnboardingPreAcceptanceEvidence(onboarding.productJourney.onboardingPreAcceptance)).not.toThrow(); + expect(onboarding.productJourney.phases).toContainEqual({ phase: "journey", outcome: "failed", code: "onboarding_work_before_acceptance" }); + expect(dependent.error).toBe("prerequisite_journey_failed"); + expect(dependent.productJourney.onboardingPreAcceptance).toBeUndefined(); + }); it("reuses a verified onboarding context for the same shared story",async()=>{ const campaign=await run(); expect(campaign.results.map((r:any)=>r.status)).toEqual(["passed","passed"]); diff --git a/tests/runner-e2e/product-journeys/catalog.ts b/tests/runner-e2e/product-journeys/catalog.ts index c018e769aab..6077ff48c36 100644 --- a/tests/runner-e2e/product-journeys/catalog.ts +++ b/tests/runner-e2e/product-journeys/catalog.ts @@ -9,7 +9,7 @@ export function preparationPreview(config: TargetConfig) { target: { id: config.id, mode: config.mode, executionEnvironment: config.executionEnvironment }, journeys: config.journeys.map(id => productJourneys.find(journey => journey.id === id)!), configuration: config.baseline, - lifetime: config.mode === "existing-cloud" ? "persistent; clean run-owned resources only" : config.mode === "new-cloud" ? "disposable; delete on pass, retain failures for 24 hours" : "managed instance; remove after every attempt", + lifetime: config.mode === "existing-cloud" ? "persistent; clean run-owned resources only" : config.mode === "new-cloud" ? "disposable; delete on pass, retain failures up to 24 hours" : "managed instance; remove after every attempt", limits: config.limits, authentication: config.mode === "managed-self-hosted" ? "local-trusted" : "normal email-code sign-in", modelProfileId: config.modelProfileId ?? null, maxDisposableStacks: config.mode === "new-cloud" ? 1 : 0, diff --git a/tests/runner-e2e/product-journeys/cloud-onboarding.test.ts b/tests/runner-e2e/product-journeys/cloud-onboarding.test.ts index 0878ade8065..68adbdd2d53 100644 --- a/tests/runner-e2e/product-journeys/cloud-onboarding.test.ts +++ b/tests/runner-e2e/product-journeys/cloud-onboarding.test.ts @@ -2,6 +2,8 @@ import { describe, expect, it, vi } from "vitest"; import { cloudOnboarding, type CloudOnboardingInput } from "./cloud-onboarding.js"; import { onboardingFirstTask } from "./onboarding-first-task.js"; import { retainOnboardingArtifact } from "./artifact-evidence.js"; +import { JourneyError } from "./types.js"; +import type { OnboardingPreAcceptanceEvidence } from "./onboarding-pre-acceptance.js"; vi.mock("@playwright/test", () => ({ expect: (locator: { isVisible(): Promise }) => ({ toBeVisible: async () => { expect(await locator.isVisible()).toBe(true); }, @@ -118,6 +120,20 @@ function fixture(entry: Entry, options: { intentFailure?: boolean; qualification } describe("Cloud onboarding visible controls", () => { + it("retains pre-acceptance evidence while preserving the failed error and withholding completion markers", async () => { + const f = fixture("portfolio"); + const receipt: OnboardingPreAcceptanceEvidence = { version: 1, checkpoint: "awaiting-proposal", violations: ["attachment_present"], + taskCount: 1, attachmentCount: 1, documentCount: 0, nonPlanningDocumentCount: 0, + firstTaskMatchesCanonicalParent: true, firstTaskStatus: "in_review", canonicalParentStatus: "in_review" }; + vi.mocked(onboardingFirstTask).mockImplementationOnce(async input => { + input.onPreAcceptanceFailure?.(receipt); + throw new JourneyError("failed", "onboarding_work_before_acceptance"); + }); + await expect(cloudOnboarding(f.input)).rejects.toMatchObject({ outcome: "failed", code: "onboarding_work_before_acceptance" }); + expect(JSON.parse(JSON.stringify(f.input.evidence)).onboardingPreAcceptance).toEqual(receipt); + expect(f.input.evidence.checks.map(check => check.id)).toEqual(["fresh-workspace", "ui-connection-and-native-agent"]); + expect(f.events).not.toContain("native:verified"); + }); it.each(["first-run", "portfolio", "create-form"] as const)("creates from %s with intent before dispatch and qualification before paid Connect", async entry => { const f = fixture(entry); const result = await cloudOnboarding(f.input); diff --git a/tests/runner-e2e/product-journeys/cloud-onboarding.ts b/tests/runner-e2e/product-journeys/cloud-onboarding.ts index 6f9a75634a7..215871b411d 100644 --- a/tests/runner-e2e/product-journeys/cloud-onboarding.ts +++ b/tests/runner-e2e/product-journeys/cloud-onboarding.ts @@ -83,7 +83,8 @@ export async function cloudOnboarding(input: CloudOnboardingInput): Promise { evidence.artifact = artifact; } }); + own: input.own, observeRun: input.observeRun, onArtifact: artifact => { evidence.artifact = artifact; }, + onPreAcceptanceFailure: receipt => { evidence.onboardingPreAcceptance = receipt; } }); await input.verifyExecution(context, [completed.artifact.originatingRunId]); evidence.checks.push({ id: "first-task-complete", passed: true }, { id: "downloadable-artifact-verified", passed: true }, { id: "native-trace-verified", passed: true }); diff --git a/tests/runner-e2e/product-journeys/launch.ts b/tests/runner-e2e/product-journeys/launch.ts index 410bb7725bf..980822013fd 100644 --- a/tests/runner-e2e/product-journeys/launch.ts +++ b/tests/runner-e2e/product-journeys/launch.ts @@ -99,7 +99,7 @@ export async function launchProductJourneys(args: string[], repositoryRoot: stri try { sha = execFileSync("git", ["rev-parse", "HEAD"], { cwd: repositoryRoot, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim(); } catch { /* Packaged harnesses may not include Git metadata. */ } const source = resolveRunnerE2ESource({ sha, ref: null, workflowRunUrl: null }); const definitionHash = createHash("sha256").update(JSON.stringify(productJourneys)); - for (const name of ["catalog.ts", "task-properties.ts", "cloud-onboarding.ts", "onboarding-connect.ts", "onboarding-first-task.ts", "artifact-evidence.ts", "fixtures.ts", "launch.ts", "types.ts", "collection.ts", "local-target.ts"]) definitionHash.update(await readFile(path.join(import.meta.dirname, name))); + for (const name of ["catalog.ts", "task-properties.ts", "cloud-onboarding.ts", "onboarding-connect.ts", "onboarding-first-task.ts", "onboarding-pre-acceptance.ts", "artifact-evidence.ts", "fixtures.ts", "launch.ts", "types.ts", "collection.ts", "local-target.ts"]) definitionHash.update(await readFile(path.join(import.meta.dirname, name))); const suiteDefinitionHash = definitionHash.digest("hex"); const expected = config.journeys.map(id => `product-journeys.${config.id}.${id === "cloud-onboarding" ? config.modelProfileId : "browser"}.${config.executionEnvironment}.${id}`); let reportPersisted = false; diff --git a/tests/runner-e2e/product-journeys/onboarding-first-task.test.ts b/tests/runner-e2e/product-journeys/onboarding-first-task.test.ts index ab452f1901c..2e559aa8584 100644 --- a/tests/runner-e2e/product-journeys/onboarding-first-task.test.ts +++ b/tests/runner-e2e/product-journeys/onboarding-first-task.test.ts @@ -4,6 +4,7 @@ import { createConnectionProof } from "../connection-evidence.js"; import { connectionDelay } from "../connection-target.js"; import { onboardingFirstTask, type OnboardingFirstTaskInput } from "./onboarding-first-task.js"; import { validateOnboardingArtifact } from "./artifact-evidence.js"; +import { validateOnboardingPreAcceptanceEvidence } from "./onboarding-pre-acceptance.js"; vi.mock("../connection-target.js", () => ({ connectionDelay: vi.fn(async () => {}) })); type Row = { id: string; [key: string]: any }; @@ -92,6 +93,90 @@ function fixture(options: Options = {}) { afterEach(() => { vi.restoreAllMocks(); vi.mocked(connectionDelay).mockReset().mockResolvedValue(undefined); }); describe("Cloud canonical onboarding first task", () => { + it.each([ + ["unexpected task set", "unexpected_task_set", (state: Parameters>[1]) => { state.tasks.push({ id: "private-early-task", title: "private task text", status: "todo" }); }, { taskCount: 2 }], + ["attachment", "attachment_present", (state: Parameters>[1]) => { state.attachments.push({ id: "private-attachment", issueId: "parent", originalFilename: "private-file.txt" }); }, { attachmentCount: 1 }], + ["non-planning document", "non_planning_document_present", (state: Parameters>[1]) => { state.documents.push({ id: "private-document", issueId: "parent", key: "private-result-key", body: "private document body" }); }, { documentCount: 1, nonPlanningDocumentCount: 1 }], + ["first task done", "first_task_done", (state: Parameters>[1]) => { state.tasks[0]!.status = "done"; }, { firstTaskStatus: "done", canonicalParentStatus: "done" }], + ] as const)("retains the observed %s violation at the failing acceptance boundary", async (_label, violation, mutate, observed) => { + const f = fixture({ mutate(phase, state) { if (phase === "proposal") mutate(state); } }); + const capture = vi.fn(); + f.input.onPreAcceptanceFailure = capture; + await expect(onboardingFirstTask(f.input)).rejects.toMatchObject({ outcome: "failed", code: "onboarding_work_before_acceptance" }); + expect(capture).toHaveBeenCalledExactlyOnceWith({ version: 1, checkpoint: "awaiting-proposal", violations: [violation], + taskCount: 1, attachmentCount: 0, documentCount: 0, nonPlanningDocumentCount: 0, + firstTaskMatchesCanonicalParent: true, firstTaskStatus: "in_review", canonicalParentStatus: "in_review", ...observed }); + expect(() => validateOnboardingPreAcceptanceEvidence(JSON.parse(JSON.stringify(capture.mock.calls[0]![0])))).not.toThrow(); + const retained = JSON.stringify(capture.mock.calls[0]![0]); + for (const text of ["private-", "parent", "proposal-run", "qa.example.test", "connection", "campaign-1"]) expect(retained).not.toContain(text); + expect(f.events).not.toContain("click:Approve"); + }); + it("retains every simultaneous guard violation from the same failed snapshot", async () => { + const f = fixture({ plan: true, mutate(phase, state) { + if (phase !== "proposal") return; + state.tasks[0]!.status = "done"; + state.tasks.push({ id: "private-early-task" }); + state.attachments.push({ id: "private-attachment", issueId: "parent" }); + state.documents.push({ id: "private-document", issueId: "parent", key: "private-result", body: "private body" }); + } }); + const capture = vi.fn(); + f.input.onPreAcceptanceFailure = capture; + await expect(onboardingFirstTask(f.input)).rejects.toMatchObject({ code: "onboarding_work_before_acceptance" }); + expect(capture).toHaveBeenCalledExactlyOnceWith({ version: 1, checkpoint: "awaiting-proposal", + violations: ["unexpected_task_set", "attachment_present", "non_planning_document_present", "first_task_done"], + taskCount: 2, attachmentCount: 1, documentCount: 2, nonPlanningDocumentCount: 1, + firstTaskMatchesCanonicalParent: true, firstTaskStatus: "done", canonicalParentStatus: "done" }); + expect(f.events).not.toContain("click:Confirm selection"); + }); + it.each(["missing", "replaced", "reordered", "unknown-status"] as const)("records closed task observations when the snapshot is %s", async mode => { + const f = fixture({ mutate(phase, state) { + if (phase !== "proposal") return; + if (mode === "missing") state.tasks = []; + if (mode === "replaced") state.tasks = [{ id: "private-replacement", status: "done" }]; + if (mode === "reordered") state.tasks.unshift({ id: "private-first", status: "done" }); + if (mode === "unknown-status") { state.tasks[0]!.status = "private future status"; state.attachments.push({ id: "private-attachment", issueId: "parent" }); } + } }); + const capture = vi.fn(); + f.input.onPreAcceptanceFailure = capture; + await expect(onboardingFirstTask(f.input)).rejects.toMatchObject({ code: "onboarding_work_before_acceptance" }); + expect(capture).toHaveBeenCalledOnce(); + expect(capture.mock.calls[0]![0]).toMatchObject({ + violations: mode === "unknown-status" ? ["attachment_present"] : mode === "missing" ? ["unexpected_task_set"] : ["unexpected_task_set", "first_task_done"], + taskCount: mode === "missing" ? 0 : mode === "reordered" ? 2 : 1, + firstTaskMatchesCanonicalParent: mode === "unknown-status", + firstTaskStatus: mode === "missing" ? "missing" : mode === "unknown-status" ? "unknown" : "done", + canonicalParentStatus: mode === "reordered" ? "in_review" : mode === "unknown-status" ? "unknown" : "missing", + }); + expect(JSON.stringify(capture.mock.calls[0]![0])).not.toContain("private"); + expect(f.events).not.toContain("click:Approve"); + }); + it("retains an opening-boundary failure before the opening answer dispatches work", async () => { + const f = fixture({ mutate(phase, state) { if (phase === "opening") state.tasks[0]!.status = "done"; } }); + const capture = vi.fn(); + f.input.onPreAcceptanceFailure = capture; + await expect(onboardingFirstTask(f.input)).rejects.toMatchObject({ code: "onboarding_work_before_acceptance" }); + expect(capture).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ checkpoint: "before-opening-answer", violations: ["first_task_done"] })); + expect(f.events).not.toContain("click:Continue"); + }); + it("does not claim the first-slot Done guard when only a later canonical parent is Done", async () => { + const f = fixture({ mutate(phase, state) { + if (phase !== "proposal") return; + state.tasks[0]!.status = "done"; + state.tasks.unshift({ id: "private-first", status: "todo" }); + } }); + const capture = vi.fn(); + f.input.onPreAcceptanceFailure = capture; + await expect(onboardingFirstTask(f.input)).rejects.toMatchObject({ code: "onboarding_work_before_acceptance" }); + expect(capture).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ violations: ["unexpected_task_set"], + firstTaskMatchesCanonicalParent: false, firstTaskStatus: "todo", canonicalParentStatus: "done" })); + }); + it.each([false, true])("does not retain failure snapshots during clean canonical success, plan mode %s", async plan => { + const f = fixture({ plan }); + const capture = vi.fn(); + f.input.onPreAcceptanceFailure = capture; + await expect(onboardingFirstTask(f.input)).resolves.toMatchObject({ onboardingIssueId: "parent", childIssueId: "child" }); + expect(capture).not.toHaveBeenCalled(); + }); it.each(["reload", "download-link"] as const)("retains the independently verified download when later %s fails", async readbackFailure => { const f = fixture({ readbackFailure }); const capture = vi.fn(); diff --git a/tests/runner-e2e/product-journeys/onboarding-first-task.ts b/tests/runner-e2e/product-journeys/onboarding-first-task.ts index ee50b6466ad..474bd615a84 100644 --- a/tests/runner-e2e/product-journeys/onboarding-first-task.ts +++ b/tests/runner-e2e/product-journeys/onboarding-first-task.ts @@ -6,6 +6,7 @@ import { activeRuns, firstTaskCompletionSettled, type Row } from "../first-task- import { isBlockedUnstartedWake, isTerminalUnstartedWake } from "../non-execution-wake.js"; import { JourneyError, type JourneyContext, type OnboardingArtifactEvidence, type TargetSession } from "./types.js"; import { retainOnboardingArtifact } from "./artifact-evidence.js"; +import { preAcceptanceTaskStatus, preAcceptanceViolations, type OnboardingPreAcceptanceEvidence } from "./onboarding-pre-acceptance.js"; export interface OnboardingFirstTaskInput { context: JourneyContext; @@ -18,6 +19,7 @@ export interface OnboardingFirstTaskInput { own: TargetSession["own"]; observeRun(run: Row): Promise; onArtifact?(artifact: OnboardingArtifactEvidence): void; + onPreAcceptanceFailure?(evidence: OnboardingPreAcceptanceEvidence): void; } export interface OnboardingFirstTaskResult { runIds: string[]; @@ -91,9 +93,19 @@ export async function onboardingFirstTask(input: OnboardingFirstTaskInput): Prom fail("onboarding_first_task_failed"); } }; - const assertBeforeAcceptance = (snapshot: Snapshot, parentId: string) => { - if (snapshot.tasks.length !== 1 || snapshot.tasks[0]!.id !== parentId || snapshot.attachments.length || - snapshot.documents.some(document => !isPlanningDocument(document)) || snapshot.tasks[0]!.status === "done") fail("onboarding_work_before_acceptance"); + const assertBeforeAcceptance = (snapshot: Snapshot, parentId: string, checkpoint: OnboardingPreAcceptanceEvidence["checkpoint"]) => { + const observed = { + taskCount: snapshot.tasks.length, attachmentCount: snapshot.attachments.length, + documentCount: snapshot.documents.length, nonPlanningDocumentCount: snapshot.documents.filter(document => !isPlanningDocument(document)).length, + firstTaskMatchesCanonicalParent: snapshot.tasks[0]?.id === parentId, + firstTaskStatus: preAcceptanceTaskStatus(snapshot.tasks[0]), + canonicalParentStatus: preAcceptanceTaskStatus(snapshot.tasks.find(task => task.id === parentId)), + }; + const violations = preAcceptanceViolations(observed); + if (violations.length) { + input.onPreAcceptanceFailure?.({ version: 1, checkpoint, violations, ...observed }); + fail("onboarding_work_before_acceptance"); + } assertRuns(snapshot, [parentId]); }; @@ -105,7 +117,7 @@ export async function onboardingFirstTask(input: OnboardingFirstTaskInput): Prom await input.own({ kind: "issue", name: parent.title, id: parent.id }); snapshot = await load(parent.id); if (seen.size) fail("onboarding_opening_started_model_work"); - assertBeforeAcceptance(snapshot, parent.id); + assertBeforeAcceptance(snapshot, parent.id, "before-opening-answer"); const opening = snapshot.interactions.filter(row => row.kind === "ask_user_questions" && row.status === "pending"); const questions = opening[0]?.payload?.questionSet?.questions ?? opening[0]?.payload?.questions ?? []; const question = questions.find((row: Row) => row.id === "first-task-opening"); @@ -129,7 +141,7 @@ export async function onboardingFirstTask(input: OnboardingFirstTaskInput): Prom let proposal: Row | undefined; while (!proposal) { snapshot = await load(parent.id); - assertBeforeAcceptance(snapshot, parent.id); + assertBeforeAcceptance(snapshot, parent.id, "awaiting-proposal"); const pending = snapshot.interactions.filter(row => row.status === "pending"); const proposals = pending.filter(isProposal); if (proposals.length > 1 || pending.some(row => row.kind === "ask_user_questions" && row.id !== opening[0]!.id)) fail("onboarding_proposal_scope_unclear"); diff --git a/tests/runner-e2e/product-journeys/onboarding-pre-acceptance.test.ts b/tests/runner-e2e/product-journeys/onboarding-pre-acceptance.test.ts new file mode 100644 index 00000000000..84e8ca87aa1 --- /dev/null +++ b/tests/runner-e2e/product-journeys/onboarding-pre-acceptance.test.ts @@ -0,0 +1,105 @@ +import { describe, expect, it } from "vitest"; +import { validateRetainedRunnerResult } from "../result-validation.js"; +import { renderCaseOutcome } from "../case-outcome.js"; +import type { RunnerE2EResult } from "../types.js"; +import type { OnboardingPreAcceptanceEvidence } from "./onboarding-pre-acceptance.js"; + +function result(): RunnerE2EResult { + return { schema: "paperclip.runner-e2e.result/v2", suiteId: "product-journeys", suiteDefinitionHash: "test", + executionId: "product-journeys.qa.runner-codex.local.cloud-onboarding", profileId: "runner-codex", environmentId: "local", caseId: "cloud-onboarding", + provider: "codex", model: "synthetic-model", runtimeMode: "native", status: "failed", error: "onboarding_work_before_acceptance", cleanup: "passed", attempt: 1, + startedAt: "2026-01-01T00:00:00Z", finishedAt: "2026-01-01T00:00:01Z", durationMs: 1000, + productJourney: { outcome: "failed", startingState: "onboarding", phases: [{ phase: "journey", outcome: "failed", code: "onboarding_work_before_acceptance" }], + checks: [], privacy: "private", resourceDisposition: "retained" } }; +} +function preAcceptanceReceipt(): OnboardingPreAcceptanceEvidence { + return { version: 1, checkpoint: "awaiting-proposal", violations: ["attachment_present"], + taskCount: 1, attachmentCount: 1, documentCount: 0, nonPlanningDocumentCount: 0, + firstTaskMatchesCanonicalParent: true, firstTaskStatus: "in_review", canonicalParentStatus: "in_review" }; +} +function passedResult(): RunnerE2EResult { + const retained = result(); + retained.status = "passed"; + delete retained.error; + retained.runIds = ["run-1"]; + Object.assign(retained.productJourney!, { outcome: "passed", campaignId: "campaign", attemptId: "attempt", + phases: [{ phase: "journey", outcome: "passed" }], resourceDisposition: "released", + checks: ["fresh-workspace", "ui-connection-and-native-agent", "first-task-complete", "downloadable-artifact-verified", "native-trace-verified"].map(id => ({ id, passed: true })), + deployment: { kind: "cloud", targetId: "qa", origin: "https://qa.example.test", commit: "a".repeat(40), cloudRelease: "release", runtimeImage: "image", configurationHash: "config" }, + operations: { campaignId: "campaign", attemptId: "attempt", modelCostUsd: null, setupCostUsd: null, requestCount: 1, + feedback: { collection: "complete", complaints: 0, suggestions: 0 }, traceIds: ["trace-1"] } }); + return retained; +} +describe("onboarding pre-acceptance retained evidence", () => { + it("accepts historical results without pre-acceptance evidence and preserves optional receipts in reports", () => { + const retained = result(); + expect(() => validateRetainedRunnerResult(retained)).not.toThrow(); + expect(renderCaseOutcome(retained, true, [])).not.toContain("Onboarding pre-acceptance evidence"); + Object.assign(retained.productJourney!, { onboardingPreAcceptance: preAcceptanceReceipt() }); + const roundTrip = JSON.parse(JSON.stringify(retained)); + expect(() => validateRetainedRunnerResult(roundTrip)).not.toThrow(); + const output = renderCaseOutcome(roundTrip, true, []); + for (const text of ["Onboarding pre-acceptance evidence", "awaiting-proposal", "attachment_present", "First task status", "Canonical parent status", "in_review", "Attachments", "Non-planning documents", "onboarding_work_before_acceptance"]) expect(output).toContain(text); + expect(roundTrip.status).toBe("failed"); + expect(roundTrip.productJourney.outcome).toBe("failed"); + }); + it.each([ + ["a passed result", passedResult], + ["another case", (): RunnerE2EResult => ({ ...result(), caseId: "task-properties", + executionId: "product-journeys.qa.browser.local.task-properties", profileId: "browser", provider: null, model: null, runtimeMode: "none" })], + ["another suite", (): RunnerE2EResult => ({ ...result(), suiteId: "first-task", executionId: "first-task.runner-codex.local.cloud-onboarding" })], + ] as const)("rejects a valid receipt on %s after accepting the same result without it", (_label, makeResult) => { + const retained = makeResult(); + expect(() => validateRetainedRunnerResult(retained)).not.toThrow(); + retained.productJourney!.onboardingPreAcceptance = preAcceptanceReceipt(); + expect(() => validateRetainedRunnerResult(retained)).toThrow("result.productJourney.onboardingPreAcceptance"); + }); + it.each(["passed", "blocked", "unsupported"] as const)("rejects a valid receipt on a %s journey outcome after accepting the same result without it", outcome => { + const retained = result(); + retained.productJourney!.outcome = outcome; + expect(() => validateRetainedRunnerResult(retained)).not.toThrow(); + retained.productJourney!.onboardingPreAcceptance = preAcceptanceReceipt(); + expect(() => validateRetainedRunnerResult(retained)).toThrow("result.productJourney.onboardingPreAcceptance"); + }); + it.each(["onboarding_artifact_evidence_missing", undefined])("rejects a valid receipt for an unrelated or absent failure code (%s)", error => { + const retained = result(); + retained.error = error; + expect(() => validateRetainedRunnerResult(retained)).not.toThrow(); + retained.productJourney!.onboardingPreAcceptance = preAcceptanceReceipt(); + expect(() => validateRetainedRunnerResult(retained)).toThrow("result.productJourney.onboardingPreAcceptance"); + }); + it.each([ + ["raw bodies", (): unknown => ({ ...preAcceptanceReceipt(), body: "private-body-must-not-render" })], + ["task identifiers", (): unknown => ({ ...preAcceptanceReceipt(), taskIds: ["private-task"] })], + ["document keys", (): unknown => ({ ...preAcceptanceReceipt(), documentKeys: ["private-key"] })], + ["unknown version", (): unknown => ({ ...preAcceptanceReceipt(), version: 2 })], + ["unknown checkpoint", (): unknown => ({ ...preAcceptanceReceipt(), checkpoint: "private text" })], + ["unknown violation", (): unknown => ({ ...preAcceptanceReceipt(), violations: ["private text"] })], + ["duplicate violations", (): unknown => ({ ...preAcceptanceReceipt(), violations: ["attachment_present", "attachment_present"] })], + ["empty violations", (): unknown => ({ ...preAcceptanceReceipt(), violations: [] })], + ["inconsistent violations", (): unknown => ({ ...preAcceptanceReceipt(), violations: ["first_task_done"] })], + ["negative counts", (): unknown => ({ ...preAcceptanceReceipt(), attachmentCount: -1 })], + ["fractional counts", (): unknown => ({ ...preAcceptanceReceipt(), taskCount: 1.5 })], + ["unsafe counts", (): unknown => ({ ...preAcceptanceReceipt(), documentCount: Number.MAX_SAFE_INTEGER + 1 })], + ["invalid document counts", (): unknown => ({ ...preAcceptanceReceipt(), nonPlanningDocumentCount: 1 })], + ["raw task status", (): unknown => ({ ...preAcceptanceReceipt(), firstTaskStatus: "private status" })], + ["raw parent status", (): unknown => ({ ...preAcceptanceReceipt(), canonicalParentStatus: "private status" })], + ["nonboolean match", (): unknown => ({ ...preAcceptanceReceipt(), firstTaskMatchesCanonicalParent: "true" })], + ["inconsistent task match", (): unknown => ({ ...preAcceptanceReceipt(), firstTaskMatchesCanonicalParent: false })], + ["inconsistent matched statuses", (): unknown => ({ ...preAcceptanceReceipt(), canonicalParentStatus: "done" })], + ["missing fields", (): unknown => ({ version: 1 })], + ["null", (): unknown => null], + ] as const)("rejects pre-acceptance evidence containing %s", (_label, makeReceipt) => { + const retained = result(); + Object.assign(retained.productJourney!, { onboardingPreAcceptance: makeReceipt() }); + expect(() => validateRetainedRunnerResult(retained)).toThrow("result.productJourney.onboardingPreAcceptance"); + }); + it("renders a fixed fallback for malformed pre-acceptance evidence without exposing its fields", () => { + const retained = result(); + Object.assign(retained.productJourney!, { onboardingPreAcceptance: { ...preAcceptanceReceipt(), body: "private-body-must-not-render" } }); + const output = renderCaseOutcome(retained, false, []); + expect(output).toContain("Onboarding pre-acceptance evidence unavailable: invalid receipt"); + expect(output).not.toContain("private-body-must-not-render"); + expect(output).not.toContain("attachment_present"); + }); +}); diff --git a/tests/runner-e2e/product-journeys/onboarding-pre-acceptance.ts b/tests/runner-e2e/product-journeys/onboarding-pre-acceptance.ts new file mode 100644 index 00000000000..0b0fe7e650e --- /dev/null +++ b/tests/runner-e2e/product-journeys/onboarding-pre-acceptance.ts @@ -0,0 +1,59 @@ +import { ISSUE_STATUSES } from "../../../packages/shared/src/constants.js"; + +const checkpoints = ["before-opening-answer", "awaiting-proposal"] as const; +const violations = ["unexpected_task_set", "attachment_present", "non_planning_document_present", "first_task_done"] as const; +const statuses = [...ISSUE_STATUSES, "missing", "unknown"] as const; + +/** Scalar observations from the first failing pre-acceptance guard; never raw rows. */ +export interface OnboardingPreAcceptanceEvidence { + version: 1; + checkpoint: typeof checkpoints[number]; + violations: Array; + taskCount: number; + attachmentCount: number; + documentCount: number; + nonPlanningDocumentCount: number; + firstTaskMatchesCanonicalParent: boolean; + firstTaskStatus: typeof statuses[number]; + canonicalParentStatus: typeof statuses[number]; +} + +const receiptKeys = { + version: true, checkpoint: true, violations: true, taskCount: true, attachmentCount: true, + documentCount: true, nonPlanningDocumentCount: true, firstTaskMatchesCanonicalParent: true, + firstTaskStatus: true, canonicalParentStatus: true, +} satisfies Record; + +export function preAcceptanceTaskStatus(task: { status?: unknown; [key: string]: unknown } | undefined): OnboardingPreAcceptanceEvidence["firstTaskStatus"] { + if (!task) return "missing"; + return ISSUE_STATUSES.find(status => status === task.status) ?? "unknown"; +} + +export function preAcceptanceViolations(observed: Pick): OnboardingPreAcceptanceEvidence["violations"] { + return [ + ...(observed.taskCount !== 1 || !observed.firstTaskMatchesCanonicalParent ? ["unexpected_task_set" as const] : []), + ...(observed.attachmentCount ? ["attachment_present" as const] : []), + ...(observed.nonPlanningDocumentCount ? ["non_planning_document_present" as const] : []), + ...(observed.firstTaskStatus === "done" ? ["first_task_done" as const] : []), + ]; +} + +/** Closed validation is shared by normalized-result readers and explicit report rendering. */ +export function validateOnboardingPreAcceptanceEvidence(value: unknown): asserts value is OnboardingPreAcceptanceEvidence { + const invalid = (): never => { throw new Error("invalid_onboarding_pre_acceptance_evidence"); }; + const keys = Object.keys(receiptKeys); + if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).length !== keys.length || keys.some(key => !Object.hasOwn(value, key))) invalid(); + const receipt = value as OnboardingPreAcceptanceEvidence; + if (receipt.version !== 1 || !checkpoints.includes(receipt.checkpoint) || + !Array.isArray(receipt.violations) || !receipt.violations.length || receipt.violations.length > violations.length || + receipt.violations.some(code => !violations.includes(code)) || new Set(receipt.violations).size !== receipt.violations.length || + [receipt.taskCount, receipt.attachmentCount, receipt.documentCount, receipt.nonPlanningDocumentCount].some(count => !Number.isSafeInteger(count) || count < 0) || + receipt.nonPlanningDocumentCount > receipt.documentCount || typeof receipt.firstTaskMatchesCanonicalParent !== "boolean" || + !statuses.includes(receipt.firstTaskStatus) || !statuses.includes(receipt.canonicalParentStatus)) invalid(); + if (receipt.taskCount === 0 && (receipt.firstTaskStatus !== "missing" || receipt.canonicalParentStatus !== "missing" || receipt.firstTaskMatchesCanonicalParent) || + receipt.taskCount > 0 && receipt.firstTaskStatus === "missing" || + receipt.firstTaskMatchesCanonicalParent && receipt.firstTaskStatus !== receipt.canonicalParentStatus || + receipt.taskCount === 1 && !receipt.firstTaskMatchesCanonicalParent && receipt.canonicalParentStatus !== "missing" || + preAcceptanceViolations(receipt).join(",") !== receipt.violations.join(",")) invalid(); +} diff --git a/tests/runner-e2e/product-journeys/types.ts b/tests/runner-e2e/product-journeys/types.ts index da0b054a606..00bdeb5c164 100644 --- a/tests/runner-e2e/product-journeys/types.ts +++ b/tests/runner-e2e/product-journeys/types.ts @@ -29,6 +29,7 @@ export interface JourneyEvidence { operations?: JourneyOperations; artifact?: OnboardingArtifactEvidence; onboardingConnect?: import("./onboarding-connect.js").OnboardingConnectEvidence; + onboardingPreAcceptance?: import("./onboarding-pre-acceptance.js").OnboardingPreAcceptanceEvidence; } export interface OnboardingArtifactEvidence { schema: "paperclip.product-journey.artifact/v1"; diff --git a/tests/runner-e2e/result-validation.ts b/tests/runner-e2e/result-validation.ts index 56f38ed0bec..3d6beece13e 100644 --- a/tests/runner-e2e/result-validation.ts +++ b/tests/runner-e2e/result-validation.ts @@ -6,6 +6,7 @@ import type { RunnerE2ECampaignAccounting, RunnerE2EResult } from "./types.js"; import { DEPENDABLE_CELLS } from "./dependable-qualification.js"; import { validateOnboardingConnectEvidence } from "./product-journeys/onboarding-connect.js"; import { validateOnboardingArtifact } from "./product-journeys/artifact-evidence.js"; +import { validateOnboardingPreAcceptanceEvidence } from "./product-journeys/onboarding-pre-acceptance.js"; type Rule = (value: unknown, at: string) => void; const invalid = (at: string): never => { @@ -346,6 +347,7 @@ const fields = { targetId: optional(string), campaignId: optional(string), attemptId: optional(string), onboardingConnect: optional((value, at) => { try { validateOnboardingConnectEvidence(value); } catch { invalid(at); } }), + onboardingPreAcceptance: optional((value, at) => { try { validateOnboardingPreAcceptanceEvidence(value); } catch { invalid(at); } }), artifact: optional((value, at) => { try { validateOnboardingArtifact(value); } catch { invalid(at); } }), operations: optional(closedShape({ campaignId: string, attemptId: string, modelCostUsd: nullable(number), setupCostUsd: nullable(number), requestCount: integer, feedback: closedShape({ collection: oneOf("complete", "partial", "unavailable"), complaints: integer, suggestions: integer }), traceIds: array(string) })), @@ -404,6 +406,9 @@ export function validateRetainedRunnerResult( result(value, "result"); const checked = value as RunnerE2EResult; const artifact = checked.productJourney?.artifact; + if (checked.productJourney?.onboardingPreAcceptance && (checked.suiteId !== "product-journeys" || checked.caseId !== "cloud-onboarding" || + checked.status !== "failed" || checked.productJourney.outcome !== "failed" || + checked.error !== "onboarding_work_before_acceptance")) invalid("result.productJourney.onboardingPreAcceptance"); if (artifact && (checked.suiteId !== "product-journeys" || checked.caseId !== "cloud-onboarding" || checked.runIds && !checked.runIds.includes(artifact.originatingRunId))) invalid("result.productJourney.artifact"); if (checked.workerTiming !== undefined) { From 8161f2a813ac6da6661cb67bfdf26bac035cdba2 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 27 Oct 2026 17:09:31 -0500 Subject: [PATCH 4/4] fix(server): wake tool-review card repair from committed changes (#17468) ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Tool requests and invocations store the execution outcome. Review cards show that outcome. > - The maintenance tick repeatedly joins these tables even when every card matches. > - Committed changes can wake repair. Existing rows can restore work after restart. > - A large company backlog also needs a bounded pass so other companies and shutdown can proceed. > - This PR uses the shared coordinator for scoped repair, continuation and failure deadlines. Settled history becomes quiet. ## Linked Issues or Issue Description **What happened?** The aggregate maintenance tick scans tool-review projections on every tick. Matching terminal history still causes database work. A company with many stale cards can also hold one worker in an unlimited drain. **What did you expect?** Relevant writes and startup should wake repair. Failed or unresolved cards should retain recovery. Matching history should cause no recurring SQL. Each normal worker pass should honor drain and shutdown. **Steps to reproduce** Start an instance with completed tool requests and matching cards. Leave it idle. The old maintenance tick keeps querying for mismatches. A large mismatch backlog also drains without a row limit or cancellation check. This is slice 07 of the sleep migration. It now targets master after #17458 landed. Related owners are pending expiry #17453 and approved recovery #17454. Their execution duties remain separate from card repair. The prior open-PR search found no duplicate projection migration. ## What Changed - Register company-scoped projection repair with the existing delivery coordinator. Remove its recurring aggregate-tick scan. - Signal through the existing review-write transaction owner and linked interaction mutations. Ordinary unlinked confirmations do not wake repair. - Keep interpretation, locks, current-state checks, activity and continuation callbacks in the gateway. A repair never repeats a provider tool call. - Limit each normal worker pass to 500 rows. Check abort and admission between rows. Save company progress through truncated and failed passes so blocked early pages cannot hide later cards. - Schedule truncated work after one second. Back off unresolved cards from thirty seconds to five minutes; fresh committed hints reset the delay. Clear obsolete cursors after empty reconstruction. - Skip repeated company discovery for scoped hints and the extra candidate query on an empty sweep with no saved cursor. Attempted or resumed passes still verify remaining mismatches because reflection returns no settlement result. - Add generated migration `0386_steady_epoch.sql` for the existing `(company_id, interaction_id)` lookup. Use the existing concurrent-index executor. Add no table. ## Verification Current candidate: `d4706fbf2a04a00ade30181eb1bd9322e8455818`. All 222 cases in the full gateway/projection/interruption, startup and scoped-deadline suites pass without skips after the query/retry efficiency repair; server types and build pass. A single committed company hint with matching retained history and a separate empty direct sweep each perform one candidate query. The unresolved-card regression failed before repair and now verifies backoff through the five-minute cap, prompt producer activation and quiet after settlement. An initial assertion incorrectly assumed an entire approval emitted one wake; its separate real writes require isolating the single-hint measurement. The earlier master integration `fe6e10629b` additionally established the following evidence before this efficiency follow-up: - **320 cases pass** across full gateway/projection/interruption, startup, scoped-deadline, narrowed identity-read and authenticated gateway HTTP suites. The HTTP selection includes all 81 cases. - **Six real PostgreSQL regressions failed before their fixes:** pass bounds, abort, drain, progress past unprojectable pages, progress past failed pages, and first repair after empty reconstruction. The complete owning selection passes all 220 cases. - Server production typechecking and build pass. Generated index migration, snapshot drift and numbering/safety checks pass. The five newest snapshots remain; master journal entries are unchanged. - A real missing-link query on 30,000 history rows changed from a sequential scan that filtered all 30,000 rows and touched 429 buffers to the new index with two buffers. Both treatments returned no rows. - Normal master integration preserves 35 independent performance files exactly. The gateway also retains master's narrowed identity read. Commands include `pnpm --filter @paperclipai/server typecheck`, `pnpm --filter @paperclipai/server build`, and server Vitest selections for `tool-gateway-service`, `server-startup-feedback-export`, `scoped-deadline-work`, `run-identity-projections`, and `connection-management.integration`, with separate PostgreSQL test fixtures. [The behavior and failure audit](doc/idle-tool-review-projection.md) records the producer contract, earlier fixture failures, index measurement, red/green regressions and integration evidence. Fresh current-head CI and Greptile/Ponytail remain required before merge. ## Risks - Signals use the existing single-active-writer database owner. Another replica or independent SQL writer needs a wake contract. - An already issued database query or reflection finishes before cancellation takes effect. Checks between rows bound further dispatch. - Legacy manual/global and disabled-scheduler one-shot repairs keep their complete-sweep behavior. The normal coordinator worker always supplies its row budget and admission controls. - Unprojectable cards and thrown failures retain recovery with a five-minute backoff cap. The company mismatch query still grows with terminal history. Empty history does not retain a recurring scan. - The index migration uses concurrent creation and the existing invalid-index recovery path. Prior SQL and journal entries remain unchanged. - Cloud sleep eligibility and external-wake coverage do not change. Local worker quiet is not proof of host or database suspension. ## Model Used OpenAI Codex, GPT-6 family, with reasoning and code execution. The exact serving model identifier and context window were not exposed. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip --- doc/idle-tool-review-projection.md | 229 +++++++++++ ...2026-10-24-recurring-server-sleep-stack.md | 57 ++- packages/db/src/client.ts | 1 + .../db/src/migrations/0386_steady_epoch.sql | 1 + ...{0381_snapshot.json => 0386_snapshot.json} | 107 +++++- packages/db/src/migrations/meta/_journal.json | 9 +- packages/db/src/schema/tool_access.ts | 1 + .../server-startup-feedback-export.test.ts | 2 + .../__tests__/tool-gateway-service.test.ts | 356 ++++++++++++++++++ server/src/index.ts | 8 +- .../services/delivery-work-notifications.ts | 1 + .../issue-thread-interactions.test.ts | 15 +- .../src/services/issue-thread-interactions.ts | 50 ++- server/src/services/tool-gateway.ts | 48 +-- .../services/tool-review-projection-work.ts | 33 ++ server/src/services/tool-review-projection.ts | 77 ++++ .../tool-review-work-notifications.ts | 1 + 17 files changed, 935 insertions(+), 61 deletions(-) create mode 100644 doc/idle-tool-review-projection.md create mode 100644 packages/db/src/migrations/0386_steady_epoch.sql rename packages/db/src/migrations/meta/{0381_snapshot.json => 0386_snapshot.json} (99%) create mode 100644 server/src/services/tool-review-projection-work.ts create mode 100644 server/src/services/tool-review-projection.ts diff --git a/doc/idle-tool-review-projection.md b/doc/idle-tool-review-projection.md new file mode 100644 index 00000000000..f1d431ea920 --- /dev/null +++ b/doc/idle-tool-review-projection.md @@ -0,0 +1,229 @@ +# Tool-review interaction repair + +The tool-action request and invocation are authoritative. The interaction card +is a projection of their outcome. Previously the aggregate maintenance tick +joined these tables repeatedly, even when every card already matched. + +The projection worker reconstructs affected companies at startup and reconciles +after committed changes. Producer hints carry the company ID. Subsequent +candidate discovery and paginated repair queries filter by that company; review +writes cannot drive a scan of another company's terminal history. The shared +scoped worker dispatches one company per pass with one-second minimum spacing. +It retains a 30-second retry only for a mismatch or failed reconciliation. +Configured idle tools, pending reviews without terminal outcomes, and matching +terminal history have no recurring projection SQL or provider calls. This is +worker quiet, not whole-instance suspension. + +## Ownership and trigger contract + +`tool-review-projection.ts` owns candidate discovery and pagination. The gateway +retains card interpretation, current-state checks, locks, activity publication, +and the existing continuation callback. The scheduler consumes company discovery, +`sweep(companyId)`, and the returned retry obligation. No provider payload enters shared scheduling. +No table is added. A concurrent company/interaction lookup index supports the +existing link checks and linked-request updates. + +The existing review notification helper now also signals projection repair. +Notifications are awaited before writes and inherit the outer transaction's +commit, rollback, and uncertainty tracking. Unrelated review changes can cause +one empty company-scoped reconciliation; they do not create a recurring deadline. +Interaction-only writes first check for an actual linked tool request using the +company and affected card IDs. Generic confirmation kinds alone do not signal +any tool-review queue. This also preserves recovery for legacy linked cards +without current tool payload flags. These reads happen in the mutation owner, +not a background poll. Sibling selection shares the update predicate and runs +under the existing issue lock before publishing the notification. + +| Producer | Notification ownership | +| --- | --- | +| Gateway signing, approval inference, execution claims, provider outcomes, and invalidation | Existing `writeToolReviewChange`; the closed-issue expiry path now uses it too | +| Human approval/rejection | `commitToolActionReview` signals in its existing transaction | +| Pending expiry, approved recovery, interrupted claims, Test-tab settlement | Existing review-write boundary | +| Review-queue invalidation | Existing review-write boundary | +| Interaction withdrawal, skip, terminal-issue expiry | Linked-request resolution signals before the mutation | +| Linked tool-card accept/reject, deleted-addressee cancellation | Projection notification before replacing card state in the owning transaction; unlinked confirmations do not notify | +| Sibling supersession, startup duplicate cleanup, new/historical comment supersession | Projection notification before card replacement, including cases where the request is already terminal | +| Comment-based confirmation resolution | Calls the interaction owner inside the same outer transaction; its later comment-ID update shares that signal | + +The audited other interaction writers do not create this mismatch: native bridge +and status-committer summary/status-only updates preserve the projection; native +review retirement owns separate completion-review cards; connection and secret +flows own their separate card types. Document-staleness and plan-resume paths +use document targets, while tool cards use `tool-action:` custom targets. +Reflection consent uses its instruction/profile/skill target keys, not tool-action +keys. A future writer that replaces tool-card result state must use the same +transaction notification boundary. A future writer that changes authoritative +tool outcomes must signal the review boundary. + +## Repair, concurrency, and lifecycle + +The mismatch predicate preserves the previous policy: terminal executed, failed, +expired, or cancelled requests with a linked interaction whose displayed tool +status differs. Cancelled requests display `expired`. Invocation error and result +summaries come from saved state. Repair never repeats a provider action. + +Candidate queries page in request-ID order, 100 rows at a time. A card that cannot +yet be projected does not starve later pages. Per-row failures do not prevent +attempting the remaining candidates; failures keep the retry. A final mismatch +check retains retries for no-op repairs rather than silently declaring them done. +Failed companies retain their own backoff across notifications while other +companies progress. An unresolved no-op projection retains a 30-second deadline; +a new relevant company change can make it actionable sooner. A company pass +still drains all its pages, preserving progress past an unprojectable card. +The joins inspect that company's history on activation. This change removes repeated +idle scans; it does not introduce an indexed projection-debt table or claim that +an activated reconciliation has constant cost independent of history size. + +The gateway locks the interaction and request, then checks the current request +status. If another repair already wrote the same status and outcome fields, +it avoids a second write and duplicate activity. Different saved details still +use the existing update path. Missing projection state remains repairable. + +The shared deadline worker retains first writes during drain, failed retries, +and changes arriving during reconciliation. Shutdown joins coordinator work. +Startup reconstructs debt from existing rows. With heartbeat scheduling disabled, +startup still performs one pass, preserving the existing disabled-mode contract. +The public/manual combined review sweep remains available; server maintenance +no longer calls it periodically. + +## Continuation and sleep limits + +Card state is not proof that continuation delivery finished. Existing +`tool_action_deliveries` receipts and their coordinator remain responsible for +that work. Activity publication still occurs after the card transaction; this +slice does not add exactly-once activity delivery or a new outbox. + +Signals remain process-local to the supported database owner. Independent SQL +writers and another active server require a separate notification/reconciliation +contract. Cloud eligibility still conservatively blocks retained tool-action +requests. No external wake or sleep-safety guard is relaxed here. + +## Verification + +Twelve new real-PostgreSQL cases exercise normal approval and single execution, +quiet configured and terminal-history states, four persisted outcome states, +outer commit/rollback, first write during drain, failure retry through drain, +foreground/worker repair contention, multi-page progress past an unprojectable +card, and an administrative card overwrite that reactivates repair. Quiet checks +observe absence of database reads across an hour of controlled time. + +The first focused run caught a missing-projection null access in the new +idempotency check; optional access fixes it. The pagination fixture also attempted +to change a referenced request ID; it now orders the additional candidates without +mutating that key. The focused rerun passed all eleven then-existing tests. +After adding the concurrent repair case, all 148 service/startup tests and 92 +gateway acceptance tests passed. Workspace typechecking and build passed. All 469 tool-access and 106 interaction +service tests also pass (815 tests across the final selections). The first +interaction run passed 105 cases but timed out in one cleanup hook during a +53-minute local run; the isolated full rerun passed in nine seconds. No production +change or timeout increase was made to force that result. Full repository tests +will run in CI; the local selections do not claim a complete repository test run. +Fresh PR CI/review remains required. + +Company-scoping follow-up reproduced two regressions: captured recovery SQL lacked +a company predicate, and ordinary confirmation creation/replacement/cancellation +published three unnecessary tool-projection wakes. Both regressions now pass +through real producers. Additional coverage keeps failed-company retry timing +independent, proves ordinary mutations still complete without recovery scans, +and exercises administrative repair of legacy cards identified by their saved +link rather than payload flags. + +Company-scoping follow-up verification: all 180 gateway and startup cases and all 152 interaction and secret-proposal route cases passed against dedicated PostgreSQL test databases. Server typechecking passed. These are local checks; stack CI and deployed sleep qualification remain separate. + + +## Indexed interaction links + +Review found that the new link check had no supporting interaction index. An +ordinary unlinked confirmation could scan all tool-action history for its company. +The generated `0386_steady_epoch.sql` migration adds the non-unique +`(company_id, interaction_id)` index concurrently, and the existing top-level +migration executor handles its creation and interrupted-build recovery. The +schema and generated snapshot describe the same index; older SQL and journal +entries are preserved and snapshot pruning retains the five newest snapshots. + +A real PostgreSQL check applied the migration to a fresh dedicated test database +and seeded 30,000 tool-action rows. The ordinary missing-link query returned no +rows in both treatments: without the index it performed a sequential scan, +filtered 30,000 rows and touched 429 shared buffers; with the index it used the +new index and touched two buffers. These are local planner measurements, not a +fleet latency or cost claim. The baseline index removal was rolled back in that +dedicated database, and the index remained valid afterwards. An initial probe +failed while binding a JSON fixture parameter before any comparison; correcting +the parameter encoding made the complete probe pass. That failed fixture is not +counted as a product regression. + +Migration numbering/safety checks, generated snapshot drift, server types and +server build pass. All 214 cases in the full gateway/projection/startup/scoped- +deadline selection pass against a separate freshly migrated database, preserving +notification quiet, company isolation, transaction settlement, and interruption +behavior. Latest-head CI and automated reviews remain required merge gates. + +## Bounded projection and lifecycle interruption + +A review found that one company could drain an unlimited backlog in a single +worker pass. Five real PostgreSQL regressions reproduced 501 rows being consumed +instead of the 500-row budget, missing abort/drain handling, and the absence of +continuation past a full page of unprojectable or failed cards. + +The worker now gives its existing service a 500-row budget, the coordinator's +abort signal, and its admission predicate. The service checks admission between +rows and reads at most 100 candidates per page. It retains the last attempted +request ID for each unfinished company, including after a failed pass, so a +poisoned early page cannot hide later healthy cards. A truncated pass schedules +a one-second continuation; the existing shared per-company fairness and failure +backoff remain in force. A completed pass that still has an unprojectable card +backs off from thirty seconds to five minutes. Fresh committed company changes +reset that delay and wake the affected scope promptly. These are real unresolved projections, +not an unconditional empty-history scan. + +Reconstruction clears continuation state for companies that no longer have +mismatches. A sixth real regression reproduced an abandoned cursor skipping the +first new earlier card after an empty reconstruction; clearing that cursor makes +the first new pass repair it immediately. The maps contain no durable truth: +restart reconstructs from the existing rows, and completed rows stop matching. +There is no cursor table, independent timer or per-producer recovery wrapper. + +Legacy manual/global and scheduler-disabled one-shot repair calls retain their +complete-sweep behavior unless they request a budget. The normal coordinator +worker always supplies the bounded options. Cancellation is observed between +rows and pages; an already issued database query or reflection finishes before +the service stops. A sweep never replays a provider tool action. + +All 220 cases across the full gateway/projection/interruption, startup and scoped +deadline suites pass, with no skipped cases. The five initial regressions and +sixth cursor regression failed before their fixes; server types and build pass. +The earlier 219-case acceptance remains evidence for the preceding revision. +Fresh integrated-head CI and both automated reviews remain merge gates. + + +After normal reconciliation with master `f6bc653f7f`, all 320 integrated cases +pass, including the 81 authenticated gateway HTTP cases and the upstream narrowed +identity-read tests. Server types and build pass. Thirty-five independent master +performance files are preserved exactly; the gateway's narrowed identity read +is preserved alongside the projection extraction. The pre-integration 220-case +selection above remains evidence for its stated revision. + + +## Review efficiency follow-up + +A company-scoped hint now enters the bounded owner directly rather than first +repeating company discovery. Startup/global reconstruction still discovers +companies from existing rows. An empty sweep with no saved cursor returns after +one candidate query; a resumed cursor or attempted reflection still needs the +final query to detect unresolved earlier cards. The reflection callback returns +no settlement result, so an attempted reflection cannot establish that a card +was repaired. + +Returned unresolved work now backs off through 30, 60, 120, 240 and 300 seconds, +matching the shared error-backoff cap. Truncated backlog continuation remains +one second. Settlement removes the retry; a new committed hint resets backoff. +No pending row is discarded, and no independent timer or table is added. + +The fixed-cadence regression failed before repair and now verifies the full +backoff cap, producer reactivation and quiet after settlement. An initial scan +assertion incorrectly assumed that a complete approval emitted only one wake; +its separate legitimate writes caused two scans even after optimization. The +corrected case isolates one committed hint and verifies one candidate scan with +matching history, followed by an empty direct sweep with one query. All 222 +cases in the full gateway, startup and scoped-deadline suites pass without skips; +server typecheck and build pass. Fresh-head CI and both reviews are still required. diff --git a/doc/plans/2026-10-24-recurring-server-sleep-stack.md b/doc/plans/2026-10-24-recurring-server-sleep-stack.md index b8976fb34fb..25d3ebf70bc 100644 --- a/doc/plans/2026-10-24-recurring-server-sleep-stack.md +++ b/doc/plans/2026-10-24-recurring-server-sleep-stack.md @@ -18,7 +18,7 @@ Do not mark an item done from a timer removal or a green check alone. | 04 | Decision retention and notifications | Retention deadlines and notification delivery are separate reasons | Pending | | 05 | Decision expiry and interrupted effects | Expiry, effect recovery, continuation recovery | Pending | | 06 | Tool connection health | Configuration/use activation and defined proactive health deadlines | Pending | -| 07 | Secret proposals, tool reviews, gateway tokens | Separate expiry/scrub/recovery owners | Secret proposals: [#17446](https://github.com/paperclipai/paperclip/pull/17446), merged; gateway credentials: [#17450](https://github.com/paperclipai/paperclip/pull/17450), merged; pending tool-review expiry: [#17453](https://github.com/paperclipai/paperclip/pull/17453), merged; approved recovery: [#17454](https://github.com/paperclipai/paperclip/pull/17454), merged after current-head CI and both 5/5 reviews; interrupted claims: [#17458](https://github.com/paperclipai/paperclip/pull/17458), integration verified and awaiting fresh CI/review; projection: [#17468](https://github.com/paperclipai/paperclip/pull/17468), interaction-link index verified and awaiting fresh CI/review | +| 07 | Secret proposals, tool reviews, gateway tokens | Separate expiry/scrub/recovery owners | Secret proposals: [#17446](https://github.com/paperclipai/paperclip/pull/17446), merged; gateway credentials: [#17450](https://github.com/paperclipai/paperclip/pull/17450), merged; pending tool-review expiry: [#17453](https://github.com/paperclipai/paperclip/pull/17453), merged; approved recovery: [#17454](https://github.com/paperclipai/paperclip/pull/17454), merged after current-head CI and both 5/5 reviews; interrupted claims: [#17458](https://github.com/paperclipai/paperclip/pull/17458), merged after current-head CI and both 5/5 reviews; projection: [#17468](https://github.com/paperclipai/paperclip/pull/17468), interaction-link index verified and awaiting fresh CI/review | | 08 | GitHub connection events and continuity | Event discovery/replay and credential continuity separately | Pending | | 09 | Merged-PR confirmations | Candidate writes, webhook activation where supported, outstanding-candidate fallback | Pending | | 10 | External-object refresh | Configuration changes, refresh deadlines, source events | Pending | @@ -280,3 +280,58 @@ initial concurrent-run timeout is retained above as evidence, not hidden. Workspace typecheck/build and migration safety/numbering pass. The first four PRs are mergeable and have all checks passed at their recorded heads. #17454 is mergeable with fresh checks and review in progress at `7a1cf03e62`. + +Slice 06 is [#17458](https://github.com/paperclipai/paperclip/pull/17458), head +`85003a7ac4`, based on #17454. Greptile review was requested and the PR is +attached to this chat. Slice 05 has fresh Greptile 5/5 at `7a1cf03e62`; CI is +running with no failure in the latest snapshot. The next branch is +`codex/sleep-07-tool-review-projection`, based on #17458. No seventh implementation +or readiness is claimed yet. The full remaining inventory stays in scope. + + +## Slice 07: tool-review interaction projection + +The implementation removes the last combined review sweep from the main tick. +It pages terminal mismatches and retains retries only for actual debt or failures. +Gateway reflection keeps locks, current-state checks, activity, and continuation +ownership; concurrent identical repairs do not write twice. The producer audit +also covers administrative card result replacements, before the mutation in the +existing transaction. See [projection repair](../idle-tool-review-projection.md). + +Twelve new lifecycle cases are included in 148 passing service/startup tests. +Gateway acceptance passes all 92 tests and workspace typechecking passes. The +initial missing-state bug and referenced-key fixture failure are recorded in the +behavior document. Build and additional consumer regressions are running; no +seventh PR is claimed ready yet. + +Historical parent evidence at the initial migration: #17454 at `7a1cf03e62` +and #17458 at `85003a7ac4` passed the recorded CI matrices and Greptile review. +Those snapshots preceded their current-head review and landing. The first six +stack PRs have now merged. The full remaining inventory is still in scope. + +Initial slice 07 local verification: 815 selected tests passed, with workspace +typecheck and build passing. One initial interaction cleanup-hook timeout is recorded in +the behavior document; the complete isolated suite then passed. Both parent +PRs #17454 and #17458 now have every check passed and are mergeable, including +the additional Paperclip Review checks. Full CI/review for slice 07 is next. + + +Slice 07 current integration: master `f6bc653f7f` contains the first six landed +slices and the independent identity/resume/sidebar performance work. This slice +adds generated concurrent interaction-link index migration `0386_steady_epoch` +and retains five schema snapshots. Projection worker passes stop at 500 rows, +honor abort/drain between rows, and resume past failed or unprojectable pages; +empty reconstruction clears obsolete cursors. Six real regressions failed before +the fixes. All 320 integrated gateway/projection/startup/deadline/identity/HTTP +cases, server types and build pass; 35 independent master files are preserved +exactly. Current-head CI and Greptile/Ponytail review remain required. Earlier +case counts above describe the broader selections at their original revisions. + + +Slice 07 follow-up: scoped hints avoid redundant discovery, empty sweeps avoid a +second candidate read, and unresolved-card retries back off to five minutes. +Fresh writes reactivate promptly and settlement is quiet. The full affected +gateway/startup/deadline selection passes 222 cases; server types/build pass. +The initial invalid one-wake-per-approval assertion and corrected isolated-hint +measurement are retained in the behavior document. Current-head CI/reviews remain +required before this slice can merge. diff --git a/packages/db/src/client.ts b/packages/db/src/client.ts index 3e4cce15e2e..342256ac462 100644 --- a/packages/db/src/client.ts +++ b/packages/db/src/client.ts @@ -504,6 +504,7 @@ const MIGRATIONS_WITH_TOP_LEVEL_STATEMENTS = new Set([ "0381_mean_scream.sql", "0382_narrow_the_executioner.sql", "0385_open_madame_web.sql", + "0386_steady_epoch.sql", "0384_funny_adam_warlock.sql", "0383_tool_review_company_expiry.sql", ]); diff --git a/packages/db/src/migrations/0386_steady_epoch.sql b/packages/db/src/migrations/0386_steady_epoch.sql new file mode 100644 index 00000000000..06356e30ced --- /dev/null +++ b/packages/db/src/migrations/0386_steady_epoch.sql @@ -0,0 +1 @@ +CREATE INDEX CONCURRENTLY IF NOT EXISTS "tool_action_requests_company_interaction_idx" ON "tool_action_requests" USING btree ("company_id","interaction_id"); diff --git a/packages/db/src/migrations/meta/0381_snapshot.json b/packages/db/src/migrations/meta/0386_snapshot.json similarity index 99% rename from packages/db/src/migrations/meta/0381_snapshot.json rename to packages/db/src/migrations/meta/0386_snapshot.json index 23802aaeece..8dd26eef4fb 100644 --- a/packages/db/src/migrations/meta/0381_snapshot.json +++ b/packages/db/src/migrations/meta/0386_snapshot.json @@ -1,6 +1,6 @@ { - "id": "2e93deb7-f24c-42d1-8c8e-30b21cff90bc", - "prevId": "bfda87fa-662b-47bb-87c0-dabc814aebd7", + "id": "da3229b5-4eab-4d8b-ba6b-d756e6c42430", + "prevId": "9965d300-e355-4f47-ba0a-951ed3b4b8a2", "version": "7", "dialect": "postgresql", "tables": { @@ -52812,6 +52812,88 @@ "method": "btree", "with": {} }, + "tool_action_requests_pending_expiry_idx": { + "name": "tool_action_requests_pending_expiry_idx", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"tool_action_requests\".\"status\" = 'pending'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "tool_action_requests_company_pending_expiry_idx": { + "name": "tool_action_requests_company_pending_expiry_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"tool_action_requests\".\"status\" = 'pending'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "tool_action_requests_executing_deadline_idx": { + "name": "tool_action_requests_executing_deadline_idx", + "columns": [ + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"tool_action_requests\".\"status\" = 'executing'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "tool_action_requests_approved_idx": { + "name": "tool_action_requests_approved_idx", + "columns": [ + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"tool_action_requests\".\"status\" = 'approved'", + "concurrently": false, + "method": "btree", + "with": {} + }, "tool_action_requests_invocation_idx": { "name": "tool_action_requests_invocation_idx", "columns": [ @@ -52827,6 +52909,27 @@ "method": "btree", "with": {} }, + "tool_action_requests_company_interaction_idx": { + "name": "tool_action_requests_company_interaction_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "interaction_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, "tool_action_requests_issue_idx": { "name": "tool_action_requests_issue_idx", "columns": [ diff --git a/packages/db/src/migrations/meta/_journal.json b/packages/db/src/migrations/meta/_journal.json index f4cfed69f11..578d8027ed9 100644 --- a/packages/db/src/migrations/meta/_journal.json +++ b/packages/db/src/migrations/meta/_journal.json @@ -2689,6 +2689,13 @@ "when": 1793060791729, "tag": "0385_open_madame_web", "breakpoints": true + }, + { + "idx": 386, + "version": "7", + "when": 1793135146893, + "tag": "0386_steady_epoch", + "breakpoints": true } ] -} +} \ No newline at end of file diff --git a/packages/db/src/schema/tool_access.ts b/packages/db/src/schema/tool_access.ts index 9f79743d6c3..b8b317ddb91 100644 --- a/packages/db/src/schema/tool_access.ts +++ b/packages/db/src/schema/tool_access.ts @@ -839,6 +839,7 @@ export const toolActionRequests = pgTable( index("tool_action_requests_executing_deadline_idx").on(table.updatedAt, table.id).where(sql`${table.status} = 'executing'`), index("tool_action_requests_approved_idx").on(table.id).where(sql`${table.status} = 'approved'`), index("tool_action_requests_invocation_idx").on(table.invocationId), + index("tool_action_requests_company_interaction_idx").on(table.companyId, table.interactionId), index("tool_action_requests_issue_idx").on(table.companyId, table.issueId), ], ); diff --git a/server/src/__tests__/server-startup-feedback-export.test.ts b/server/src/__tests__/server-startup-feedback-export.test.ts index 1a9fcf51576..cb7da55e61a 100644 --- a/server/src/__tests__/server-startup-feedback-export.test.ts +++ b/server/src/__tests__/server-startup-feedback-export.test.ts @@ -72,6 +72,8 @@ const { settleInterruptedActionReviews: vi.fn(async () => ({ scanned: 0 })), nextActionReviewInterruptionAt: vi.fn(async () => null), recoverApprovedActionReviews: vi.fn(async () => ({ scanned: 0, retry: false })), + repairActionReviewProjections: vi.fn(async () => ({ scanned: 0, retry: false })), + actionReviewProjectionCompanies: vi.fn(async () => []), approvedActionReviewCompanies: vi.fn(async () => []), sweepActionReviews: vi.fn(async () => ({ scanned: 0 })), sweepExpiredActionReviews: vi.fn(async () => ({ scanned: 0 })), diff --git a/server/src/__tests__/tool-gateway-service.test.ts b/server/src/__tests__/tool-gateway-service.test.ts index 35dabccbe22..0d277ee4dbf 100644 --- a/server/src/__tests__/tool-gateway-service.test.ts +++ b/server/src/__tests__/tool-gateway-service.test.ts @@ -1,3 +1,6 @@ +import { toolReviewProjectionService } from "../services/tool-review-projection.js"; +import { registerToolReviewProjectionWork } from "../services/tool-review-projection-work.js"; +import { issueThreadInteractionService } from "../services/issue-thread-interactions.js"; import { registerToolReviewInterruptionWork } from "../services/tool-review-interruption-work.js"; import { writeToolReviewChange } from "../services/tool-review-work-notifications.js"; import { deleteCompany } from "../services/company-deletion.js"; @@ -281,6 +284,8 @@ describeEmbeddedPostgres("tool gateway service", () => { await coordinator?.stop(); coordinator = undefined; vi.useRealTimers(); vi.restoreAllMocks(); await db.execute(sql`drop trigger if exists sleep_review_fail on tool_invocations`); + await db.execute(sql`drop trigger if exists sleep_projection_fail on issue_thread_interactions`); + await db.execute(sql`drop function if exists sleep_projection_fail()`); await db.execute(sql`drop function if exists sleep_review_fail()`); await db.execute(sql`drop sequence if exists sleep_review_failure_attempt`); expect(errors).toEqual([]); @@ -352,6 +357,357 @@ describeEmbeddedPostgres("tool gateway service", () => { return { provider, release, started }; } + describe("tool review projection worker", () => { + async function startProjection() { + coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => !draining, + canReconcile: () => true, onError: error => errors.push(error) }); + await registerToolReviewProjectionWork(coordinator, { sweep: gateway.repairActionReviewProjections, companies: gateway.actionReviewProjectionCompanies }, () => !draining).ready; + } + async function savedOutcome(pending: Awaited>, source = db, + status: "executed" | "failed" | "expired" | "cancelled" = "executed") { + await writeToolReviewChange(source, pending.companyId, async tx => { + await tx.update(toolInvocations).set({ status: status === "executed" ? "succeeded" : "failed", + errorCode: status === "executed" ? null : "saved_failure", errorMessage: null, + resultSummary: { summary: "Durable result" }, completedAt: new Date() }) + .where(eq(toolInvocations.id, pending.invocationId)); + await tx.update(toolActionRequests).set({ status, updatedAt: new Date() }) + .where(eq(toolActionRequests.id, pending.id)); + }); + } + async function acceptedCard(pending: Awaited>) { + expect(pending.interactionId).not.toBeNull(); + await db.update(issueThreadInteractions).set({ status: "accepted", result: { version: 1, outcome: "accepted" } }) + .where(eq(issueThreadInteractions.id, pending.interactionId!)); + } + async function projection(pending: Awaited>) { + const [row] = await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.id, pending.interactionId!)); + return (row.result as { toolAction?: { status: string; resultSummary: string; errorCode: string | null } } | null)?.toolAction; + } + + it("becomes quiet with configuration and repairs a real foreground approval without replay", async () => { + await startProjection(); await quiet(); + const pending = await request(); + await gateway.approveActionRequest({ companyId: fixture.company.id, actionRequestId: pending.id, actor: { userId: "board" } }); + await quiet(); expect(await projection(pending)).toMatchObject({ status: "executed" }); + expect(await db.select().from(toolCallEvents).where(eq(toolCallEvents.reasonCode, "approved_action_executed"))).toHaveLength(1); + const before = (await db.select().from(activityLog).where(eq(activityLog.action, "issue.thread_interaction_updated"))).length; + await gateway.repairActionReviewProjections(); + expect((await db.select().from(activityLog).where(eq(activityLog.action, "issue.thread_interaction_updated"))).length).toBe(before); + }); + + it("keeps projection scans scoped to the company whose review changed", async () => { + const other = await createRunFixture(db); + await db.insert(toolPolicies).values(reviewNotePolicyRow(other.company)); + const foreign = await request(gateway, db, other); + await gateway.approveActionRequest({ companyId: other.company.id, actionRequestId: foreign.id, actor: { userId: "board" } }); + await startProjection(); await quiet(); + const before = await projection(foreign); + const reads: Array<{ query: string; params: unknown[] }> = []; + const debug = db.$client.options.debug; + db.$client.options.debug = (_id, query, params) => { + if (/^select/i.test(query) && query.includes('"tool_action_requests"') && query.includes("coalesce(")) + reads.push({ query, params: [...params] }); + }; + try { + for (let index = 0; index < 3; index++) { + const pending = await request(); + await gateway.approveActionRequest({ companyId: fixture.company.id, actionRequestId: pending.id, actor: { userId: "board" } }); + await settle(1500); expect(await projection(pending)).toMatchObject({ status: "executed" }); + } + } finally { db.$client.options.debug = debug; } + expect(reads.length).toBeGreaterThan(0); + for (const read of reads) { + expect(read.query).toContain('"tool_action_requests"."company_id" ='); + expect(read.params).toContain(fixture.company.id); + expect(read.params).not.toContain(other.company.id); + } + expect(await projection(foreign)).toEqual(before); await quiet(); + }); + + it("uses one candidate scan for a committed company hint with matching retained history", async () => { + const pending = await request(); + await gateway.approveActionRequest({ companyId: fixture.company.id, actionRequestId: pending.id, actor: { userId: "board" } }); + await startProjection(); await quiet(); + const reads: string[] = []; + const debug = db.$client.options.debug; + db.$client.options.debug = (_id, query) => { + if (/^select/i.test(query) && query.includes('"tool_action_requests"') && query.includes("coalesce(")) reads.push(query); + }; + try { + await writeToolReviewChange(db, pending.companyId, async tx => { + await tx.update(toolActionRequests).set({ updatedAt: new Date() }).where(eq(toolActionRequests.id, pending.id)); + }); + await settle(); + expect(reads).toHaveLength(1); + await quiet(); + expect(reads).toHaveLength(1); + reads.length = 0; + expect(await gateway.repairActionReviewProjections(fixture.company.id)).toMatchObject({ scanned: 0, retry: false }); + expect(reads).toHaveLength(1); + } finally { db.$client.options.debug = debug; } + }); + + it("backs off unresolved cards to five minutes and clears the retry after settlement", async () => { + const pending = await request(); + await savedOutcome(pending, db, "failed"); + await startProjection(); + for (const delay of [30_000, 60_000, 120_000, 240_000, 300_000, 300_000]) { + const next = coordinator!.nextWakeAt(); + expect(next).not.toBeNull(); + expect(next! - Date.now()).toBeGreaterThan(delay - 1500); + expect(next! - Date.now()).toBeLessThanOrEqual(delay); + await settle(next! - Date.now() + 100); + } + expect(await projection(pending)).toBeUndefined(); + await acceptedCard(pending); + await writeToolReviewChange(db, pending.companyId, async tx => { + await tx.update(toolActionRequests).set({ updatedAt: new Date() }).where(eq(toolActionRequests.id, pending.id)); + }); + await settle(); + expect(await projection(pending)).toMatchObject({ status: "failed" }); + await quiet(); + }); + + it("does not wake projection repair for ordinary confirmation creation, replacement, or cancellation", async () => { + await startProjection(); await quiet(); + const interactions = issueThreadInteractionService(db); + const scope = { id: fixture.issue.id, companyId: fixture.company.id }; + const [recipient] = await db.insert(agents).values({ companyId: fixture.company.id, + name: "Plan recipient", role: "engineer", adapterType: "process" }).returning(); + const input = { kind: "request_confirmation" as const, addresseeAgentId: recipient.id, + payload: { version: 1 as const, prompt: "Approve this plan?" } }; + const signal = vi.fn(); + const unsubscribe = subscribeDeliveryWork(db, DELIVERY_QUEUES.toolReviewProjection, signal); + const reads: string[] = []; + const debug = db.$client.options.debug; + db.$client.options.debug = (_id, query) => { + if (/^select/i.test(query) && query.includes('"tool_action_requests"') && query.includes("coalesce(")) reads.push(query); + }; + try { + const first = await interactions.create(scope, input, { agentId: fixture.agent.id }); + const second = await interactions.create(scope, input, { agentId: fixture.agent.id }); + const cancelled = await interactions.cancelPendingForDeletedAddressee(fixture.company.id, recipient.id); + expect(cancelled.map(row => row.id)).toEqual([second.id]); + expect((await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.id, first.id)))[0].status).toBe("expired"); + await settle(); + expect(signal).not.toHaveBeenCalled(); + expect(reads).toEqual([]); + await quiet(); + } finally { unsubscribe(); db.$client.options.debug = debug; } + }); + + it.each(["executed", "failed", "expired", "cancelled"] as const)("reconstructs a saved %s result after restart and leaves terminal history quiet", async status => { + const pending = await request(); await acceptedCard(pending); await savedOutcome(pending, db, status); + await startProjection(); await quiet(); + expect(await projection(pending)).toMatchObject({ status: status === "cancelled" ? "expired" : status, + resultSummary: "Durable result", errorCode: status === "executed" ? null : "saved_failure" }); + expect(await db.select().from(toolCallEvents).where(eq(toolCallEvents.reasonCode, "approved_action_executed"))).toEqual([]); + }); + + it("retains a first terminal write during drain without passive scans", async () => { + const pending = await request(); await acceptedCard(pending); + await startProjection(); await quiet(); draining = true; + await savedOutcome(pending); await settle(); + const reads = vi.spyOn(db, "select"); + await settle(60 * 60_000); expect(reads).not.toHaveBeenCalled(); reads.mockRestore(); + expect(await projection(pending)).toBeUndefined(); + draining = false; await settle(); await quiet(); + expect(await projection(pending)).toMatchObject({ status: "executed" }); + }); + + it.each([false, true])("waits for the outer outcome transaction (rollback %s)", async rollback => { + const pending = await request(); await acceptedCard(pending); await startProjection(); await quiet(); + let entered!: () => void, release!: () => void; + const ready = new Promise(resolve => { entered = resolve; }); + const gate = new Promise(resolve => { release = resolve; }); + const aborted = new Error("fixture rollback"); + const running = db.transaction(async tx => { + await savedOutcome(pending, tx as unknown as typeof db); + entered(); await gate; if (rollback) throw aborted; + }).catch(error => { if (error !== aborted) throw error; }); + await ready; + try { await vi.advanceTimersByTimeAsync(60_000); expect(await projection(pending)).toBeUndefined(); } + finally { release(); await running; } + await vi.waitFor(async () => { + await vi.advanceTimersByTimeAsync(30_000); + expect(idleWorkSnapshot().active).toBe(0); + if (rollback) expect(await projection(pending)).toBeUndefined(); + else expect(await projection(pending)).toMatchObject({ status: "executed" }); + }, { timeout: 5000 }); + await quiet(); + }); + + it("retries a failed projection through drain without executing the saved action", async () => { + const pending = await request(); await acceptedCard(pending); await savedOutcome(pending); + await db.execute(sql`create function sleep_projection_fail() returns trigger language plpgsql as $$ + begin raise exception 'projection fixture failure'; end $$`); + await db.execute(sql`create trigger sleep_projection_fail before update on issue_thread_interactions + for each row when (new.result->'toolAction'->>'status' = 'executed') execute function sleep_projection_fail()`); + await startProjection(); expect(errors.length).toBeGreaterThan(0); errors.length = 0; + expect(await projection(pending)).toBeUndefined(); + draining = true; + await db.execute(sql`drop trigger sleep_projection_fail on issue_thread_interactions`); + await settle(60 * 60_000); draining = false; + await vi.waitFor(async () => { + await vi.advanceTimersByTimeAsync(30_000); + expect(await projection(pending)).toMatchObject({ status: "executed" }); + }, { timeout: 5000 }); + await quiet(); + expect(await db.select().from(toolCallEvents).where(eq(toolCallEvents.reasonCode, "approved_action_executed"))).toEqual([]); + }); + + it("backs off a failing company while another company's projection completes", async () => { + const other = await createRunFixture(db); + await db.insert(toolPolicies).values(reviewNotePolicyRow(other.company)); + const foreign = await request(gateway, db, other); await acceptedCard(foreign); await savedOutcome(foreign, db, "failed"); + await db.execute(sql`create function sleep_projection_fail() returns trigger language plpgsql as $$ + begin raise exception 'company projection fixture failure'; end $$`); + await db.execute(sql`create trigger sleep_projection_fail before update on issue_thread_interactions + for each row when (new.result->'toolAction'->>'status' = 'failed') execute function sleep_projection_fail()`); + await startProjection(); expect(errors).toHaveLength(1); errors.length = 0; + const retryAt = coordinator!.nextWakeAt(); expect(retryAt).not.toBeNull(); + const pending = await request(); await acceptedCard(pending); await savedOutcome(pending); + await request(gateway, db, other); + await settle(5000); + expect(await projection(pending)).toMatchObject({ status: "executed" }); + expect(await projection(foreign)).toBeUndefined(); + expect(errors).toEqual([]); expect(coordinator!.nextWakeAt()).toBe(retryAt); + await db.execute(sql`drop trigger sleep_projection_fail on issue_thread_interactions`); + await settle(); await quiet(); + expect(await projection(foreign)).toMatchObject({ status: "failed" }); + expect(await db.select().from(toolCallEvents).where(eq(toolCallEvents.reasonCode, "approved_action_executed"))).toEqual([]); + }); + + it("rechecks the projection under lock when foreground repair wins the race", async () => { + const pending = await request(); await acceptedCard(pending); await savedOutcome(pending); + const transaction = db.transaction.bind(db); + let entered!: () => void, release!: () => void; + const ready = new Promise(resolve => { entered = resolve; }); + const gate = new Promise(resolve => { release = resolve; }); + const intercepted = vi.spyOn(db, "transaction").mockImplementationOnce(async callback => { + entered(); await gate; return transaction(callback); + }); + const repair = gateway.repairActionReviewProjections(); + await ready; + try { await gateway.repairActionReviewProjections(); } finally { release(); } + await repair; intercepted.mockRestore(); + const updates = await db.select().from(activityLog).where(and(eq(activityLog.companyId, fixture.company.id), + eq(activityLog.action, "issue.thread_interaction_updated"))); + expect(updates).toHaveLength(1); + expect(await projection(pending)).toMatchObject({ status: "executed" }); + await startProjection(); await quiet(); + }); + + async function projectionBacklog(count: number) { + const pending = await request(); await acceptedCard(pending); await savedOutcome(pending, db, "failed"); + const [template] = await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.id, pending.interactionId!)); + const cards = Array.from({ length: count - 1 }, () => ({ ...template, id: randomUUID(), idempotencyKey: randomUUID() })); + if (cards.length) await db.insert(issueThreadInteractions).values(cards); + const requests = cards.map((card, index) => ({ ...pending, + id: `ffffffff-ffff-4fff-afff-${String(index).padStart(12, "0")}`, + interactionId: card.id, status: "failed" as const })); + if (requests.length) await db.insert(toolActionRequests).values(requests); + const cardByRequest = new Map([pending, ...requests].map(row => [row.id, row.interactionId!])); + const reflect = async (id: string) => { + await db.update(issueThreadInteractions).set({ result: sql`${issueThreadInteractions.result} + || ${JSON.stringify({ toolAction: { status: "failed" } })}::jsonb` }) + .where(eq(issueThreadInteractions.id, cardByRequest.get(id)!)); + }; + return { cardByRequest, reflect }; + } + + it("bounds a projection worker pass and continues its saved backlog", async () => { + await projectionBacklog(501); + await startProjection(); + const projected = async () => (await db.select().from(issueThreadInteractions)) + .filter(card => (card.result as { toolAction?: { status: string } } | null)?.toolAction?.status === "failed").length; + expect(await projected()).toBe(500); + expect(coordinator!.nextWakeAt()).not.toBeNull(); + await settle(2000); await quiet(); + expect(await projected()).toBe(501); + expect(await db.select().from(toolCallEvents).where(eq(toolCallEvents.reasonCode, "approved_action_executed"))).toEqual([]); + }); + + it("clears an abandoned projection cursor after empty reconstruction before the next write", async () => { + const backlog = await projectionBacklog(3); + const service = toolReviewProjectionService(db, input => backlog.reflect(input.actionRequestId)); + expect(await service.sweep(fixture.company.id, { maxRows: 1 })).toMatchObject({ scanned: 1, truncated: true }); + for (const id of backlog.cardByRequest.keys()) await backlog.reflect(id); + expect(await service.companies(fixture.company.id)).toEqual([]); + const firstId = [...backlog.cardByRequest.keys()].sort()[0]!; + await db.update(issueThreadInteractions).set({ result: sql`${issueThreadInteractions.result} - 'toolAction'` }) + .where(eq(issueThreadInteractions.id, backlog.cardByRequest.get(firstId)!)); + expect(await service.sweep(fixture.company.id, { maxRows: 500 })).toMatchObject({ scanned: 1, retry: false }); + }); + + it.each(["abort", "drain"] as const)("stops projection between rows on %s and resumes without losing cards", async mode => { + const backlog = await projectionBacklog(5), controller = new AbortController(); + const seen: string[] = []; let admitted = true; + const service = toolReviewProjectionService(db, async input => { + seen.push(input.actionRequestId); await backlog.reflect(input.actionRequestId); + if (seen.length === 1) { if (mode === "abort") controller.abort(); else admitted = false; } + }); + expect(await service.sweep(fixture.company.id, { maxRows: 500, signal: controller.signal, shouldContinue: () => admitted })) + .toMatchObject({ scanned: 1, retry: true, truncated: true }); + expect(seen).toHaveLength(1); + admitted = true; + expect(await service.sweep(fixture.company.id, { maxRows: 500 })).toMatchObject({ scanned: 4, retry: false }); + expect(new Set(seen).size).toBe(5); + }); + + it.each(["unprojectable", "failed"] as const)("continues beyond a full %s page before revisiting it", async mode => { + const backlog = await projectionBacklog(501); + const blocked = new Set([...backlog.cardByRequest.keys()].sort().slice(0, 500)), seen: string[] = []; + const service = toolReviewProjectionService(db, async input => { + seen.push(input.actionRequestId); + if (blocked.has(input.actionRequestId)) { if (mode === "failed") throw new Error("saved card unavailable"); return; } + await backlog.reflect(input.actionRequestId); + }); + const first = service.sweep(fixture.company.id, { maxRows: 500 }); + if (mode === "failed") await expect(first).rejects.toBeInstanceOf(AggregateError); + else expect(await first).toMatchObject({ scanned: 500, retry: true, truncated: true }); + expect(seen).toHaveLength(500); seen.length = 0; + expect(await service.sweep(fixture.company.id, { maxRows: 500 })).toMatchObject({ scanned: 1, retry: true, truncated: false }); + expect(seen).toHaveLength(1); expect(blocked.has(seen[0]!)).toBe(false); + }); + + it("does not starve later pages behind a card that cannot yet reflect its outcome", async () => { + const pending = await request(); await savedOutcome(pending, db, "failed"); + const [template] = await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.id, pending.interactionId!)); + const copies = Array.from({ length: 101 }, () => ({ ...template, id: randomUUID(), idempotencyKey: randomUUID(), + status: "accepted" as const, result: { version: 1 as const, outcome: "accepted" as const } })); + await db.insert(issueThreadInteractions).values(copies); + await db.insert(toolActionRequests).values(copies.map((card, index) => ({ ...pending, + id: `ffffffff-ffff-4fff-afff-${String(index).padStart(12, "0")}`, + interactionId: card.id, status: "failed" as const }))); + await startProjection(); + expect(coordinator!.nextWakeAt()).not.toBeNull(); + const cards = await db.select().from(issueThreadInteractions); + expect(cards.filter(card => (card.result as { toolAction?: { status: string } } | null)?.toolAction?.status === "failed")).toHaveLength(101); + await db.update(issueThreadInteractions).set({ addresseeAgentId: fixture.agent.id }).where(eq(issueThreadInteractions.id, pending.interactionId!)); + await issueThreadInteractionService(db).cancelPendingForDeletedAddressee(fixture.company.id, fixture.agent.id); + await settle(); await quiet(); + expect(await projection(pending)).toMatchObject({ status: "failed" }); + }); + + it.each([false, true])("reactivates when an administrative card mutation overwrites a settled projection (legacy %s)", async legacy => { + const pending = await request(); + if (legacy) { + const [card] = await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.id, pending.interactionId!)); + const payload = { ...card.payload } as Record; + delete payload.toolAction; delete payload.target; + await db.update(issueThreadInteractions).set({ payload }).where(eq(issueThreadInteractions.id, pending.interactionId!)); + } + await db.update(issueThreadInteractions).set({ addresseeAgentId: fixture.agent.id, + result: { version: 1, outcome: "accepted" } }).where(eq(issueThreadInteractions.id, pending.interactionId!)); + await savedOutcome(pending, db, "failed"); await startProjection(); await quiet(); + expect(await projection(pending)).toMatchObject({ status: "failed" }); + await issueThreadInteractionService(db).cancelPendingForDeletedAddressee(fixture.company.id, fixture.agent.id); + await settle(); await quiet(); + expect(await projection(pending)).toMatchObject({ status: "failed", errorCode: "saved_failure" }); + }); + }); + describe("interrupted review recovery worker", () => { async function startInterruption() { coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => !draining, diff --git a/server/src/index.ts b/server/src/index.ts index 50627307a54..bef68b441e7 100644 --- a/server/src/index.ts +++ b/server/src/index.ts @@ -1,3 +1,4 @@ +import { registerToolReviewProjectionWork } from "./services/tool-review-projection-work.js"; import { registerToolReviewInterruptionWork } from "./services/tool-review-interruption-work.js"; import { registerToolReviewRecoveryWork } from "./services/tool-review-recovery-work.js"; import { registerToolReviewExpiryWork } from "./services/tool-review-expiry-work.js"; @@ -1486,7 +1487,10 @@ async function startServerWithDatabaseTeardown( } else { await app.locals.toolGateway.settleInterruptedActionReviews(); } - return app.locals.toolGateway.sweepActionReviews({ includeExpiry: false, includeApproved: false, includeInterrupted: false }); + return config.heartbeatSchedulerEnabled + ? registerToolReviewProjectionWork(deliveryWork, { sweep: app.locals.toolGateway.repairActionReviewProjections, companies: app.locals.toolGateway.actionReviewProjectionCompanies }, + () => !isIdleTaskDrainActive() && !heartbeatSchedulerStopped && !isWarmStandby()).ready + : app.locals.toolGateway.repairActionReviewProjections(); }).catch((err: unknown) => logger.error({ err }, "startup tool review recovery failed")); await timeStartupRecovery("gateway_sessions", () => config.heartbeatSchedulerEnabled ? registerGatewayCredentialExpiryWork(deliveryWork, app.locals.toolGateway, @@ -1917,8 +1921,6 @@ async function startServerWithDatabaseTeardown( logger.error({ err }, "periodic tool connection health sweep failed"); })); - trackHeartbeatSchedulerWork(app.locals.toolGateway.sweepActionReviews({ includeExpiry: false, includeApproved: false, includeInterrupted: false }).catch((err: unknown) => logger.error({ err }, "tool review recovery failed"))); - if (isIdleTaskDrainActive() || heartbeatSchedulerStopped) return; if (!(await heartbeat.resolveSchedulingSuppression()).suppressed) { // Periodically reap orphaned runs (5-min staleness threshold) and make sure diff --git a/server/src/services/delivery-work-notifications.ts b/server/src/services/delivery-work-notifications.ts index 9c943677dac..8af5f57babe 100644 --- a/server/src/services/delivery-work-notifications.ts +++ b/server/src/services/delivery-work-notifications.ts @@ -9,6 +9,7 @@ export const DELIVERY_QUEUES = { executionStatus: "execution-status", executionDisposition: "execution-disposition", environmentCleanup: "environment-cleanup", + toolReviewProjection: "tool-review-projection", toolReviewInterruption: "tool-review-interruption", toolReviewRecovery: "tool-review-recovery", toolReviewExpiry: "tool-review-expiry", diff --git a/server/src/services/issue-thread-interactions.test.ts b/server/src/services/issue-thread-interactions.test.ts index e2c9ac62044..24e1489006f 100644 --- a/server/src/services/issue-thread-interactions.test.ts +++ b/server/src/services/issue-thread-interactions.test.ts @@ -14,7 +14,7 @@ type SelectRow = Record; function createSelectChain(rows: SelectRow[] | ((table: unknown) => SelectRow[])) { return { from(table: unknown) { - const selectedRows = typeof rows === "function" ? rows(table) : rows; + let selectedRows = typeof rows === "function" ? rows(table) : rows; const query = { innerJoin() { return query; @@ -25,6 +25,10 @@ function createSelectChain(rows: SelectRow[] | ((table: unknown) => SelectRow[]) for() { return query; }, + limit(count: number) { + selectedRows = selectedRows.slice(0, count); + return query; + }, then(callback: (rows: SelectRow[]) => unknown) { return Promise.resolve(callback(selectedRows)); }, @@ -292,7 +296,7 @@ describe("issueThreadInteractionService", () => { ]); }); - it("withdraws a pending interaction with attribution and rejects repeats", async () => { + it("withdraws an unlinked pending interaction with attribution and rejects repeats", async () => { const { issueThreadInteractionService } = await import("./issue-thread-interactions.js"); const interactionRow = { id: "interaction-withdraw", companyId: "company-1", issueId: "11111111-1111-4111-8111-111111111111", @@ -308,8 +312,7 @@ describe("issueThreadInteractionService", () => { expect(withdrawn.status).toBe("cancelled"); expect(withdrawn.result).toEqual({ version: 1, outcome: "withdrawn", reason: "Replanning" }); expect(withdrawn.resolvedByAgentId).toBe("agent-1"); - expect(state.toolActionRequestUpdates).toHaveLength(1); - expect(state.toolActionRequestUpdates[0]).toMatchObject({ status: "cancelled", resolvedByAgentId: "agent-1" }); + expect(state.toolActionRequestUpdates).toHaveLength(0); const resolvedState = createFakeDb({ interactionRow: { ...interactionRow, status: "accepted" } }); const resolvedSvc = issueThreadInteractionService(resolvedState.db as never); await expect(resolvedSvc.withdrawInteraction( @@ -388,7 +391,9 @@ describe("issueThreadInteractionService", () => { }, result: null, resolvedAt: null, createdAt: new Date("2026-07-25T10:00:00.000Z"), updatedAt: new Date("2026-07-25T10:00:00.000Z"), }; - const state = createFakeDb({ interactionRow }); + const state = createFakeDb({ interactionRow, parentRows: [{ + id: "33333333-3333-4333-8333-333333333333", companyId: "company-1", interactionId: interactionRow.id, + }] }); const svc = issueThreadInteractionService(state.db as never); const expired = await svc.expirePendingInteractionsForTerminalIssue( { id: interactionRow.issueId, companyId: "company-1", status: "cancelled" }, diff --git a/server/src/services/issue-thread-interactions.ts b/server/src/services/issue-thread-interactions.ts index 48ecf1d9dbe..44eb4391055 100644 --- a/server/src/services/issue-thread-interactions.ts +++ b/server/src/services/issue-thread-interactions.ts @@ -1073,8 +1073,22 @@ class InteractionResolvedConcurrentlyError extends Error { // tool_action_requests row. Administrative resolutions (withdraw, terminal-issue // expiry) must settle that row too, or the parked call stays approvable under // its own one-hour lifecycle after its card is gone. +async function hasLinkedToolActionRequests(db: Pick, companyId: string, interactionIds: string[]) { + if (interactionIds.length === 0) return false; + const [request] = await db.select({ id: toolActionRequests.id }).from(toolActionRequests) + .where(and(eq(toolActionRequests.companyId, companyId), inArray(toolActionRequests.interactionId, interactionIds))) + .limit(1); + return request !== undefined; +} + +async function notifyToolProjectionForInteractions(db: Pick, companyId: string, interactionIds: string[]) { + // The persisted link also covers legacy cards without current payload flags. + if (await hasLinkedToolActionRequests(db, companyId, interactionIds)) + await notifyDeliveryWork(db, DELIVERY_QUEUES.toolReviewProjection, companyId); +} + async function resolveLinkedToolActionRequests( - db: Pick, + db: Pick, interaction: Pick, outcome: { status: "expired" | "cancelled"; @@ -1083,7 +1097,8 @@ async function resolveLinkedToolActionRequests( now: Date; }, ) { - if (interaction.kind !== "request_confirmation") return; + if (interaction.kind !== "request_confirmation" || + !(await hasLinkedToolActionRequests(db, interaction.companyId, [interaction.id]))) return; await notifyToolReviewChange(db, interaction.companyId); await db .update(toolActionRequests) @@ -2240,6 +2255,7 @@ export function issueThreadInteractionService( }) : undefined; + if (lockedCurrent.kind === "request_confirmation") await notifyToolProjectionForInteractions(tx, lockedCurrent.companyId, [lockedCurrent.id]); const [updated] = await tx .update(issueThreadInteractions) .set({ @@ -2517,6 +2533,7 @@ export function issueThreadInteractionService( now, }); + if (lockedCurrent.kind === "request_confirmation") await notifyToolProjectionForInteractions(tx, lockedCurrent.companyId, [lockedCurrent.id]); const [resolved] = await tx .update(issueThreadInteractions) .set({ @@ -3273,6 +3290,7 @@ export function issueThreadInteractionService( const cancelled: IssueThreadInteraction[] = []; for (const row of rows) { const updated = await db.transaction(async (tx) => { + if (row.kind === "request_confirmation") await notifyToolProjectionForInteractions(tx, row.companyId, [row.id]); const [resolved] = await tx .update(issueThreadInteractions) .set({ @@ -3357,6 +3375,7 @@ export function issueThreadInteractionService( const expired: IssueThreadInteraction[] = []; for (const { row, replacementInteractionId } of supersededRows) { const updated = await db.transaction(async (tx) => { + if (row.kind === "request_confirmation") await notifyToolProjectionForInteractions(tx, row.companyId, [row.id]); const [updatedRow] = await tx .update(issueThreadInteractions) .set({ @@ -3776,6 +3795,19 @@ export function issueThreadInteractionService( data.kind === "ask_user_questions" ? buildSupersededByNewerInteractionResult(row.id) : buildSupersededByNewerRequestResult(row.id); + const siblingCondition = and( + eq(issueThreadInteractions.companyId, issue.companyId), + eq(issueThreadInteractions.issueId, issue.id), + eq(issueThreadInteractions.kind, data.kind), + eq(issueThreadInteractions.createdByAgentId, actor.agentId), + eq(issueThreadInteractions.status, "pending"), + ne(issueThreadInteractions.id, row.id), + ); + if (data.kind === "request_confirmation") { + // The issue lock above excludes concurrent interaction creation. + const siblings = await tx.select({ id: issueThreadInteractions.id }).from(issueThreadInteractions).where(siblingCondition); + await notifyToolProjectionForInteractions(tx, issue.companyId, siblings.map(sibling => sibling.id)); + } const supersededRows = await tx .update(issueThreadInteractions) .set({ @@ -3786,17 +3818,7 @@ export function issueThreadInteractionService( resolvedAt: now, updatedAt: now, }) - .where( - and( - eq(issueThreadInteractions.companyId, issue.companyId), - eq(issueThreadInteractions.issueId, issue.id), - eq(issueThreadInteractions.kind, data.kind), - eq(issueThreadInteractions.createdByAgentId, actor.agentId), - eq(issueThreadInteractions.status, "pending"), - ne(issueThreadInteractions.id, row.id), - - ), - ) + .where(siblingCondition) .returning(); for (const supersededRow of supersededRows) { await resolveLinkedToolActionRequests(tx, supersededRow, { @@ -4442,6 +4464,7 @@ export function issueThreadInteractionService( .delete(toolOauthStates) .where(eq(toolOauthStates.interactionId, row.id)); } + if (row.kind === "request_confirmation") await notifyToolProjectionForInteractions(tx, row.companyId, [row.id]); const [resolved] = await tx .update(issueThreadInteractions) .set({ @@ -4610,6 +4633,7 @@ export function issueThreadInteractionService( ); if (!sampleConfirmationRow) continue; const updatedInteractions = await db.transaction(async (tx) => { + await notifyToolProjectionForInteractions(tx, issue.companyId, confirmationRowIds); const updatedRows = await tx .update(issueThreadInteractions) .set({ diff --git a/server/src/services/tool-gateway.ts b/server/src/services/tool-gateway.ts index 2d94a361de2..4cacb30e47e 100644 --- a/server/src/services/tool-gateway.ts +++ b/server/src/services/tool-gateway.ts @@ -1,3 +1,4 @@ +import { toolReviewProjectionService } from "./tool-review-projection.js"; import { toolReviewInterruptionService } from "./tool-review-interruption.js"; import { bindVerifiedToolApprovalArguments, claimToolTestApproval, releaseToolApproval, persistToolTestOutcome, startToolInvocation, type ToolApprovalClaim } from "./tool-approval-execution.js"; import { approvedToolReviewCompanies, prepareApprovedToolReview, recoverApprovedToolReviews } from "./tool-review-recovery.js"; @@ -2398,6 +2399,11 @@ export function createToolGatewayService( ? "stale_target" : null; if (!outcome) return; + const projection = asRecord(currentResult?.toolAction); + if (projection?.status === (input.status === "cancelled" ? "expired" : input.status) + && projection.errorCode === (input.errorCode ?? null) + && projection.errorMessage === (input.errorMessage ?? null) + && projection.resultSummary === (input.resultSummary ?? null)) return false; const now = new Date(); await tx @@ -8125,10 +8131,10 @@ export function createToolGatewayService( return { projectId: issue.projectId }; } const expiredAt = new Date(); - await db + await writeToolReviewChange(db, claimed.companyId, tx => tx .update(toolActionRequests) .set({ status: "expired", resolvedAt: expiredAt, updatedAt: expiredAt }) - .where(eq(toolActionRequests.id, claimed.id)); + .where(eq(toolActionRequests.id, claimed.id))); await reflectToolActionInteractionLifecycle({ actionRequestId: claimed.id, status: "expired", @@ -8820,6 +8826,7 @@ export function createToolGatewayService( }; } + const reviewProjection = toolReviewProjectionService(db, reflectToolActionInteractionLifecycle); const reviewInterruption = toolReviewInterruptionService(db, async settled => { void emitConnectionInvoked(db, settled.invocationId); await reflectToolActionInteractionLifecycle(settled); @@ -9917,6 +9924,8 @@ export function createToolGatewayService( return buildTestCallStatus(actionRequest, invocation); }, + repairActionReviewProjections: reviewProjection.sweep, + actionReviewProjectionCompanies: reviewProjection.companies, settleInterruptedActionReviews: reviewInterruption.sweep, nextActionReviewInterruptionAt: reviewInterruption.next, sweepExpiredActionReviews: reviewExpiry.sweep, @@ -9951,40 +9960,7 @@ export function createToolGatewayService( }, async sweepActionReviews(input: { includeExpiry?: boolean; includeApproved?: boolean; includeInterrupted?: boolean } = {}) { - // A process may stop between persisting a provider outcome and updating the - // feed projection. Reconcile from authoritative rows before delivering it. - const unreflected = await db - .select({ request: toolActionRequests, invocation: toolInvocations }) - .from(toolActionRequests) - .innerJoin( - issueThreadInteractions, - eq(issueThreadInteractions.id, toolActionRequests.interactionId), - ) - .innerJoin( - toolInvocations, - eq(toolInvocations.id, toolActionRequests.invocationId), - ) - .where( - and( - inArray(toolActionRequests.status, [ - "executed", - "failed", - "expired", - "cancelled", - ]), - sql`coalesce(${issueThreadInteractions.result}->'toolAction'->>'status', '') <> case when ${toolActionRequests.status} = 'cancelled' then 'expired' else ${toolActionRequests.status} end`, - ), - ) - .limit(100); - for (const { request, invocation } of unreflected) - await reflectToolActionInteractionLifecycle({ - actionRequestId: request.id, - status: request.status as - "executed" | "failed" | "expired" | "cancelled", - errorCode: invocation.errorCode, - errorMessage: invocation.errorMessage, - resultSummary: invocation.resultSummary?.summary, - }); + await reviewProjection.sweep(); let scanned = input.includeExpiry === false ? 0 : (await reviewExpiry.sweep()).scanned; if (input.includeApproved !== false) scanned += (await this.recoverApprovedActionReviews()).scanned; if (input.includeInterrupted !== false) scanned += (await reviewInterruption.sweep()).scanned; diff --git a/server/src/services/tool-review-projection-work.ts b/server/src/services/tool-review-projection-work.ts new file mode 100644 index 00000000000..b400f19f615 --- /dev/null +++ b/server/src/services/tool-review-projection-work.ts @@ -0,0 +1,33 @@ +import type { createDeliveryWorkCoordinator } from "./delivery-work-coordinator.js"; +import { DELIVERY_QUEUES } from "./delivery-work-notifications.js"; +import { registerScopedDeadlineWork } from "./scoped-deadline-work.js"; +import type { toolReviewProjectionService } from "./tool-review-projection.js"; + +export function registerToolReviewProjectionWork( + coordinator: ReturnType, + service: ReturnType, + canRun: () => boolean, +) { + const unresolvedPasses = new Map(); + return registerScopedDeadlineWork(coordinator, { + queue: DELIVERY_QUEUES.toolReviewProjection, + batchSize: 1, + decodeScope: hint => hint === "*" ? undefined : hint, + matches: (entry, companyId?: string) => companyId === undefined || entry.companyId === companyId, + load: async (companyId?: string) => { + const rows = companyId ? [{ companyId }] : await service.companies(); + for (const scope of unresolvedPasses.keys()) { + if (!companyId || scope === companyId) unresolvedPasses.delete(scope); + } + return rows.map(row => ({ ...row, id: row.companyId, dueAt: Date.now() })); + }, + check: async (entry, signal) => { + const result = await service.sweep(entry.companyId, { maxRows: 500, signal, shouldContinue: canRun }); + if (!result.retry) { unresolvedPasses.delete(entry.id); return null; } + if (result.truncated) return { ...entry, dueAt: Date.now() + 1000 }; + const count = Math.min((unresolvedPasses.get(entry.id) ?? 0) + 1, 5); + unresolvedPasses.set(entry.id, count); + return { ...entry, dueAt: Date.now() + Math.min(300_000, 30_000 * 2 ** (count - 1)) }; + }, + }, canRun); +} diff --git a/server/src/services/tool-review-projection.ts b/server/src/services/tool-review-projection.ts new file mode 100644 index 00000000000..32644929cac --- /dev/null +++ b/server/src/services/tool-review-projection.ts @@ -0,0 +1,77 @@ +import { and, asc, eq, gt, inArray, sql } from "drizzle-orm"; +import { issueThreadInteractions, toolActionRequests, toolInvocations, type Db } from "@paperclipai/db"; + +export function toolReviewProjectionService(db: Db, reflect: (input: { + actionRequestId: string; + status: "executed" | "failed" | "expired" | "cancelled"; + errorCode: string | null; + errorMessage: string | null; + resultSummary: string | null; +}) => Promise) { + const mismatch = and( + inArray(toolActionRequests.status, ["executed", "failed", "expired", "cancelled"]), + sql`coalesce(${issueThreadInteractions.result}->'toolAction'->>'status', '') <> case when ${toolActionRequests.status} = 'cancelled' then 'expired' else ${toolActionRequests.status} end`, + ); + const candidates = (companyId?: string, cursor?: string) => db + .select({ request: toolActionRequests, invocation: toolInvocations }) + .from(toolActionRequests) + .innerJoin(issueThreadInteractions, eq(issueThreadInteractions.id, toolActionRequests.interactionId)) + .innerJoin(toolInvocations, eq(toolInvocations.id, toolActionRequests.invocationId)) + .where(and(mismatch, companyId ? eq(toolActionRequests.companyId, companyId) : undefined, + cursor ? gt(toolActionRequests.id, cursor) : undefined)) + .orderBy(asc(toolActionRequests.id)); + + const continuations = new Map(); + return { + async companies(companyId?: string) { + const rows = await db.select({ companyId: toolActionRequests.companyId }).from(toolActionRequests) + .innerJoin(issueThreadInteractions, eq(issueThreadInteractions.id, toolActionRequests.interactionId)) + .innerJoin(toolInvocations, eq(toolInvocations.id, toolActionRequests.invocationId)) + .where(and(mismatch, companyId ? eq(toolActionRequests.companyId, companyId) : undefined)) + .groupBy(toolActionRequests.companyId); + const pending = new Set(rows.map(row => row.companyId)); + for (const scope of continuations.keys()) { + if (companyId && scope !== companyId) continue; + if (scope === "*" ? rows.length === 0 : !pending.has(scope)) continuations.delete(scope); + } + return rows; + }, + async sweep(companyId?: string, options: { + maxRows?: number; + signal?: AbortSignal; + shouldContinue?: () => boolean; + } = {}) { + const maxRows = options.maxRows ?? Infinity; + const scope = companyId ?? "*"; + let cursor = maxRows === Infinity ? undefined : continuations.get(scope); + const resumed = cursor !== undefined; + let scanned = 0, completed = false; + const canContinue = () => !options.signal?.aborted && (options.shouldContinue?.() ?? true); + const failures: unknown[] = []; + while (scanned < maxRows && canContinue()) { + const pageSize = Math.min(100, maxRows - scanned); + const rows = await candidates(companyId, cursor).limit(pageSize); + for (const { request, invocation } of rows) { + if (!canContinue()) break; + try { + await reflect({ actionRequestId: request.id, + status: request.status as "executed" | "failed" | "expired" | "cancelled", + errorCode: invocation.errorCode, errorMessage: invocation.errorMessage, + resultSummary: invocation.resultSummary?.summary ?? null }); + } catch (error) { failures.push(error); } + scanned++; + cursor = request.id; + } + if (!canContinue()) break; + if (rows.length < pageSize) { completed = true; break; } + } + if (maxRows !== Infinity) { + if (completed) continuations.delete(scope); + else if (cursor) continuations.set(scope, cursor); + } + if (failures.length) throw new AggregateError(failures, "Tool review projection repair failed"); + return { scanned, truncated: !completed, + retry: !completed || ((scanned > 0 || resumed) && (await candidates(companyId).limit(1)).length > 0) }; + }, + }; +} diff --git a/server/src/services/tool-review-work-notifications.ts b/server/src/services/tool-review-work-notifications.ts index 44957fefc1b..1ed9dfe7520 100644 --- a/server/src/services/tool-review-work-notifications.ts +++ b/server/src/services/tool-review-work-notifications.ts @@ -5,6 +5,7 @@ export async function notifyToolReviewChange(transaction: object, companyId: str await notifyDeliveryWork(transaction, DELIVERY_QUEUES.toolReviewExpiry, companyId); await notifyDeliveryWork(transaction, DELIVERY_QUEUES.toolReviewRecovery, companyId); await notifyDeliveryWork(transaction, DELIVERY_QUEUES.toolReviewInterruption, companyId); + await notifyDeliveryWork(transaction, DELIVERY_QUEUES.toolReviewProjection, companyId); } export function writeToolReviewChange(db: Db, companyId: string, write: (transaction: Db) => Promise): Promise {