From 5db5734774a408c0e70a859bc38926009832d5a0 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sat, 24 Oct 2026 09:28:17 -0700 Subject: [PATCH 001/110] fix(plugins): scope operational reads to the caller's companies (#17435) ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - One instance hosts many companies, and company boundaries are the main isolation contract > - Plugin worker logs, job runs and webhook deliveries store a `company_id` attribution (NULL for instance scope) > - The plugin diagnostics routes checked board org access, but they did not filter those rows by the caller's companies > - A board member of one company could therefore read another company's log messages, run errors and delivery errors > - This pull request scopes those reads to the caller's companies and keeps the instance-wide view for instance administrators > - The benefit is that plugin diagnostics obey the same tenant boundary as the rest of the plugin routes ## Linked Issues or Issue Description **What happened?** A board user who is a member of only company A could read plugin operational rows attributed to company B. `GET /api/plugins/:pluginId/logs` returned log rows with `company_id` values outside the caller's companies. `GET /api/plugins/:pluginId/jobs/:jobId/runs` returned other companies' run rows, including their error text and run logs. `GET /api/plugins/:pluginId/dashboard` returned other companies' recent job runs and webhook deliveries. The routes only required board org access and filtered on plugin id or job id. **Expected behavior** A board member sees only operational rows for companies the member can access. An instance administrator (and the local implicit board) keeps the instance-wide view, which includes instance-scope rows where `company_id` is NULL. **Steps to reproduce** 1. Create two companies, A and B, on an authenticated instance. 2. Install a plugin and produce a log row, a job run and a webhook delivery for company B. 3. Sign in as a board user who is a member of company A only. 4. Call `GET /api/plugins/:pluginId/logs`, `GET /api/plugins/:pluginId/jobs/:jobId/runs` and `GET /api/plugins/:pluginId/dashboard`. Before this change, the responses included company B rows. After this change, they do not. **Paperclip version or commit** Reproduced on `2e6d3f7` (`master`, 2026-10-24). The report came from a scoped security audit of `52a66af29ddccf1fcac25f1f6efa9e9958e11fbd`. **Deployment mode** Self-hosted server, authenticated mode. The defect does not depend on the deployment mode, but `local_trusted` always yields an instance-admin actor and hides it. ## What Changed - Added `pluginOperationalReadCompanyIds()` in `server/src/routes/plugins.ts`. It returns `null` for instance admins and the local implicit board, and the actor's company ids for every other board actor. - Scoped `GET /api/plugins/:pluginId/logs` with `inArray(pluginLogs.companyId, companyIds)`. - Scoped `GET /api/plugins/:pluginId/jobs/:jobId/runs` through a new optional `companyIds` argument on `pluginJobStore.listRunsByJob()`. - Scoped the dashboard's recent job runs through the same optional argument on `pluginJobStore.listRunsByPlugin()`, and scoped its webhook delivery query. - Added `server/src/__tests__/plugin-operational-reads-tenant-scope.test.ts`. It starts embedded Postgres, seeds two companies plus instance-scope rows, and asserts the single-company view and the instance-admin view for all three routes. ## Verification - Red first: with the test added and the route unchanged, 3 of 4 cases failed and the response contained the company B rows. - Green after the fix: `pnpm exec vitest run server/src/__tests__/plugin-operational-reads-tenant-scope.test.ts` passed (4 tests). - Related suites: `pnpm exec vitest run server/src/__tests__/plugin-routes-authz.test.ts server/src/__tests__/plugin-tenant-isolation.test.ts server/src/__tests__/plugin-install-route-security.test.ts` passed (59 tests). - Typecheck: `pnpm --filter @paperclipai/server typecheck` passed. ## Risks - Behavior change for non-admin board members: they no longer see instance-scope rows (`company_id` NULL) or rows for companies they cannot access. Instance administrators keep the full view. For a single-company instance the visible rows are the same, except instance-scope rows. - No schema or migration change. No API shape change. Row-level filtering only. - A plugin that writes diagnostics without a `company_id` will show fewer rows to non-admin users. That is the intended tenant boundary. ## Model Used - Provider: OpenRouter - Model: `deepseek/deepseek-v4.1-flash-1017` (DeepSeek V4.1 Flash) - Harness: OpenCode, with tool use, code execution, and multi-agent delegation - Reasoning: enabled (thinking mode) - Context window: not exposed by the harness ## 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 - [ ] 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 --- ...gin-operational-reads-tenant-scope.test.ts | 244 ++++++++++++++++++ server/src/routes/plugins.ts | 48 +++- server/src/services/plugin-job-store.ts | 25 +- 3 files changed, 311 insertions(+), 6 deletions(-) create mode 100644 server/src/__tests__/plugin-operational-reads-tenant-scope.test.ts diff --git a/server/src/__tests__/plugin-operational-reads-tenant-scope.test.ts b/server/src/__tests__/plugin-operational-reads-tenant-scope.test.ts new file mode 100644 index 00000000000..1f9b4db1c49 --- /dev/null +++ b/server/src/__tests__/plugin-operational-reads-tenant-scope.test.ts @@ -0,0 +1,244 @@ +import { randomUUID } from "node:crypto"; +import express from "express"; +import request from "supertest"; +import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest"; +import { + companies, + createDb, + pluginJobRuns, + pluginJobs, + pluginLogs, + pluginWebhookDeliveries, + plugins, +} from "@paperclipai/db"; +import { errorHandler } from "../middleware/index.js"; +import { pluginRoutes } from "../routes/plugins.js"; +import { pluginJobStore } from "../services/plugin-job-store.js"; +import { + getEmbeddedPostgresTestSupport, + startEmbeddedPostgresTestDatabase, +} from "./helpers/embedded-postgres.js"; + +/** + * Regression coverage for tenant scoping on plugin operational reads. + * + * `plugin_logs`, `plugin_job_runs` and `plugin_webhook_deliveries` all carry a + * `company_id` attribution (NULL for instance-scope rows). A board member of + * one company must not be able to read rows attributed to another company + * through the plugin diagnostics routes; instance administrators keep the + * instance-wide view. + */ + +const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport(); +const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip; + +if (!embeddedPostgresSupport.supported) { + console.warn( + `Skipping plugin operational-read tenant-scope tests on this host: ${embeddedPostgresSupport.reason ?? "unsupported environment"}`, + ); +} + +function issuePrefix(id: string) { + return `T${id.replace(/-/g, "").slice(0, 6).toUpperCase()}`; +} + +type Actor = { + type: "board"; + source: string; + userId: string; + companyIds: string[]; + memberships: Array<{ companyId: string; membershipRole: string; status: string }>; + isInstanceAdmin: boolean; +}; + +function buildApp(actor: Actor, db: ReturnType) { + const app = express(); + app.use(express.json()); + app.use((req, _res, next) => { + (req as unknown as { actor: Actor }).actor = actor; + next(); + }); + app.use( + "/api", + pluginRoutes( + db, + {} as never, + { jobStore: pluginJobStore(db) } as never, + undefined, + undefined, + undefined, + ), + ); + app.use(errorHandler); + return app; +} + +describeEmbeddedPostgres("plugin operational reads are company-scoped", () => { + let db!: ReturnType; + let tempDb: Awaited> | null = null; + + const companyA = randomUUID(); + const companyB = randomUUID(); + const pluginId = randomUUID(); + const jobId = randomUUID(); + + const logA = randomUUID(); + const logB = randomUUID(); + const logInstance = randomUUID(); + + const runA = randomUUID(); + const runB = randomUUID(); + const runInstance = randomUUID(); + + const deliveryA = randomUUID(); + const deliveryB = randomUUID(); + const deliveryInstance = randomUUID(); + + const boardA: Actor = { + type: "board", + source: "session", + userId: `user-${randomUUID()}`, + companyIds: [companyA], + memberships: [{ companyId: companyA, membershipRole: "owner", status: "active" }], + isInstanceAdmin: false, + }; + + const instanceAdmin: Actor = { + type: "board", + source: "session", + userId: `admin-${randomUUID()}`, + companyIds: [], + memberships: [], + isInstanceAdmin: true, + }; + + beforeAll(async () => { + tempDb = await startEmbeddedPostgresTestDatabase("paperclip-plugin-operational-reads-"); + db = createDb(tempDb.connectionString); + + await db.insert(companies).values([ + { id: companyA, name: `Company A ${companyA}`, issuePrefix: issuePrefix(companyA) }, + { id: companyB, name: `Company B ${companyB}`, issuePrefix: issuePrefix(companyB) }, + ]); + + await db.insert(plugins).values({ + id: pluginId, + pluginKey: "paperclip.operational-reads-test", + packageName: "@paperclipai/plugin-operational-reads-test", + version: "0.0.1", + apiVersion: 1, + categories: ["automation"], + manifestJson: { + id: "paperclip.operational-reads-test", + apiVersion: 1, + name: "Operational reads test", + version: "0.0.1", + entrypoints: {}, + capabilities: [], + } as never, + status: "ready", + }); + + await db.insert(pluginJobs).values({ + id: jobId, + pluginId, + jobKey: "sync", + schedule: "0 * * * *", + }); + + const base = Date.now(); + await db.insert(pluginLogs).values([ + { id: logA, pluginId, companyId: companyA, level: "info", message: "company A log", createdAt: new Date(base) }, + { id: logB, pluginId, companyId: companyB, level: "warn", message: "company B secret log", createdAt: new Date(base + 1_000) }, + { id: logInstance, pluginId, companyId: null, level: "debug", message: "instance log", createdAt: new Date(base + 2_000) }, + ]); + + await db.insert(pluginJobRuns).values([ + { id: runA, jobId, pluginId, companyId: companyA, trigger: "manual", status: "succeeded", createdAt: new Date(base) }, + { id: runB, jobId, pluginId, companyId: companyB, trigger: "manual", status: "failed", error: "company B failure", logs: ["company B run log"], createdAt: new Date(base + 1_000) }, + { id: runInstance, jobId, pluginId, companyId: null, trigger: "scheduled", status: "succeeded", createdAt: new Date(base + 2_000) }, + ]); + + await db.insert(pluginWebhookDeliveries).values([ + { id: deliveryA, pluginId, companyId: companyA, webhookKey: "hook", status: "succeeded", payload: { who: "A" }, createdAt: new Date(base) }, + { id: deliveryB, pluginId, companyId: companyB, webhookKey: "hook", status: "failed", error: "company B delivery error", payload: { who: "B" }, createdAt: new Date(base + 1_000) }, + { id: deliveryInstance, pluginId, companyId: null, webhookKey: "hook", status: "succeeded", payload: { who: "instance" }, createdAt: new Date(base + 2_000) }, + ]); + }, 20_000); + + afterEach(async () => { + // Fixtures are seeded once for the suite; nothing mutates them. + }); + + afterAll(async () => { + await db.delete(pluginWebhookDeliveries); + await db.delete(pluginJobRuns); + await db.delete(pluginJobs); + await db.delete(pluginLogs); + await db.delete(plugins); + await db.delete(companies); + await db.$client.end({ timeout: 1 }).catch(() => {}); + await tempDb?.cleanup(); + tempDb = null; + }); + + it("returns only the caller's company logs to a single-company board member", async () => { + const app = buildApp(boardA, db); + + const res = await request(app).get(`/api/plugins/${pluginId}/logs`); + + expect(res.status).toBe(200); + expect(res.body.map((row: { id: string }) => row.id)).toEqual([logA]); + expect(res.body[0].companyId).toBe(companyA); + expect(JSON.stringify(res.body)).not.toContain("company B secret log"); + }); + + it("returns only the caller's company job runs to a single-company board member", async () => { + const app = buildApp(boardA, db); + + const res = await request(app).get(`/api/plugins/${pluginId}/jobs/${jobId}/runs`); + + expect(res.status).toBe(200); + expect(res.body.map((row: { id: string }) => row.id)).toEqual([runA]); + expect(JSON.stringify(res.body)).not.toContain("company B failure"); + }); + + it("scopes dashboard job runs and webhook deliveries to the caller's company", async () => { + const app = buildApp(boardA, db); + + const res = await request(app).get(`/api/plugins/${pluginId}/dashboard`); + + expect(res.status).toBe(200); + expect(res.body.recentJobRuns.map((row: { id: string }) => row.id)).toEqual([runA]); + expect(res.body.recentWebhookDeliveries.map((row: { id: string }) => row.id)).toEqual([ + deliveryA, + ]); + expect(JSON.stringify(res.body)).not.toContain("company B"); + }); + + it("keeps the instance-wide view for instance administrators", async () => { + const app = buildApp(instanceAdmin, db); + + const logs = await request(app).get(`/api/plugins/${pluginId}/logs`); + const runs = await request(app).get(`/api/plugins/${pluginId}/jobs/${jobId}/runs`); + const dashboard = await request(app).get(`/api/plugins/${pluginId}/dashboard`); + + expect(logs.status).toBe(200); + expect(logs.body.map((row: { id: string }) => row.id)).toEqual([logInstance, logB, logA]); + + expect(runs.status).toBe(200); + expect(runs.body.map((row: { id: string }) => row.id)).toEqual([runInstance, runB, runA]); + + expect(dashboard.status).toBe(200); + expect(dashboard.body.recentJobRuns.map((row: { id: string }) => row.id)).toEqual([ + runInstance, + runB, + runA, + ]); + expect(dashboard.body.recentWebhookDeliveries.map((row: { id: string }) => row.id)).toEqual([ + deliveryInstance, + deliveryB, + deliveryA, + ]); + }); +}); diff --git a/server/src/routes/plugins.ts b/server/src/routes/plugins.ts index 3071e30f3c9..9c1a82df448 100644 --- a/server/src/routes/plugins.ts +++ b/server/src/routes/plugins.ts @@ -28,7 +28,7 @@ import { authorizationService } from "../services/authorization.js"; import { fileURLToPath } from "node:url"; import { Router } from "express"; import type { Request, Response } from "express"; -import { and, desc, eq, gte } from "drizzle-orm"; +import { and, desc, eq, gte, inArray } from "drizzle-orm"; import type { Db } from "@paperclipai/db"; import { agents, @@ -697,6 +697,27 @@ export function pluginRoutes( await issuesSvc.assertCheckoutOwner(issueId, req.actor.agentId, runId); } + /** + * Company ids that bound tenant-attributed plugin reads. + * + * `plugin_logs`, `plugin_job_runs` and `plugin_webhook_deliveries` carry a + * `company_id` attribution (NULL for instance-scope rows). Instance + * administrators (and the local implicit board) keep the instance-wide view; + * every other board actor is restricted to its own companies, so a member of + * one company cannot read another company's operational rows. + * + * Returns `null` for the unscoped instance-wide view. + */ + function pluginOperationalReadCompanyIds(req: Request): string[] | null { + if (req.actor.type !== "board") { + return []; + } + if (req.actor.source === "local_implicit" || req.actor.isInstanceAdmin) { + return null; + } + return req.actor.companyIds ?? []; + } + async function resolvePluginAuditCompanyIds(req: Request): Promise { if (typeof (db as { select?: unknown }).select === "function") { const rows = await db @@ -2220,7 +2241,16 @@ export function pluginRoutes( const level = req.query.level as string | undefined; const since = req.query.since as string | undefined; + const companyIds = pluginOperationalReadCompanyIds(req); + if (companyIds && companyIds.length === 0) { + res.json([]); + return; + } + const conditions = [eq(pluginLogs.pluginId, plugin.id)]; + if (companyIds) { + conditions.push(inArray(pluginLogs.companyId, companyIds)); + } if (level) { conditions.push(eq(pluginLogs.level, level)); } @@ -2649,7 +2679,11 @@ export function pluginRoutes( } try { - const runs = await jobDeps.jobStore.listRunsByJob(jobId, limit); + const runs = await jobDeps.jobStore.listRunsByJob( + jobId, + limit, + pluginOperationalReadCompanyIds(req), + ); res.json(runs); } catch (err) { const message = err instanceof Error ? err.message : String(err); @@ -3033,6 +3067,8 @@ export function pluginRoutes( return; } + const companyIds = pluginOperationalReadCompanyIds(req); + // --- Worker diagnostics --- let worker: { status: string; @@ -3080,7 +3116,7 @@ export function pluginRoutes( if (jobDeps) { try { - const runs = await jobDeps.jobStore.listRunsByPlugin(plugin.id, undefined, 10); + const runs = await jobDeps.jobStore.listRunsByPlugin(plugin.id, undefined, 10, companyIds); // Also fetch job definitions so we can include jobKey const jobs = await jobDeps.jobStore.listJobs(plugin.id); const jobKeyMap = new Map(jobs.map((j) => [j.id, j.jobKey])); @@ -3117,6 +3153,10 @@ export function pluginRoutes( }> = []; try { + const deliveryConditions = [eq(pluginWebhookDeliveries.pluginId, plugin.id)]; + if (companyIds) { + deliveryConditions.push(inArray(pluginWebhookDeliveries.companyId, companyIds)); + } const deliveries = await db .select({ id: pluginWebhookDeliveries.id, @@ -3129,7 +3169,7 @@ export function pluginRoutes( createdAt: pluginWebhookDeliveries.createdAt, }) .from(pluginWebhookDeliveries) - .where(eq(pluginWebhookDeliveries.pluginId, plugin.id)) + .where(and(...deliveryConditions)) .orderBy(desc(pluginWebhookDeliveries.createdAt)) .limit(10); diff --git a/server/src/services/plugin-job-store.ts b/server/src/services/plugin-job-store.ts index f5fdbce1a42..bd590a1f882 100644 --- a/server/src/services/plugin-job-store.ts +++ b/server/src/services/plugin-job-store.ts @@ -30,7 +30,7 @@ * @see PLUGIN_SPEC.md §21.3 — `plugin_jobs` / `plugin_job_runs` tables */ -import { and, desc, eq } from "drizzle-orm"; +import { and, desc, eq, inArray } from "drizzle-orm"; import type { Db } from "@paperclipai/db"; import { plugins, pluginJobs, pluginJobRuns } from "@paperclipai/db"; import type { @@ -422,15 +422,26 @@ export function pluginJobStore(db: Db) { * * @param jobId - UUID of the job * @param limit - Maximum number of rows to return (default: 50) + * @param companyIds - Optional tenant scope. `null`/omitted keeps the + * instance-wide view (used by instance administrators); an array limits + * rows to those companies; an empty array returns no rows. */ async listRunsByJob( jobId: string, limit = 50, + companyIds: string[] | null = null, ): Promise<(typeof pluginJobRuns.$inferSelect)[]> { + if (companyIds && companyIds.length === 0) { + return []; + } + const conditions = [eq(pluginJobRuns.jobId, jobId)]; + if (companyIds) { + conditions.push(inArray(pluginJobRuns.companyId, companyIds)); + } return db .select() .from(pluginJobRuns) - .where(eq(pluginJobRuns.jobId, jobId)) + .where(and(...conditions)) .orderBy(desc(pluginJobRuns.createdAt)) .limit(limit); }, @@ -441,16 +452,26 @@ export function pluginJobStore(db: Db) { * @param pluginId - UUID of the owning plugin * @param status - Optional status filter * @param limit - Maximum number of rows to return (default: 50) + * @param companyIds - Optional tenant scope. `null`/omitted keeps the + * instance-wide view (used by instance administrators); an array limits + * rows to those companies; an empty array returns no rows. */ async listRunsByPlugin( pluginId: string, status?: PluginJobRunStatus, limit = 50, + companyIds: string[] | null = null, ): Promise<(typeof pluginJobRuns.$inferSelect)[]> { + if (companyIds && companyIds.length === 0) { + return []; + } const conditions = [eq(pluginJobRuns.pluginId, pluginId)]; if (status) { conditions.push(eq(pluginJobRuns.status, status)); } + if (companyIds) { + conditions.push(inArray(pluginJobRuns.companyId, companyIds)); + } return db .select() .from(pluginJobRuns) From d1fdfced9d2899570d58f8ded3c4b4e70dc3f4d5 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sat, 24 Oct 2026 09:34:10 -0700 Subject: [PATCH 002/110] feat(evals): route Runner sessions through a controller gateway (#17440) ## Thinking Path > - Paperclip manages AI agents and their work. > - Runner Evals test provider behavior against a mock control plane. > - A campaign budget needs to observe and admit each provider request. > - The existing eval CLI does not select the provider-home mode needed for a controller-assigned route. > - A proxy URL alone therefore cannot establish controlled Codex routing. > - This change adds an explicit route with an isolated home and retained identity. > - The controller can use that route as the basis for request accounting and admission. ## Linked Issues or Issue Description **What happened?** The direct Runner eval CLI passes the ambient environment to the native transport. The transport deliberately removes an environment-only preconfigured-home marker unless its explicit option is also set. This prevents a controller from assigning a Codex gateway through that marker alone. **Expected behavior** A controller can explicitly route a supported eval attempt through its local proxy. The provider receives the proxy token and isolated configuration. The artifact identifies the assigned route on success and failure. Ordinary direct runs keep their current path. **Steps to reproduce** Run the new CLI tests for `--gateway-config`. They validate the descriptor, inspect the actual transport inputs and provider sanitizers, and check retained artifacts and owned-home cleanup. The local probe also ran built native Codex and ACPX Claude against a fake loopback API using only synthetic credentials. Related request-accounting work: https://github.com/paperclipai/paperclip/pull/17432. ## What Changed - Add an explicit gateway descriptor bound to the requested provider, exact model, campaign, execution, and attempt. - Accept only the controller's IPv4 loopback URL and a separate proxy token. - Create a fresh provider home for native Codex and ACPX Claude. Exclude ambient provider credentials, subscription logins, proxies, and startup hooks. - Retain route identity and descriptor hash in successful and failed artifacts. Remove the owned home in finalization. - Document the CLI contract and its limits. The Runner eval CLI owns this behavior. It uses the existing native preconfigured-home contract. Production routing, permissions, and provider protocols are unchanged. ## Verification - Initial verification passed 56 focused gateway/CLI tests and 246 CLI and adjacent provider-isolation tests. After the admission repair, all 247 CLI and adjacent provider-isolation tests passed, with TypeScript checks and build passing again. - Runner TypeScript checks and build passed. - The native daemon rebuilt from the candidate base with locked, offline dependencies. - Local fake-API probe: six authenticated Responses requests from native Codex and six authenticated Messages requests from ACPX Claude reached the assigned endpoint. Claude also made an unauthenticated hello check. The final commit retained both route artifacts. All 27 retained files were scanned for the synthetic proxy token and contained none. Both temporary homes were removed, and all four recorded provider/daemon PIDs were absent after exit. - The fake API intentionally rejected inference. Codex retained a failed turn; Claude retained a timeout. These are route observations, not passing semantic evals or live provider qualification. No paid provider calls ran. - The first focused command used the wrong directory and discovered no tests. It was corrected before the successful runs above. - Full Runner validation: 3,967 tests passed, 13 skipped, and five failed in three unchanged installation and native-settlement files. The failures were two installation timeouts and three retained-cleanup settlement failures. One isolated run passed all 109 applicable tests with six skips. This shows recovery, not a proven cause for the original five failures; those remain retained. Hosted [CI 40111220754](https://github.com/paperclipai/paperclip/actions/runs/40111220754) passed on final commit `a5c47b64e56c1228fca718b72a81ddc3b1d185a4`, including repository typecheck, build, tests and Runner checks. All 57 checks passed or were neutral/skipped, and the legacy status passed. Greptile and Paperclip reviews both scored 5/5 on that commit; no findings remain unresolved. - Rebased onto current master `71c04c0bfb205cc9e7f7bc20c29fd76051b44cc4`. Its added change concerns server cleanup; Runner source is unchanged. - An actual ACPX Codex probe failed before reaching the fake API. Review and source inspection confirmed that Runner deliberately rejects its preconfigured home to protect Runner state. This route is now rejected before service creation. Both explicit and default ACPX Codex admission regressions failed before the repair. The unsupported lane is not presented as qualified. ## Risks This is an explicit new CLI route. Unsupported providers fail before service creation. Upstream route is a controller declaration, not independent billing evidence. The local probe saw six Codex requests where legacy usage counted one, so the controller's request ledger must remain the budget source. Campaign allocation, proxy lifecycle, hosted workflow wiring, dedicated OTLP relay routing, and paid qualification are separate remaining integration steps. This PR enables none of those schedules. ## Model Used OpenAI Codex, GPT-6 family, with reasoning, tool use, and code execution. The exact serving model ID and context-window size 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, including the information available in this session - [x] I checked ROADMAP.md; this is eval infrastructure, not a competing core feature - [x] I searched for duplicate PRs for this exact route change - [x] I described the issue in-PR using the bug template labels - [x] I have not referenced internal or instance-local issues - [x] My branch describes the change and contains no internal issue ID - [x] Relevant focused tests pass - [x] I added tests for the new contract and lifecycle - [x] I updated the relevant documentation - [x] I described the risks and unqualified behavior - [x] All current-head Paperclip CI gates are green - [x] Current-head Greptile is 5/5 with no unresolved findings - [x] I will address review findings before merge --------- Co-authored-by: Paperclip --- .../docs/runner-protocol-live-evals.md | 55 ++++++ .../src/cli/eval-gateway-runtime.test.ts | 156 ++++++++++++++++++ .../src/cli/eval-gateway-runtime.ts | 104 ++++++++++++ .../paperclip-runner/src/cli/eval-session.ts | 52 +++--- 4 files changed, 345 insertions(+), 22 deletions(-) create mode 100644 packages/paperclip-runner/src/cli/eval-gateway-runtime.test.ts create mode 100644 packages/paperclip-runner/src/cli/eval-gateway-runtime.ts diff --git a/packages/paperclip-runner/docs/runner-protocol-live-evals.md b/packages/paperclip-runner/docs/runner-protocol-live-evals.md index b7f8efad0c2..a7114ed7c31 100644 --- a/packages/paperclip-runner/docs/runner-protocol-live-evals.md +++ b/packages/paperclip-runner/docs/runner-protocol-live-evals.md @@ -104,6 +104,61 @@ Claude Managed uses its Agent version, while AgentCore uses its qualification revision. Transport API or beta versions remain separate protocol metadata and must not replace that runtime identity in a report. +## Controller-assigned gateway route + +The Runner eval CLI accepts `--gateway-config /absolute/path/gateway.json` for +native Codex and ACPX Claude. This is an explicit route for a controller +that owns a local budget proxy. Normal invocations keep the direct path. +ACPX Codex is rejected before service creation because its runtime prohibits +preconfigured homes to protect Runner state. +The descriptor must bind the exact model and attempt ID from `request.json`: + +```json +{ + "schema": "paperclip.runner-eval.gateway/v1", + "provider": "openai", + "model": "gpt-5.4-mini", + "baseUrl": "http://127.0.0.1:4567", + "campaignId": "campaign-id", + "executionId": "cell-id", + "attemptId": "attempt-id", + "upstreamRoute": "direct" +} +``` + +Use `anthropic` for ACPX Claude. `upstreamRoute` is the controller's declaration: +`direct` or `braintrust`. It is not an independent verification of the upstream. +The base URL must be the proxy's explicit IPv4 loopback address and port, with +no path, query, fragment, or embedded credential. The controller supplies its +32-byte hexadecimal token through `PAPERCLIP_RUNNER_EVAL_GATEWAY_TOKEN`. +Do not put provider or Braintrust credentials in this child environment or file. + +```sh +node /path/to/runner/dist/cli/eval-session.js \ + --request /path/to/request.json --output /path/to/artifact.json \ + --gateway-config /path/to/gateway.json +``` + +The CLI validates the descriptor before creating a provider service. It creates +an owned temporary home, pins Codex's Responses endpoint or Claude's Messages +endpoint and exact model, and passes only the assigned proxy credential. +It does not copy ambient provider keys, subscription logins, proxy settings, +startup hooks, or user homes into this route. Unsupported harnesses and +mismatched descriptor identities fail before provider creation. The temporary +home is removed on success and failure. + +Success and failure artifacts retain `requestRouting`: controller gateway mode, +provider, declared upstream route, campaign/execution/attempt IDs, and the +SHA-256 of the descriptor bytes. The token and endpoint are excluded from this +metadata. Existing artifact usage and provider outcomes remain authoritative +for their respective fields; the route declaration is not a billing receipt. +The controller must retain its request ledger and link these identities to it. + +This entry point does not itself allocate a campaign budget, run the proxy, or +change the hosted matrix. The controller must enforce request admission, +deadlines, and limits before forwarding traffic. A local fake-API probe only +proves routing; it does not qualify live provider or Braintrust behavior. + ## Hosted campaign Use the `Runner Direct Live Protocol Evals` workflow. Dispatch the workflow diff --git a/packages/paperclip-runner/src/cli/eval-gateway-runtime.test.ts b/packages/paperclip-runner/src/cli/eval-gateway-runtime.test.ts new file mode 100644 index 00000000000..cd1cb1e03e1 --- /dev/null +++ b/packages/paperclip-runner/src/cli/eval-gateway-runtime.test.ts @@ -0,0 +1,156 @@ +import { createHash } from "node:crypto"; +import { existsSync } from "node:fs"; +import { chmod, mkdtemp, readFile, readdir, rm, stat, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, expect, it, vi } from "vitest"; +import { createSanitizedCodexEnvironment } from "../drivers/codex/app-server-transport.js"; +import { createSanitizedAcpxSpawnInput } from "../drivers/acpx/environment.js"; +import { createCapabilityFixtureState } from "../mock-core/capability-control-plane-types.js"; +import type { CapabilityLiveSessionSnapshot } from "../live/live-session.js"; +import { parseEvalSessionRequest } from "./eval-session-contract.js"; +import { prepareEvalGatewayRuntime } from "./eval-gateway-runtime.js"; +import { runEvalSessionCli } from "./eval-session.js"; + +const roots: string[] = []; +afterEach(async () => { + vi.unstubAllEnvs(); + for (const root of roots.splice(0)) { + for (const entry of await readdir(root).catch(() => [])) { + if (entry.startsWith(".paperclip-eval-runtime-context-")) await chmod(join(root, entry, "instructions"), 0o700).catch(() => undefined); + } + await rm(root, { recursive: true, force: true }); + } +}); +const token = "a".repeat(64); +async function fixture(provider = "codex", acpxAgent?: string) { + const root = await mkdtemp(join(tmpdir(), "runner-gateway-test-")); roots.push(root); + const model = acpxAgent === "claude" ? "claude-sonnet-5" : "gpt-5.6-sol"; + const binary = join(root, "runnerd"); + await writeFile(binary, "fake runnerd"); + const request = parseEvalSessionRequest({ + schema: "paperclip-runner/eval-session-request/v1", attemptId: "attempt-1", prompt: "Read the governed task.", + provider, ...(acpxAgent ? { acpxAgent } : {}), model, + runnerd: { path: binary, sha256: createHash("sha256").update("fake runnerd").digest("hex") }, + limits: { turnTimeoutMs: 120000, maxAgentTurns: 1, maxEstimatedCostNanodollars: 100000000 }, + session: { workingDirectory: root }, + }); + const descriptor = { schema: "paperclip.runner-eval.gateway/v1", provider: acpxAgent === "claude" ? "anthropic" : "openai", + model, baseUrl: "http://127.0.0.1:4567", campaignId: "campaign-1", executionId: "cell-1", attemptId: "attempt-1", upstreamRoute: "braintrust" }; + const descriptorPath = join(root, "gateway.json"); + await writeFile(descriptorPath, JSON.stringify(descriptor)); + return { root, request, descriptor, descriptorPath }; +} + +it.each([["codex", undefined], ["acpx", "claude"]])("routes %s/%s with only its proxy credential and an owned home", async (provider, agent) => { + const f = await fixture(provider, agent); + const gateway = await prepareEvalGatewayRuntime(f.descriptorPath, f.request, { + PATH: process.env.PATH, HOME: "/ambient/home", CODEX_HOME: "/ambient/codex", CLAUDE_CONFIG_DIR: "/ambient/claude", + PAPERCLIP_RUNNER_EVAL_GATEWAY_TOKEN: token, OPENAI_API_KEY: "ambient-openai", CODEX_API_KEY: "ambient-codex", + ANTHROPIC_API_KEY: "ambient-anthropic", ANTHROPIC_AUTH_TOKEN: "ambient-oauth", CLAUDE_CODE_OAUTH_TOKEN: "ambient-claude", + BRAINTRUST_API_KEY: "ambient-braintrust", AWS_SECRET_ACCESS_KEY: "ambient-aws", GH_TOKEN: "ambient-github", + HTTPS_PROXY: "https://ambient-proxy", NODE_OPTIONS: "--require ambient-hook", PAPERCLIP_CONFIGURED_ENVIRONMENT_KEYS: '["GH_TOKEN"]', + }); + const env = gateway.transportOptions.environment; + try { + expect(gateway.transportOptions.homeMode).toBe("preconfigured"); + expect(JSON.stringify(env)).not.toContain("ambient"); + expect(env.OPENAI_API_KEY).toBeUndefined(); + expect(env.CODEX_API_KEY).toBeUndefined(); + expect(env.BRAINTRUST_API_KEY).toBeUndefined(); + expect(env.PAPERCLIP_RUNNER_EVAL_GATEWAY_TOKEN).toBeUndefined(); + const child = provider === "codex" ? createSanitizedCodexEnvironment(env) : createSanitizedAcpxSpawnInput(env, agent as "codex" | "claude").env; + expect(child.HOME).toBe(env.HOME); + if (agent === "claude") { + expect(child.ANTHROPIC_API_KEY).toBe(token); + expect(child.ANTHROPIC_BASE_URL).toBe(f.descriptor.baseUrl); + expect(child.CLAUDE_CODE_SUBAGENT_MODEL).toBe(f.request.model); + expect(JSON.parse(await readFile(join(env.CLAUDE_CONFIG_DIR!, "settings.json"), "utf8"))).toEqual({ model: f.request.model, availableModels: [f.request.model] }); + } else { + expect(child.PAPERCLIP_AI_PROVIDER_KEY).toBe(token); + const config = await readFile(join(env.CODEX_HOME!, "config.toml"), "utf8"); + expect(config).toContain('base_url = "http://127.0.0.1:4567/v1"'); + expect(config).toContain('env_key = "PAPERCLIP_AI_PROVIDER_KEY"'); + expect(config).toContain("requires_openai_auth = false"); + expect(config).toContain("shell_snapshot = false"); + expect(config).not.toContain(token); + expect((await stat(join(env.CODEX_HOME!, "config.toml"))).mode & 0o777).toBe(0o600); + } + expect(JSON.stringify(gateway.evidence)).not.toContain(token); + expect(gateway.evidence).toMatchObject({ mode: "controller_gateway", attemptId: f.request.attemptId, declaredUpstreamRoute: "braintrust" }); + } finally { await gateway.close(); } + expect(existsSync(env.HOME!)).toBe(false); +}); + +it.each([ + { baseUrl: "https://api.openai.com" }, { baseUrl: "http://localhost:4567" }, + { baseUrl: "http://127.0.0.1:4567/v1" }, { baseUrl: "http://127.0.0.1:99999" }, + { baseUrl: "http://127.0.0.1:4567?token=secret" }, { attemptId: "another-attempt" }, + { model: "another-model" }, { campaignId: "bad identity" }, { unexpectedSecret: "must-not-print" }, +])("rejects invalid descriptor binding %j", async (change) => { + const f = await fixture(); + await writeFile(f.descriptorPath, JSON.stringify({ ...f.descriptor, ...change })); + await expect(prepareEvalGatewayRuntime(f.descriptorPath, f.request, { PAPERCLIP_RUNNER_EVAL_GATEWAY_TOKEN: token })) + .rejects.toThrow("Invalid controller gateway descriptor"); +}); + +it("rejects missing tokens and unsupported provider routes before runtime creation", async () => { + const f = await fixture(); + await expect(prepareEvalGatewayRuntime(f.descriptorPath, f.request, {})).rejects.toThrow("gateway token"); + await expect(prepareEvalGatewayRuntime(f.descriptorPath, { ...f.request, provider: "opencode" }, { PAPERCLIP_RUNNER_EVAL_GATEWAY_TOKEN: token })).rejects.toThrow("does not support"); + await writeFile(f.descriptorPath, JSON.stringify({ ...f.descriptor, provider: "anthropic" })); + await expect(prepareEvalGatewayRuntime(f.descriptorPath, f.request, { PAPERCLIP_RUNNER_EVAL_GATEWAY_TOKEN: token })).rejects.toThrow("does not support"); +}); + +it.each([false, true])("the real CLI retains route identity and removes the owned home after failure=%s", async (fail) => { + const f = await fixture(); + vi.stubEnv("PAPERCLIP_RUNNER_EVAL_GATEWAY_TOKEN", token); + vi.stubEnv("OPENAI_API_KEY", "upstream-must-not-reach-provider"); + const requestPath = join(f.root, "request.json"), outputPath = join(f.root, "artifact.json"); + await writeFile(requestPath, JSON.stringify(f.request)); + const state = JSON.stringify(createCapabilityFixtureState({})); + const snapshot = { + sessionId: "session-1", revision: 1, providerThreadId: "provider-1", providerSessionId: "provider-1", + providerModel: { id: f.request.model, provider: "openai" }, status: "idle", activeTurnId: null, + createdAt: "2026-10-24T00:00:00Z", updatedAt: "2026-10-24T00:00:01Z", + authority: { companyId: "company-1", actorId: "actor-1", taskId: "task-1", runId: "run-1", sessionId: "session-1", scenarioId: "gateway-test" }, + config: { provider: "codex", driver: "codex_app_server", seedState: state, workingDirectory: f.root, scenario: { id: "gateway-test" }, capabilities: [], explicitClaims: [], turnTimeoutMs: 1000 }, + mockState: state, process: null, networkEvidence: { realPaperclipRequests: 0, childPaperclipEnvironmentKeys: [] }, + transcript: [], evidence: [], authorizationRecords: [], attempts: [], terminalTurns: [{ turnId: "turn-1", status: "completed" }], + usageLedger: [{ receiptId: "receipt-1", turnId: "turn-1", providerCalls: 1, providerRequests: 1, inputTokens: 100, outputTokens: 10, cachedInputTokens: 0, reasoningTokens: 0, costNanodollars: 0 }], usageUnavailable: [], + } as unknown as CapabilityLiveSessionSnapshot; + let home: string | undefined; + const factory = vi.fn((_binary, options) => { + expect(options.homeMode).toBe("preconfigured"); + expect(options.environment.OPENAI_API_KEY).toBeUndefined(); + expect(options.environment.PAPERCLIP_AI_PROVIDER_KEY).toBe(token); + home = options.environment.HOME; + expect(existsSync(home!)).toBe(true); + return { create: async () => ({ + sendMessage: async () => { if (fail) throw new Error("simulated provider failure"); return { turnId: "turn-1", status: "completed", snapshot }; }, + completeAttempt: async () => undefined, shutdown: async () => { snapshot.status = "closed"; }, snapshot: () => snapshot, + }) } as never; + }); + const result = await runEvalSessionCli(["--request", requestPath, "--output", outputPath, "--gateway-config", f.descriptorPath], { serviceFactory: factory }); + expect(result).toBe(fail ? 2 : 0); + expect(factory).toHaveBeenCalledTimes(1); + expect(existsSync(home!)).toBe(false); + const raw = await readFile(outputPath, "utf8"), artifact = JSON.parse(raw); + expect(artifact.requestRouting).toMatchObject({ mode: "controller_gateway", provider: "openai", campaignId: "campaign-1", executionId: "cell-1", attemptId: "attempt-1" }); + expect(raw).not.toContain(token); + expect(raw).not.toContain("upstream-must-not-reach-provider"); + if (fail) expect(artifact.infrastructureError).toBe("simulated provider failure"); +}); + + +it.each(["codex", undefined])("rejects ACPX Codex (%s) before creating any provider service", async (agent) => { + const f = await fixture("acpx", agent); + vi.stubEnv("PAPERCLIP_RUNNER_EVAL_GATEWAY_TOKEN", token); + const requestPath = join(f.root, "request.json"), outputPath = join(f.root, "artifact.json"); + await writeFile(requestPath, JSON.stringify(f.request)); + const factory = vi.fn(() => { throw new Error("must not create a provider service"); }); + await expect(runEvalSessionCli(["--request", requestPath, "--output", outputPath, "--gateway-config", f.descriptorPath], { serviceFactory: factory })) + .rejects.toThrow("Controller gateway does not support this eval provider"); + expect(factory).not.toHaveBeenCalled(); + expect(existsSync(outputPath)).toBe(false); +}); diff --git a/packages/paperclip-runner/src/cli/eval-gateway-runtime.ts b/packages/paperclip-runner/src/cli/eval-gateway-runtime.ts new file mode 100644 index 00000000000..0d32670c3a6 --- /dev/null +++ b/packages/paperclip-runner/src/cli/eval-gateway-runtime.ts @@ -0,0 +1,104 @@ +import { createHash } from "node:crypto"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import type { EvalSessionRequest } from "./eval-session-contract.js"; + +export interface EvalGatewayDescriptor { + schema: "paperclip.runner-eval.gateway/v1"; + provider: "openai" | "anthropic"; + model: string; + baseUrl: string; + campaignId: string; + executionId: string; + attemptId: string; + upstreamRoute: "direct" | "braintrust"; +} + +const TOKEN_ENV = "PAPERCLIP_RUNNER_EVAL_GATEWAY_TOKEN"; +const safeId = (value: unknown) => typeof value === "string" && /^[A-Za-z0-9][A-Za-z0-9_.:/-]{0,511}$/.test(value); + +export async function prepareEvalGatewayRuntime( + descriptorPath: string, + request: EvalSessionRequest, + source: NodeJS.ProcessEnv = process.env, +) { + const raw = await readFile(descriptorPath, "utf8"); + let descriptor: EvalGatewayDescriptor; + try { + if (Buffer.byteLength(raw) > 8192) throw new Error(); + descriptor = JSON.parse(raw) as EvalGatewayDescriptor; + const fields = ["schema", "provider", "model", "baseUrl", "campaignId", "executionId", "attemptId", "upstreamRoute"]; + if (!descriptor || typeof descriptor !== "object" || Array.isArray(descriptor) + || Object.keys(descriptor).length !== fields.length || Object.keys(descriptor).some(key => !fields.includes(key)) + || descriptor.schema !== "paperclip.runner-eval.gateway/v1" + || !["openai", "anthropic"].includes(descriptor.provider) + || !["direct", "braintrust"].includes(descriptor.upstreamRoute) + || ![descriptor.campaignId, descriptor.executionId, descriptor.attemptId].every(safeId) + || descriptor.attemptId !== request.attemptId || descriptor.model !== request.model + || typeof descriptor.baseUrl !== "string" || !/^http:\/\/127\.0\.0\.1:[1-9][0-9]{0,4}$/.test(descriptor.baseUrl)) throw new Error(); + const url = new URL(descriptor.baseUrl); + if (!url.port || Number(url.port) > 65535) throw new Error(); + } catch { + throw new Error("Invalid controller gateway descriptor"); + } + const provider = request.provider ?? "codex"; + const codex = provider === "codex"; + const claude = provider === "acpx" && request.acpxAgent === "claude"; + if (!codex && !claude || descriptor.provider !== (codex ? "openai" : "anthropic")) { + throw new Error("Controller gateway does not support this eval provider"); + } + const token = source[TOKEN_ENV]; + if (typeof token !== "string" || !/^[a-f0-9]{64}$/.test(token)) throw new Error("Missing or invalid controller gateway token"); + const root = await mkdtemp(join(tmpdir(), "paperclip-runner-eval-gateway-")); + try { + const home = join(root, "home"), codexHome = join(root, "codex"), claudeHome = join(root, "claude"); + const environment: NodeJS.ProcessEnv = Object.fromEntries( + ["PATH", "LANG", "LANGUAGE", "LC_ALL", "TZ", "SystemRoot", "WINDIR", "PATHEXT"] + .flatMap(key => source[key] === undefined ? [] : [[key, source[key]!]]), + ); + Object.assign(environment, { + HOME: home, CODEX_HOME: codexHome, CLAUDE_CONFIG_DIR: claudeHome, + XDG_CONFIG_HOME: join(root, "config"), XDG_DATA_HOME: join(root, "data"), XDG_CACHE_HOME: join(root, "cache"), + TMPDIR: join(root, "tmp"), TMP: join(root, "tmp"), TEMP: join(root, "tmp"), + PAPERCLIP_RUNNER_HOME_MODE: "preconfigured", + }); + for (const directory of [home, codexHome, claudeHome, environment.XDG_CONFIG_HOME!, environment.XDG_DATA_HOME!, environment.XDG_CACHE_HOME!, environment.TMPDIR!]) { + await mkdir(directory, { mode: 0o700 }); + } + if (codex) { + environment.PAPERCLIP_AI_PROVIDER_KEY = token; + await writeFile(join(codexHome, "config.toml"), [ + 'model_provider = "paperclip_eval"', + `model = ${JSON.stringify(request.model)}`, + '[model_providers.paperclip_eval]', + 'name = "Paperclip eval controller"', + `base_url = ${JSON.stringify(descriptor.baseUrl + "/v1")}`, + 'wire_api = "responses"', 'requires_openai_auth = false', 'env_key = "PAPERCLIP_AI_PROVIDER_KEY"', + '[features]', 'shell_snapshot = false', '', + ].join("\n"), { mode: 0o600, flag: "wx" }); + } else { + Object.assign(environment, { + ANTHROPIC_API_KEY: token, ANTHROPIC_BASE_URL: descriptor.baseUrl, + CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1", ACPX_CLAUDE_INCLUDE_USER_SETTINGS: "1", + ANTHROPIC_MODEL: request.model, ANTHROPIC_DEFAULT_OPUS_MODEL: request.model, + ANTHROPIC_DEFAULT_SONNET_MODEL: request.model, ANTHROPIC_DEFAULT_HAIKU_MODEL: request.model, + CLAUDE_CODE_SUBAGENT_MODEL: request.model, + }); + await writeFile(join(claudeHome, "settings.json"), JSON.stringify({ model: request.model, availableModels: [request.model] }) + "\n", { mode: 0o600, flag: "wx" }); + } + return { + transportOptions: { homeMode: "preconfigured" as const, environment }, + evidence: { + mode: "controller_gateway" as const, provider: descriptor.provider, + declaredUpstreamRoute: descriptor.upstreamRoute, + campaignId: descriptor.campaignId, executionId: descriptor.executionId, attemptId: descriptor.attemptId, + descriptorSha256: createHash("sha256").update(raw).digest("hex"), + }, + close: () => rm(root, { recursive: true, force: true }), + }; + } catch (error) { + await rm(root, { recursive: true, force: true }); + throw error; + } +} diff --git a/packages/paperclip-runner/src/cli/eval-session.ts b/packages/paperclip-runner/src/cli/eval-session.ts index 788dc61602b..c42a22ec933 100644 --- a/packages/paperclip-runner/src/cli/eval-session.ts +++ b/packages/paperclip-runner/src/cli/eval-session.ts @@ -23,6 +23,7 @@ import { CapabilityLiveSessionService, type CapabilityLiveSession, type CapabilityLiveSessionSnapshot, + type CapabilityLiveSessionServiceOptions, type CapabilityLiveTurnResult, type CreateCapabilityLiveSessionInput, } from "../live/live-session.js"; @@ -35,6 +36,7 @@ import { type EvalSessionUsage, } from "./eval-session-contract.js"; import { evalProviderTransportOptions } from "./eval-provider-runtime.js"; +import { prepareEvalGatewayRuntime } from "./eval-gateway-runtime.js"; import { NativeSessionCloseUnrecoverableError } from "../contracts/native-session-backend.js"; interface EvalSessionCliOptions { @@ -42,6 +44,7 @@ interface EvalSessionCliOptions { outputPath: string; candidateProfile?: EvalCandidateProfile; expectedAcpxProfile?: Record; + gatewayConfigPath?: string; } function argument(args: string[], name: string): string { @@ -52,7 +55,7 @@ function argument(args: string[], name: string): string { } export function parseEvalSessionCliArgs(args: string[]): EvalSessionCliOptions { - const allowed = new Set(["--request", "--output", "--candidate-profile", "--expected-acpx-profile"]); + const allowed = new Set(["--request", "--output", "--candidate-profile", "--expected-acpx-profile", "--gateway-config"]); const seen = new Set(); for (let index = 0; index < args.length; index += 2) { if (!allowed.has(args[index] ?? "")) { @@ -89,6 +92,7 @@ export function parseEvalSessionCliArgs(args: string[]): EvalSessionCliOptions { return { ...(candidateProfile === undefined ? {} : { candidateProfile }), ...(expectedAcpxProfile === undefined ? {} : { expectedAcpxProfile }), + ...(seen.has("--gateway-config") ? { gatewayConfigPath: argument(args, "--gateway-config") } : {}), requestPath: argument(args, "--request"), outputPath: argument(args, "--output"), }; @@ -362,6 +366,7 @@ export async function runEvalSessionCli( options: { serviceFactory?: ( runnerBinary: string, + transportOptions: NonNullable, ) => CapabilityLiveSessionService; } = {}, ): Promise { @@ -398,32 +403,31 @@ export async function runEvalSessionCli( const requestedDriver = request.driver ?? expectedEvalSessionDriver(requestedProvider); const requestedProviderVersion = evalSessionProviderVersion(request); - const runtimeContext = await prepareEvalRuntimeContext( - resolve(request.session.workingDirectory ?? process.cwd()), - ); - const service = options.serviceFactory?.(runnerdPath) ?? - new CapabilityLiveSessionService({ - transportOptions: { - ...evalProviderTransportOptions(requestedProvider, request.limits.turnTimeoutMs, request.session.workingDirectory), - runnerBinary: runnerdPath, - ...(cli.candidateProfile === undefined ? {} : { acpxCandidateProfile: cli.candidateProfile }), - runtimeContext, - baseInstructions: evalRuntimeSystemInstructions(runtimeContext), - // The transport performs the provider-specific allowlisting. Supplying - // the source environment here is still required: without it the - // isolated Codex home has no credential source and runnerd receives no - // executable PATH from the Evalbook CLI process. - environment: process.env, - onDiagnostic: (message) => { - process.stderr.write(`[eval-session runnerd] ${message}\n`); - }, - }, - }); + const gateway = cli.gatewayConfigPath + ? await prepareEvalGatewayRuntime(cli.gatewayConfigPath, request) + : undefined; let session: CapabilityLiveSession | null = null; let turn: CapabilityLiveTurnResult | null = null; let snapshot: CapabilityLiveSessionSnapshot | null = null; try { + const runtimeContext = await prepareEvalRuntimeContext( + resolve(request.session.workingDirectory ?? process.cwd()), + ); + const transportOptions: NonNullable = { + ...evalProviderTransportOptions(requestedProvider, request.limits.turnTimeoutMs, request.session.workingDirectory), + runnerBinary: runnerdPath, + ...(cli.candidateProfile === undefined ? {} : { acpxCandidateProfile: cli.candidateProfile }), + runtimeContext, + baseInstructions: evalRuntimeSystemInstructions(runtimeContext), + environment: process.env, + ...gateway?.transportOptions, + onDiagnostic: (message) => { + process.stderr.write(`[eval-session runnerd] ${message}\n`); + }, + }; + const service = options.serviceFactory?.(runnerdPath, transportOptions) + ?? new CapabilityLiveSessionService({ transportOptions }); // PR3 expands this same service input with the two qualified remote // profiles. The cast keeps this isolated PR typecheckable before PR3 lands; // the runtime fields and their fail-closed validation are already present. @@ -470,6 +474,7 @@ export async function runEvalSessionCli( build: PAPERCLIP_RUNNER_BUILD_METADATA, runnerd: { path: "[withheld]", sha256: `sha256:${actualDigest}` }, requestedModel: request.model, + ...(gateway ? { requestRouting: gateway.evidence } : {}), ...(cli.candidateProfile === undefined ? {} : { diagnosticCandidateProfile: cli.candidateProfile }), provider: requestedProvider, driver: requestedDriver, @@ -549,6 +554,7 @@ export async function runEvalSessionCli( build: PAPERCLIP_RUNNER_BUILD_METADATA, runnerd: { path: "[withheld]", sha256: `sha256:${actualDigest}` }, requestedModel: request.model, + ...(gateway ? { requestRouting: gateway.evidence } : {}), ...(cli.candidateProfile === undefined ? {} : { diagnosticCandidateProfile: cli.candidateProfile }), provider: requestedProvider, driver: requestedDriver, @@ -575,6 +581,8 @@ export async function runEvalSessionCli( }, }, null, 2)}\n`); return 2; + } finally { + await gateway?.close(); } } From 62f60bf158746c5807763778326b1eba4f2ed18a Mon Sep 17 00:00:00 2001 From: Nicky Leach Date: Sat, 24 Oct 2026 09:40:08 -0700 Subject: [PATCH 003/110] Measure first deliverable text in native run traces (#17434) --- doc/observability.md | 35 +++++++ doc/run-log-events.md | 14 +++ maps/agent-access-map/runs-adapters.md | 3 + maps/feature-map/runs-adapters.md | 3 + .../native-deliverable-text.test.ts | 56 +++++++++++ .../native-runtime/native-deliverable-text.ts | 57 ++++++++++++ .../native-session-executor.test.ts | 92 +++++++++++++++++++ .../native-runtime/native-session-executor.ts | 15 +++ 8 files changed, 275 insertions(+) create mode 100644 server/src/services/native-runtime/native-deliverable-text.test.ts create mode 100644 server/src/services/native-runtime/native-deliverable-text.ts diff --git a/doc/observability.md b/doc/observability.md index ae4deb44c38..55328507d0c 100644 --- a/doc/observability.md +++ b/doc/observability.md @@ -627,6 +627,41 @@ execution identity, or an existing assistant/reasoning/tool item start or completion. Usage updates and empty deltas do not count. This is a first activity metric, not time to a finished answer. +`task.time_to_first_token` measures the wait until text is deliverable to the +task transcript for each native dispatch. The first qualifying event is a +nonempty assistant or reasoning text delta, a completed assistant or reasoning +item with text, or an accepted run result with a nonempty summary. Text released +by redaction at item/turn/session completion also qualifies. Item identities and +text fields follow the task transcript projection; item starts, tools, usage, +empty text, result proposals, and duplicate PRP replay do not end the wait. + +The first-text milestone occurs after `task.prepare` and Runner startup. The +timing span is a cumulative interval, not a separate preparation step: + +```text +accepted ingress → queue → task.prepare → Runner startup → provider work → first text +└────────────────────── task.time_to_first_token ──────────────────────────────────┘ +``` + +The span starts at the native run trace's historical start: +the accepted comment or attested question response when present, otherwise run +creation from the queue span. Callers without preparation history start at native +dispatch. The interval includes queueing, Core preparation, workspace preparation, +Runner startup, provider latency, transport, and durable event ingestion. It ends +in Core's commit callback, when the text is readable through the run-events API, +using the Core clock rather than the provider event timestamp. Browser delivery +and rendering are excluded. The name is retained for existing trace queries; +this measures the first deliverable text, not an exact model token boundary. +Only the first qualifying event in a dispatch emits a span. Its `eventKind` is +`reasoning` for thinking text and `agentMessage` for assistant text or a result. +A dispatch without deliverable text emits no sample, including an early failure. +Same-run recovery retains the original historical start and can emit a new sample +only for newly committed output; it does not reconstruct prior first-token timing. +`task.time_to_first_token` is a child of `task.provider_session` that overlaps +queueing, preparation and execution; do not add its duration to those phases. +No text or provider event identifiers are exported. The existing duration attribute +is `paperclip.native.span.duration_ms`. + `tool.request.input_stream` measures the observed request-input window: from an ACP tool announcement to its last input update before the provider reports the tool complete. It can include provider buffering and transport. It is not diff --git a/doc/run-log-events.md b/doc/run-log-events.md index d9cbb905cb0..b449def19f6 100644 --- a/doc/run-log-events.md +++ b/doc/run-log-events.md @@ -64,6 +64,20 @@ instance run log and add no first-party Telemetry or OpenTelemetry export. ## Provider-pack preparation timing +`run.performance.span` also records `task.time_to_first_token` once per native +dispatch at the first newly committed deliverable text: assistant or reasoning +`item.delta`/`item.completed`, a redaction tail released at completion, or an +accepted run-result summary. Its +`durationMs` starts at the native run trace's historical start (accepted ingress, +otherwise queued run creation, or dispatch when history is absent) and ends at Core +commit callback. `startOffsetMs` is zero, and `eventKind` is `agentMessage` or +`reasoning`. It includes preparation and startup, but excludes browser +delivery/rendering. This measures text availability, not an exact model token. +Empty text, item starts, tools, usage, result proposals, and duplicate replay do +not qualify. No deliverable text means no timing sample. A recovered dispatch can +record newly committed output from the original start; it does not reproduce +earlier output timing. The event contains no text or provider identifiers. + The existing `run.performance.span` event also records `provider_pack.select`, `provider_pack.discover`, `provider_pack.verify`, `provider_pack.verify_preinstalled`, `provider_pack.link_preinstalled`, `provider_pack.clear_stale`, `provider_pack.upload`, diff --git a/maps/agent-access-map/runs-adapters.md b/maps/agent-access-map/runs-adapters.md index be3a21b69a8..7f5552f9919 100644 --- a/maps/agent-access-map/runs-adapters.md +++ b/maps/agent-access-map/runs-adapters.md @@ -199,6 +199,9 @@ existing hashed run ID. Controller startup phase spans carry no custom attribute Native controller setup and settlement phases use that same run hash, including assigned MCP discovery; neither tool definitions nor credentials are recorded. Both retain operator-controlled tracing; unconfigured clients stay silent. +The native first-text span ends after text is committed for the existing run-events +reader, including reasoning and completed responses. It exports only the bounded +text kind and timing, with no text content or new agent access. This adds no agent API, credential access, run-log write, or recovery authority. See [the tracing contract](../../doc/observability.md#controller-preparation-phases). Live latency verification remains separate from the existing access baseline. diff --git a/maps/feature-map/runs-adapters.md b/maps/feature-map/runs-adapters.md index cdbd1510f11..c44576823c7 100644 --- a/maps/feature-map/runs-adapters.md +++ b/maps/feature-map/runs-adapters.md @@ -38,6 +38,9 @@ without restricting the root span name. Compare workspace preparation with its `controller.startup.`. A recovery pause or deployment drain is not model execution time. See the [tracing contract](../../doc/observability.md#controller-preparation-phases). These source-level diagnostics do not establish a live response-time budget. +`task.time_to_first_token` measures accepted ingress through the first committed +text that the task transcript can show, including thinking and completed +responses. It includes preparation and startup, and excludes browser latency. Inspect `native.controller.` for backend construction, assigned-tool discovery and post-turn cleanup. Compare those intervals with the actual model turn; do not count a nested discovery interval twice. diff --git a/server/src/services/native-runtime/native-deliverable-text.test.ts b/server/src/services/native-runtime/native-deliverable-text.test.ts new file mode 100644 index 00000000000..49b55e08f77 --- /dev/null +++ b/server/src/services/native-runtime/native-deliverable-text.test.ts @@ -0,0 +1,56 @@ +import { describe, expect, it } from "vitest"; +import type { PrpEvent } from "../../vendor/paperclip-runner/index.js"; +import { createNativeDeliverableTextObservation } from "./native-deliverable-text.js"; + +function event(eventType: string, payload: Record, itemId?: string) { + return { eventType, payload, ...(itemId ? { itemId } : {}) } as PrpEvent; +} + +describe("native deliverable text", () => { + it.each(["agentMessage", "assistant_message", "reasoning"])("accepts streamed and completed %s text", (kind) => { + const observe = createNativeDeliverableTextObservation(); + const expected = kind === "reasoning" ? "reasoning" : "agentMessage"; + expect(observe(event("item.delta", { kind, text: "text" }, "message"))).toBe(expected); + expect(observe(event("item.completed", { kind, text: "text" }))).toBe(expected); + }); + + it("matches nested and inherited transcript item identities without counting starts", () => { + const observe = createNativeDeliverableTextObservation(); + expect(observe(event("item.started", { item: { id: "message", type: "agentMessage", text: "hidden" } }))).toBeNull(); + expect(observe(event("item.delta", { item: { id: "message", text: "visible" } }))).toBe("agentMessage"); + expect(observe(event("item.started", { kind: "reasoning" }, "thought"))).toBeNull(); + expect(observe(event("item.delta", { text: "thinking" }, "thought"))).toBe("reasoning"); + }); + + it("accepts text released by redaction at terminal boundaries", () => { + const observe = createNativeDeliverableTextObservation(); + expect(observe(event("item.delta", { kind: "reasoning", text: "" }, "thought"))).toBeNull(); + expect(observe(event("turn.completed", { outputTails: [ + { itemId: "thought", payload: { text: "settled thought" } }, + ] }))).toBe("reasoning"); + }); + + it("accepts an accepted result summary without any streamed text", () => { + const observe = createNativeDeliverableTextObservation(); + const result = { schema: "paperclip.run_result.v1", summary: "Done" }; + expect(observe(event("run.result.proposed", result))).toBeNull(); + expect(observe(event("run.result.accepted", { result }))).toBe("agentMessage"); + }); + + it.each([ + event("item.delta", { kind: "agentMessage", delta: "not projected" }, "message"), + event("item.delta", { kind: "agentMessage", content: "not projected" }, "message"), + event("item.delta", { kind: "agentMessage", text: "missing identity" }), + event("item.delta", { kind: "agentMessage", text: " " }, "message"), + event("item.completed", { kind: "reasoning", text: 42 }), + event("item.completed", { kind: "usage", text: "tokens" }), + event("item.completed", { kind: "toolCall", text: "arguments" }), + event("tool.execution.started", { executionId: "tool", text: "tool" }), + event("turn.started", { kind: "agentMessage", text: "metadata" }), + event("run.result.accepted", { result: { schema: "other", summary: "wrong schema" } }), + event("run.result.accepted", { result: { schema: "paperclip.run_result.v1", summary: " " } }), + event("turn.completed", { outputTails: [{ payload: { kind: "agentMessage", text: "no identity" } }] }), + ])("ignores text that the task transcript cannot show: %j", (candidate) => { + expect(createNativeDeliverableTextObservation()(candidate)).toBeNull(); + }); +}); diff --git a/server/src/services/native-runtime/native-deliverable-text.ts b/server/src/services/native-runtime/native-deliverable-text.ts new file mode 100644 index 00000000000..e228303ea0e --- /dev/null +++ b/server/src/services/native-runtime/native-deliverable-text.ts @@ -0,0 +1,57 @@ +import type { PrpEvent } from "../../vendor/paperclip-runner/index.js"; + +type TextKind = "agentMessage" | "reasoning"; + +function record(value: unknown): Record { + return value && typeof value === "object" && !Array.isArray(value) + ? value as Record + : {}; +} + +function text(value: unknown): string | null { + return typeof value === "string" && value.length > 0 ? value : null; +} + +export function createNativeDeliverableTextObservation() { + const itemKinds = new Map(); + const observeItem = (payload: Record, envelopeItemId?: string): TextKind | null => { + const item = record(payload.item); + const itemId = text(envelopeItemId) ?? text(payload.itemId) ?? text(item.id); + const kind = (text(payload.kind) ?? text(item.kind) ?? text(item.type) ?? "") + .replaceAll("_", "").toLowerCase() || (itemId ? itemKinds.get(itemId) : ""); + if (itemId && kind) itemKinds.set(itemId, kind); + if (!(text(payload.text) ?? text(item.text))?.trim()) return null; + if (kind === "reasoning") return "reasoning"; + return kind === "agentmessage" || kind === "assistantmessage" ? "agentMessage" : null; + }; + + return (event: Pick): TextKind | null => { + const payload = record(event.payload); + if (/^(item|turn|session)\.(completed|failed|cancelled|interrupted|closed)$/.test(event.eventType) + && Array.isArray(payload.outputTails)) { + for (const value of payload.outputTails) { + const tail = record(value); + const tailPayload = record(tail.payload); + const itemId = text(tail.itemId) ?? text(tailPayload.itemId) ?? text(record(tailPayload.item).id); + if (!itemId || typeof tailPayload.text !== "string") continue; + const kind = observeItem(tailPayload, itemId); + if (kind) return kind; + } + } + if (event.eventType === "item.started") { + observeItem(payload, event.itemId); + return null; + } + if (event.eventType === "item.delta" || event.eventType === "item.completed") { + const item = record(payload.item); + if (event.eventType === "item.delta" && + !(text(event.itemId) ?? text(payload.itemId) ?? text(item.id))) return null; + return observeItem(payload, event.itemId); + } + if (event.eventType === "run.result.accepted") { + const result = record(payload.result); + if (result.schema === "paperclip.run_result.v1" && text(result.summary)?.trim()) return "agentMessage"; + } + return null; + }; +} diff --git a/server/src/services/native-runtime/native-session-executor.test.ts b/server/src/services/native-runtime/native-session-executor.test.ts index 6c48569a2d6..66a235cc2ba 100644 --- a/server/src/services/native-runtime/native-session-executor.test.ts +++ b/server/src/services/native-runtime/native-session-executor.test.ts @@ -6324,6 +6324,98 @@ describe("native terminal-turn accounting", () => { }); describe("native resumed preparation timing", () => { + it.each(["comment.to_run_created", "question_response.to_run_created", "heartbeat.queue", "native_dispatch"])( + "records first assistant text once from %s through Core preparation and event receipt", + async (ingress) => { + const startedAtMs = Date.now() - 5_000; + const events: AdapterRuntimeEvent[] = []; + const clock = vi.spyOn(Date, "now").mockReturnValue(startedAtMs + 4_000); + const event = (eventType: string, payload: Record) => ({ + eventType, payload, itemId: "message", emittedAt: new Date(startedAtMs + 2_000).toISOString(), + }) as PrpEvent; + state.execute.mockReset().mockImplementationOnce(async () => { + for (const candidate of [ + event("turn.submitted", {}), + event("turn.started", {}), + event("item.started", { kind: "agentMessage" }), + event("item.completed", { kind: "agentMessage", text: " " }), + event("item.delta", { kind: "agentMessage", text: " " }), + event("item.delta", { kind: "agentMessage", text: 42 }), + event("item.delta", { kind: "reasoning", text: "" }), + event("item.delta", { kind: "toolCall", text: "arguments" }), + event("item.delta", { kind: "usage", text: "tokens" }), + event("tool.execution.started", { executionId: "tool-1" }), + ]) await accountingEvents.committed!(candidate); + await accountingEvents.duplicate!(event("item.delta", { kind: "agentMessage", text: "replayed text" })); + expect(events.some((candidate) => candidate.payload?.span === "task.time_to_first_token")).toBe(false); + clock.mockReturnValue(startedAtMs + 4_500); + await accountingEvents.committed!(event("item.delta", { kind: "agentMessage", text: "first text" })); + clock.mockReturnValue(startedAtMs + 4_750); + await accountingEvents.committed!(event("item.delta", { kind: "agentMessage", text: "later text" })); + return { result: { summary: "cancelled" }, terminal: { runTerminalState: "cancelled" }, + turnId: "turn", normalizedSessionId: "session", providerSessionId: null, + driverKind: "test", driverVersion: "1", nativeEventCount: 1, highestContiguousSourceSeq: 1 }; + }); + try { + await executePaperclipNativeSession({ + db: leaseDb(), execution, runnerInstanceId: "runner", + preparationSpans: ingress === "native_dispatch" ? [] : [{ name: ingress, startedAtMs, endedAtMs: startedAtMs + 100 }], + onEvent: async (event) => { events.push(event); }, + }); + } finally { clock.mockRestore(); } + const ttft = events.filter((event) => event.payload?.span === "task.time_to_first_token"); + expect(ttft).toHaveLength(1); + expect(ttft[0]?.payload).toMatchObject({ parentSpan: "task.provider_session", startOffsetMs: 0, + durationMs: ingress === "native_dispatch" ? 500 : 4_500, eventKind: "agentMessage", outcome: "ok" }); + expect(events.find((event) => event.payload?.span === "provider.time_to_first_agent_event")?.payload) + .toMatchObject({ parentSpan: "agent.turn", eventKind: "agentMessage" }); + expect(JSON.stringify(ttft)).not.toContain("first text"); + expect(JSON.stringify(ttft)).not.toContain("later text"); + }, + ); + + it.each([ + ["item.delta", { kind: "reasoning", text: "thinking" }, "reasoning"], + ["item.completed", { kind: "reasoning", text: "thought" }, "reasoning"], + ["item.completed", { kind: "agentMessage", text: "answer" }, "agentMessage"], + ["run.result.accepted", { result: { schema: "paperclip.run_result.v1", summary: "done" } }, "agentMessage"], + ["turn.completed", { outputTails: [{ itemId: "message", payload: { kind: "agentMessage", text: "settled text" } }] }, "agentMessage"], + ] as const)("records first deliverable %s %j once", async (eventType, payload, eventKind) => { + const events: AdapterRuntimeEvent[] = []; + state.execute.mockReset().mockImplementationOnce(async () => { + const first = { eventType, payload, itemId: "message" } as unknown as PrpEvent; + await accountingEvents.duplicate!(first); + expect(events.some((event) => event.payload?.span === "task.time_to_first_token")).toBe(false); + await accountingEvents.committed!(first); + await accountingEvents.committed!({ eventType: "item.delta", itemId: "message", + payload: { kind: "agentMessage", text: "later text" } } as unknown as PrpEvent); + return { result: { summary: "cancelled" }, terminal: { runTerminalState: "cancelled" }, + turnId: "turn", normalizedSessionId: "session", providerSessionId: null, + driverKind: "test", driverVersion: "1", nativeEventCount: 1, highestContiguousSourceSeq: 1 }; + }); + await executePaperclipNativeSession({ db: leaseDb(), execution, runnerInstanceId: "runner", + onEvent: async (event) => { events.push(event); } }); + const ttft = events.filter((event) => event.payload?.span === "task.time_to_first_token"); + expect(ttft).toHaveLength(1); + expect(ttft[0]?.payload).toMatchObject({ parentSpan: "task.provider_session", eventKind, outcome: "ok" }); + expect(JSON.stringify(ttft)).not.toContain("later text"); + }); + + it("omits first-token timing when execution fails before assistant output", async () => { + const events: AdapterRuntimeEvent[] = []; + const failure = new Error("provider failed before output"); + const issueProjection = vi.spyOn(issueServiceModule, "issueService").mockReturnValue({ + update: vi.fn(async () => ({ status: "blocked", statusVersion: 1 })), + } as unknown as ReturnType); + state.execute.mockReset().mockRejectedValueOnce(failure); + try { + await expect(executePaperclipNativeSession({ db: leaseDb(), execution, runnerInstanceId: "runner", + onEvent: async (event) => { events.push(event); }, + })).rejects.toBe(failure); + } finally { issueProjection.mockRestore(); } + expect(events.some((event) => event.payload?.span === "task.time_to_first_token")).toBe(false); + }); + it("keeps answered-question ingress at the run root rather than charging it to preparation", async () => { const answeredAtMs = Date.now(); const events: AdapterRuntimeEvent[] = []; diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index 69ffd01db7d..61092b3ce54 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -37,6 +37,7 @@ import { createAgentIdentityRedactor } from "../agent-identity-redaction.js"; import { parseCodexCliVersion } from "./codex-runtime-compatibility.js"; import { createNativeToolTrace, type NativeToolTrace } from "./native-tool-trace.js"; import { createNativeProviderFailureObservation } from "./native-provider-failure.js"; +import { createNativeDeliverableTextObservation } from "./native-deliverable-text.js"; import { createNativeGitHubAccess, type NativeGitHubAccess } from "./native-github-access.js"; import { resolveGitHubOperationCredentials } from "../github-operation-credentials.js"; import { bindManagedNativeCredentialTurn, completeManagedNativeCredentialTurn } from "./managed-native-credentials.js"; @@ -8248,6 +8249,8 @@ async function executePaperclipNativeSessionWithinScope( let turnSubmittedAtMs: number | null = null; let turnStartedAtMs: number | null = null; let firstAgentEventRecorded = false; + let firstTokenRecorded = false; + const observeDeliverableText = createNativeDeliverableTextObservation(); let providerUsageLimitObserved = false; const providerFailureObservation = createNativeProviderFailureObservation(input.execution.provider); let turnCompletedAtMs: number | null = null; @@ -8374,6 +8377,17 @@ async function executePaperclipNativeSessionWithinScope( privateKeyPem: input.runnerEnvironment?.PAPERCLIP_AGENT_PRIVATE_KEY, assertControllerActive, onCommittedEvent: async (event) => { + const textKind = !firstTokenRecorded ? observeDeliverableText(event) : null; + if (textKind) { + firstTokenRecorded = true; + await trace.record({ + name: "task.time_to_first_token", + parentName: "task.provider_session", + startedAtMs: trace.traceStartedAtMs, + endedAtMs: Date.now(), + attributes: { eventKind: textKind }, + }); + } await observeAccountingEvent(event); await toolTrace.observe(event); if (event.eventType === "item.completed" && @@ -8586,6 +8600,7 @@ async function executePaperclipNativeSessionWithinScope( ); }, onDuplicateEvent: async (event) => { + if (!firstTokenRecorded) observeDeliverableText(event); await observeAccountingEvent(event); // A crash can happen after the event commit but before its callback // finishes. Recover only idempotent durable projections here; activity, From b7506671b9cf4ae098bf791ebad3db941d492fa7 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sat, 24 Oct 2026 09:59:35 -0700 Subject: [PATCH 004/110] fix: preserve qualified snapshots during native setup validation (#17445) ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Native agent setup can validate a selected sandbox before the agent runs. > - A qualified snapshot binds the saved environment and resolved runtime to an immutable provider snapshot. > - Setup validation changes lease retention so each test starts fresh and leaves an archived sandbox for inspection. > - The test passed that changed config as the saved environment, which made valid snapshot proof appear stale. > - This pull request keeps saved qualification separate from the two test retention settings. > - Native setup can use the qualified snapshot and still clean up its test lease. ## Linked Issues or Issue Description Related: #15997, #17262. **What happened?** Native setup validation can return `environment_lease_acquire_failed` for a sandbox whose saved snapshot qualification is valid. The test changes `reuseLease` and `archiveOnRelease` before the runtime checks the saved configuration fingerprint. **Expected behavior** The test must qualify the original saved environment, acquire a fresh lease from its immutable snapshot, and preserve archive-on-release in the lease metadata. A changed image, provider, runtime config, or stale proof must still fail. **Steps to reproduce** 1. Save a Daytona snapshot environment with `reuseLease: true` and `archiveOnRelease: false`. 2. Store valid company-scoped snapshot qualification for the saved and resolved runtime configurations. 3. Run native agent setup validation against that environment. 4. Observe that the validation retention overrides invalidate the saved fingerprint before a provider lease is acquired. **Paperclip version or commit** Reproduced from master at `785d54636e1c8513ee5503d602daf6a5ee1970d6`. The fix is based on `62f60bf158746c5807763778326b1eba4f2ed18a`. **Deployment mode** Any server with a qualified native Daytona sandbox environment. ## What Changed - Pass the original saved environment to native setup lease acquisition. - Allow only `reuseLease` and `archiveOnRelease` to differ in the run configuration. Apply those fields after saved snapshot qualification. - Keep both retention fields in the acquired lease metadata so provider release still archives the test sandbox. - Add service-to-runtime cases for valid and stale proof, immutable snapshot selection, fresh lease retention, release behavior, and rejected non-retention overrides. - Extend the route regression to require the original saved configuration. ## Verification - The focused route regression failed before the fix because acquisition had no `configuredEnvironment`. - All 101 focused route, snapshot, and orchestration tests passed on the exact rebased head. - Full repository typecheck and build passed on exact head `15e13e119941090e85638005de54b2d14ea52c00`. - The local database regression could not start PostgreSQL because macOS could not allocate system semaphores. The full `pnpm test:run` attempt also reported database startup failures and was stopped as incomplete. Neither attempt is counted as passing. - Exact-head Linux CI passed all 179 environment runtime integration tests, including the seven new regression cases. Its server shard passed 3,635 tests with 16 existing skips. All exact-head CI gates passed. The final repository review must also complete before merge. - No live provider or model call is part of this verification. This PR does not deploy the fix. ## Risks The acquisition boundary now accepts two explicit retention-only differences. All other config fields, environment identity, company-scoped proof, resolved runtime fingerprint, and template binding remain subject to the existing checks. Regression cases reject changed snapshot, image, provider, and environment variables before provider dispatch. No schema or API contract changes. No user-facing command or documentation contract changes. ## Model Used OpenAI Codex, GPT-6 family, with reasoning, repository inspection, code execution, and test tools. The session does not expose an exact backend model identifier or 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 `#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 --- .../agent-test-environment-routes.test.ts | 4 ++ .../src/__tests__/environment-runtime.test.ts | 60 +++++++++++++++++++ server/src/services/agent-environment-test.ts | 1 + server/src/services/environment-runtime.ts | 6 +- 4 files changed, 68 insertions(+), 3 deletions(-) diff --git a/server/src/__tests__/agent-test-environment-routes.test.ts b/server/src/__tests__/agent-test-environment-routes.test.ts index a45feeff6bb..dcc2efacf48 100644 --- a/server/src/__tests__/agent-test-environment-routes.test.ts +++ b/server/src/__tests__/agent-test-environment-routes.test.ts @@ -804,6 +804,10 @@ describe("agent test-environment route", () => { expect(mockEnvironmentRuntime.acquireRunLease).toHaveBeenCalledWith( expect.objectContaining({ applyCustomImageTemplate: true, + configuredEnvironment: expect.objectContaining({ + id: "11111111-1111-4111-8111-111111111111", + config: { provider: "fake-plugin" }, + }), // The Test lease re-checks the company binding, so a binding change // between the route guard and the lease cannot open a foreign sandbox. assertCompanyBinding: true, diff --git a/server/src/__tests__/environment-runtime.test.ts b/server/src/__tests__/environment-runtime.test.ts index b5f4964700f..b926be7e975 100644 --- a/server/src/__tests__/environment-runtime.test.ts +++ b/server/src/__tests__/environment-runtime.test.ts @@ -45,6 +45,7 @@ import { import * as sandboxProviderRuntime from "../services/sandbox-provider-runtime.ts"; import * as environmentsModule from "../services/environments.ts"; import { logger } from "../middleware/logger.ts"; +import { agentEnvironmentTestService } from "../services/agent-environment-test.js"; import { resolveRunnerEnvironmentForRun } from "../services/runner-environment-lifecycle.js"; import { environmentService } from "../services/environments.ts"; import { remoteExecutionHasStopped } from "../services/remote-execution-termination.ts"; @@ -358,6 +359,65 @@ describeEmbeddedPostgres("environmentRuntimeService", () => { expect(acquired.lease.metadata?.snapshot).toBe(expectedSnapshot); }); + it.each(["qualified", "changed-base", "changed-runtime"] as const)("validates native setup against saved snapshot qualification (%s)", async state => { + const pluginId = randomUUID(); + const { companyId, environment: baseEnvironment } = await seedEnvironment(); + const config = { provider: "daytona", snapshot: "managed-snapshot", reuseLease: true, archiveOnRelease: false, timeoutMs: 1234 }; + await insertSandboxProviderPlugin(pluginId, { environmentDrivers: [{ driverKey: "daytona", kind: "sandbox_provider", displayName: "Daytona", configSchema: { type: "object" } }] }); + const svc = environmentService(db); + await svc.update(baseEnvironment.id, { driver: "sandbox", config }); + const environment = (await svc.getById(baseEnvironment.id))!; + const parsed = await resolveEnvironmentDriverConfigForRuntime(db, companyId, environment); + const snapshotId = "a6b9e7d0-f886-471a-b461-640dd03e8d0f"; + const proof = { v: 2, companyId, snapshot: config.snapshot, template: null, + baseConfigFingerprint: createHash("sha256").update(stableStringify(config)).digest("hex"), + runtimeConfigFingerprint: state === "changed-runtime" ? "0".repeat(64) : createHash("sha256").update(stableStringify(parsed.config)).digest("hex"), + snapshotIdentity: { provider: "daytona", requestedRef: config.snapshot, id: snapshotId, name: config.snapshot, organizationId: "provider-account", createdAt: "2000-01-01T00:00:00.000Z" }, + }; + await db.update(environments).set({ metadata: { paperclipSandboxPlatformProbes: { [companyId]: proof } }, + ...(state === "changed-base" ? { config: { ...config, snapshot: "replacement-snapshot" } } : {}) }).where(eq(environments.id, environment.id)); + const worker = createFreshPluginLeaseWorker(pluginId); + vi.mocked(worker.call).mockImplementation(async (_id, method, params: any) => { + if (method === "environmentAcquireLease") return { providerLeaseId: "setup-snapshot-lease", metadata: { provider: "daytona", snapshot: params.config.snapshot, remoteCwd: "/workspace" } }; + if (method === "environmentRealizeWorkspace") return { cwd: "/workspace" }; + if (method === "environmentReleaseLease") return { providerLeaseId: params.providerLeaseId, state: "archived" }; + throw new Error(`Unexpected ${method}`); + }); + const result = await agentEnvironmentTestService(db, worker).resolveAdapterTestExecutionContext({ companyId, environmentId: environment.id, adapterType: "paperclip_runner" }); + if (state !== "qualified") { + expect(result.executionTarget).toBeNull(); + expect(result.fallbackChecks).toMatchObject([{ code: "environment_lease_acquire_failed", detail: expect.stringContaining("sandbox_snapshot_qualification_required") }]); + expect(worker.call).not.toHaveBeenCalled(); + return; + } + expect(result.fallbackChecks).toEqual([]); + expect(result.executionTarget).toMatchObject({ kind: "remote", transport: "sandbox" }); + expect(worker.call).toHaveBeenCalledWith(pluginId, "environmentAcquireLease", expect.objectContaining({ config: expect.objectContaining({ snapshot: snapshotId, reuseLease: false, archiveOnRelease: true }) }), expect.any(Number)); + const leases = await svc.listLeases(environment.id); + expect(leases).toHaveLength(1); + expect(leases[0]).toMatchObject({ leasePolicy: "ephemeral", heartbeatRunId: null, providerLeaseId: "setup-snapshot-lease" }); + expect(leases[0]!.metadata).toMatchObject({ snapshot: snapshotId, reuseLease: false, archiveOnRelease: true }); + await result.release("released"); + expect(worker.call).toHaveBeenCalledWith(pluginId, "environmentReleaseLease", expect.objectContaining({ config: expect.objectContaining({ archiveOnRelease: true }), providerLeaseId: "setup-snapshot-lease" }), expect.any(Number)); + expect((await svc.getById(environment.id))!.config).toEqual(config); + }); + + it.each([ + { snapshot: "another-snapshot" }, + { image: "another-image" }, + { provider: "another-provider" }, + { env: { DIFFERENT_RUNTIME: "changed" } }, + ])("rejects non-retention run overrides before provider dispatch (%j)", async override => { + const { companyId, environment: baseEnvironment } = await seedEnvironment(); + const environment = { ...baseEnvironment, driver: "sandbox", config: { provider: "daytona", snapshot: "managed-snapshot" } }; + const worker = createFreshPluginLeaseWorker(randomUUID()); + const service = environmentRuntimeService(db, { pluginWorkerManager: worker }); + await expect(service.acquireRunLease({ companyId, environment: { ...environment, config: { ...environment.config, ...override, reuseLease: false, archiveOnRelease: true } }, + configuredEnvironment: environment, issueId: null, heartbeatRunId: null, persistedExecutionWorkspace: null, adapterType: "paperclip_runner" })) + .rejects.toThrow("Run environment does not match its saved configuration."); + expect(worker.call).not.toHaveBeenCalled(); + }); + it.each(["failed-probe", "config-change", "config-and-metadata-change"] as const)("refuses a mutable snapshot after %s invalidates its proof", async invalidation => { const { companyId, environment: baseEnvironment, runId } = await seedEnvironment(); const config = { provider: "daytona", snapshot: "managed-snapshot", reuseLease: false }; diff --git a/server/src/services/agent-environment-test.ts b/server/src/services/agent-environment-test.ts index 5183beec2a8..1bf658d31df 100644 --- a/server/src/services/agent-environment-test.ts +++ b/server/src/services/agent-environment-test.ts @@ -231,6 +231,7 @@ export function agentEnvironmentTestService(db: Db, pluginWorkerManager?: Plugin ...(environment.driver === "plugin" && input.adapterType === "paperclip_runner" ? { requestedExpiresAt: new Date(Date.now() + 180_000) } : {}), environment: testEnvironment, + configuredEnvironment: environment, issueId: null, heartbeatRunId: null, persistedExecutionWorkspace: null, diff --git a/server/src/services/environment-runtime.ts b/server/src/services/environment-runtime.ts index edf646410d4..b3c53737bef 100644 --- a/server/src/services/environment-runtime.ts +++ b/server/src/services/environment-runtime.ts @@ -1856,8 +1856,8 @@ function createSandboxEnvironmentDriver( // or account used for qualification and custom-template resolution. if (configuredEnvironment.id !== input.environment.id || configuredEnvironment.driver !== input.environment.driver - || stableStringify({ ...configuredEnvironment.config, reuseLease: undefined }) - !== stableStringify({ ...input.environment.config, reuseLease: undefined })) { + || stableStringify({ ...configuredEnvironment.config, reuseLease: undefined, archiveOnRelease: undefined }) + !== stableStringify({ ...input.environment.config, reuseLease: undefined, archiveOnRelease: undefined })) { throw new Error("Run environment does not match its saved configuration."); } const storedParsed = parseEnvironmentDriverConfig(input.environment); @@ -1877,7 +1877,7 @@ function createSandboxEnvironmentDriver( && hasSandboxSnapshotQualification(configuredEnvironment, input.companyId)) { throw new Error("sandbox_snapshot_qualification_required: The snapshot qualification is missing or stale. Test this environment again before running Paperclip Runner."); } - if (input.configuredEnvironment) parsed.config = { ...parsed.config, reuseLease: storedParsed.config.reuseLease }; + if (input.configuredEnvironment) parsed.config = { ...parsed.config, reuseLease: storedParsed.config.reuseLease, archiveOnRelease: storedParsed.config.archiveOnRelease }; if (pinnedSnapshotId) parsed.config = { ...parsed.config, snapshot: pinnedSnapshotId }; // Check if this provider should be handled by a plugin. From 7ae81c9fa7c9bc76252fb047eabbba7d33175429 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sat, 24 Oct 2026 10:29:15 -0700 Subject: [PATCH 005/110] fix(slack): support rich questions and complete review delivery (#17255) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Questions and review decisions must work in the conversation where a task started. > - Slack omitted question context and did not publish several review kinds. > - Some answers saved in Paperclip also lost their authorized continuation or their final Slack reply. > - A settled card and a successful run did not prove that the user received the result. > - This pull request preserves complete questions and follows the existing answer and delivery receipts through continuation. > - Users can read the request, submit an authorized decision, and receive the resumed task's result in the same conversation. ## Linked Issues or Issue Description Refs #17045 and #17218. **What happened?** Slack question cards could omit instructions and editable starting text. Checkbox reviews, item verdicts, task suggestions, and connection requests had no publication path. Complex question answers submitted in Paperclip could fail continuation authorization. Several review continuations completed without delivering their result to Slack. **Expected behavior** Show the actual question and context. Use native Slack controls when they preserve the form contract. Otherwise provide an explicit Paperclip review link. Persist one authorized response, resume through the existing delivery path, settle the card, and deliver the useful result to its originating conversation. **Steps to reproduce** 1. Start a task in Slack and ask a text or choice question with instructions and help text. 2. Submit native text and choice responses, then submit a complex form through Paperclip. 3. Accept a checklist, submit item decisions, select suggested tasks, or decline a connection request. 4. Inspect the saved answer, continuation run, original Slack card, and final Slack reply independently. ## What Changed - Preserve full prompts, context, descriptions, recommendations, help, and editable starting text. Use direct buttons for short choices, inline searchable selects for longer lists, and native checkboxes with explicit submission for multiple choices. - Add native custom-answer and validated-text modals, ordinary confirmation buttons, checklist decisions, per-item verdicts with reasons, suggested-task creation/dismissal, and connection decline. Keep governed approvals, permission grants, and forms that cannot be represented faithfully in the full Paperclip review surface. - Keep Slack-specific canonical-validation feedback in its owning platform module. Shared callbacks delegate without interpreting provider presentation. - Reuse the existing canonical interaction transactions, callback receipts, publication queue, and continuation delivery. Share ordinary confirmation handling across Telegram and Slack. Recheck current authorization and commit response receipts atomically. - Settle cards with the saved answer and remove stale controls. Ignore passive Slack link callbacks so opening a task does not display a false answer error. - Validate exact multi-select receipt mappings during native continuation. Recover automation-origin connection replies from their published prompt after validating the durable connection receipt. - Keep oversized multi-select handoffs free of unused native tokens, and retain the complete Paperclip form for 101–128 choices plus Other. Make the original-conversation audience explicit before submitting a Slack modal. - Add rollback, provider serialization, callback, continuation, and negative authorization regressions. Update the connector playbook and feature/access maps. No React or application UI changes are included. - Add a durable Q01–Q11 qualification index and provider coverage matrix. Require distinct functional, good-experience, and best-available-control assessments; real unanswered/answering/settled evidence; saved results, continuation and navigation proof; and retained failures. Mark other providers unaudited rather than assuming Slack parity. ## Verification Candidate: `e0017d446b1016a38d65382366cd1408cce33039`. The eleven-core-format live Slack gallery is pinned to `c3d458b2a06b660448940fd8cf33c5906f0058d5`; subsequent boundary fixes and the sharing notice have automated verification, not new live screenshots. - Real Slack UI testing covered all 11 formats: text, closed choice, long single select, multiple choices, choices with a custom answer, pattern-validated text, confirmation, checklist, item verdicts, suggested tasks, and connection requests. Each has unanswered/answering/answered screenshots as applicable, an inspected saved result, one continuation, and an individual experience review in the local HTML gallery. - The dedicated private QA app/channel used signed callbacks to the local candidate. A separately approved password-protected, read-only preview proved connection-review, suggested-task review, and created-task navigation. Anonymous access, writes, and credential routes were denied. No OAuth grant was attempted. - Real testing exposed and repaired a multi-select continuation failure and a misleading error on link-button clicks. Failed attempts remain in the evidence. The final navigation replay opened the exact pending connection request and declined it in Slack without granting access. Suggested-task creation produced the selected child with the correct parent and description. - Final review-fix verification: **32 form tests**, **28 provider/form-rendering tests**, **30 publication tests**, and **171 native continuation/authorization tests** passed. Earlier **3 atomic-resolution rollback**, **9 targeted callback/publication/Telegram**, and **28 review-continuation** cases passed. The final Slack/Teams modal subset also passed. The automation-origin connection cases, 101/128 custom-choice cases, and oversized multi-select continuation reproduced before their fixes and passed afterward; failing logs remain retained. These counts describe relevant runs, not a reliability percentage. - CI on `b5885b85fd` exposed a test fixture that assumed every Slack modal block was an input; the new sharing notice correctly renders a non-input block. The fixture now selects input blocks safely. The exact signed-modal correction/one-continuation test passed locally, together with 14 Slack form/modal tests. The failing CI log and its specific cause remain recorded. - `pnpm -r typecheck` and `pnpm build` passed. Server typechecking was repeated after the final source changes. Map and module-boundary checks and `git diff --check` passed. - The full `pnpm test:run` was attempted and stopped after repeated embedded PostgreSQL semaphore exhaustion on this host. Its 1,395-test chat suite found two stale native-control assertions; both were corrected and re-tested in a focused run. Focused database suites used separate disposable databases on existing local PostgreSQL. The full suite is not claimed green; new-head CI must complete before merge. - Final-head CI passed on `e0017d446b1016a38d65382366cd1408cce33039`: all test/build jobs and required `ci / verify` and `ci / e2e` gates are green ([run](https://github.com/paperclipai/paperclip/actions/runs/40115430194)). Greptile and Ponytail both reviewed this exact head at 5/5, the security scan passed, and all review threads are resolved. - All three QA app callbacks were restored to staging. Both temporary tunnels and local proxies were closed. The local endpoint was archived and its local credential copies removed. The candidate app was stopped. Limits: provider execution used a deterministic Claude protocol fixture, not an LLM. This is local real-provider UX proof, not deployed staging or broader Codie/Claude qualification. The public preview intentionally blocked ancillary artifact routes, so its destination pages could show a partial-history warning. The complete permission-grant flow and every oversized/mixed-form branch were not driven manually. Earlier fixture, test, and provider failures remain recorded. ## Risks - New reply routes require durable origin proof. Incorrect receipt matching could lose a reply or route it incorrectly. Tests cover missing, forged, mismatched, and revoked authority. - Governed forms keep their Paperclip resolution checks. This change does not grant new approval authority to Slack. - Existing completed review results can become deliverable through the repaired publication path without another provider run. - No schema, lockfile, workflow, public task-status model, or runtime-instruction change is included. This branch is not deployed. ## Model Used OpenAI Codex, GPT-6 family, with code execution and tool use. The exact backend model ID and context-window size 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 linked existing issues or described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links - [x] My branch name describes the change and contains no internal Paperclip ticket id - [x] I have run focused 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 on the new head - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups on the new head - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip --- .../create-issue-interaction-ui/SKILL.md | 43 ++- doc/connections/CHAT-CONNECTOR-UX.md | 26 ++ doc/connections/CHAT-QUESTION-COVERAGE.md | 139 ++++++++++ doc/connections/CONNECTOR-PLAYBOOK.md | 249 +++++++++++++++++- doc/connections/README.md | 4 + .../questions-and-approvals.md | 17 ++ maps/feature-map/questions-and-approvals.md | 23 +- packages/shared/src/types/chat-channels.ts | 8 + .../chat-channels.integration.test.ts | 48 +++- .../chat-interaction-publications.test.ts | 223 ++++++++++++++-- .../__tests__/heartbeat-run-summary.test.ts | 2 +- .../issue-thread-interactions-service.test.ts | 27 ++ .../satisfied-connection-intents.test.ts | 24 +- server/src/services/chat-channels.ts | 1 + .../chat-channels/interactions/callbacks.ts | 112 ++++---- .../confirmation-actions.ts | 215 ++++++++------- .../chat-channels/publication-replacement.ts | 13 - .../chat-channels/publications/transport.ts | 2 + .../services/chat-channels/slack/adapter.ts | 25 +- .../chat-channels/slack/cards.test.ts | 91 +++++++ .../src/services/chat-channels/slack/cards.ts | 98 +++++++ .../slack/question-forms.test.ts | 28 ++ .../chat-channels/slack/question-forms.ts | 24 ++ .../services/chat-interaction-arbitration.ts | 5 +- .../chat-interaction-continuation.test.ts | 142 ++++++++++ .../services/chat-interaction-continuation.ts | 75 ++++++ .../services/chat-interaction-forms.test.ts | 44 ++++ server/src/services/chat-interaction-forms.ts | 37 +++ .../services/chat-interaction-presentation.ts | 83 ++++++ .../services/chat-interaction-publications.ts | 235 ++++++++++------- .../services/chat-publication-projection.ts | 20 ++ .../src/services/chat-question-forms.test.ts | 61 ++++- server/src/services/chat-question-forms.ts | 100 ++++--- server/src/services/chat-run-publications.ts | 32 ++- server/src/services/chat-sdk-runtime.ts | 9 +- .../services/chat-slack-native-modal.test.ts | 39 ++- server/src/services/connection-intents.ts | 5 +- server/src/services/heartbeat-run-summary.ts | 3 +- .../src/services/issue-thread-interactions.ts | 52 +++- server/src/services/issues.ts | 37 ++- .../external-chat-question-response.ts | 71 +++-- .../external-chat-wait.integration.test.ts | 86 ++++-- .../services/satisfied-connection-intents.ts | 9 +- 43 files changed, 2171 insertions(+), 416 deletions(-) create mode 100644 doc/connections/CHAT-QUESTION-COVERAGE.md rename server/src/services/chat-channels/{telegram => interactions}/confirmation-actions.ts (77%) create mode 100644 server/src/services/chat-channels/slack/cards.test.ts create mode 100644 server/src/services/chat-channels/slack/cards.ts create mode 100644 server/src/services/chat-channels/slack/question-forms.test.ts create mode 100644 server/src/services/chat-channels/slack/question-forms.ts create mode 100644 server/src/services/chat-interaction-continuation.test.ts create mode 100644 server/src/services/chat-interaction-continuation.ts create mode 100644 server/src/services/chat-interaction-forms.test.ts create mode 100644 server/src/services/chat-interaction-forms.ts create mode 100644 server/src/services/chat-interaction-presentation.ts diff --git a/.agents/skills/create-issue-interaction-ui/SKILL.md b/.agents/skills/create-issue-interaction-ui/SKILL.md index 984a81ad612..645454d1d5a 100644 --- a/.agents/skills/create-issue-interaction-ui/SKILL.md +++ b/.agents/skills/create-issue-interaction-ui/SKILL.md @@ -39,22 +39,25 @@ Do NOT install this on production Paperclip agents. This guide is for repository ## Mental model -Every issue-thread interaction has four moving parts: +Every issue-thread interaction has five moving parts: | Layer | Owns | |--------------|---------------------------------------------------------------------------------------------------| | Shared | Kind constant, payload/result interfaces, Zod validators, exported types, shared-test coverage. | | Server | Service create/accept/reject/respond, staleness, supersede, idempotency, activity log, wake send. | | UI | Card pending/resolved/stale states, fixtures, Storybook, issue-thread/IssueDetail wiring. | +| Channels | Complete question/context, native response or Paperclip handoff, callback authorization, and settled provider cards. | | Helpers/Docs | CLI command, MCP tool, plugin SDK type+host+testing path, `skills/paperclip` guidance. | -The four existing kinds are the canonical prior art. Pick the closest one and -copy its plumbing rather than inventing parallel mechanics: +Use the current `ISSUE_THREAD_INTERACTION_KINDS` as the inventory. Pick the +closest existing kind and reuse its plumbing rather than inventing parallel mechanics: - `request_confirmation` — single yes/no bound to a `target` with stale/supersede. - `request_checkbox_confirmation` — bounded multi-select against an immutable option set. - `ask_user_questions` — small typed form, no target binding. -- `suggest_tasks` — proposes tasks the board can accept individually. +- `request_item_verdicts` — requests individual decisions on a set of items. +- `suggest_tasks` — proposes tasks a permitted resolver can accept individually. +- `connection_intent` — requests authorized connection setup or access. If your new card needs target binding and a yes/no-style resolution, model it after the two `request_*` kinds. If it is a structured form, model it after @@ -130,15 +133,16 @@ Touch: Server invariants: -- Board-only resolution. Agent-authored accept/reject must be rejected with - the existing 403 path; do not add a per-kind bypass. +- Resolver authority. Use the current resolver policy, company cap, and named + addressee checks in the shared service. Governed actions retain their required + human approval; neither a new kind nor a channel callback widens authority. - Company scoping. Reads, writes, expiration, and supersede must all filter by `companyId`. Never trust an `issueId` alone. - Stale target. If `target` was specified at create time and a newer revision lands, the interaction expires with `outcome: "stale_target"`. Do not write bespoke staleness — call the same helper the other `request_*` kinds use. -- Supersede on user comment. Default `supersedeOnUserComment: true` unless - the payload schema documents otherwise. +- Supersede on user comment. Preserve the payload schema's default and explicit + choice; an ordinary comment must not silently answer a pending question. - Idempotency. The deterministic `idempotencyKey` shape from the existing kinds (`:::`) must be honored; duplicate POSTs must return the existing card, not stack. @@ -183,6 +187,24 @@ UI invariants: - Stale, superseded, and accepted states render distinct copy; reuse the existing resolution-component shell. +### 3a. Channel questions and review cards + +Read the [chat channel connector contract](../../../doc/connections/CONNECTOR-PLAYBOOK.md#chat-channel-connectors). +Every new kind or changed form needs a usable path through each supported +conversation channel: complete safe question/context plus native response controls +or an explicit link to the authorized Paperclip surface. Include runtime/composer +variants; do not assume that adding a board card makes it available in Slack. + +Extend the existing presentation, publication, response, and settlement owners. +Preserve authorization and the existing continuation/delivery receipts. Cover +resolved, rejected, expired, superseded, and recovery paths so a settled request +cannot remain actionable in the channel. Keep dismissal distinct from resolution. + +Run local serialization and lifecycle tests first, then verify affected forms in +the actual provider with an authorized test conversation. Capture rendering, +answer persistence, the intended continuation, and final card/result delivery. +State clearly when provider HTTP was simulated or live acceptance is outstanding. + ### 4. CLI, MCP, plugin SDK helpers External callers must be able to create the new interaction without @@ -246,11 +268,14 @@ If UI vitest fails with `act is not a function`, the shell is running with - [ ] Service handles create, accept, reject/respond, stale-target, supersede-on-user-comment, idempotency, activity log, and continuation wake. -- [ ] Routes honor board-only resolution and company scoping. +- [ ] Routes and channel callbacks honor current resolver authority and company scoping. - [ ] UI renders pending, resolved, stale, disabled/submitting, and validation-error states; resolved-state large selections summarize by count first. - [ ] Fixtures and Storybook entries exist for the new kind. +- [ ] Every supported channel has a native response or explicit Paperclip handoff + for the form, with settlement and continuation coverage. Local simulations + and real-provider acceptance are reported separately. - [ ] CLI, MCP, and plugin SDK helpers all accept the new payload shape and have test coverage. - [ ] `skills/paperclip/SKILL.md` and `references/api-reference.md` updated. diff --git a/doc/connections/CHAT-CONNECTOR-UX.md b/doc/connections/CHAT-CONNECTOR-UX.md index 167ae968863..c83814714e0 100644 --- a/doc/connections/CHAT-CONNECTOR-UX.md +++ b/doc/connections/CHAT-CONNECTOR-UX.md @@ -259,6 +259,32 @@ assignment, delegation, and origin-thread completion use normal Paperclip workflows. Identify missing workflow capabilities separately rather than adding a connector-specific task lifecycle. +## Questions and review cards through the channel + +A connected conversation must carry every user-question form, including requests +shown above the Paperclip composer and questions from the runtime. Follow the +[chat channel contract](./CONNECTOR-PLAYBOOK.md#chat-channel-connectors) for the +complete inventory, native-response versus Paperclip-handoff decision, current +authorization, and resolution/continuation behavior. Show the actual question +and useful context in the channel; a title and **Respond** button alone do not +satisfy that contract. Unsupported native controls need an explicit, usable +handoff, not a missing request. + +Use the [eleven-experience inventory](./CONNECTOR-PLAYBOOK.md#question-experience-inventory) +and [provider coverage index](./CHAT-QUESTION-COVERAGE.md) to record the best +supported controls and justified handoffs. Grade functional correctness, good +experience, and best feasible experience separately. Review actual unanswered, +answering, and settled screens yourself; saved answers must remain readable +within the conversation's authorized audience. A browser fallback does not pass +the quality bar when a suitable native control avoids it. + +The optional first-message test in onboarding does not replace engineering +qualification of these conversation loops. Follow the +[per-format evidence standard](./CONNECTOR-PLAYBOOK.md#retain-inspectable-per-format-evidence), +including actual link clicks, saved responses, continuation and delivery receipts, +and retained failures. Keep real-provider evidence separate from local simulations, +live-model runs, and deployed verification. + ## Apply and verify For a requested redesign, identify the relevant principles and fix the concrete diff --git a/doc/connections/CHAT-QUESTION-COVERAGE.md b/doc/connections/CHAT-QUESTION-COVERAGE.md new file mode 100644 index 00000000000..fac2d514346 --- /dev/null +++ b/doc/connections/CHAT-QUESTION-COVERAGE.md @@ -0,0 +1,139 @@ +# Chat channel question coverage index + +This is the index of per-provider question qualification records. The +[connector playbook](./CONNECTOR-PLAYBOOK.md#question-experience-inventory) owns +the Q01–Q11 inventory, control-selection principles, and acceptance standard. +Keep that inventory and this index in sync when a channel or question experience +changes. Provider capability flags alone do not establish support for a form. + +## Provider records + +The provider list comes from `CHAT_PROVIDERS` in +`packages/shared/src/types/chat-channels.ts`. Add a record for a new provider; +update the affected record for a changed form. An unaudited row means this index +has no qualification record for it, not that the provider lacks controls or that +its existing implementation is broken. + +| Provider | Q01–Q11 record | Scope and status | +| --- | --- | --- | +| Slack | [October 24, 2026 baseline](#slack-october-24-2026) | All eleven core experiences observed in real Slack against a local candidate; limited scope below. Later changes require affected-case remeasurement. | +| GitHub | Not yet indexed | Audit all applicable question paths, including comment replies and authenticated handoffs; no qualification claim here. | +| Discord | Not yet indexed | Audit all applicable question paths; no qualification claim here. | +| Microsoft Teams | Not yet indexed | Audit all applicable question paths; no qualification claim here. | +| Telegram | Not yet indexed | Audit all applicable question paths; no qualification claim here. | +| Speko | Not yet indexed | Establish applicable conversational paths and equivalents for controls; no qualification claim here. | +| AgentMail | Not yet indexed | Include email reply and authenticated handoff behavior; no qualification claim here. | +| iMessage Photon | Not yet indexed | Audit all applicable question paths; no qualification claim here. | + +Do not turn an untested native path into “unsupported” or “not applicable.” +Research provider capabilities before choosing a response path. A text/reply-only +channel can meet the standard with an understandable, correctly bound reply or +an exact authenticated handoff; it need not imitate Slack's UI. + +## Provider record template + +Keep the record here or in a provider-specific document linked above. Use one row +per inventory ID and relevant variant. Every row needs a state, including gaps; +never drop difficult forms from the denominator. + +Record metadata once per campaign: + +- Accountable owner, date, source commit and dirty-tree fingerprint if relevant, + provider/client surface, adapter/SDK versions, and redacted configuration. +- Test scope: local serialization, real-provider local candidate, live-model + behavior, or deployed verification. Name a deterministic fixture as such. +- Source entry points: runtime input, composer/card, legacy payload, or canonical + question set. List applicable variants and those not exercised. +- Authorized isolated bot/channel and conversation references, reproducible + setup, evidence location accessible to reviewers, and cleanup outcome. Keep + private conversation links and credentials out of public repository records. + +Use this row schema: + +| Field | Required content | +| --- | --- | +| Inventory ID and variant | Q01–Q11 or a newly added ID, exact payload/source entry point, and required/optional/default/size variations. | +| Provider capability and treatment | Native control, structured reply, or Paperclip handoff; official capability/limit reference and installed adapter behavior. Explain why this is the best feasible path. | +| Canonical mapping and authority | How the response maps to the saved question/decision, actor and conversation, including validation and current authorization. A review-link click is navigation, not a response or grant. | +| Functional status | Pass, fail, not run, or not applicable with reason; expected versus actual saved result, canonical continuation policy/count, artifacts, and delivery receipts. | +| Experience grades | Separate ✓/✕ for good experience and best feasible experience, with a short rationale after inspecting unanswered, answering, and settled states. Missing inspection is not run. | +| Evidence and history | Actual provider captures and link-click outcomes, durable-state correlation, failed attempts, repair/retest, and exact candidate for each attempt. | +| Remaining coverage | Untested variants, boundary/negative-test coverage, provider constraints, and any live-model or deployment gap. Name the next required check. | + +Prefer a browsable per-format gallery. Keep the conclusions and coverage gaps in +this durable record or the PR even if its temporary preview expires. Sensitive +evidence can stay in an access-controlled artifact with an accessible reference; +do not copy secrets or private tenant data into the index. Reuse existing test +harnesses and publication/continuation contracts instead of inventing a provider +workflow engine to fill a matrix cell. + +## Slack: October 24, 2026 + +Reference implementation and review: +[PR #17255](https://github.com/paperclipai/paperclip/pull/17255). +The local campaign's final implementation was recorded as +`c3d458b2a06b660448940fd8cf33c5906f0058d5`; captures were collected during its +implementation, with failures and repairs retained in the campaign gallery. +This is a historical evidence summary, not a certification of later PR heads +or staging. The PR verification section records later regression fixes/checks. + +**Scope:** dedicated real Slack QA conversation, local server candidate, desktop +Slack client, and a deterministic agent protocol fixture. Each core case had an +actual unanswered/answered pair, saved result, one intended continuation, and a +published final reply. Open controls and validation states were captured where +applicable. The author inspected the gallery and graded each captured experience. +The local gallery remains in the originating work chat; it is not a public or +permanent hosted acceptance artifact. Reproduce affected cases when that private +evidence is unavailable to the reviewer. + +The table describes exercised paths, not every possible payload within a kind. +The playbook defines the preferred behavior and broader variant requirements. + +| ID | Path exercised in Slack | Observed functional result | Good / best feasible | Scope notes | +| --- | --- | --- | --- | --- | +| Q01 | Native multiline text modal | Pass | ✓ / ✓ | Full prompt/context, editable starting text, saved answer retained. | +| Q02 | Direct choice buttons | Pass | ✓ / ✓ | Descriptions and recommendation visible; selected label retained. | +| Q03 | Inline searchable single-select | Pass | ✓ / ✓ | Selected the thirteenth option by searching; saved label remained visible. | +| Q04 | Checkboxes and explicit submit | Pass after repair | ✓ / ✓ | Empty submission feedback, two selected labels retained, and one continuation after fixing multi-selection authorization. Original failure retained. | +| Q05 | Choice buttons plus **Other…** text modal | Pass | ✓ / ✓ | Both listed and custom answers exercised; descriptions and recommendation retained. | +| Q06 | Native text modal with inline validation | Pass | ✓ / ✓ | Invalid pattern kept the draft open; corrected answer saved and continued. Not every numeric/length variant was tested live. | +| Q07 | Accept/Reject buttons | Pass | ✓ / ✓ | Ordinary acceptance exercised. Governed and required-reason variants retain the canonical review path; not all were tested live. | +| Q08 | Checklist with Save and Reject | Pass | ✓ / ✓ | Defaults and bounds visible; over-selection rejected, correction saved, exact selection retained. | +| Q09 | Native per-item radio choices and reason fields | Pass | ✓ / ✓ | Required-reason validation and atomic submission exercised; decisions and reasons readable afterward. | +| Q10 | Create task, multi-proposal selection/Create selected, and Dismiss | Pass | ✓ / ✓ | Reviewed created task title/description/parent independently; clicked review and created-task links to their correct destinations. | +| Q11 | Authenticated **Review connection** handoff and native **Not now** | Pass after repair | ✓ / ✓ | Clicked the exact review destination and exercised decline without a grant; removed a spurious error caused by the passive link callback. No OAuth/access grant attempted. | + +**Remaining scope:** these eleven cases do not establish all large/mixed-form +boundaries, every terminal state, mobile behavior, other providers, live-model +judgment, or deployed staging behavior. Deterministic regressions cover additional +authorization, duplicate-response, and fallback cases. Later review identified +oversized multi-select continuation and large custom-choice fallback defects; +their failed-before tests, fixes, and final-head verification belong to the PR +record and must not be hidden by this core-case scorecard. + +**Cleanup:** restored the QA app's original callbacks, closed temporary callback +and read-only preview tunnels, and removed temporary local credential copies. +The read-only preview exercised navigation, not a connection permission grant. + +### Lessons behind the quality bar + +The PAP-701 investigation and this campaign exposed distinct failures: + +1. A title plus **Respond** hid the actual question and context. Inventory + question content and its answering path, not only interaction kinds. +2. The first eleven-case gallery proved saved results returned to Slack, but + only three cases answered natively and only one passed the complete UX + review. Functional parity and “native” are both weaker than a good experience. +3. Real multi-select submission saved correctly but failed continuation + authorization. Inspect durable results and subsequent delivery alongside the + screenshots; a settled card is not completion. +4. The connection review link reached its destination while its callback also + displayed a misleading error. Click every relevant handoff/result link and + inspect both sides before grading it. +5. Later boundary review found gaps beyond the core gallery. Keep core-case UX + evidence separate from boundary coverage, retain failures, and remeasure + changed paths on the candidate that will ship. + +These are reusable acceptance requirements. The eleven Slack cases, particular +option counts, fixture choice, and temporary tunnel setup are campaign details; +future providers must research their own controls, limits, and delivery mechanism. diff --git a/doc/connections/CONNECTOR-PLAYBOOK.md b/doc/connections/CONNECTOR-PLAYBOOK.md index 8f4b2566b33..9343d1441c0 100644 --- a/doc/connections/CONNECTOR-PLAYBOOK.md +++ b/doc/connections/CONNECTOR-PLAYBOOK.md @@ -3,7 +3,8 @@ Audience: agents and engineers researching, implementing, testing, reviewing, and shipping Paperclip app connections. -Status: canonical end-to-end authoring guide for Apps v2 catalog connections. +Status: canonical end-to-end authoring guide for Apps v2 tool connections and +chat channel connectors. Experimental voice connections use the same company-scoped channel endpoints, vault, task bindings, delivery ledger and publications, with `transport: voice` @@ -33,7 +34,12 @@ For chat and email setup, account linking, and ongoing configuration, also follo layout, credential instructions, provider handoffs, identity linking, optional message tests, and management pages, with examples for other providers. -Use it when Paperclip acts on an external system through a governed connection: a stored credential, a capability catalog, access profiles and policy rules, and audit. Inbound integrations, such as an external client acting on Paperclip, use gateway or webhook guidance instead. +Use the tool-connection workflow when Paperclip acts on an external system +through a governed credential and capability catalog. For conversations with +agents in Slack or another messaging provider, also follow +[Chat channel connectors](#chat-channel-connectors), including inbound messages, +questions, responses, and delivery. Other inbound integrations, such as an +external API client acting on Paperclip, use gateway or webhook guidance. **A catalog entry is a convenience layer, not a prerequisite.** An operator can connect any standards-compliant remote HTTP MCP server from **Connect your own MCP server** @@ -196,6 +202,7 @@ read/write proof separately and never describe metadata discovery as live proof. - [Golden-path agent tutorial](#golden-path-agent-tutorial) - [Connection UX and user journeys](#connection-ux-and-user-journeys) - [Optional agent instructions](#optional-agent-instructions) +- [Chat channel connectors](#chat-channel-connectors) - [Chat and email connector UX](./CHAT-CONNECTOR-UX.md) - [Production validation evidence](#step-9-align-with-production-validation) - [AppDefinition field reference](#appdefinition-field-reference) @@ -221,6 +228,238 @@ A complete connector proposal produces: denied/quarantined call when the method declares one, revoke, and audit evidence. +## Chat channel connectors + +A tool connection gives an agent actions it can call. A chat channel connector +makes Slack, Teams, Discord, Telegram, email, or another conversation surface a +place where a person can conduct work with an agent. It must carry questions, +decisions, follow-ups, and results through the conversation. Authentication, +tool discovery, and a successful outbound message alone do not qualify it. +A provider can offer both kinds of connection; do not assume that its tool +connection also implements its conversation channel. + +Reuse company-scoped endpoints, verified identity links, task/conversation +bindings, durable interactions, publication queues, and response-delivery receipts. +Keep provider payloads, UI limits, and callback protocols in their platform module; +follow [chat channel platform boundaries](../../rules/chat-channel-platform-boundaries.mdc). +Setup and account linking follow [Chat connector UX](./CHAT-CONNECTOR-UX.md). + +### Cover every user-question form + +For a new channel, build a capability matrix from the current shared interaction +kinds, payload validators, and runtime/composer question entry points. For a new +or changed form, update that matrix for every supported channel. Start with +`ISSUE_THREAD_INTERACTION_KINDS` in `packages/shared/src/constants.ts` and the +question contracts in `packages/shared/src/types/issue.ts` and +`packages/shared/src/validators/issue.ts`; do not treat this list as frozen. + +| Request family | Required coverage | +| --- | --- | +| `ask_user_questions` and runtime/composer input questions | Free text, single-select, multi-select, multiple questions, custom answers, and editable starting text. Include legacy payloads and canonical `paperclip.question_set.v1` forms. | +| `request_confirmation` | The decision, supporting context, and accept/reject outcome. | +| `request_checkbox_confirmation` | The options, selection constraints, and exact submitted selection. | +| `request_item_verdicts` | Each item, its evidence/context, and individual decisions. | +| `suggest_tasks` | The proposed tasks and the decision for each proposal. | +| `connection_intent` | The requested connection/access, why it is needed, and the authorized setup or review path. | +| Approval or runtime permission requests outside the interaction kinds | An explicit route to the existing authorized approval surface; a chat response must not create new approval authority. | + +### Question experience inventory + +The request-family table describes contracts; it is not a sufficient UX test +inventory. Enumerate these eleven experiences separately because the same +`ask_user_questions` kind can require very different controls. These IDs are +shared with the [channel question coverage index](./CHAT-QUESTION-COVERAGE.md). +Add rows when the contracts gain an experience this inventory does not cover. + +| ID | Experience | Preferred interaction when the provider supports it | +| --- | --- | --- | +| Q01 | Free text | Native text entry with the full prompt, useful context, editable starting text, and multiline support where needed. | +| Q02 | Short, closed single choice | Direct labeled buttons. Preserve option descriptions and recommendations; do not require a modal just to choose one item. | +| Q03 | Long option single-select | An inline searchable picker where available; preserve complete labels and the selected value. | +| Q04 | Multiple selection | Checkboxes or a multi-select with an explicit submit action and visible selection bounds. Selecting one item must not prematurely submit the form. | +| Q05 | Choice plus custom answer | The appropriate choice controls plus an explicit **Other…** text-entry path. Test both a listed answer and a custom answer. | +| Q06 | Validated text | Text entry with the expected format/example, field-level errors, and a retained editable draft after invalid input. Cover the contract's pattern, length, and numeric constraints. | +| Q07 | Ordinary confirmation | Clear accept/reject controls with the decision and context visible. Governed actions and required reasons must retain their canonical review requirements. | +| Q08 | Checklist confirmation | Labeled selections, descriptions, editable defaults, selection bounds, explicit save, and rejection where supported by the contract. | +| Q09 | Per-item verdicts | A decision for each item, its evidence/context, conditional reasons, and submission using the canonical atomic or partial-resolution semantics. | +| Q10 | Suggested tasks | Direct creation for one proposal; selection and **Create selected** for several; dismissal and a review/edit handoff. Show links to the actual created tasks afterward. | +| Q11 | Connection request | Explain the requested access and purpose. Provide a usable link to the exact authenticated review and a native decline when supported. A link click must never grant access. | + +The inventory is a minimum, not eleven happy-path fixtures standing in for all +behavior. Record applicable variants under each ID: + +- Runtime input, composer cards, legacy payloads, and canonical question sets; + multiple questions, mixed forms, and repeated labels such as Yes/No in + different questions. +- Required/optional inputs, empty answers, editable defaults, descriptions, + recommendations, Unicode, long labels/context, and custom-answer combinations. +- Every control-selection threshold: just below, at, and above the provider's + button, option, text, block, and modal limits. Test a fallback form through its + response and continuation, not only the fallback card. Provider limits differ; + research the current official documentation and installed SDK. +- Accepted/rejected/dismissed outcomes, cancelled editing, expired or superseded + requests, duplicate callbacks, revoked access, and recovery after publication + or finalization failure. Cover document/attachment review and governed + permissions separately wherever they affect the question's meaning. + +### Choose and record the best available response path + +Keep a per-provider matrix linked from the +[channel question coverage index](./CHAT-QUESTION-COVERAGE.md). For every ID and +applicable variant, record native controls, a structured reply flow, or an exact +Paperclip handoff; the provider capability/limit supporting that choice; the +canonical answer mapping; and the evidence and remaining gaps. Generic adapter +flags such as `cards` or `modals` are discovery hints, not per-form qualification. +A provider lacking a native control still needs a usable response path. Mark +**not applicable** only when the underlying workflow cannot occur, with a reason. +Do not use it to hide an unimplemented renderer or unavailable test account. + +Use the richest practical interaction that preserves meaning, authorization, +and accessibility. A functional browser fallback is not the best experience +when a supported native control removes unnecessary work. A richer-looking +control is also wrong if it drops options, changes validation, or implies new +authority. Explain unavoidable handoffs before the click and preserve the +originating conversation through resolution. Do not force all providers to +Slack's controls or to the least capable provider's interface. + +**Every applicable form needs a usable path from the originating conversation.** +Prefer native controls or a reply flow when the channel can preserve the form's +meaning, validation, and authorization. Otherwise publish an explicit link to +the exact Paperclip question or review surface. A fallback is supported behavior; +silently omitting the request is a defect. Record which path each row uses. + +- Show the actual question and relevant context, including descriptions, help, + option labels/details, recommendations, and required/optional status. A title + such as “Identify the failed runner change” plus **Respond** is insufficient + when the payload contains a more specific question. +- Prefer direct buttons for a few closed choices, a searchable selector for a + longer list, and a checklist with an explicit submit action for multiple choices. + Use a native modal for free text, custom answers, and per-item verdicts with + reasons. Show errors next to the relevant input without discarding the draft. + Task suggestions must support selecting which tasks to create and dismissing + them. Connection requests may offer a native decline; granting access stays + on the authenticated review surface. Keep the saved labels, answers, verdicts, + and reasons readable after the controls disappear. +- Preserve text, numeric, pattern, length, and selection validation. Starting + text is editable draft content, never an implicit answer. Preserve repeated + choices within separate questions. If native controls cannot do this, use the + explicit Paperclip handoff rather than dropping fields or changing semantics. +- Respect provider message, block, option, and modal limits. For oversized forms, + show a useful question/context excerpt, state that the full request is in + Paperclip, and provide its link. Do not silently truncate a decision or label + a partial form as complete. +- Apply the existing safe external-text projection and audience rules to prompts, + help, drafts, links, and results. Keep secrets and restricted content on the + authorized Paperclip surface; explain the handoff without exposing that content. +- Bind a response to the persisted question, conversation, and verified actor. + Recheck current access, resolver audience, target freshness, and endpoint + authority. Use the same authoritative resolution service as Paperclip. A + channel callback or ordinary reply cannot bypass a governed action's approval. +- Persist the answer once and use the existing continuation policy and delivery + receipts. Duplicate clicks, provider retries, and recovery must not create + duplicate decisions or continuations. Preserve task and conversation context. + A Paperclip fallback response must retain its authenticated Board receipt; + never fabricate a provider callback. Follow each review kind's existing wake + or delivery receipt when routing its later result back to the conversation. + A settled card alone does not prove that the resumed task delivered its result. +- Reflect accepted, rejected, expired, and superseded outcomes in the original + channel card or an explicit follow-up. Honor the canonical meaning of dismissal + or deferral; it is not an answer or permission to resume. Include automatic + reconciliation and recovery paths, so resolved requests do not remain actionable. + +Apply this contract when adding a channel and whenever a question, card, composer, +or runtime bridge gains a new form or field. A working Paperclip card does not +establish channel support. The +[interaction-authoring skill](../../.agents/skills/create-issue-interaction-ui/SKILL.md) +must include channel publication, response, and settlement in the same change. + +### Verify and grade each experience + +Declare the inventory and finish line before implementation. For each affected +format: implement the best supported interaction, exercise it end to end in the +actual provider, capture evidence, inspect that evidence yourself, and repair +any remaining UX gap. Do not wait for the requester to ask separately for real +provider testing, screenshots, or a judgment about quality. + +Start locally with the smallest failing case and exercise the installed SDK, +serialized provider payloads, authenticated inbound responses, persisted answers, +and the existing continuation path. Work through one format at a time, using +focused regressions before the next real-provider attempt. An authorized local +candidate connected to a dedicated test bot/channel can provide this proof +before staging deployment. Keep provider webhook ingress, internal API access, +and human-facing board URLs separate. Use only the necessary authorized callback +or preview exposure; restore provider configuration and remove temporary access +at the end. Infrastructure failures remain named blockers, not product passes. + +For a new channel, qualify every applicable matrix row. For a behavior change, +repeat affected rows and shared paths, including native and Paperclip-fallback +journeys: + +request → visible question/context → response → persisted resolution → intended +continuation → settled card and result in the originating conversation. + +Record independent judgments for each row: + +| Judgment | Pass standard | +| --- | --- | +| Functional result | The exact answer/decision is saved, authorization is preserved, the canonical continuation policy runs without duplicate work, and the intended result is accessible in the originating conversation. | +| Good experience (✓/✕) | The person can understand the question, answer it, recover from an error, and read the saved outcome without guessing. Inspect unanswered, answering, and settled states. | +| Best feasible experience (✓/✕) | The chosen controls use the provider's available capabilities well. There is no avoidable modal, browser hop, lost context, or unnecessary interaction. Any handoff has a concrete capability, validation, or authorization reason. | + +Use **not run** for missing evidence and explain it; it is not a check mark. +A native modal is appropriate for substantial text or a multi-item review but +can be needless friction for a simple choice. A settled “Answered” badge that +hides the saved choice or text fails the experience check. Publish only the +safe, authorized answer projection, and make its audience clear at entry; +sensitive review content may require a clearly explained authenticated handoff. + +### Retain inspectable per-format evidence + +Produce an HTML gallery or equivalent browsable report with one section per +format and variant. Capture actual provider screens, not reconstructed cards: + +- **Unanswered:** the full question/context and available controls. +- **Answering:** the open picker/modal or selected values; include invalid input + and the preserved draft for validation cases. For a one-click button, the + before/after pair is sufficient. +- **Answered:** the settled card with the permitted saved answer, labels, + decisions, and reasons, plus the resumed result or review receipt. +- **Handoffs and artifacts:** actually click review and created-result links, + confirm the correct authenticated destination, and inspect the resulting + task/artifact. A valid-looking URL or successful API response is insufficient. + +Inspect each captured state yourself. Put functional status, both UX grades, +a short rationale, and any repair/retest next to the evidence. These are author +acceptance artifacts for channel qualification, not a blanket screenshot +request for unrelated UI PRs. Keep material failed attempts and their causes +alongside successful retries; a retry must not erase the failure history. + +Correlate screenshots with the canonical saved response, answer actor/authority, +continuation count, publication/delivery receipts, and actual created artifacts. +A visually settled multi-select can still fail continuation authorization; a +review link can navigate correctly while also firing an erroneous answer +callback. Test these complete paths. Deterministic coverage must also include +repeated callbacks, stale requests, revoked membership/identity/access, mixed +forms, and provider-limit fallback boundaries. + +Record the candidate revision, dirty-tree fingerprint if applicable, date, +provider/adapter configuration, source entry point, test conversation, and +reproduction steps without secrets. State whether the agent was a deterministic +protocol fixture or a live model. Keep local simulations, real-provider +acceptance, live-model behavior, and deployed verification separate. Storybook, +substituted HTTP, a green run badge, or an agent's success claim cannot establish +real-channel acceptance. Proof for one channel, one client surface, or eleven +core cases does not qualify every provider or boundary variant. + +Link accessible redacted evidence from the provider record and PR; retain the +requirements and conclusions in the repository even if a temporary preview +expires. Update the [coverage index](./CHAT-QUESTION-COVERAGE.md) with precise +scope and gaps. When later changes affect rendering, authorization, or delivery, +rerun the affected cases on that candidate; do not relabel old screenshots as +current proof. A format is complete only when its applicable functional and +experience checks pass. Report provider limitations and outstanding acceptance +explicitly; missing evidence leaves the affected qualification pending. + ## Optional agent instructions Some connections need standing guidance: tools tell an agent what it *can* do, @@ -1456,6 +1695,11 @@ A catalog connection is ready only when every applicable item is true: - [ ] Official docs and live metadata agree on the endpoint and auth flow. - [ ] Self-serve/provider-approval classification is documented. - [ ] Every exposed method has completed the full live lifecycle. +- [ ] Chat channels have an indexed per-format capability/qualification matrix, + a justified best-available response path, and inspected real-provider + evidence for affected conversation loops. Functional, answering, and + settled-state UX checks pass; remaining gaps are explicit under + [Chat channel connectors](#chat-channel-connectors). - [ ] The default path asks only for required configuration. - [ ] Optional own-OAuth and expert fields are folded under Advanced. - [ ] Scopes are explicit and contained; caller widening is rejected. @@ -1735,6 +1979,7 @@ connector proposal or PR. No separate private validation issue is required. | Allowed execution | A narrow read succeeds through the gateway; writes follow the effective policy. | Tool, actor, decision, redacted result, and correlated call/audit record. Use a disposable resource for an authorized live write; otherwise mark write execution untested. | | Denied execution | Ungranted actors, another company, disallowed resources, revoked connections, and declared blocked/quarantined actions cannot execute. | Expected denial and reason code, with the automated or live test that exercised the boundary. Cover listing where the policy requires tools to be hidden. | | Runtime delivery | An actual agent/run-scoped gateway call succeeds when runtime logic changes. Chat/email also routes an incoming message and its reply to the same task. | Redacted task/conversation and call correlation; identify live versus simulated events. | +| Chat questions and decisions | Every applicable question experience has the best feasible controls or a justified handoff, saves the answer, and delivers the intended continuation result. | [Indexed per-format qualification](./CHAT-QUESTION-COVERAGE.md), actual unanswered/answering/answered captures, separate functional and UX grades, saved-response/delivery evidence, and retained failures. | | Refresh and recovery | Catalog refresh, token refresh/reconnect, and recoverable failures preserve the correct identity and policy. | Before/after outcome, redacted error code, and successful retry; no duplicated connection. | | Revoke and reconnect | Revocation blocks subsequent execution; supported reconnect reuses the intended identity/history. | Removal or denial evidence followed by reconnect result. | | Activity and secret handling | Activity explains what occurred and why; stored responses, logs, and artifacts contain no credential values. | Actor, run/issue context, resource, decision, reason code, outcome, plus redaction-check result. | diff --git a/doc/connections/README.md b/doc/connections/README.md index 017c332e3b2..ab5f12475cf 100644 --- a/doc/connections/README.md +++ b/doc/connections/README.md @@ -8,6 +8,10 @@ agent tutorial from provider research and protocol classification through manifest generation, branding, secrets, deterministic tests, real-account proof, and PR submission. +Chat and email channels: [conversation-channel contract](./CONNECTOR-PLAYBOOK.md#chat-channel-connectors), +[question inventory and quality bar](./CONNECTOR-PLAYBOOK.md#question-experience-inventory), +and [per-provider question coverage index](./CHAT-QUESTION-COVERAGE.md). + Runtime authentication: [AI Connections](./AI-CONNECTIONS.md). Long-term memory: [Experimental memory connectors](./MEMORY.md). diff --git a/maps/agent-access-map/questions-and-approvals.md b/maps/agent-access-map/questions-and-approvals.md index 9e38f6ac818..b6874e75f8d 100644 --- a/maps/agent-access-map/questions-and-approvals.md +++ b/maps/agent-access-map/questions-and-approvals.md @@ -620,4 +620,21 @@ Evidence: `source-only` — [answer delivery](../../server/src/services/question Verification: `not-run` — Answer in actual configured channel -> one persisted result/useful originating reply; wrong/unlinked/expired sender denied. Overlap two conversations and verify no cross-delivery/replay. +Slack presentation uses opaque native response tokens for text, choices, +multiple selections, custom answers, validated text, ordinary confirmations, +checklists, item verdicts, suggested tasks, and connection decline. Permission +grants, governed approvals, and forms that exceed native limits retain authenticated +Paperclip review. Link clicks are passive and confer no decision authority. +Current company, audience, identity, connection, and governed-action checks apply. +Selections map back to the canonical response through the existing transaction +and callback receipt. Terminal cards retain the submitted answer only in the +original authorized conversation. Native multi-choice continuation validates the +exact saved selection mapping; a native answer token cannot be substituted by a +Board receipt. Later review replies follow the +[existing wake and connection-delivery receipts](../../server/src/services/chat-interaction-continuation.ts). +For automation-origin connection requests, validated receipts can recover the +conversation from the published prompt. Local Slack proof covers eleven formats +with a deterministic protocol fixture; production agent authority and other +provider paths retain their independent verification requirements. + Gaps: Slack/Discord/Telegram/email/iMessage and runtime paths independently not-run until driven. diff --git a/maps/feature-map/questions-and-approvals.md b/maps/feature-map/questions-and-approvals.md index 01cf138fab5..62a3d6e178c 100644 --- a/maps/feature-map/questions-and-approvals.md +++ b/maps/feature-map/questions-and-approvals.md @@ -187,9 +187,26 @@ Automated: [chat question forms](../../server/src/services/chat-question-forms.t and [interaction publications](../../server/src/__tests__/chat-interaction-publications.test.ts) cover serialization and delivery logic with fixtures. -Free-text and multi-question cards must show their title, question prompts, help -text, and relevant context beside Respond. Settled cards must not expose saved -free-text answers. The interaction publication database suite covers both states. +Free-text and multi-question cards show their title, prompts, help, and context. +Slack modals retain instructions and editable starting text. Closed single-choice +questions use buttons for up to five options and an inline searchable selector +for six to 100. Multiple choices use checkboxes (up to ten) or a multiple selector, +then explicit Submit. Custom choices combine direct buttons with an Other modal; +pattern errors appear beside the native input. Ordinary confirmations use buttons; +checklists preserve defaults and bounds; item verdicts use radio choices and reasons; +suggested tasks use Create, selection, and Dismiss. Connection requests offer +Review connection and native Not now, without granting access from Slack. + +Governed approvals, unsupported mixed forms, attachments, and oversized requests +retain the full Paperclip review path. Link clicks navigate without attempting an +answer. Terminal edits preserve the submitted response in the same authorized +conversation and remove stale controls. Inspect the saved interaction, exactly +one continuation, and useful reply independently. See the +[continuation regressions](../../server/src/services/chat-interaction-continuation.test.ts) +and [Slack card tests](../../server/src/services/chat-channels/slack/cards.test.ts). +Local real-Slack proof for eleven formats, including native validation and public +link navigation, is recorded with PR #17255. It uses a deterministic protocol +fixture and does not establish deployed staging or model reliability. Manual: use a disposable provider conversation, answer as the linked sender, and check the task's persisted result and one continuation. Repeat from an diff --git a/packages/shared/src/types/chat-channels.ts b/packages/shared/src/types/chat-channels.ts index e83627fbadc..4a2c5b0a211 100644 --- a/packages/shared/src/types/chat-channels.ts +++ b/packages/shared/src/types/chat-channels.ts @@ -409,6 +409,14 @@ export interface SafeExternalChatCard { title: string; body?: string; actions?: SafeExternalChatCardAction[]; + /** A compact choice whose opaque option tokens use the normal action ledger. */ + selection?: { + actionId: string; + label: string; + multiple?: boolean; + submitLabel?: string; + options: Array<{ actionId: string; label: string; description?: string; selected?: boolean }>; + }; } export interface SafeChatPublicationPayload { diff --git a/server/src/__tests__/chat-channels.integration.test.ts b/server/src/__tests__/chat-channels.integration.test.ts index c2ef1b9a34d..4fd186e6271 100644 --- a/server/src/__tests__/chat-channels.integration.test.ts +++ b/server/src/__tests__/chat-channels.integration.test.ts @@ -40886,6 +40886,46 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => { await service.shutdown(); }); + it.each(["request_confirmation", "request_checkbox_confirmation", "request_item_verdicts", "suggest_tasks", "connection_intent"] as const)("delivers and replaces a Slack %s card through the publication service", async kind => { + const previousPublicUrl = process.env.PAPERCLIP_PUBLIC_URL; + process.env.PAPERCLIP_PUBLIC_URL = "https://paperclip.example"; + const fixture = await seedCompany(); + const { callbacks, endpoint, service } = await configuredSlackEndpoint(fixture); + try { + const thread = makeThread({ channelId: "C-REVIEW", id: "slack:C-REVIEW:4500.1", name: "reviews" }); + await deliverMessage({ callbacks, endpointId: endpoint.id, thread: thread.thread, message: makeMessage({ id: "4500.1", text: "@maya review this change", mentioned: true, userId: `U-REVIEW-${randomUUID()}` }), trigger: "mention" }); + await qualifySetupRoundTrip(service, endpoint.id); + await service.test(endpoint.id, "owner-user"); + const [conversation] = await readChatConversationsByEndpointId(endpoint.id); + const sourceRunId = randomUUID(); + await db.insert(heartbeatRuns).values({ id: sourceRunId, companyId: fixture.companyId, agentId: fixture.assignedAgentId, status: "succeeded", responsibleUserId: "owner-user", contextSnapshot: { issueId: conversation.issueId, taskId: conversation.issueId, source: "automation" } }); + const interactions = issueThreadInteractionService(db); + const issue = { id: conversation.issueId, companyId: fixture.companyId }; + const interaction = kind === "connection_intent" + ? await interactions.createConnectionIntent(issue, { sourceRunId, addresseeUserId: "owner-user", idempotencyKey: `slack-review:${sourceRunId}`, payload: { version: 1, serviceSlug: "notion", serviceName: "Notion", requestingAgentId: fixture.assignedAgentId, requestingAgentName: "Maya", phase: "requested" } }) + : await interactions.create(issue, { kind, sourceRunId, payload: kind === "suggest_tasks" ? { version: 1, tasks: [{ clientKey: "docs", title: "Review migration notes" }] } : kind === "request_item_verdicts" ? { version: 1, prompt: "Review migration notes", items: [{ id: "docs", label: "Migration notes" }] } : { version: 1, prompt: "Review migration notes", ...(kind === "request_checkbox_confirmation" ? { options: [{ id: "docs", label: "Migration notes" }] } : {}) } } as Parameters[1], { agentId: fixture.assignedAgentId }); + await service.processPendingPublications(); + const rows = () => db.select().from(chatPublications).where(and(eq(chatPublications.endpointId, endpoint.id), eq(sql`${chatPublications.payload}->>'interactionId'`, interaction.id))); + const [original] = await rows(); + expect(original?.state).toBe("published"); + expect(original?.payload.card?.actions).toEqual(expect.arrayContaining([expect.objectContaining({ type: "callback" })])); + if (kind === "connection_intent") expect(original?.payload.card?.actions).toContainEqual({ type: "link", label: "Review connection", url: expect.any(String) }); + if (kind === "connection_intent") await interactions.resolveConnectionIntent(issue, interaction.id, { version: 1, outcome: "declined" }, { userId: "owner-user" }); + else if (kind === "request_item_verdicts") await interactions.submitItemVerdicts(issue, interaction.id, { verdicts: [{ id: "docs", verdict: "approve" }] }, { userId: "owner-user" }); + else await interactions.rejectInteraction(issue, interaction.id, {}, { userId: "owner-user" }); + await service.processPendingPublications(); + const publications = await rows(); + const terminal = publications.find(row => row.id !== original.id); + expect(terminal?.state).toBe("published"); + expect(terminal?.providerMessageId).toBe(original.providerMessageId); + expect(terminal?.payload.card?.actions).toBeUndefined(); + } finally { + await service.shutdown(); + if (previousPublicUrl === undefined) delete process.env.PAPERCLIP_PUBLIC_URL; + else process.env.PAPERCLIP_PUBLIC_URL = previousPublicUrl; + } + }); + it("publishes a closed-choice question, settles its Slack card, and delivers its exact continuation response", async () => { const fixture = await seedCompany(); const continuationRunId = randomUUID(); @@ -41944,10 +41984,10 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => { }; expect(metadata).toEqual({ c: expect.any(String), m: view.callback_id }); const select = view.blocks.find( - (block) => block.element.type === "static_select", + (block) => block.element?.type === "radio_buttons", )!; const text = view.blocks.find( - (block) => block.element.type === "plain_text_input", + (block) => block.element?.type === "plain_text_input", )!; const production = select.element.options!.find( (option) => option.text.text === "Production", @@ -41966,7 +42006,7 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => { values: { [select.block_id]: { [select.element.action_id]: { - type: "static_select", + type: "radio_buttons", selected_option: production, }, }, @@ -42631,7 +42671,7 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => { privateMetadata?: string; }; const selectField = modal.children.find( - (child) => child.type === "select", + (child) => child.type === (provider === "slack" ? "radio_select" : "select"), ); const textField = modal.children.find( (child) => child.type === "text_input", diff --git a/server/src/__tests__/chat-interaction-publications.test.ts b/server/src/__tests__/chat-interaction-publications.test.ts index d99bc1d13dc..f5a77bf08d6 100644 --- a/server/src/__tests__/chat-interaction-publications.test.ts +++ b/server/src/__tests__/chat-interaction-publications.test.ts @@ -3,6 +3,8 @@ import { and, eq, sql } from "drizzle-orm"; import { afterAll, beforeAll, describe, expect, it } from "vitest"; import { agents, + applyPendingMigrations, + EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, chatActions, chatConversations, chatEndpoints, @@ -27,7 +29,10 @@ import { startEmbeddedPostgresTestDatabase, } from "./helpers/embedded-postgres.js"; -const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport(); +import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js"; + +const externalUrl = resolveExternalTestDatabaseUrl("PAPERCLIP_CHAT_PUBLICATIONS_TEST_DATABASE_URL"); +const embeddedPostgresSupport = externalUrl ? { supported: true } : await getEmbeddedPostgresTestSupport(); const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip; @@ -43,16 +48,16 @@ describeEmbeddedPostgres( beforeAll(async () => { process.env.PAPERCLIP_PUBLIC_URL = "https://paperclip.example"; - tempDb = await startEmbeddedPostgresTestDatabase( - "paperclip-terminal-chat-interaction-", - ); - db = createDb(tempDb.connectionString); - }, 20_000); + if (externalUrl) await applyPendingMigrations(externalUrl); + else tempDb = await startEmbeddedPostgresTestDatabase("paperclip-terminal-chat-interaction-"); + db = createDb(externalUrl ?? tempDb!.connectionString); + }, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS); afterAll(async () => { if (previousPublicUrl === undefined) delete process.env.PAPERCLIP_PUBLIC_URL; else process.env.PAPERCLIP_PUBLIC_URL = previousPublicUrl; + await db?.$client.end({ timeout: 1 }); await tempDb?.cleanup(); }); @@ -230,6 +235,24 @@ describeEmbeddedPostgres( }; } + it("publishes a larger Slack choice as an inline selection backed by durable answer tokens", async () => { + const fixture = await seedBoundIssue(["slack", "microsoft-teams"]); + const interaction = await issueThreadInteractionService(db).create( + { id: fixture.issueId, companyId: fixture.companyId }, + { kind: "ask_user_questions", payload: { version: 1, questions: [{ + id: "fixture", prompt: "Which fixture?", selectionMode: "single", options: Array.from({ length: 13 }, (_, i) => ({ id: `fixture-${i}`, label: `Fixture ${i + 1}` })), + }] } }, { agentId: fixture.agentId }, + ); + const publications = await publicationsForInteraction(fixture.companyId, interaction.id); + const native = publications.find(row => row.payload.card?.selection); + expect(native?.payload.card?.selection?.options).toHaveLength(13); + expect(native?.payload.card?.actions).toBeUndefined(); + expect(native?.payload.card?.body).not.toContain("- Fixture"); + const tokens = await db.select().from(chatActions).where(eq(chatActions.endpointId, native!.endpointId)); + expect(tokens.filter(token => token.kind === "question_answer")).toHaveLength(13); + expect(publications.find(row => row.id !== native!.id)?.payload.card?.actions).toEqual([expect.objectContaining({ label: "Respond" })]); + }); + it("shows the free-text question and context alongside Respond", async () => { const fixture = await seedBoundIssue(["slack"]); const interaction = await issueThreadInteractionService(db).create( @@ -259,6 +282,96 @@ describeEmbeddedPostgres( }); }); + it.each(["text", "single_select", "multi_select", "custom", "pattern", "oversized"] as const)("publishes the complete %s question with an actionable response path", async shape => { + const fixture = await seedBoundIssue(["slack"]); + const question = { + id: "agent", prompt: "Which agent failed?", helpText: "Send the link and error text.", required: true, + answerMode: shape === "multi_select" ? "multi_select" as const : shape === "text" || shape === "pattern" || shape === "oversized" ? "text" as const : "single_select" as const, + ...(shape === "single_select" || shape === "multi_select" || shape === "custom" ? { options: [{ id: "codie", label: "Codie", description: "Native runner", recommended: true }, { id: "claude", label: "Claude", description: "Legacy runner" }] } : {}), + ...(shape === "custom" ? { customAnswer: { enabled: true, label: "Another agent", placeholder: "Paste the agent link" } } : {}), + ...(shape === "pattern" ? { textValidation: { pattern: "^[A-Z]+$" } } : {}), + ...(shape === "oversized" ? { initialText: "x".repeat(3001) } : {}), + }; + const service = issueThreadInteractionService(db); + const interaction = await service.create({ id: fixture.issueId, companyId: fixture.companyId }, { + kind: "ask_user_questions", title: "Identify the failed change", + payload: { version: 1, questionSet: { schema: "paperclip.question_set.v1", description: "The answer determines the next test.", questions: [question] } }, + } as Parameters[1], { agentId: fixture.agentId }); + const [publication] = await publicationsForInteraction(fixture.companyId, interaction.id); + expect(publication.payload.card?.body).toContain(question.prompt); + expect(publication.payload.card?.body).toContain(question.helpText); + expect(publication.payload.card?.body).toContain("The answer determines the next test."); + expect(publication.payload.text).toContain(question.prompt); + if (shape === "multi_select") { + expect(publication.payload.card?.selection).toMatchObject({ multiple: true, options: [ + { label: "Codie (recommended)", description: "Native runner" }, { label: "Claude", description: "Legacy runner" }, + ] }); + } else if (question.options && shape !== "custom") { + expect(publication.payload.card?.body).toContain("Codie (recommended): Native runner"); + expect(publication.payload.card?.body).toContain("Claude: Legacy runner"); + } + if (shape === "custom") { + expect(publication.payload.card?.body).toContain("- Codie (recommended): Native runner"); + expect(publication.payload.card?.actions?.map(action => action.label)).toEqual(["Codie", "Claude", "Other…"]); + const tokens = await db.select().from(chatActions).where(eq(chatActions.endpointId, publication.endpointId)); + expect(tokens.map(token => token.kind).sort()).toEqual(["question_answer", "question_answer", "question_form_open", "question_form_submit"].sort()); + } + if (shape === "oversized") { + expect(publication.payload.card?.actions).toEqual([{ type: "link", label: "Open in Paperclip", url: expect.stringContaining(fixture.issueId) }]); + } else if (shape !== "multi_select") { + expect(publication.payload.card?.actions?.every(action => action.type === "callback")).toBe(true); + } + }); + + it.each([100, 101, 128])("preserves the complete response path for %i choices plus Other", async count => { + const fixture = await seedBoundIssue(["slack"]); + const service = issueThreadInteractionService(db); + const options = Array.from({ length: count }, (_, index) => ({ id: `choice-${index}`, label: `Choice ${index}` })); + const interaction = await service.create({ id: fixture.issueId, companyId: fixture.companyId }, { + kind: "ask_user_questions", + payload: { version: 1, questionSet: { schema: "paperclip.question_set.v1", questions: [{ + id: "choice", prompt: "Choose a fixture", answerMode: "single_select", required: true, + options, customAnswer: { enabled: true }, + }] } }, + }, { agentId: fixture.agentId }); + const [publication] = await publicationsForInteraction(fixture.companyId, interaction.id); + const tokens = await db.select().from(chatActions).where(eq(chatActions.endpointId, publication.endpointId)); + if (count === 100) { + expect(publication.payload.card?.selection?.options).toHaveLength(count); + expect(publication.payload.card?.actions).toEqual([ + expect.objectContaining({ type: "callback", label: "Other…" }), + ]); + expect(tokens.filter(token => token.kind === "question_answer")).toHaveLength(count); + } else { + expect(publication.payload.card?.selection).toBeUndefined(); + expect(publication.payload.card?.actions).toEqual([ + { type: "link", label: "Open in Paperclip", url: expect.stringContaining(fixture.issueId) }, + ]); + expect(tokens).toEqual([]); + await markInteractionCardsPublished(fixture.companyId, interaction.id); + await service.answerQuestions({ id: fixture.issueId, companyId: fixture.companyId }, interaction.id, { + answers: [{ questionId: "choice", optionIds: [options[count - 1]!.id] }], + }, { userId: "board-user" }); + const settled = await publicationsForInteraction(fixture.companyId, interaction.id); + expect(settled.find(row => row.id !== publication.id)?.payload.card?.body).toContain(`Answered: Choice ${count - 1}`); + } + }); + + it("keeps repeated choices and help under each question", async () => { + const fixture = await seedBoundIssue(["slack"]); + const interaction = await issueThreadInteractionService(db).create( + { id: fixture.issueId, companyId: fixture.companyId }, + { kind: "ask_user_questions", payload: { version: 1, questions: ["Codie", "Claude"].map(agent => ({ id: agent, prompt: `Convert ${agent}?`, helpText: "Keep the existing configuration.", selectionMode: "single" as const, options: [{ id: "yes", label: "Yes" }, { id: "no", label: "No" }] })) } }, + { agentId: fixture.agentId }, + ); + const [publication] = await publicationsForInteraction(fixture.companyId, interaction.id); + const body = publication.payload.card!.body!; + expect(body.match(/- Yes/g)).toHaveLength(2); + expect(body.match(/- No/g)).toHaveLength(2); + expect(body.match(/Keep the existing configuration/g)).toHaveLength(2); + expect(body.slice(body.indexOf("Convert Claude?"))).toContain("- Yes"); + }); + it("publishes prompts only for the endpoint's verified immutable agent", async () => { const fixture = await seedBoundIssue(); const service = issueThreadInteractionService(db); @@ -371,7 +484,7 @@ describeEmbeddedPostgres( expect(await publicationsForInteraction(fixture.companyId, interaction.id)).toEqual([]); }); - it("keeps unsupported governance interactions authoritative in Paperclip", async () => { + it("delivers native checkbox reviews in Slack", async () => { const fixture = await seedBoundIssue(); const interaction = await issueThreadInteractionService(db).create( { id: fixture.issueId, companyId: fixture.companyId }, @@ -386,9 +499,84 @@ describeEmbeddedPostgres( { agentId: fixture.agentId }, ); - await expect( - publicationsForInteraction(fixture.companyId, interaction.id), - ).resolves.toEqual([]); + const publications = await publicationsForInteraction(fixture.companyId, interaction.id); + expect(publications).toHaveLength(1); + expect(publications[0].endpointId).toBe(fixture.endpointIds.slack); + expect(publications[0].payload.card).toMatchObject({ + selection: { multiple: true, options: [{ label: "US" }] }, + actions: [{ type: "callback", label: "Reject" }], + }); + await markInteractionCardsPublished(fixture.companyId, interaction.id); + await issueThreadInteractionService(db).rejectInteraction( + { id: fixture.issueId, companyId: fixture.companyId }, interaction.id, {}, { userId: "board-user" }, + ); + const settled = await publicationsForInteraction(fixture.companyId, interaction.id); + expect(settled).toHaveLength(2); + expect(settled.find(row => row.id !== publications[0].id)?.payload.card?.body).toBe("Rejected"); + expect(settled.find(row => row.id !== publications[0].id)?.payload.card?.actions).toBeUndefined(); + }); + + it.each([ + { kind: "suggest_tasks", payload: { version: 1, tasks: [{ clientKey: "docs", title: "Review the migration", description: "Verify preserved configuration" }] }, expected: "Review the migration" }, + { kind: "request_item_verdicts", payload: { version: 1, prompt: "Review each change", items: [{ id: "docs", label: "Migration notes", description: "Verify preserved configuration" }] }, expected: "Migration notes" }, + ] as const)("delivers and settles $kind reviews in Slack", async ({ kind, payload, expected }) => { + const fixture = await seedBoundIssue(); + const service = issueThreadInteractionService(db); + const issue = { id: fixture.issueId, companyId: fixture.companyId }; + const interaction = await service.create(issue, { kind, payload } as Parameters[1], { agentId: fixture.agentId }); + const [original] = await publicationsForInteraction(fixture.companyId, interaction.id); + expect(original?.endpointId).toBe(fixture.endpointIds.slack); + expect(original?.payload.card?.body).toContain(expected); + expect(original?.payload.card?.body).toContain("Verify preserved configuration"); + expect(original?.payload.card?.actions).toEqual(kind === "request_item_verdicts" ? [{ type: "callback", actionId: expect.any(String), label: "Review decisions", style: "primary" }] : [{ type: "callback", actionId: expect.any(String), label: "Create task", style: "primary" }, { type: "callback", actionId: expect.any(String), label: "Dismiss", style: "default" }, { type: "link", label: "Revise in Paperclip", url: expect.stringContaining(fixture.issueId) }]); + await markInteractionCardsPublished(fixture.companyId, interaction.id); + if (kind === "request_item_verdicts") { + await service.submitItemVerdicts(issue, interaction.id, { verdicts: [{ id: "docs", verdict: "approve" }] }, { userId: "board-user" }); + } else { + await service.rejectInteraction(issue, interaction.id, {}, { userId: "board-user" }); + } + const settled = await publicationsForInteraction(fixture.companyId, interaction.id); + expect(settled).toHaveLength(2); + expect(settled.find(row => row.id !== original.id)?.payload.card?.body).toBe(kind === "request_item_verdicts" ? "Migration notes: approve" : "Dismissed — no tasks created."); + expect(settled.find(row => row.id !== original.id)?.payload.card?.actions).toBeUndefined(); + }); + + it("settles an item review superseded by a historical human comment", async () => { + const fixture = await seedBoundIssue(["slack"]); + const service = issueThreadInteractionService(db); + const issue = { id: fixture.issueId, companyId: fixture.companyId }; + const interaction = await service.create(issue, { kind: "request_item_verdicts", payload: { version: 1, prompt: "Review these items", supersedeOnUserComment: true, items: [{ id: "docs", label: "Migration notes" }] } }, { agentId: fixture.agentId }); + const [original] = await markInteractionCardsPublished(fixture.companyId, interaction.id); + await db.insert(issueComments).values({ companyId: fixture.companyId, issueId: fixture.issueId, authorUserId: "board-user", body: "Use the updated proposal instead.", createdAt: new Date(Date.now() + 1000) }); + const expired = await service.expireRequestConfirmationsSupersededByHistoricalComments(issue); + expect(expired).toHaveLength(1); + expect(expired[0].status).toBe("expired"); + const publications = await publicationsForInteraction(fixture.companyId, interaction.id); + expect(publications).toHaveLength(2); + expect(publications.find(row => row.id !== original.id)?.payload.card?.body).toBe("Expired in Paperclip"); + }); + + it.each(["decline", "reassign"] as const)("delivers, deduplicates and settles an addressed connection request on %s without a second wake owner", async outcome => { + const fixture = await seedBoundIssue(); + const sourceRunId = randomUUID(); + await db.insert(heartbeatRuns).values({ id: sourceRunId, companyId: fixture.companyId, agentId: fixture.agentId, status: "running", responsibleUserId: "board-user", contextSnapshot: { issueId: fixture.issueId } }); + const service = issueThreadInteractionService(db); + const issue = { id: fixture.issueId, companyId: fixture.companyId }; + const input = { sourceRunId, addresseeUserId: "board-user", idempotencyKey: "connection-slack", payload: { version: 1 as const, serviceSlug: "notion", serviceName: "Notion", requestingAgentId: fixture.agentId, requestingAgentName: "Codie", phase: "requested" as const } }; + const interaction = await service.createConnectionIntent(issue, input); + await service.createConnectionIntent(issue, input); + const [original] = await publicationsForInteraction(fixture.companyId, interaction.id); + expect(original?.payload.card?.body).toContain("Codie needs Notion"); + expect(original?.payload.card?.actions).toEqual([{ type: "link", label: "Review connection", url: expect.stringContaining(fixture.issueId) }, { type: "callback", actionId: expect.any(String), label: "Not now", style: "default" }]); + expect(await publicationsForInteraction(fixture.companyId, interaction.id)).toHaveLength(1); + await markInteractionCardsPublished(fixture.companyId, interaction.id); + await expect(service.resolveConnectionIntent(issue, interaction.id, { version: 1, outcome: "declined" }, { userId: "different-user" })).rejects.toMatchObject({ status: 403 }); + if (outcome === "decline") await service.resolveConnectionIntent(issue, interaction.id, { version: 1, outcome: "declined" }, { userId: "board-user" }); + else await db.transaction(async tx => issueThreadInteractionService(tx as unknown as typeof db).expireConnectionIntentsForOwnershipChange(issue)); + const settled = await publicationsForInteraction(fixture.companyId, interaction.id); + expect(settled).toHaveLength(2); + expect(settled.find(row => row.id !== original.id)?.payload.card?.body).toBe(outcome === "decline" ? "Declined: Notion. No access was granted." : "Expired in Paperclip"); + expect((await db.select().from(chatActions).where(eq(chatActions.companyId, fixture.companyId))).filter(action => action.kind === "interaction_wakeup")).toEqual([]); }); it("settles a card when the dispatcher claims it between the read and cancellation CAS", async () => { @@ -532,7 +720,7 @@ describeEmbeddedPostgres( ]); }); - it("settles form answers without claiming a surface or exposing free text", async () => { + it("retains question and answer context while redacting credentials in settled form cards", async () => { const fixture = await seedBoundIssue(); const service = issueThreadInteractionService(db); const interaction = await service.create( @@ -573,7 +761,7 @@ describeEmbeddedPostgres( { questionId: "label", optionIds: [], - otherText: "private free-text label", + otherText: "Runner conversion failed. password=do-not-publish-this", }, ], }, @@ -585,12 +773,12 @@ describeEmbeddedPostgres( expect(settlements).toHaveLength(2); for (const settlement of settlements) { expect(settlement.payload).toMatchObject({ - text: "Answered.", - card: { kind: "question", body: "Answered." }, + text: expect.stringContaining("Enter a label\n\nAnswered: Runner conversion failed."), + card: { kind: "question", body: expect.stringContaining("Choose a tree\n\nAnswered: Cedar") }, }); expect(settlement.payload.card?.actions ?? []).toHaveLength(0); expect(JSON.stringify(settlement.payload)).not.toContain( - "private free-text label", + "do-not-publish-this", ); expect(JSON.stringify(settlement.payload)).not.toContain( "Answered in Paperclip", @@ -775,7 +963,8 @@ describeEmbeddedPostgres( originals.find((row) => row.endpointId === fixture.endpointIds.slack) ?.payload.card?.actions, ).toEqual([ - expect.objectContaining({ type: "link", label: "Open in Paperclip" }), + expect.objectContaining({ type: "callback", label: "Accept" }), + expect.objectContaining({ type: "callback", label: "Reject" }), ]); expect( originals.find( @@ -991,7 +1180,7 @@ describeEmbeddedPostgres( ); expect( publications.some((row) => - row.payload.card?.actions?.some((action) => action.type === "link"), + row.payload.card?.actions?.some((action) => action.type === "callback"), ), ).toBe(true); }); diff --git a/server/src/__tests__/heartbeat-run-summary.test.ts b/server/src/__tests__/heartbeat-run-summary.test.ts index c47eeef0c98..33b03986b83 100644 --- a/server/src/__tests__/heartbeat-run-summary.test.ts +++ b/server/src/__tests__/heartbeat-run-summary.test.ts @@ -63,7 +63,7 @@ describe("scheduled continuation presentation", () => { }); describe("continuation origin verification", () => { - it.each(["native_status_decision", "issue.monitor", "tool_action_review", "issue.comment", "issue.comment.created", "issue.update"]) + it.each(["native_status_decision", "issue.monitor", "tool_action_review", "issue.comment", "issue.comment.created", "issue.update", "issue.interaction.respond", "issue.interaction.accept", "issue.interaction.reject", "issue.interaction.verdicts", "issue.interaction.cancel", "issue.interaction.withdraw", "external_chat.interaction.resolve", "connection_intent.resolved"]) ("checks %s without treating candidacy as publication authority", source => { expect(isChatOriginPublicationCandidate({ source })).toBe(true); expect(isExternalChatPresentationContext({ source })).toBe(false); diff --git a/server/src/__tests__/issue-thread-interactions-service.test.ts b/server/src/__tests__/issue-thread-interactions-service.test.ts index 97ef4f5be2f..3532bc7d663 100644 --- a/server/src/__tests__/issue-thread-interactions-service.test.ts +++ b/server/src/__tests__/issue-thread-interactions-service.test.ts @@ -2729,6 +2729,33 @@ describeEmbeddedPostgres("issueThreadInteractionService", () => { expect((await db.select().from(issueThreadInteractions))[0]?.status).toBe("pending"); }); + it.each(["verdicts", "suggestions", "dismiss"] as const)( + "rolls back %s when external action authorization or receipt ownership changes", + async (kind) => { + const { companyId, issueId } = await seedConfirmationIssue("External form transaction"); + const issue = { id: issueId, companyId }; + const interaction = await interactionsSvc.create(issue, kind === "verdicts" + ? { kind: "request_item_verdicts", payload: { version: 1, prompt: "Review", items: [{ id: "api", label: "API" }] } } + : { kind: "suggest_tasks", payload: { version: 1, tasks: [{ clientKey: "check", title: "Check the result" }] } }, + { userId: "local-board" }); + const resolve = (options: import("../services/issue-thread-interactions.js").InteractionResolutionMutationOptions) => kind === "verdicts" + ? interactionsSvc.submitItemVerdicts(issue, interaction.id, { verdicts: [{ id: "api", verdict: "approve" }] }, { userId: "local-board" }, options) + : kind === "dismiss" + ? interactionsSvc.rejectInteraction(issue, interaction.id, {}, { userId: "local-board" }, options) + : interactionsSvc.acceptInteraction(issue, interaction.id, { selectedClientKeys: ["check"] }, { userId: "local-board" }, options); + for (const hook of ["beforeResolveInTransaction", "afterResolveInTransaction"] as const) { + await expect(resolve({ [hook]: async () => { throw new Error("External action no longer authorized"); } })).rejects.toThrow("External action no longer authorized"); + expect((await interactionsSvc.listForIssue(issueId)).find(item => item.id === interaction.id)).toMatchObject({ status: "pending", result: null }); + expect(await db.select({ id: issues.id }).from(issues).where(eq(issues.parentId, issueId))).toEqual([]); + } + await resolve({}); + const resolved = (await interactionsSvc.listForIssue(issueId)).find(item => item.id === interaction.id); + expect(resolved?.status).toBe(kind === "verdicts" ? "answered" : kind === "dismiss" ? "rejected" : "accepted"); + const children = await db.select({ id: issues.id }).from(issues).where(eq(issues.parentId, issueId)); + expect(children).toHaveLength(kind === "suggestions" ? 1 : 0); + }, + ); + it("submits request_item_verdicts partially and completes when all items are resolved", async () => { const { companyId, issueId } = await seedConfirmationIssue("Item verdict partial submit"); diff --git a/server/src/__tests__/satisfied-connection-intents.test.ts b/server/src/__tests__/satisfied-connection-intents.test.ts index 36bfab8c9d9..36eb4555df3 100644 --- a/server/src/__tests__/satisfied-connection-intents.test.ts +++ b/server/src/__tests__/satisfied-connection-intents.test.ts @@ -1,8 +1,9 @@ +import { enqueueIssueInteractionChatPublications } from "../services/chat-interaction-publications.js"; import { randomUUID } from "node:crypto"; import { eq, sql } from "drizzle-orm"; import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; import { activityLog, agentWakeupRequests, agents, approvals, authUsers, companies, companyMemberships, connectionGrants, connectionGrantDelegations, - connectionIntentDeliveries, createDb, environmentLeases, heartbeatRunEvents, heartbeatRuns, issueApprovals, issueRecoveryActions, issueThreadInteractions, issues, projects, toolApplications, + chatConversations, chatEndpoints, chatPublications, connectionIntentDeliveries, createDb, environmentLeases, heartbeatRunEvents, heartbeatRuns, issueApprovals, issueRecoveryActions, issueThreadInteractions, issues, projects, toolApplications, toolCatalogEntries, toolConnectionInstalls, toolConnections, toolProfileBindings, toolProfiles, toolPolicies, } from "@paperclipai/db"; import { createPostgresRunDispatchAdapter } from "../modules/run-dispatch/adapters/postgres.js"; @@ -59,6 +60,27 @@ describePostgres("already available connection requests", () => { return run!; } + it("settles a published Slack card when existing access retires the connection request", async () => { + const f = await seed(); + const endpointId = randomUUID(); + const [app] = await db.insert(toolApplications).values({ companyId: f.companyId, applicationKey: `chat:slack:${endpointId}`, name: "Slack", type: "chat", status: "active" }).returning(); + const [connection] = await db.insert(toolConnections).values({ companyId: f.companyId, applicationId: app.id, name: "Slack channel", uid: endpointId, connectionPurpose: "channel", transport: "chat_sdk", status: "active", enabled: true }).returning(); + await db.insert(chatEndpoints).values({ id: endpointId, companyId: f.companyId, connectionId: connection.id, provider: "slack", publicId: randomUUID(), assignedAgentId: f.agentId, status: "active", capabilities: { threads: true, directMessages: true, nativeStreaming: false, messageEdits: true, messageDeletes: false, reactions: true, files: true, cards: true, actions: true, modals: true, slashCommands: true, ephemeralMessages: true, proactiveDirectMessages: true } }); + await db.insert(chatConversations).values({ companyId: f.companyId, endpointId, issueId: f.issueId, externalConversationId: "C-CONNECTION", externalThreadId: "slack:C-CONNECTION:123.1", externalLabel: "Connection setup", state: "active" }); + await db.update(issueThreadInteractions).set({ createdByAgentId: f.agentId }).where(eq(issueThreadInteractions.id, f.intent.id)); + const interaction = await issueThreadInteractionService(db).getById(f.intent.id); + expect(interaction).not.toBeNull(); + const [original] = await enqueueIssueInteractionChatPublications(db, interaction!); + expect(original).toBeDefined(); + await db.update(chatPublications).set({ state: "published", providerMessageId: "123.2" }).where(eq(chatPublications.id, original.id)); + expect(await satisfiedConnectionIntentService(db).sweepPending()).toMatchObject({ satisfied: 1 }); + const publications = await db.select().from(chatPublications).where(eq(chatPublications.endpointId, endpointId)); + expect(publications).toHaveLength(2); + const terminal = publications.find(row => row.id !== original.id); + expect(terminal?.payload.card?.body).toBe("Expired in Paperclip"); + expect(terminal?.payload.card?.actions).toBeUndefined(); + }); + it("ignores an already available connection before the worker retires its card", async () => { const f = await seed(); const run = await retry(f); expect(await createPostgresRunDispatchAdapter(db).evaluateScheduledRetryGate({ companyId: f.companyId, runId: run.id, now: new Date() })).toMatchObject({ allowed: true }); diff --git a/server/src/services/chat-channels.ts b/server/src/services/chat-channels.ts index 6963c785d7f..e53608b49de 100644 --- a/server/src/services/chat-channels.ts +++ b/server/src/services/chat-channels.ts @@ -3437,6 +3437,7 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) { redactError, CONFIRMATION_WAKEUP_RETRY_BACKOFF_MS, get heartbeat() { return options.heartbeat; }, }); const { handleAction, handleModalSubmit, reconcileTerminalConfirmationActions } = createChatInteractionCallbacks(db, { + heartbeat: options.heartbeat, CAPABILITIES, MAX_ERROR_TEXT, actionThreadMatchesConversation, nonDirectDestinationAllowed, sameTeamsThreadIdentity, ensurePrincipal, endpointRecord, runtimeCallbackRecord, runtimeCallbackEndpoint, requireCurrentExternalActionAuthorization, isExternalActionAuthorizationChange, diff --git a/server/src/services/chat-channels/interactions/callbacks.ts b/server/src/services/chat-channels/interactions/callbacks.ts index 93c1e5f9f07..e9580a762b0 100644 --- a/server/src/services/chat-channels/interactions/callbacks.ts +++ b/server/src/services/chat-channels/interactions/callbacks.ts @@ -1,3 +1,5 @@ +import { slackQuestionFormValidationError } from "../slack/question-forms.js"; +import { chatInteractionForm, chatItemVerdicts } from "../../chat-interaction-forms.js"; import { createDiscordQuestionForms } from "../discord/question-forms.js"; import { createProviderEffects, type ProviderEffectPayload } from "../provider-effects.js"; @@ -38,6 +40,7 @@ import type { ChatAdapterCapabilities, ChatProvider, SafeChatPublicationPayload, + IssueThreadInteraction, } from "@paperclipai/shared"; import { @@ -74,6 +77,8 @@ import { import { enqueueTerminalIssueInteractionChatPublications, nativeChatQuestion, + nativeChatMultiQuestion, + nativeChatCustomQuestion, TELEGRAM_CALLBACK_DATA_LIMIT_BYTES, telegramChatSdkCallbackData, } from "../../chat-interaction-publications.js"; @@ -104,10 +109,11 @@ import type { } from "chat"; import type { EndpointRecord } from "../runtime-types.js"; -import { createTelegramConfirmationActions } from "../telegram/confirmation-actions.js"; +import { createChatConfirmationActions } from "./confirmation-actions.js"; type ResourceRow = typeof chatEndpointResources.$inferSelect; type PrincipalResolution = { principal: typeof chatExternalPrincipals.$inferSelect; userId: string | null; linkedDenied: boolean }; type InteractionCallbacksOptions = { + heartbeat: import("../../issue-assignment-wakeup.js").IssueAssignmentWakeupDeps; CAPABILITIES: Record; MAX_ERROR_TEXT: number; actionThreadMatchesConversation: (provider: ChatProvider, actionThreadId: string, conversationThreadId: string) => boolean; @@ -137,8 +143,8 @@ type InteractionCallbacksOptions = { export function createChatInteractionCallbacks(db: Db, options: InteractionCallbacksOptions) { const { CAPABILITIES, MAX_ERROR_TEXT, actionThreadMatchesConversation, nonDirectDestinationAllowed, sameTeamsThreadIdentity, ensurePrincipal, endpointRecord, runtimeCallbackRecord, runtimeCallbackEndpoint, requireCurrentExternalActionAuthorization, isExternalActionAuthorizationChange, recordCurrentMicrosoftTeamsRoute, lockTelegramCallbackNoticeAuthority, stageProviderEffect, scheduleProviderEffect, invalidateRuntime, redactError, persistence, questionResponses, scheduleMessageProcessing, processPendingPublications } = options; const { handleDiscordFormCorrection, acceptDiscordQuestionForm } = createDiscordQuestionForms(db, { requireCurrentExternalActionAuthorization, isExternalActionAuthorizationChange, persistence }); - const { reconcileTerminalConfirmationActions, handleTelegramConfirmation } = createTelegramConfirmationActions(db, { - requireCurrentExternalActionAuthorization, isExternalActionAuthorizationChange, scheduleMessageProcessing, processPendingPublications, + const { reconcileTerminalConfirmationActions, handleChatConfirmation } = createChatConfirmationActions(db, { + heartbeat: options.heartbeat, requireCurrentExternalActionAuthorization, isExternalActionAuthorizationChange, scheduleMessageProcessing, processPendingPublications, get confirmationResolutionPersistBarrier() { return options.confirmationResolutionPersistBarrier; }, }); @@ -896,10 +902,10 @@ export function createChatInteractionCallbacks(db: Db, options: InteractionCallb (!correction && event.provider !== "telegram" && event.event.value !== payload.interactionId) || - !payload.card?.actions?.some( - (action) => - action.type === "callback" && action.actionId === sourceActionId, - ) + !(payload.card?.actions?.some( + (action) => action.type === "callback" && action.actionId === sourceActionId, + ) || payload.card?.selection?.options.some(option => option.actionId === sourceActionId) || + payload.card?.selection?.multiple && payload.card.selection.actionId === sourceActionId) ) { return deny(safelyKnown); } @@ -956,12 +962,11 @@ export function createChatInteractionCallbacks(db: Db, options: InteractionCallb } return deny(safelyKnown); } - if (interaction.kind === "request_confirmation") { - return handleTelegramConfirmation({ record, event, runtimeContext, conversation, principal: { ...principal, userId: principal.userId }, issued, interaction, deny, safelyKnown }); - } - if (interaction.kind !== "ask_user_questions") { - return deny(safelyKnown); + if (interaction.kind === "request_confirmation" || event.provider === "slack" && (interaction.kind === "request_checkbox_confirmation" || interaction.kind === "suggest_tasks" || interaction.kind === "connection_intent")) { + return handleChatConfirmation({ record, event, runtimeContext, conversation, principal: { ...principal, userId: principal.userId }, issued, interaction, deny, safelyKnown }); } + const formInteraction = chatInteractionForm(interaction, event.provider); + if (!formInteraction) return deny(safelyKnown); if (isChatQuestionFormOpenActionId(sourceActionId)) { if ( event.provider !== "slack" && @@ -1001,7 +1006,7 @@ export function createChatInteractionCallbacks(db: Db, options: InteractionCallb companyId: record.endpoint.companyId, endpointId: record.endpoint.id, conversationId: conversation.id, - interaction, + interaction: formInteraction, openActionId: sourceActionId, }); if (!resolved || resolved.publicationId !== issued.publication.id) { @@ -1167,17 +1172,28 @@ export function createChatInteractionCallbacks(db: Db, options: InteractionCallb tokenPayload.publicationId !== issued.publication.id || tokenPayload.interactionId !== payload.interactionId || typeof tokenPayload.questionId !== "string" || - typeof tokenPayload.optionId !== "string" + (typeof tokenPayload.optionId !== "string" && !Array.isArray(tokenPayload.selectionOptions)) ) { return deny(safelyKnown); } - const question = nativeChatQuestion(interaction); - const option = question?.options.find( - (candidate) => candidate.id === tokenPayload.optionId, - ); - if (!question || question.id !== tokenPayload.questionId || !option) - return deny(safelyKnown); + if (interaction.kind !== "ask_user_questions") return deny(safelyKnown); + const multiple = event.provider === "slack" && Array.isArray(tokenPayload.selectionOptions); + const question = multiple ? nativeChatMultiQuestion(interaction) : nativeChatQuestion(interaction, event.provider === "slack" ? 100 : undefined) ?? (event.provider === "slack" ? nativeChatCustomQuestion(interaction) : null); + if (!question || question.id !== tokenPayload.questionId) return deny(safelyKnown); + const selected = multiple ? event.selectionValues : undefined; + if (multiple && (!selected || new Set(selected).size !== selected.length)) return deny(safelyKnown); + const optionIds = multiple ? selected!.map(value => { + const mapping = (tokenPayload.selectionOptions as Array<{ value?: unknown; optionId?: unknown }>).find(item => item.value === value); + return typeof mapping?.optionId === "string" ? mapping.optionId : null; + }) : [tokenPayload.optionId as string]; + const selectedOptions = optionIds.map(id => question.options.find(option => option.id === id)); + if (selectedOptions.some(option => !option)) return deny(safelyKnown); + if (multiple && !optionIds.length && question.required !== false) { + await event.event.thread?.postEphemeral(event.event.user, { markdown: "Choose at least one option, then select Submit answer." }, { fallbackToDM: false }); + return; + } + const answerLabel = selectedOptions.map(option => option!.label).join("; ") || "No options selected"; await options.questionResolutionPersistBarrier?.(); @@ -1201,11 +1217,11 @@ export function createChatInteractionCallbacks(db: Db, options: InteractionCallb issue, interaction.id, { - answers: [{ questionId: question.id, optionIds: [option.id] }], + answers: [{ questionId: question.id, optionIds: optionIds as string[] }], }, { userId: principal.userId }, { - beforeResolveInTransaction: async (tx) => { + beforeResolveInTransaction: async (tx: DbTransaction) => { await requireCurrentExternalActionAuthorization(tx, { conversationId: conversation.id, endpointId: record.endpoint.id, @@ -1214,7 +1230,7 @@ export function createChatInteractionCallbacks(db: Db, options: InteractionCallb runtimeContext, }); }, - afterResolveInTransaction: async (tx, resolved) => { + afterResolveInTransaction: async (tx: DbTransaction, resolved: IssueThreadInteraction) => { const [completed] = await tx .update(chatActions) .set({ @@ -1225,6 +1241,7 @@ export function createChatInteractionCallbacks(db: Db, options: InteractionCallb messageId: event.event.messageId, actionId: event.event.actionId, value: event.event.value ?? null, + ...(multiple ? { selectionValues: selected } : {}), }, result: { interactionId: resolved.id, @@ -1298,13 +1315,13 @@ export function createChatInteractionCallbacks(db: Db, options: InteractionCallb payload: projectSafeChatPublication({ classification: "external", source: "issue_interaction", - text: `Answered: ${option.label}.`, + text: `Answered: ${answerLabel}.`, interaction: { id: resolved.id, card: { kind: "question", title: question.prompt, - body: `Answered: ${option.label}.`, + body: `Answered: ${answerLabel}.`, actions: [], }, }, @@ -1644,6 +1661,7 @@ export function createChatInteractionCallbacks(db: Db, options: InteractionCallb const interaction = ( await issueThreadInteractionService(db).listForIssue(conversation.issueId) ).find((candidate) => candidate.id === loaded.interactionId); + const formInteraction = interaction ? chatInteractionForm(interaction, event.provider) : null; const discordReplayAnswersMatch = ( resolved: typeof interaction, ): boolean => { @@ -1673,7 +1691,7 @@ export function createChatInteractionCallbacks(db: Db, options: InteractionCallb ) => interaction?.companyId === record.endpoint.companyId && interaction.issueId === conversation.issueId && - interaction.kind === "ask_user_questions" && + (interaction.kind === "ask_user_questions" || event.provider === "slack" && interaction.kind === "request_item_verdicts") && interaction.status === "answered" && interaction.resolvedByUserId === principal.userId && current?.status === "processed" && @@ -1716,7 +1734,7 @@ export function createChatInteractionCallbacks(db: Db, options: InteractionCallb !interaction || interaction.companyId !== record.endpoint.companyId || interaction.issueId !== conversation.issueId || - interaction.kind !== "ask_user_questions" || + !formInteraction || interaction.status !== "pending" ) { // Another callback can commit the same token between the initial token @@ -1727,7 +1745,7 @@ export function createChatInteractionCallbacks(db: Db, options: InteractionCallb if ( interaction?.companyId === record.endpoint.companyId && interaction.issueId === conversation.issueId && - interaction.kind === "ask_user_questions" && + (interaction.kind === "ask_user_questions" || event.provider === "slack" && interaction.kind === "request_item_verdicts") && interaction.status === "answered" ) { try { @@ -1775,20 +1793,20 @@ export function createChatInteractionCallbacks(db: Db, options: InteractionCallb const validation = validateChatQuestionFormSubmission({ callbackId: event.event.callbackId, privateMetadata: event.event.privateMetadata, - interaction, + interaction: formInteraction, payload: loaded.payload, values: event.event.values, }); if (!validation.ok) { if (validation.code === "invalid_form") { if (event.provider === "discord") { - return handleDiscordFormCorrection({ record, event, runtimeContext, conversation, principal: { ...principal, userId: principal.userId }, loaded, originalPublication, providerMessageId, interaction, payload, validation, deny }); + return handleDiscordFormCorrection({ record, event, runtimeContext, conversation, principal: { ...principal, userId: principal.userId }, loaded, originalPublication, providerMessageId, interaction: formInteraction, payload, validation, deny }); } return chatQuestionFormValidationResponse({ provider: event.provider, callbackId: event.event.callbackId, privateMetadata: event.event.privateMetadata, - interaction, + interaction: formInteraction, payload: loaded.payload, values: event.event.values, }); @@ -1827,19 +1845,12 @@ export function createChatInteractionCallbacks(db: Db, options: InteractionCallb ); } await options.questionResolutionPersistBarrier?.(); - let answered: Awaited< - ReturnType< - ReturnType["answerQuestions"] - > - >; + const itemVerdicts = chatItemVerdicts(interaction, validation.answers, loaded.payload); + if (itemVerdicts && Object.keys(itemVerdicts.errors).length) return { action: "errors", errors: itemVerdicts.errors }; + let answered: IssueThreadInteraction; try { - answered = await issueThreadInteractionService(db).answerQuestions( - issue, - interaction.id, - { answers: validation.answers }, - { userId: principal.userId }, - { - beforeResolveInTransaction: async (tx) => { + const mutationOptions = { + beforeResolveInTransaction: async (tx: DbTransaction) => { await requireCurrentExternalActionAuthorization(tx, { conversationId: conversation.id, endpointId: event.endpointId, @@ -1848,7 +1859,7 @@ export function createChatInteractionCallbacks(db: Db, options: InteractionCallb runtimeContext, }); }, - afterResolveInTransaction: async (tx, resolved) => { + afterResolveInTransaction: async (tx: DbTransaction, resolved: IssueThreadInteraction) => { const claimed = await claimChatQuestionFormSubmission(tx, { actionRowId: loaded.actionRowId, principalId: principal.principal.id, @@ -1900,8 +1911,10 @@ export function createChatInteractionCallbacks(db: Db, options: InteractionCallb }, }); }, - }, - ); + }; + answered = itemVerdicts + ? (await issueThreadInteractionService(db).submitItemVerdicts(issue, interaction.id, { verdicts: itemVerdicts.verdicts }, { userId: principal.userId }, mutationOptions)).interaction + : await issueThreadInteractionService(db).answerQuestions(issue, interaction.id, { answers: validation.answers }, { userId: principal.userId }, mutationOptions); } catch (error) { if (isExternalActionAuthorizationChange(error)) { await db.transaction(async (tx) => { @@ -1953,6 +1966,10 @@ export function createChatInteractionCallbacks(db: Db, options: InteractionCallb error && typeof error === "object" ? (error as { status?: unknown }).status : null; + if (event.provider === "slack") { + const response = slackQuestionFormValidationError(error, loaded.payload.fields); + if (response) return response; + } if (status === 403) { return deny( "chat_modal_resolution_not_authorized", @@ -2003,7 +2020,8 @@ export function createChatInteractionCallbacks(db: Db, options: InteractionCallb ); } scheduleMessageProcessing(async () => { - await questionResponses.deliver(answered.id); + if (answered.kind === "ask_user_questions") await questionResponses.deliver(answered.id); + else await processPendingPublications(); }); return acceptedResponse(); } diff --git a/server/src/services/chat-channels/telegram/confirmation-actions.ts b/server/src/services/chat-channels/interactions/confirmation-actions.ts similarity index 77% rename from server/src/services/chat-channels/telegram/confirmation-actions.ts rename to server/src/services/chat-channels/interactions/confirmation-actions.ts index 8e5c9971b8f..caaef9ab99f 100644 --- a/server/src/services/chat-channels/telegram/confirmation-actions.ts +++ b/server/src/services/chat-channels/interactions/confirmation-actions.ts @@ -1,3 +1,6 @@ +import { connectionIntentService } from "../../connection-intents.js"; +import { queueIssueAssignmentWakeup, type IssueAssignmentWakeupDeps } from "../../issue-assignment-wakeup.js"; +import { chatInteractionPresentation } from "../../chat-interaction-presentation.js"; import type { DbTransaction, RuntimeContext, LifecycleRuntimeFence } from "../runtime-types.js"; import { notifyChatPublicationWork } from "../../chat-work-notifications.js"; @@ -37,8 +40,8 @@ import { issueThreadInteractionService } from "../../issue-thread-interactions.j import type { EndpointRecord } from "../runtime-types.js"; import type { ActionEvent } from "chat"; -import { nativeTelegramConfirmation } from "../../chat-interaction-publications.js"; -type TelegramConfirmationInput = { +import { nativeChatConfirmation, nativeChatCheckbox, nativeChatSuggestions } from "../../chat-interaction-publications.js"; +type ChatConfirmationInput = { record: EndpointRecord; event: ChatSdkCallbackEvent; runtimeContext: RuntimeContext; @@ -49,21 +52,22 @@ type TelegramConfirmationInput = { deny: (known?: { conversationId?: string | null; principalId?: string | null }) => Promise; safelyKnown: { conversationId: string; principalId: string }; }; -type TelegramConfirmationOptions = { +type ChatConfirmationOptions = { + heartbeat: IssueAssignmentWakeupDeps; requireCurrentExternalActionAuthorization: (tx: DbTransaction, input: { conversationId: string; endpointId: string; expectedUserId: string; principalId: string; runtimeContext: LifecycleRuntimeFence }) => Promise; isExternalActionAuthorizationChange: (error: unknown) => boolean; scheduleMessageProcessing: (task: () => Promise) => void; processPendingPublications: () => Promise; confirmationResolutionPersistBarrier?: () => Promise; }; -export function createTelegramConfirmationActions(db: Db, options: TelegramConfirmationOptions) { +export function createChatConfirmationActions(db: Db, options: ChatConfirmationOptions) { const { requireCurrentExternalActionAuthorization, isExternalActionAuthorizationChange, scheduleMessageProcessing, processPendingPublications } = options; - async function handleTelegramConfirmation(input: TelegramConfirmationInput) { + async function handleChatConfirmation(input: ChatConfirmationInput) { const { record, event, runtimeContext, conversation, principal, issued, interaction, deny, safelyKnown } = input; if ( - event.provider !== "telegram" || - !nativeTelegramConfirmation(interaction) + (event.provider !== "telegram" && event.provider !== "slack") || + !(nativeChatConfirmation(interaction) || event.provider === "slack" && (nativeChatCheckbox(interaction) || nativeChatSuggestions(interaction) || interaction.kind === "connection_intent")) ) { return deny(safelyKnown); } @@ -134,107 +138,95 @@ export function createTelegramConfirmationActions(db: Db, options: TelegramConfi } const decision = tokenPayload.decision; + if (interaction.kind === "connection_intent" && decision !== "reject") return deny(safelyKnown); + let selectedOptionIds: string[] | undefined; + if (interaction.kind === "request_checkbox_confirmation" && decision === "accept") { + const mappings = tokenPayload.selectionOptions as Array<{ value: string; optionId: string }> | undefined; + const values = event.selectionValues; + if (!Array.isArray(mappings) || !values || new Set(values).size !== values.length || + values.some(value => !mappings.some(item => item.value === value))) return deny(safelyKnown); + selectedOptionIds = values.map(value => mappings.find(item => item.value === value)!.optionId); + const minimum = interaction.payload.minSelected ?? 0; + const maximum = interaction.payload.maxSelected ?? interaction.payload.options.length; + if (values.length < minimum || values.length > maximum) { + await event.event.thread?.postEphemeral(event.event.user, { markdown: `That selection was not saved. ${minimum === maximum ? `Select exactly ${minimum}` : `Select between ${minimum} and ${maximum}`} checks, then save.` }, { fallbackToDM: false }); + return; + } + } + let selectedClientKeys: string[] | undefined; + if (interaction.kind === "suggest_tasks" && decision === "accept") { + const mappings = tokenPayload.selectionOptions as Array<{ value: string; optionId: string }> | undefined; + if (!Array.isArray(mappings) || !mappings.length) return deny(safelyKnown); + const values = mappings.length === 1 ? [mappings[0].value] : event.selectionValues; + if (!values || new Set(values).size !== values.length || values.some(value => !mappings.some(item => item.value === value))) return deny(safelyKnown); + if (!values.length) { + await event.event.thread?.postEphemeral(event.event.user, { markdown: "No tasks were created. Select at least one task, then choose Create selected." }, { fallbackToDM: false }); + return; + } + selectedClientKeys = values.map(value => mappings.find(item => item.value === value)!.optionId); + } + const mutationOptions = { + beforeResolveInTransaction: async (tx: DbTransaction) => { + await requireCurrentExternalActionAuthorization(tx, { + conversationId: conversation.id, + endpointId: record.endpoint.id, + expectedUserId: principal.userId!, + principalId: principal.principal.id, + runtimeContext, + }); + }, + afterResolveInTransaction: async (tx: DbTransaction, resolved: import("@paperclipai/shared").IssueThreadInteraction) => { + const [owned] = await tx + .update(chatActions) + .set({ + principalId: principal.principal.id, + status: "processing", + payload: { + ...tokenPayload, + messageId: event.event.messageId, + actionId: event.event.actionId, + value: event.event.value ?? null, + ...(selectedOptionIds ? { selectedOptionIds } : {}), + }, + result: { + code: "confirmation_resolution_committed_by_provider", + interactionId: resolved.id, + interactionStatus: resolved.status, + }, + updatedAt: new Date(), + }) + .where( + and( + eq(chatActions.id, action.id), + eq(chatActions.status, "issued"), + ), + ) + .returning({ id: chatActions.id }); + if (!owned) { + throw new Error( + "External confirmation action ownership changed before interaction commit", + ); + } + }, + }; + let createdIssues: Array<{ id: string; assigneeAgentId: string | null; status: string }> = []; try { if (decision === "accept") { - await issueThreadInteractionService(db).acceptInteraction( + const accepted = await issueThreadInteractionService(db).acceptInteraction( issue, interaction.id, - {}, + { ...(selectedOptionIds ? { selectedOptionIds } : {}), ...(selectedClientKeys ? { selectedClientKeys } : {}) }, { userId: principal.userId }, - { - beforeResolveInTransaction: async (tx) => { - await requireCurrentExternalActionAuthorization(tx, { - conversationId: conversation.id, - endpointId: record.endpoint.id, - expectedUserId: principal.userId!, - principalId: principal.principal.id, - runtimeContext, - }); - }, - afterResolveInTransaction: async (tx, resolved) => { - const [owned] = await tx - .update(chatActions) - .set({ - principalId: principal.principal.id, - status: "processing", - payload: { - ...tokenPayload, - messageId: event.event.messageId, - actionId: event.event.actionId, - value: null, - }, - result: { - code: "confirmation_resolution_committed_by_provider", - interactionId: resolved.id, - interactionStatus: resolved.status, - }, - updatedAt: new Date(), - }) - .where( - and( - eq(chatActions.id, action.id), - eq(chatActions.status, "issued"), - ), - ) - .returning({ id: chatActions.id }); - if (!owned) { - throw new Error( - "External confirmation action ownership changed before interaction commit", - ); - } - }, - }, + mutationOptions, ); + createdIssues = accepted.createdIssues; } else { - await issueThreadInteractionService(db).rejectInteraction( - issue, - interaction.id, - {}, - { userId: principal.userId }, - { - beforeResolveInTransaction: async (tx) => { - await requireCurrentExternalActionAuthorization(tx, { - conversationId: conversation.id, - endpointId: record.endpoint.id, - expectedUserId: principal.userId!, - principalId: principal.principal.id, - runtimeContext, - }); - }, - afterResolveInTransaction: async (tx, resolved) => { - const [owned] = await tx - .update(chatActions) - .set({ - principalId: principal.principal.id, - status: "processing", - payload: { - ...tokenPayload, - messageId: event.event.messageId, - actionId: event.event.actionId, - value: null, - }, - result: { - code: "confirmation_resolution_committed_by_provider", - interactionId: resolved.id, - interactionStatus: resolved.status, - }, - updatedAt: new Date(), - }) - .where( - and( - eq(chatActions.id, action.id), - eq(chatActions.status, "issued"), - ), - ) - .returning({ id: chatActions.id }); - if (!owned) { - throw new Error( - "External confirmation action ownership changed before interaction commit", - ); - } - }, - }, - ); + + if (interaction.kind === "connection_intent") { + await connectionIntentService(db).decline(interaction.id, principal.userId, undefined, { mutationOptions }); + } else { + await issueThreadInteractionService(db).rejectInteraction(issue, interaction.id, {}, { userId: principal.userId }, mutationOptions); + } } } catch (error) { if (isExternalActionAuthorizationChange(error)) { @@ -264,6 +256,7 @@ export function createTelegramConfirmationActions(db: Db, options: TelegramConfi throw error; } + for (const createdIssue of createdIssues) await queueIssueAssignmentWakeup({ heartbeat: options.heartbeat, issue: createdIssue, reason: "issue_assigned", mutation: "interaction_accept", contextSource: "issue.interaction.accept", requestedByActorType: "user", requestedByActorId: principal.userId }); await options.confirmationResolutionPersistBarrier?.(); if (!(await settleTerminalConfirmationAction(action.id))) { throw new Error( @@ -355,7 +348,7 @@ export function createTelegramConfirmationActions(db: Db, options: TelegramConfi !conversation || !publication || !endpoint || - endpoint.provider !== "telegram" || + (endpoint.provider !== "telegram" && endpoint.provider !== "slack") || publication.conversationId !== conversation.id || publication.payload.interactionId !== token.interactionId ) { @@ -379,8 +372,8 @@ export function createTelegramConfirmationActions(db: Db, options: TelegramConfi ).find((candidate) => candidate.id === token.interactionId); if ( !interaction || - interaction.kind !== "request_confirmation" || - !nativeTelegramConfirmation(interaction) + (interaction.kind !== "request_confirmation" && interaction.kind !== "request_checkbox_confirmation" && interaction.kind !== "suggest_tasks" && interaction.kind !== "connection_intent") || + !(nativeChatConfirmation(interaction) || endpoint.provider === "slack" && (nativeChatCheckbox(interaction) || nativeChatSuggestions(interaction) || interaction.kind === "connection_intent")) ) { await db .update(chatActions) @@ -480,14 +473,14 @@ export function createTelegramConfirmationActions(db: Db, options: TelegramConfi } const resolvedByUserId = interaction.resolvedByUserId; const shouldWake = - Boolean(issue.assigneeAgentId) && + interaction.kind !== "connection_intent" && Boolean(issue.assigneeAgentId) && issue.status !== "done" && issue.status !== "cancelled" && (interaction.continuationPolicy === "wake_assignee" || (interaction.continuationPolicy === "wake_assignee_on_accept" && interaction.status === "accepted")); const resolutionLabel = - interaction.status === "accepted" ? "Accepted" : "Rejected"; + interaction.status === "accepted" ? "Accepted" : interaction.kind === "connection_intent" ? "Declined" : "Rejected"; const resolvedByThisProviderAction = action.result?.code === "confirmation_resolution_committed_by_provider"; return db.transaction(async (tx) => { @@ -556,13 +549,15 @@ export function createTelegramConfirmationActions(db: Db, options: TelegramConfi payload: projectSafeChatPublication({ classification: "external", source: "issue_interaction", - text: `${resolutionLabel}: ${interaction.payload.prompt}`, + text: `${resolutionLabel}: ${chatInteractionPresentation(interaction).title}`, interaction: { id: interaction.id, card: { kind: "confirmation", - title: interaction.payload.prompt, - body: resolutionLabel, + title: chatInteractionPresentation(interaction).title, + body: interaction.kind === "request_checkbox_confirmation" && interaction.status === "accepted" + ? `Saved checks: ${interaction.payload.options.filter(option => interaction.result?.selectedOptionIds?.includes(option.id)).map(option => option.label).join("; ") || "none selected"}` + : resolutionLabel, actions: [], }, }, @@ -652,5 +647,5 @@ export function createTelegramConfirmationActions(db: Db, options: TelegramConfi } return settled; } - return { settleTerminalConfirmationAction, reconcileTerminalConfirmationActions, handleTelegramConfirmation }; + return { settleTerminalConfirmationAction, reconcileTerminalConfirmationActions, handleChatConfirmation }; } diff --git a/server/src/services/chat-channels/publication-replacement.ts b/server/src/services/chat-channels/publication-replacement.ts index 626161201a2..b3bf6e08143 100644 --- a/server/src/services/chat-channels/publication-replacement.ts +++ b/server/src/services/chat-channels/publication-replacement.ts @@ -469,10 +469,6 @@ export function createChatPublicationReplacement(db: Db, options: ChatPublicatio eq(issueThreadInteractions.id, payload.interactionId), eq(issueThreadInteractions.companyId, publication.companyId), eq(issueThreadInteractions.issueId, publication.issueId), - inArray(issueThreadInteractions.kind, [ - "ask_user_questions", - "request_confirmation", - ]), ), ); runId = interaction?.runId ?? null; @@ -643,10 +639,6 @@ export function createChatPublicationReplacement(db: Db, options: ChatPublicatio eq(issueThreadInteractions.id, payload.interactionId), eq(issueThreadInteractions.companyId, publication.companyId), eq(issueThreadInteractions.issueId, publication.issueId), - inArray(issueThreadInteractions.kind, [ - "ask_user_questions", - "request_confirmation", - ]), ), ) .then((rows) => rows[0] ?? null); @@ -711,10 +703,6 @@ export function createChatPublicationReplacement(db: Db, options: ChatPublicatio eq(issueThreadInteractions.companyId, publication.companyId), eq(issueThreadInteractions.issueId, publication.issueId), eq(issueThreadInteractions.sourceRunId, sourceRunId), - inArray(issueThreadInteractions.kind, [ - "ask_user_questions", - "request_confirmation", - ]), ), ) .then((rows) => rows.map((row) => row.id)); @@ -940,7 +928,6 @@ export function createChatPublicationReplacement(db: Db, options: ChatPublicatio where consuming_interaction.company_id = ${publication.companyId}::uuid and consuming_interaction.issue_id = ${publication.issueId}::uuid and consuming_interaction.source_run_id = ${lane.runId}::uuid - and consuming_interaction.kind in ('ask_user_questions', 'request_confirmation') and ${chatPublications.payload}->>'interactionId' = consuming_interaction.id::text and ${chatPublications.idempotencyKey} = 'interaction:' || consuming_interaction.id::text || ':' || ${publication.endpointId} )`, diff --git a/server/src/services/chat-channels/publications/transport.ts b/server/src/services/chat-channels/publications/transport.ts index e375fe805ed..1480939a7ab 100644 --- a/server/src/services/chat-channels/publications/transport.ts +++ b/server/src/services/chat-channels/publications/transport.ts @@ -1,3 +1,4 @@ +import { slackPublicationCard } from "../slack/cards.js"; import type { PublicationTransportInput } from "./types.js"; import { createPhotonPublicationDelivery } from "../imessage-photon/publications.js"; import { createOutboundAttachments } from "../outbound-attachments.js"; @@ -122,6 +123,7 @@ function safeCardForPublication( payload: SafeChatPublicationPayload, provider: ChatProvider, ) { + if (provider === "slack") return slackPublicationCard(payload); if (!payload.card) return null; const children = []; if (payload.card.body) children.push(CardText(payload.card.body)); diff --git a/server/src/services/chat-channels/slack/adapter.ts b/server/src/services/chat-channels/slack/adapter.ts index 6f3d691a8bd..9e76796544b 100644 --- a/server/src/services/chat-channels/slack/adapter.ts +++ b/server/src/services/chat-channels/slack/adapter.ts @@ -1,7 +1,30 @@ import { SlackAdapter } from "@chat-adapter/slack"; -import type { LinkPreview } from "chat"; +import type { AdapterPostableMessage, LinkPreview, RawMessage } from "chat"; +import { slackSelectionMessage } from "./cards.js"; export class PaperclipSlackAdapter extends SlackAdapter { + override async postMessage(threadId: string, message: AdapterPostableMessage): Promise { + const payload = slackSelectionMessage(message); + if (!payload) return super.postMessage(threadId, message); + const { channel, threadTs } = this.decodeThreadId(threadId); + try { + const result = await this._client.chat.postMessage(await this.withToken({ channel, thread_ts: threadTs || undefined, ...payload, unfurl_links: false, unfurl_media: false })); + if (!result.ts) throw new Error("Slack did not return a message receipt"); + return { id: result.ts, threadId, raw: result }; + } catch (error) { this.handleSlackError(error); } + } + + override async editMessage(threadId: string, messageId: string, message: AdapterPostableMessage): Promise { + const payload = slackSelectionMessage(message); + if (!payload) return super.editMessage(threadId, messageId, message); + const { channel } = this.decodeThreadId(threadId); + try { + const result = await this._client.chat.update(await this.withToken({ channel, ts: messageId, ...payload })); + if (!result.ts) throw new Error("Slack did not return an edit receipt"); + return { id: result.ts, threadId, raw: result }; + } catch (error) { this.handleSlackError(error); } + } + // The SDK polls for an optional Slack unfurl for two seconds before it // delivers a message containing a URL. Paperclip accepts the message text, // links and files directly; preview metadata is not part of task admission. diff --git a/server/src/services/chat-channels/slack/cards.test.ts b/server/src/services/chat-channels/slack/cards.test.ts new file mode 100644 index 00000000000..b379b4982b3 --- /dev/null +++ b/server/src/services/chat-channels/slack/cards.test.ts @@ -0,0 +1,91 @@ +import { describe, expect, it } from "vitest"; +import { cardToBlockKit } from "@chat-adapter/slack"; +import { projectSafeChatPublication } from "../../chat-publication-projection.js"; +import { isPassiveSlackAction, normalizeSlackSelectionAction, slackPublicationCard, slackSelectionMessage, slackSelectionValues } from "./cards.js"; + +describe("Slack interaction card wire payloads", () => { + it.each([120, 32000, 100000])("renders a %i-character request within Slack limits", length => { + const payload = projectSafeChatPublication({ + classification: "external", source: "issue_interaction", text: "Read this request in Paperclip", + interaction: { id: "interaction-1", card: { + kind: "question", title: "😀".repeat(160), body: "Q".repeat(length), + actions: [{ type: "link", label: "😀".repeat(80), url: "https://paperclip.example/issues/task-1" }], + } }, + }); + const blocks = cardToBlockKit(slackPublicationCard(payload)!) as Array<{ + type: string; + text?: { text: string }; + elements?: Array<{ text: { text: string } }>; + }>; + expect(blocks.length).toBeLessThanOrEqual(50); + expect(blocks[0]).toMatchObject({ type: "header", text: { text: "😀".repeat(150) } }); + for (const block of blocks) { + if (block.type === "section") expect(Array.from(block.text!.text).length).toBeLessThanOrEqual(3000); + if (block.type === "actions") expect(block.elements![0]).toMatchObject({ text: { text: "😀".repeat(75) } }); + } + const wire = JSON.stringify(blocks); + if (length > 32000) expect(wire).toContain("too long for Slack"); + else expect(blocks.filter(block => block.type === "section").map(block => block.text!.text).join("")).toBe("Q".repeat(length)); + expect(wire).toContain("https://paperclip.example/issues/task-1"); + }); +}); + + +describe("Slack inline selection", () => { + it("renders searchable choices with opaque tokens and no repeated prompt", () => { + const payload = projectSafeChatPublication({ classification: "external", source: "issue_interaction", text: "Choose a fixture", interaction: { + id: "interaction-1", card: { kind: "question", title: "Which fixture?", body: "Which fixture?\n\nChoose one.", selection: { + actionId: "pcs:interaction-1", label: "Choose a fixture", options: Array.from({ length: 13 }, (_, i) => ({ actionId: `pcq:option-${i}`, label: `Fixture ${i + 1}` })), + } }, + } }); + const wire = slackSelectionMessage({ card: slackPublicationCard(payload)! }); + expect(wire?.blocks).toContainEqual(expect.objectContaining({ type: "actions", elements: [expect.objectContaining({ type: "static_select", options: expect.arrayContaining([expect.objectContaining({ value: "pcq:option-12|interaction-1", text: { type: "plain_text", text: "Fixture 13" } })]) })] })); + expect(JSON.stringify(wire?.blocks).match(/Which fixture\?/g)).toHaveLength(1); + const event = { actionId: "pcs:interaction-1", value: "pcq:option-12|interaction-1" } as Parameters[0]; + expect(normalizeSlackSelectionAction(event)).toMatchObject({ actionId: "pcq:option-12", value: "interaction-1" }); + const forged = { ...event, value: "pcq:option-12|other-interaction" }; + expect(normalizeSlackSelectionAction(forged)).toBe(forged); + }); +}); + + +it("keeps multiple selections editable until explicit submit", () => { + const payload = projectSafeChatPublication({ classification: "external", source: "issue_interaction", text: "Choose coverage", interaction: { id: "interaction-1", card: { kind: "question", title: "Coverage?", selection: { actionId: "pcq:submit", label: "Choose coverage", multiple: true, submitLabel: "Submit answer", options: [{ actionId: "pcq:legacy", label: "Legacy" }, { actionId: "pcq:native", label: "Native" }] } } } }); + const wire = slackSelectionMessage({ card: slackPublicationCard(payload)! }); + expect(wire?.blocks).toContainEqual({ type: "actions", elements: [{ type: "checkboxes", action_id: "pcsv:pcq:submit", options: [{ text: { type: "plain_text", text: "Legacy" }, value: "pcq:legacy" }, { text: { type: "plain_text", text: "Native" }, value: "pcq:native" }] }] }); + expect(wire?.blocks.at(-1)).toMatchObject({ elements: [{ type: "button", action_id: "pcq:submit", value: "interaction-1" }] }); + const event = { actionId: "pcq:submit", raw: { state: { values: { block: { "pcsv:pcq:submit": { selected_options: [{ value: "pcq:legacy" }, { value: "pcq:native" }] } } } } } } as Parameters[0]; + expect(slackSelectionValues(event)).toEqual(["pcq:legacy", "pcq:native"]); + expect(slackSelectionValues({ ...event, actionId: "pcq:unrelated" })).toBeUndefined(); +}); + + +describe("untrusted Slack selection state", () => { + const event = (raw: unknown) => ({ actionId: "pcq:submit", raw } as Parameters[0]); + it.each([null, [], { state: null }, { state: { values: { block: null } } }, + { state: { values: { block: { "pcsv:pcq:submit": { selected_options: [null] } } } } }, + { state: { values: { block: { "pcsv:pcq:submit": { selected_options: [{ value: "x" }, { value: "x" }] } } } } }, + ])("rejects malformed or duplicate selections without throwing: %j", raw => { + expect(slackSelectionValues(event(raw))).toBeUndefined(); + }); + it("does not choose between ambiguous state blocks", () => { + const field = { "pcsv:pcq:submit": { selected_options: [{ value: "x" }] } }; + expect(slackSelectionValues(event({ state: { values: { one: field, two: field } } }))).toBeUndefined(); + }); + it("preserves an explicit empty selection", () => { + expect(slackSelectionValues(event({ state: { values: { one: { "pcsv:pcq:submit": { selected_options: [] } } } } }))).toEqual([]); + }); +}); + +it("acknowledges rendered link buttons without treating navigation as an answer", () => { + const payload = projectSafeChatPublication({ classification: "external", source: "issue_interaction", text: "Review GitHub", interaction: { id: "interaction-1", card: { kind: "question", title: "Connect GitHub", actions: [{ type: "link", label: "Review connection", url: "https://paperclip.example/issues/task-1" }, { type: "callback", label: "Not now", actionId: "pcq:decline" }] } } }); + const blocks = cardToBlockKit(slackPublicationCard(payload)!); + const actions = blocks.flatMap(block => block.type === "actions" ? block.elements : []); + const link = actions.find((action): action is { url: string; action_id: string } => + typeof action === "object" && action !== null && "url" in action && "action_id" in action + && typeof action.url === "string" && typeof action.action_id === "string"); + expect(link).toMatchObject({ type: "button", url: "https://paperclip.example/issues/task-1" }); + expect(isPassiveSlackAction({ actionId: link!.action_id! })).toBe(true); + expect(isPassiveSlackAction({ actionId: "pcsv:pcq:submit" })).toBe(true); + expect(isPassiveSlackAction({ actionId: "pcq:decline" })).toBe(false); +}); diff --git a/server/src/services/chat-channels/slack/cards.ts b/server/src/services/chat-channels/slack/cards.ts new file mode 100644 index 00000000000..9a2b98a6e84 --- /dev/null +++ b/server/src/services/chat-channels/slack/cards.ts @@ -0,0 +1,98 @@ +import { cardToBlockKit } from "@chat-adapter/slack"; +import type { AdapterPostableMessage, ActionEvent } from "chat"; +import type { SafeChatPublicationPayload } from "@paperclipai/shared"; +import { Actions, Button, Card, CardText, LinkButton, type CardElement } from "chat"; +import { isChatQuestionFormOpenActionId } from "../../chat-question-forms.js"; + +const MAX_CARD_BODY_LENGTH = 32_000; + +export function slackInteractionRequiresBoard(body: string): boolean { + return Array.from(body).length > MAX_CARD_BODY_LENGTH; +} + +export function slackPublicationCard(payload: SafeChatPublicationPayload): CardElement | null { + const card = payload.card; + if (!card) return null; + const children: CardElement["children"] = []; + const body = Array.from((card.body ?? "").split("\n\n").filter(paragraph => paragraph.trim() !== card.title.trim()).join("\n\n")); + const visibleBody = body.slice(0, MAX_CARD_BODY_LENGTH); + for (let offset = 0; offset < visibleBody.length; offset += 2000) { + children.push(CardText(visibleBody.slice(offset, offset + 2000).join(""))); + } + if (body.length > MAX_CARD_BODY_LENGTH) children.push(CardText("This request is too long for Slack. Open it in Paperclip to read the complete request and respond.")); + const actions = (card.actions ?? []).map(action => { + const label = Array.from(action.label).slice(0, 75).join(""); + return action.type === "callback" + ? Button({ id: action.actionId, label, style: action.style ?? "default", value: payload.interactionId, actionType: isChatQuestionFormOpenActionId(action.actionId) ? "modal" : undefined }) + : LinkButton({ label, url: action.url }); + }); + if (actions.length) children.push(Actions(actions)); + const rendered = Card({ title: Array.from(card.title).slice(0, 150).join(""), children }); + if (!card.selection) return rendered; + return Object.assign(rendered, { paperclipSelection: card.selection, paperclipInteractionId: payload.interactionId }); +} + +/** Slack-only wire rendering; the durable publication contains provider-neutral choices. */ +export function slackSelectionMessage(message: AdapterPostableMessage) { + if (typeof message !== "object" || !("card" in message)) return null; + const card = message.card as CardElement & { + paperclipSelection?: NonNullable["selection"]; + paperclipInteractionId?: string; + }; + const selection = card.paperclipSelection; + if (!selection || !card.paperclipInteractionId) return null; + const options = selection.options.map(option => ({ + text: { type: "plain_text" as const, text: option.label }, + value: selection.multiple ? option.actionId : `${option.actionId}|${card.paperclipInteractionId}`, + ...(option.description ? { description: { type: "plain_text" as const, text: option.description } } : {}), + })); + const blocks = cardToBlockKit(card); + const initial_options = options.filter((_, index) => selection.options[index].selected); + const initial = initial_options.length ? { initial_options } : {}; + const footer = blocks.filter(block => block.type === "actions"); + for (let i = blocks.length - 1; i >= 0; i--) if (blocks[i].type === "actions") blocks.splice(i, 1); + if (selection.multiple) { + blocks.push({ type: "actions", elements: [options.length <= 10 + ? { type: "checkboxes", action_id: `pcsv:${selection.actionId}`, options, ...initial } + : { type: "multi_static_select", action_id: `pcsv:${selection.actionId}`, placeholder: { type: "plain_text", text: selection.label }, options, ...initial }] }); + blocks.push({ type: "actions", elements: [{ type: "button", action_id: selection.actionId, text: { type: "plain_text", text: selection.submitLabel ?? "Submit" }, value: card.paperclipInteractionId, style: "primary" }, ...footer.flatMap(block => block.type === "actions" ? block.elements : [])] }); + } else { + blocks.push({ type: "actions", elements: [{ type: "static_select", action_id: selection.actionId, placeholder: { type: "plain_text", text: selection.label }, options, ...(initial_options[0] ? { initial_option: initial_options[0] } : {}) }] }); + } + if (!selection.multiple) blocks.push(...footer); + return { text: message.fallbackText ?? card.title ?? "Choose an answer", blocks }; +} + +/** URL buttons navigate in Slack; checkbox edits wait for an explicit submit. */ +export function isPassiveSlackAction(event: Pick): boolean { + return event.actionId.startsWith("link-") || event.actionId.startsWith("pcsv:"); +} + +/** Convert the selected opaque token to the existing authorized button-answer path. */ +export function normalizeSlackSelectionAction(event: ActionEvent): ActionEvent { + if (!event.actionId.startsWith("pcs:")) return event; + const [actionId, interactionId, extra] = (event.value ?? "").split("|"); + if (extra !== undefined || !actionId?.startsWith("pcq:") || event.actionId !== `pcs:${interactionId}`) return event; + return { ...event, actionId, value: interactionId }; +} + + +/** Selection changes stay client-side; only the explicit submit resolves work. */ +export function slackSelectionValues(event: ActionEvent): string[] | undefined { + const record = (value: unknown): Record | null => + value && typeof value === "object" && !Array.isArray(value) + ? value as Record : null; + const values = record(record(record(event.raw)?.state)?.values); + if (!values) return undefined; + const fieldId = `pcsv:${event.actionId}`; + const matches = Object.values(values).flatMap(block => { + const field = record(record(block)?.[fieldId]); + return field ? [field] : []; + }); + if (matches.length !== 1) return undefined; + const selected = matches[0].selected_options; + if (!Array.isArray(selected) || selected.length > 100) return undefined; + const tokens = selected.map(option => record(option)?.value); + if (tokens.some(value => typeof value !== "string") || new Set(tokens).size !== tokens.length) return undefined; + return tokens as string[]; +} diff --git a/server/src/services/chat-channels/slack/question-forms.test.ts b/server/src/services/chat-channels/slack/question-forms.test.ts new file mode 100644 index 00000000000..ace6ce66abe --- /dev/null +++ b/server/src/services/chat-channels/slack/question-forms.test.ts @@ -0,0 +1,28 @@ +import { describe, expect, it } from "vitest"; +import { forbidden, unprocessable } from "../../../errors.js"; +import { slackQuestionFormValidationError } from "./question-forms.js"; + +const fields = ["first", "second"].map(questionId => ({ + fieldId: `field-${questionId}`, questionId, kind: "text" as const, + maxLength: 3000, minLength: 0, inputType: "text" as const, required: true, +})); + +describe("Slack canonical form validation feedback", () => { + it("attaches a format error to its question without reflecting internal details", () => { + expect(slackQuestionFormValidationError(unprocessable( + "Question second does not match the required format", { code: "invalid_question_response" }, + ), fields)).toEqual({ action: "errors", errors: { "field-second": "Use the required format shown above." } }); + }); + + it("uses safe feedback when canonical validation has no specific field", () => { + expect(slackQuestionFormValidationError(unprocessable( + "private validation detail", { code: "invalid_question_response" }, + ), fields)).toEqual({ action: "errors", errors: { "field-first": "The answer could not be validated. Please try again." } }); + }); + + it("leaves authorization and unrelated failures to shared handling", () => { + for (const error of [null, forbidden(), unprocessable("Other failure"), new Error("transport failure")]) { + expect(slackQuestionFormValidationError(error, fields)).toBeNull(); + } + }); +}); diff --git a/server/src/services/chat-channels/slack/question-forms.ts b/server/src/services/chat-channels/slack/question-forms.ts new file mode 100644 index 00000000000..bd074f61cc6 --- /dev/null +++ b/server/src/services/chat-channels/slack/question-forms.ts @@ -0,0 +1,24 @@ +import type { ModalResponse } from "chat"; +import type { ChatQuestionFormSubmitTokenPayload } from "../../chat-question-forms.js"; + +/** Keep Slack's modal open when canonical answer validation rejects a field. */ +export function slackQuestionFormValidationError( + error: unknown, + fields: ChatQuestionFormSubmitTokenPayload["fields"], +): ModalResponse | null { + if (!error || typeof error !== "object") return null; + const failure = error as { status?: unknown; details?: { code?: unknown } }; + if (failure.status !== 422 || failure.details?.code !== "invalid_question_response") return null; + const message = error instanceof Error ? error.message : ""; + const field = fields.find(item => + message === `Question ${item.questionId} does not match the required format`) ?? fields[0]; + if (!field) return null; + return { + action: "errors", + errors: { + [field.fieldId]: message.includes("does not match the required format") + ? "Use the required format shown above." + : "The answer could not be validated. Please try again.", + }, + }; +} diff --git a/server/src/services/chat-interaction-arbitration.ts b/server/src/services/chat-interaction-arbitration.ts index dbb98715828..98b709e15a5 100644 --- a/server/src/services/chat-interaction-arbitration.ts +++ b/server/src/services/chat-interaction-arbitration.ts @@ -47,12 +47,9 @@ export async function hasChatRunOwnedProviderInteraction( eq(issueThreadInteractions.companyId, input.companyId), eq(issueThreadInteractions.issueId, input.issueId), eq(issueThreadInteractions.sourceRunId, input.runId), - inArray(issueThreadInteractions.kind, [ - "ask_user_questions", - "request_confirmation", - ]), or( and( + inArray(issueThreadInteractions.kind, ["ask_user_questions", "request_confirmation"]), eq(issueThreadInteractions.status, "pending"), exists( db diff --git a/server/src/services/chat-interaction-continuation.test.ts b/server/src/services/chat-interaction-continuation.test.ts new file mode 100644 index 00000000000..28da03b155e --- /dev/null +++ b/server/src/services/chat-interaction-continuation.test.ts @@ -0,0 +1,142 @@ +import { randomUUID } from "node:crypto"; +import { and, eq } from "drizzle-orm"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { + agents, agentWakeupRequests, authUsers, chatConversations, chatEndpoints, chatMessageLinks, + chatPublications, connectionIntentDeliveries, companies, companyMemberships, closeRegisteredClients, createDb, heartbeatRuns, + issueComments, issueThreadInteractions, issues, toolApplications, toolConnections, +} from "@paperclipai/db"; +import { startEmbeddedPostgresTestDatabase } from "../__tests__/helpers/embedded-postgres.js"; +import { resolveChatRunPresentationAuthorizationReason, enqueueChatRunMilestones } from "./chat-run-publications.js"; +import { CHAT_RUN_PRESENTATION_AUTHORIZATION_REASON, isChatOriginPublicationCandidate, isExternalChatPresentationContext, resolveHeartbeatRunResponse } from "./heartbeat-run-summary.js"; +import { resolveChatOriginPublicationBindings } from "./issues.js"; + +describe("chat interaction continuation delivery", () => { + const externalUrl = process.env.PAPERCLIP_TEST_DATABASE_URL; + let temporary: Awaited> | null = null; + let db: ReturnType; + beforeAll(async () => { + if (!externalUrl) temporary = await startEmbeddedPostgresTestDatabase("chat-interaction-delivery-"); + db = createDb(externalUrl ?? temporary!.connectionString); + await db.insert(authUsers).values({ id: "requester", name: "Requester", email: "requester@example.test", createdAt: new Date(), updatedAt: new Date() }).onConflictDoNothing(); + }, 30_000); + afterAll(async () => { await temporary?.cleanup(); if (externalUrl) await closeRegisteredClients(externalUrl); }); + async function fixture(kind = "request_checkbox_confirmation", status = "accepted") { + const [company] = await db.insert(companies).values({ name: "Continuation", issuePrefix: randomUUID().slice(0, 8) }).returning(); + await db.insert(companyMemberships).values({ companyId: company.id, principalType: "user", principalId: "requester", status: "active", membershipRole: "owner" }); + const [agent] = await db.insert(agents).values({ companyId: company.id, name: "Worker", adapterType: "paperclip_runner" }).returning(); + const [issue] = await db.insert(issues).values({ companyId: company.id, title: "Repository QA", status: "in_progress", assigneeAgentId: agent.id, responsibleUserId: "requester" }).returning(); + const [application] = await db.insert(toolApplications).values({ companyId: company.id, applicationKey: randomUUID(), name: "Slack", type: "chat" }).returning(); + const [connection] = await db.insert(toolConnections).values({ companyId: company.id, applicationId: application.id, name: "Slack", uid: randomUUID(), connectionPurpose: "channel", transport: "chat_sdk" }).returning(); + const [endpoint] = await db.insert(chatEndpoints).values({ companyId: company.id, connectionId: connection.id, provider: "slack", publicId: randomUUID(), assignedAgentId: agent.id, status: "active" }).returning(); + const [conversation] = await db.insert(chatConversations).values({ companyId: company.id, endpointId: endpoint.id, issueId: issue.id, externalConversationId: "test-channel", externalThreadId: randomUUID(), externalLabel: "QA" }).returning(); + const [comment] = await db.insert(issueComments).values({ companyId: company.id, issueId: issue.id, authorType: "user", authorUserId: "requester", body: "QA the runner migration" }).returning(); + await db.insert(chatMessageLinks).values({ companyId: company.id, endpointId: endpoint.id, conversationId: conversation.id, commentId: comment.id, providerMessageId: randomUUID(), direction: "inbound" }); + const [source] = await db.insert(heartbeatRuns).values({ companyId: company.id, agentId: agent.id, + status: "succeeded", responsibleUserId: "requester", contextSnapshot: { + source: "chat:slack", issueId: issue.id, endpointId: endpoint.id, wakeCommentId: comment.id, + } }).returning(); + const [interaction] = await db.insert(issueThreadInteractions).values({ companyId: company.id, issueId: issue.id, + kind, status, sourceRunId: source.id, payload: { version: 1 } as never, + result: { version: 1, outcome: "resolved", complete: status === "answered", items: [{ id: "one", verdict: "approve" }] } as never, + }).returning(); + const isConnection = kind === "connection_intent"; + if (isConnection) await db.insert(connectionIntentDeliveries).values({ companyId: company.id, interactionId: interaction.id }); + const isVerdicts = kind === "request_item_verdicts"; + const payload = { issueId: issue.id, interactionId: interaction.id, interactionKind: kind, + interactionStatus: status, ...(isConnection ? {} : { sourceRunId: source.id }), mutation: "interaction", + ...(isVerdicts ? { newlyResolvedItemIds: ["one"] } : {}), + }; + const sourceName = isVerdicts ? "verdicts" : status === "rejected" ? "reject" : status === "cancelled" ? "cancel" : "accept"; + const [successor] = await db.insert(heartbeatRuns).values({ companyId: company.id, agentId: agent.id, + status: "running", responsibleUserId: "requester", contextSnapshot: { ...payload, source: isConnection ? "connection_intent.resolved" : `issue.interaction.${sourceName}` }, + }).returning(); + const [wake] = await db.insert(agentWakeupRequests).values({ companyId: company.id, agentId: agent.id, + source: "automation", reason: "issue_commented", status: "claimed", runId: successor.id, payload, + idempotencyKey: isConnection ? `connection-intent:${interaction.id}:${status}` : isVerdicts ? `request_item_verdicts:${issue.id}:${interaction.id}:123` : `interaction:${interaction.id}:${status}`, + }).returning(); + await db.insert(chatPublications).values({ companyId: company.id, issueId: issue.id, endpointId: endpoint.id, + conversationId: conversation.id, state: "published", idempotencyKey: `interaction:${interaction.id}:${endpoint.id}`, + payload: { interactionId: interaction.id, text: "Please review the QA result" }, + }); + const bindings = () => resolveChatOriginPublicationBindings(db, company.id, issue.id, successor.id); + return { company, agent, issue, endpoint, conversation, source, successor, wake, interaction, bindings }; + } + + it.each([ + ["request_confirmation", "accepted"], ["request_confirmation", "rejected"], + ["request_checkbox_confirmation", "accepted"], ["request_checkbox_confirmation", "rejected"], + ["suggest_tasks", "accepted"], ["suggest_tasks", "rejected"], + ["connection_intent", "accepted"], ["connection_intent", "rejected"], + ["request_item_verdicts", "answered"], ["request_item_verdicts", "pending"], + ])("delivers the final response after %s becomes %s", async (kind, status) => { + const f = await fixture(kind, status); + expect(await f.bindings()).toEqual([{ companyId: f.company.id, endpointId: f.endpoint.id, conversationId: f.conversation.id }]); + const authorization = isChatOriginPublicationCandidate(f.successor.contextSnapshot) + ? await resolveChatRunPresentationAuthorizationReason(db, { companyId: f.company.id, issueId: f.issue.id, runId: f.successor.id }) : null; + expect(authorization).toBe(CHAT_RUN_PRESENTATION_AUTHORIZATION_REASON); + const resolved = resolveHeartbeatRunResponse({ resultJson: {}, + existingComment: { id: "bookkeeping", body: "Saved the review." }, + finalAgentMessage: { text: "Verified result delivered.", channel: "final", sourceEventId: "final" }, + preferFinalResponseOverExistingComment: isExternalChatPresentationContext(f.successor.contextSnapshot, authorization === CHAT_RUN_PRESENTATION_AUTHORIZATION_REASON), + }); + expect(resolved.decision).toMatchObject({ chosenSource: "final_agent_message", commentAction: "create" }); + await enqueueChatRunMilestones(db); + const published = await db.select().from(chatPublications).where(and(eq(chatPublications.issueId, f.issue.id), eq(chatPublications.idempotencyKey, `run:${f.successor.id}:working:${f.endpoint.id}`))); + expect(published).toHaveLength(1); + expect(published[0].conversationId).toBe(f.conversation.id); + await db.update(heartbeatRuns).set({ status: "cancelled" }).where(eq(heartbeatRuns.id, f.successor.id)); + }); + + it.each(["wake", "source", "agent", "conversation", "internal"])("withholds replies with invalid %s authority", async fault => { + const f = await fixture(); + if (fault === "wake") await db.update(agentWakeupRequests).set({ runId: null }).where(eq(agentWakeupRequests.id, f.wake.id)); + if (fault === "source") await db.update(issueThreadInteractions).set({ sourceRunId: null }).where(eq(issueThreadInteractions.id, f.interaction.id)); + if (fault === "agent") { + const [other] = await db.insert(agents).values({ companyId: f.company.id, name: "Other", adapterType: "process" }).returning(); + await db.update(agentWakeupRequests).set({ agentId: other.id }).where(eq(agentWakeupRequests.id, f.wake.id)); + } + if (fault === "conversation") { + const [other] = await db.insert(issues).values({ companyId: f.company.id, title: "Unrelated task" }).returning(); + await db.update(chatConversations).set({ issueId: other.id }).where(eq(chatConversations.id, f.conversation.id)); + } + if (fault === "internal") await db.update(heartbeatRuns).set({ contextSnapshot: { ...f.successor.contextSnapshot, source: "issue.assigned" } }).where(eq(heartbeatRuns.id, f.successor.id)); + expect(await f.bindings()).toEqual([]); + }); + + it.each(["key", "unsaved", "payload", "skipped"])("rejects an item-review wake with %s proof", async fault => { + const f = await fixture("request_item_verdicts", "pending"); + if (fault === "key") await db.update(agentWakeupRequests).set({ idempotencyKey: "forged" }).where(eq(agentWakeupRequests.id, f.wake.id)); + if (fault === "unsaved") await db.update(issueThreadInteractions).set({ result: null }).where(eq(issueThreadInteractions.id, f.interaction.id)); + if (fault === "payload") await db.update(agentWakeupRequests).set({ payload: { ...f.wake.payload, newlyResolvedItemIds: ["not-saved"] } }).where(eq(agentWakeupRequests.id, f.wake.id)); + if (fault === "skipped") await db.update(agentWakeupRequests).set({ status: "skipped" }).where(eq(agentWakeupRequests.id, f.wake.id)); + expect(await f.bindings()).toEqual([]); + }); + it.each(["accepted", "rejected"])("delivers an automation-origin connection %s through its published Slack prompt", async status => { + const f = await fixture("connection_intent", status); + await db.update(heartbeatRuns).set({ contextSnapshot: { source: "automation", issueId: f.issue.id } }).where(eq(heartbeatRuns.id, f.source.id)); + expect(await f.bindings()).toEqual([{ companyId: f.company.id, endpointId: f.endpoint.id, conversationId: f.conversation.id }]); + expect(await resolveChatRunPresentationAuthorizationReason(db, { companyId: f.company.id, issueId: f.issue.id, runId: f.successor.id })).toBe(CHAT_RUN_PRESENTATION_AUTHORIZATION_REASON); + await db.update(heartbeatRuns).set({ status: "cancelled" }).where(eq(heartbeatRuns.id, f.successor.id)); + }); + + it.each(["publication", "receipt"])("withholds automation-origin connection replies without the %s", async missing => { + const f = await fixture("connection_intent", "rejected"); + await db.update(heartbeatRuns).set({ contextSnapshot: { source: "automation", issueId: f.issue.id } }).where(eq(heartbeatRuns.id, f.source.id)); + if (missing === "publication") await db.update(chatPublications).set({ state: "pending" }).where(eq(chatPublications.issueId, f.issue.id)); + if (missing === "receipt") await db.delete(connectionIntentDeliveries).where(eq(connectionIntentDeliveries.interactionId, f.interaction.id)); + expect(await f.bindings()).toEqual([]); + await db.update(heartbeatRuns).set({ status: "cancelled" }).where(eq(heartbeatRuns.id, f.successor.id)); + }); + + it.each(["delivery", "wake", "key", "pending", "source"])("rejects connection continuation with missing %s proof", async fault => { + const f = await fixture("connection_intent", "rejected"); + if (fault === "delivery") await db.delete(connectionIntentDeliveries).where(eq(connectionIntentDeliveries.interactionId, f.interaction.id)); + if (fault === "wake") await db.update(agentWakeupRequests).set({ runId: null }).where(eq(agentWakeupRequests.id, f.wake.id)); + if (fault === "key") await db.update(agentWakeupRequests).set({ idempotencyKey: "forged" }).where(eq(agentWakeupRequests.id, f.wake.id)); + if (fault === "pending") await db.update(issueThreadInteractions).set({ status: "pending" }).where(eq(issueThreadInteractions.id, f.interaction.id)); + if (fault === "source") await db.update(issueThreadInteractions).set({ sourceRunId: null }).where(eq(issueThreadInteractions.id, f.interaction.id)); + expect(await f.bindings()).toEqual([]); + }); + +}); diff --git a/server/src/services/chat-interaction-continuation.ts b/server/src/services/chat-interaction-continuation.ts new file mode 100644 index 00000000000..9c827712e2c --- /dev/null +++ b/server/src/services/chat-interaction-continuation.ts @@ -0,0 +1,75 @@ +import { agentWakeupRequests, connectionIntentDeliveries, issueThreadInteractions, type Db } from "@paperclipai/db"; +import { and, eq, ne, or, inArray, sql } from "drizzle-orm"; + +function record(value: unknown): Record { + return value && typeof value === "object" && !Array.isArray(value) + ? value as Record : {}; +} + +// Item reviews may resume after a partial decision. Their existing wake key is +// windowed, so an interaction/status key cannot prove this continuation. Match +// the server-owned wake to saved decisions before following its source run. +export async function resolveItemVerdictContinuationWake(db: Db, input: { + companyId: string; issueId: string; interactionId: string; sourceRunId: string; + runId: string; agentId: string; result: unknown; +}): Promise<{ id: string } | null> { + const result = record(input.result); + if (result.outcome !== "resolved" || !Array.isArray(result.items)) return null; + const savedIds = new Set(result.items.map(item => record(item).id)); + const prefix = `request_item_verdicts:${input.issueId}:${input.interactionId}:`; + const wakes = await db.select({ id: agentWakeupRequests.id, + key: agentWakeupRequests.idempotencyKey, payload: agentWakeupRequests.payload, + }).from(agentWakeupRequests).where(and( + eq(agentWakeupRequests.companyId, input.companyId), + eq(agentWakeupRequests.agentId, input.agentId), + eq(agentWakeupRequests.runId, input.runId), + eq(agentWakeupRequests.source, "automation"), + eq(agentWakeupRequests.reason, "issue_commented"), + ne(agentWakeupRequests.status, "skipped"), + )); + return wakes.find(wake => { + const payload = record(wake.payload); + const ids = payload.newlyResolvedItemIds; + return wake.key?.startsWith(prefix) && /^\d+$/.test(wake.key.slice(prefix.length)) && + payload.issueId === input.issueId && payload.interactionId === input.interactionId && + payload.sourceRunId === input.sourceRunId && payload.interactionKind === "request_item_verdicts" && + payload.mutation === "interaction" && Array.isArray(ids) && ids.length > 0 && + ids.every(id => typeof id === "string" && savedIds.has(id)); + }) ?? null; +} + +export async function resolveConnectionIntentContinuationSource(db: Db, input: { + companyId: string; issueId: string; interactionId: string; runId: string; agentId: string; +}): Promise { + const [receipt] = await db.select({ sourceRunId: issueThreadInteractions.sourceRunId }) + .from(issueThreadInteractions) + .innerJoin(connectionIntentDeliveries, and( + eq(connectionIntentDeliveries.companyId, issueThreadInteractions.companyId), + eq(connectionIntentDeliveries.interactionId, issueThreadInteractions.id), + )) + .innerJoin(agentWakeupRequests, and( + eq(agentWakeupRequests.companyId, input.companyId), + eq(agentWakeupRequests.agentId, input.agentId), + eq(agentWakeupRequests.runId, input.runId), + eq(agentWakeupRequests.source, "automation"), + eq(agentWakeupRequests.reason, "issue_commented"), + ne(agentWakeupRequests.status, "skipped"), + sql`${agentWakeupRequests.idempotencyKey} = 'connection-intent:' || ${issueThreadInteractions.id}::text || ':' || ${issueThreadInteractions.status}`, + sql`${agentWakeupRequests.payload}->>'issueId' = ${input.issueId}`, + sql`${agentWakeupRequests.payload}->>'interactionId' = ${input.interactionId}`, + sql`${agentWakeupRequests.payload}->>'interactionKind' = 'connection_intent'`, + sql`${agentWakeupRequests.payload}->>'interactionStatus' = ${issueThreadInteractions.status}`, + )) + .where(and( + eq(issueThreadInteractions.companyId, input.companyId), + eq(issueThreadInteractions.issueId, input.issueId), + eq(issueThreadInteractions.id, input.interactionId), + eq(issueThreadInteractions.kind, "connection_intent"), + or(inArray(issueThreadInteractions.status, ["accepted", "rejected"]), and( + eq(issueThreadInteractions.status, "expired"), + sql`${issueThreadInteractions.result}->>'outcome' = 'expired'`, + sql`jsonb_typeof(${issueThreadInteractions.result}->'connectionId') = 'string'`, + )), + )).limit(1); + return receipt?.sourceRunId ?? null; +} diff --git a/server/src/services/chat-interaction-forms.test.ts b/server/src/services/chat-interaction-forms.test.ts new file mode 100644 index 00000000000..41485c08f88 --- /dev/null +++ b/server/src/services/chat-interaction-forms.test.ts @@ -0,0 +1,44 @@ +import { describe, expect, it } from "vitest"; +import type { IssueThreadInteraction, RequestItemVerdictsInteraction } from "@paperclipai/shared"; +import { chatInteractionForm, chatItemVerdicts } from "./chat-interaction-forms.js"; +import { chatQuestionFormActionRecords, createChatQuestionFormDraft, parseChatQuestionFormSubmitTokenPayload } from "./chat-question-forms.js"; + +function review(): RequestItemVerdictsInteraction { + return { + id: "review-1", kind: "request_item_verdicts", status: "pending", summary: "Review the migration", + payload: { version: 1, prompt: "Check both artifacts", items: [{ id: "api", label: "API", description: "The route" }, { id: "docs", label: "Docs" }], verdicts: ["approve", "reject"], requireReasonOn: ["reject"] }, + result: null, + } as RequestItemVerdictsInteraction; +} + +describe("Slack item reviews", () => { + it("maps opaque form values to canonical verdicts and requires the reason for rejection", () => { + const source = review(); + const view = chatInteractionForm(source, "slack")!; + expect(view.summary).toContain(source.payload.prompt); + const draft = createChatQuestionFormDraft(view, { nativeProvider: "slack" })!; + const payload = parseChatQuestionFormSubmitTokenPayload(chatQuestionFormActionRecords(draft, { companyId: "company", conversationId: "conversation", endpointId: "endpoint", publicationId: "publication" })[1].payload)!; + const answers = [{ questionId: "verdict:api", optionIds: ["approve"] }, { questionId: "verdict:docs", optionIds: ["reject"] }]; + const missing = chatItemVerdicts(source, answers, payload)!; + const reasonField = payload.fields.find(field => field.questionId === "reason:docs")!; + expect(missing.errors).toEqual({ [reasonField.fieldId]: "Explain why you chose reject." }); + const complete = chatItemVerdicts(source, [...answers, { questionId: "reason:docs", optionIds: [], otherText: " Missing examples " }], payload)!; + expect(complete).toEqual({ errors: {}, verdicts: [{ id: "api", verdict: "approve" }, { id: "docs", verdict: "reject", reason: "Missing examples" }] }); + expect(chatItemVerdicts(source, [{ questionId: "verdict:api", optionIds: ["approve"] }, { questionId: "verdict:docs", optionIds: ["approve"] }], payload)!.errors).toEqual({}); + }); + + it("shows only unresolved items and preserves full context", () => { + const source = review(); + source.result = { version: 1, outcome: "resolved", complete: false, items: [{ id: "api", verdict: "approve" }] } as RequestItemVerdictsInteraction["result"]; + const view = chatInteractionForm(source, "slack")!; + expect(view.payload.questions.map(question => question.id)).toEqual(["verdict:docs", "reason:docs"]); + expect(source.kind).toBe("request_item_verdicts"); + }); + + it("keeps unsupported providers, attachments, and oversize reviews on the complete surface", () => { + const source = review(); + expect(chatInteractionForm(source, "telegram")).toBeNull(); + expect(chatInteractionForm({ ...source, payload: { ...source.payload, items: [{ id: "api", label: "API", attachmentId: "attachment" }] } } as IssueThreadInteraction, "slack")).toBeNull(); + expect(chatInteractionForm({ ...source, payload: { ...source.payload, items: Array.from({ length: 13 }, (_, i) => ({ id: `item-${i}`, label: `Item ${i}` })) } }, "slack")).toBeNull(); + }); +}); diff --git a/server/src/services/chat-interaction-forms.ts b/server/src/services/chat-interaction-forms.ts new file mode 100644 index 00000000000..3ec93b814f0 --- /dev/null +++ b/server/src/services/chat-interaction-forms.ts @@ -0,0 +1,37 @@ +import type { AskUserQuestionsInteraction, AskUserQuestionsAnswer, IssueThreadInteraction, RequestItemVerdictValue } from "@paperclipai/shared"; +import type { ChatQuestionFormSubmitTokenPayload } from "./chat-question-forms.js"; + +/** A view model for the existing form transport; canonical interactions keep their original kind. */ +export function chatInteractionForm(interaction: IssueThreadInteraction, provider: string): AskUserQuestionsInteraction | null { + if (interaction.kind === "ask_user_questions") return interaction; + if (provider !== "slack" || interaction.kind !== "request_item_verdicts" || interaction.payload.target || + interaction.payload.items.length > 12 || interaction.payload.items.some(item => item.attachmentId)) return null; + const remaining = interaction.payload.items.filter(item => !interaction.result?.items.some(result => result.id === item.id)); + if (!remaining.length) return null; + const verdicts = interaction.payload.verdicts ?? ["approve", "reject"]; + const reasons = interaction.payload.requireReasonOn ?? []; + return { ...interaction, kind: "ask_user_questions", result: null, summary: [interaction.summary, interaction.payload.prompt, interaction.payload.detailsMarkdown].filter(Boolean).join("\n\n"), payload: { + version: 1, title: "Review decisions", + questions: remaining.flatMap(item => [ + { id: `verdict:${item.id}`, prompt: item.label, helpText: [item.description, item.previewMarkdown, item.href].filter(Boolean).join("\n\n"), required: true, selectionMode: "single" as const, + options: verdicts.map(verdict => ({ id: verdict, label: verdict[0].toUpperCase() + verdict.slice(1) })) }, + { id: `reason:${item.id}`, prompt: `${interaction.payload.reasonLabel ?? "Reason"}: ${item.label}`, helpText: reasons.length ? `Required for: ${reasons.join(", ")}.` : "Optional explanation.", required: false, selectionMode: "single" as const, allowOther: true, + options: [{ id: "text", label: "Reason", freeText: true }] }, + ]), + } }; +} + +export function chatItemVerdicts(interaction: IssueThreadInteraction, answers: AskUserQuestionsAnswer[], payload: ChatQuestionFormSubmitTokenPayload) { + if (interaction.kind !== "request_item_verdicts") return null; + const errors: Record = {}; + const verdicts = interaction.payload.items.filter(item => !interaction.result?.items.some(result => result.id === item.id)).map(item => { + const verdict = answers.find(answer => answer.questionId === `verdict:${item.id}`)?.optionIds[0] as RequestItemVerdictValue; + const reason = answers.find(answer => answer.questionId === `reason:${item.id}`)?.otherText?.trim(); + if (interaction.payload.requireReasonOn?.includes(verdict) && !reason) { + const field = payload.fields.find(field => field.questionId === `reason:${item.id}`); + if (field) errors[field.fieldId] = `Explain why you chose ${verdict}.`; + } + return { id: item.id, verdict, ...(reason ? { reason } : {}) }; + }); + return { verdicts, errors }; +} diff --git a/server/src/services/chat-interaction-presentation.ts b/server/src/services/chat-interaction-presentation.ts new file mode 100644 index 00000000000..b3749e17eff --- /dev/null +++ b/server/src/services/chat-interaction-presentation.ts @@ -0,0 +1,83 @@ +import type { AskUserQuestionsInteraction, IssueThreadInteraction } from "@paperclipai/shared"; + +export function chatInteractionPresentation(interaction: IssueThreadInteraction, options: { compactChoices?: boolean; nativeCustomAnswer?: boolean } = {}) { + const context = [interaction.summary].filter((value): value is string => Boolean(value?.trim())); + switch (interaction.kind) { + case "ask_user_questions": { + const { payload } = interaction; + if (payload.questionSet?.description) context.push(payload.questionSet.description); + for (const question of payload.questions) { + const source = payload.questionSet?.questions.find(item => item.id === question.id); + if (source?.header && source.header !== question.helpText && source.header !== question.prompt) context.push(source.header); + context.push(question.prompt); + if (question.helpText) context.push(question.helpText); + for (const option of question.options.filter(item => !item.freeText || question.options.length > 1)) { + if (options.nativeCustomAnswer && option.freeText) continue; + const recommended = source?.options?.find(item => item.id === option.id)?.recommended; + if (options.compactChoices && option.label.length <= 60 && (option.description?.length ?? 0) <= 75) continue; + context.push(`- ${option.label}${recommended ? " (recommended)" : ""}${option.description ? `: ${option.description}` : ""}`); + } + if (!options.compactChoices && !options.nativeCustomAnswer && (source?.customAnswer || (question.allowOther && question.options.some(item => !item.freeText)))) { + context.push("You can also provide your own answer."); + } + } + return { + title: payload.title ?? interaction.title ?? "Input needed", + body: context.join("\n\n"), + }; + } + case "request_confirmation": + case "request_checkbox_confirmation": + case "request_item_verdicts": { + const { payload } = interaction; + context.push(payload.prompt); + if (payload.detailsMarkdown) context.push(payload.detailsMarkdown); + if (interaction.kind === "request_checkbox_confirmation") { + const minimum = interaction.payload.minSelected ?? 0; + const maximum = interaction.payload.maxSelected; + if (minimum > 0 || maximum != null) context.push(minimum === maximum + ? `Select exactly ${minimum}.` + : `Select ${minimum}–${maximum ?? interaction.payload.options.length} checks.`); + for (const option of interaction.payload.options) { + if (options.compactChoices && option.label.length <= 60 && (option.description?.length ?? 0) <= 75) continue; + context.push(`- ${option.label}${option.description ? `: ${option.description}` : ""}`); + } + } + if (interaction.kind === "request_item_verdicts") { + for (const item of interaction.payload.items) { + context.push(`- ${item.label}${item.description ? `: ${item.description}` : ""}`); + } + } + return { title: payload.prompt, body: context.join("\n\n") }; + } + case "suggest_tasks": { + for (const task of interaction.payload.tasks.filter(item => !item.hiddenInPreview)) { + if (options.compactChoices && task.title.length <= 60 && (task.description?.length ?? 0) <= 75) continue; + context.push(`- ${task.title}${task.description ? `: ${task.description}` : ""}`); + } + return { title: interaction.title ?? "Review suggested tasks", body: context.join("\n\n") }; + } + case "connection_intent": { + const { payload } = interaction; + context.push(`${payload.requestingAgentName} needs ${payload.serviceName}${payload.accessRequest ? ` (${payload.accessRequest.connectionName})` : ""}.`); + context.push("The addressed user must review this connection request in Paperclip."); + return { title: interaction.title ?? `Connect ${payload.serviceName}`, body: context.join("\n\n") }; + } + } +} + +/** Keep the submitted response readable without publishing internal result metadata. */ +export function answeredChatQuestionBody(interaction: AskUserQuestionsInteraction): string { + const lines = [...new Set([interaction.summary, interaction.payload.questionSet?.description] + .filter((value): value is string => Boolean(value?.trim())))]; + for (const question of interaction.payload.questions) { + const answer = interaction.result?.answers.find(item => item.questionId === question.id); + const labels = (answer?.optionIds ?? []).flatMap(id => { + const option = question.options.find(item => item.id === id && !item.freeText); + return option ? [option.label] : []; + }); + if (answer?.otherText?.trim()) labels.push(answer.otherText.trim()); + lines.push(question.prompt, labels.length ? `Answered: ${labels.join("; ")}` : "No answer provided (optional)."); + } + return lines.join("\n\n"); +} diff --git a/server/src/services/chat-interaction-publications.ts b/server/src/services/chat-interaction-publications.ts index 79018caf4fd..72b1779e68d 100644 --- a/server/src/services/chat-interaction-publications.ts +++ b/server/src/services/chat-interaction-publications.ts @@ -1,3 +1,6 @@ +import { chatInteractionForm } from "./chat-interaction-forms.js"; +import { slackInteractionRequiresBoard } from "./chat-channels/slack/cards.js"; +import { answeredChatQuestionBody, chatInteractionPresentation } from "./chat-interaction-presentation.js"; import { notifyChatPublicationWork } from "./chat-work-notifications.js"; import { nativePhotonInteraction } from "./photon/interactions.js"; import { randomBytes } from "node:crypto"; @@ -16,6 +19,8 @@ import type { AskUserQuestionsQuestion, IssueThreadInteraction, RequestConfirmationInteraction, + RequestCheckboxConfirmationInteraction, + SuggestTasksInteraction, SafeExternalChatCardAction, } from "@paperclipai/shared"; import { projectSafeChatPublication } from "./chat-publication-projection.js"; @@ -68,7 +73,34 @@ function terminalNativeInteractionCopy( } return null; } - if (interaction.kind !== "ask_user_questions") return null; + if (interaction.kind === "request_checkbox_confirmation" && interaction.status === "accepted") { + const labels = interaction.payload.options.filter(option => interaction.result?.selectedOptionIds?.includes(option.id)).map(option => option.label); + const body = labels.length ? `Saved checks: ${labels.join("; ")}` : "Saved checks: none selected."; + return { body, text: body }; + } + if (interaction.kind === "request_item_verdicts" && interaction.status === "answered") { + const body = interaction.payload.items.map(item => { + const result = interaction.result?.items.find(result => result.id === item.id); + return `${item.label}: ${result?.verdict ?? "pending"}${result?.reason ? ` — ${result.reason}` : ""}`; + }).join("\n\n"); + return { body, text: body }; + } + if (interaction.kind === "suggest_tasks" && (interaction.status === "accepted" || interaction.status === "rejected")) { + const body = interaction.status === "rejected" ? "Dismissed — no tasks created." : + (interaction.result?.createdTasks ?? []).map(task => { + const url = publicChatTaskUrl(task.issueId); + return `Created: ${task.identifier ?? "Task"} — ${task.title}${url ? `\n${url}` : ""}`; + }).join("\n\n"); + return { body, text: body }; + } + if (interaction.kind === "connection_intent" && (interaction.status === "accepted" || interaction.status === "rejected")) { + const body = interaction.status === "accepted" ? `Connected: ${interaction.payload.serviceName}` : `Declined: ${interaction.payload.serviceName}. No access was granted.`; + return { body, text: body }; + } + if (interaction.kind !== "ask_user_questions") { + const body = ({ accepted: "Accepted", rejected: "Rejected", answered: "Answered", cancelled: "Cancelled in Paperclip", expired: "Expired in Paperclip" } as Record)[interaction.status]; + return body ? { body, text: `${body}.` } : null; + } if (interaction.status === "answered") { const question = nativeChatQuestion(interaction); const answer = question @@ -82,7 +114,7 @@ function terminalNativeInteractionCopy( (candidate) => candidate.id === answer.optionIds[0], ) : null; - const body = option ? `Answered: ${option.label}.` : "Answered."; + const body = option ? `Answered: ${option.label}.` : answeredChatQuestionBody(interaction); return { body, text: body }; } if (interaction.status === "cancelled") { @@ -149,13 +181,14 @@ export function telegramCallbackDataByteLength( export function nativeChatQuestion( interaction: AskUserQuestionsInteraction, + maxOptions = MAX_NATIVE_QUESTION_OPTIONS, ): AskUserQuestionsQuestion | null { if (interaction.payload.questions.length !== 1) return null; const question = interaction.payload.questions[0]; if ( question.selectionMode !== "single" || question.allowOther === true || - question.options.length > MAX_NATIVE_QUESTION_OPTIONS || + question.options.length > maxOptions || question.options.some((option) => option.freeText === true) ) { return null; @@ -163,13 +196,36 @@ export function nativeChatQuestion( return question; } +export function nativeChatCustomQuestion(interaction: AskUserQuestionsInteraction): AskUserQuestionsQuestion | null { + const question = interaction.payload.questions[0]; + if (interaction.payload.questions.length !== 1 || !question || question.selectionMode !== "single" || !question.allowOther || + !interaction.payload.questionSet?.questions[0]?.customAnswer) return null; + const options = question.options.filter(option => !option.freeText); + return options.length > 0 && options.length <= 100 ? { ...question, options } : null; +} + +export function nativeChatMultiQuestion(interaction: AskUserQuestionsInteraction): AskUserQuestionsQuestion | null { + const question = interaction.payload.questions[0]; + if (interaction.payload.questions.length !== 1 || !question || question.selectionMode !== "multi" || question.allowOther || question.options.length === 0 || question.options.length > 100 || question.options.some(option => option.freeText)) return null; + return question; +} + +export function nativeChatSuggestions(interaction: IssueThreadInteraction): SuggestTasksInteraction | null { + return interaction.kind === "suggest_tasks" && interaction.payload.tasks.filter(task => !task.hiddenInPreview).length > 0 && interaction.payload.tasks.length <= 100 ? interaction : null; +} + +export function nativeChatCheckbox(interaction: IssueThreadInteraction): RequestCheckboxConfirmationInteraction | null { + return interaction.kind === "request_checkbox_confirmation" && !interaction.payload.rejectRequiresReason && + interaction.payload.target?.type !== "issue_document" && interaction.payload.options.length <= 100 ? interaction : null; +} + /** - * Telegram can safely render ordinary binary confirmations as inline buttons. + * Slack and Telegram can render ordinary binary confirmations as inline buttons. * Confirmations that collect a rejection reason or authorize a credential, * connection, or tool side effect stay in Paperclip, where the complete * governed review UI and permission checks are available. */ -export function nativeTelegramConfirmation( +export function nativeChatConfirmation( interaction: IssueThreadInteraction, ): RequestConfirmationInteraction | null { if (interaction.kind !== "request_confirmation") return null; @@ -185,40 +241,6 @@ export function nativeTelegramConfirmation( return interaction; } -function textForQuestionInteraction( - interaction: AskUserQuestionsInteraction, - taskUrl: string | null, -): string { - const lines = [ - interaction.payload.title ?? interaction.title ?? "Input needed", - "", - ]; - if (interaction.summary) lines.push(interaction.summary, ""); - for (const question of interaction.payload.questions) { - lines.push(question.prompt); - if (question.helpText) lines.push(question.helpText); - for (const option of question.options) lines.push(`- ${option.label}`); - lines.push(""); - } - lines.push( - taskUrl - ? `Open the task in Paperclip to respond: ${taskUrl}` - : "Open the task in Paperclip to respond.", - ); - return lines.join("\n"); -} - -function genericInteractionText(taskUrl: string | null): string { - return [ - "This task needs an authorized response in Paperclip.", - taskUrl - ? `Open the task in Paperclip to respond: ${taskUrl}` - : "Open the task in Paperclip to respond.", - ] - .filter((value): value is string => Boolean(value)) - .join("\n\n"); -} - /** * Enqueues one immutable outbox item per live external task binding. A lone * closed single-select question receives compact executable buttons. Slack and @@ -230,17 +252,6 @@ export async function enqueueIssueInteractionChatPublications( interaction: IssueThreadInteraction, ) { if (interaction.status !== "pending") return []; - // The first native-chat wave intentionally externalizes only questions and - // confirmations. Other governance interactions have richer partial and - // terminal semantics that are authoritative in Paperclip; projecting a - // generic link card without complete settlement/recovery would leave stale - // provider prompts after a board decision. - if ( - interaction.kind !== "ask_user_questions" && - interaction.kind !== "request_confirmation" - ) { - return []; - } // An endpoint is one immutable provider bot identity. Never externalize a // user/system-authored interaction, or let one agent speak through another // agent's endpoint. If the interaction names a source run, verify that run's @@ -285,30 +296,46 @@ export async function enqueueIssueInteractionChatPublications( if (bindings.length === 0) return []; const taskUrl = publicChatInteractionTaskUrl(interaction.issueId); - const question = - interaction.kind === "ask_user_questions" - ? nativeChatQuestion(interaction) - : null; const inserted: Array = []; for (const { conversation, endpoint } of bindings) { if (endpoint.assignedAgentId !== interaction.createdByAgentId) continue; + if (endpoint.provider !== "slack" && interaction.kind !== "ask_user_questions" && interaction.kind !== "request_confirmation") continue; + let connectionDecline = endpoint.provider === "slack" && endpoint.capabilities.actions && interaction.kind === "connection_intent" ? interaction : null; + let suggestions = endpoint.provider === "slack" && endpoint.capabilities.actions ? nativeChatSuggestions(interaction) : null; + const suggestedOptions = suggestions?.payload.tasks.filter(task => !task.hiddenInPreview).map(task => ({ actionId: createChatQuestionOptionActionToken(), option: { id: task.clientKey, label: task.title, description: task.description } })) ?? []; + let checklist = endpoint.provider === "slack" && endpoint.capabilities.actions ? nativeChatCheckbox(interaction) : null; + const checklistOptions = checklist?.payload.options.map(option => ({ actionId: createChatQuestionOptionActionToken(), option })) ?? []; + const customQuestion = endpoint.provider === "slack" && endpoint.capabilities.modals === true && interaction.kind === "ask_user_questions" ? nativeChatCustomQuestion(interaction) : null; + const multipleQuestion = endpoint.provider === "slack" && interaction.kind === "ask_user_questions" ? nativeChatMultiQuestion(interaction) : null; + const question = interaction.kind === "ask_user_questions" + ? multipleQuestion ?? customQuestion ?? nativeChatQuestion(interaction, endpoint.provider === "slack" ? 100 : MAX_NATIVE_QUESTION_OPTIONS) : null; + const inlineSelection = endpoint.provider === "slack" && question && (multipleQuestion !== null || question.options.length > 5); + const multipleActionId = multipleQuestion ? createChatQuestionOptionActionToken() : null; + const presentation = chatInteractionPresentation(interaction, { compactChoices: Boolean(inlineSelection || checklist || suggestedOptions.length > 1), nativeCustomAnswer: Boolean(customQuestion) }); + const requiresBoard = endpoint.provider === "slack" && slackInteractionRequiresBoard(presentation.body); + if (requiresBoard) { + connectionDecline = null; + suggestions = null; + checklist = null; + } + const formInteraction = chatInteractionForm(interaction, endpoint.provider); const formDraft = - interaction.kind === "ask_user_questions" && + !requiresBoard && (!inlineSelection || customQuestion) && formInteraction && (endpoint.provider === "slack" || endpoint.provider === "discord" || endpoint.provider === "microsoft-teams") && endpoint.capabilities.actions === true && endpoint.capabilities.modals === true ? createChatQuestionFormDraft( - interaction, - endpoint.provider === "discord" - ? { nativeProvider: "discord" } + formInteraction, + (endpoint.provider === "discord" || endpoint.provider === "slack") + ? { nativeProvider: endpoint.provider } : {}, ) : null; const supportsCallbacks = - endpoint.provider !== "imessage-photon" && - formDraft === null && + !requiresBoard && endpoint.provider !== "imessage-photon" && + (formDraft === null || customQuestion !== null) && question !== null && endpoint.capabilities.actions === true; const questionActionTokens = supportsCallbacks @@ -318,11 +345,11 @@ export async function enqueueIssueInteractionChatPublications( })) : []; const confirmation = - endpoint.provider === "telegram" && endpoint.capabilities.actions === true - ? nativeTelegramConfirmation(interaction) + !requiresBoard && (endpoint.provider === "telegram" || endpoint.provider === "slack") && endpoint.capabilities.actions === true + ? nativeChatConfirmation(interaction) ?? checklist : null; - const confirmationActionTokens = confirmation - ? (["accept", "reject"] as const).map((decision) => ({ + const confirmationActionTokens = confirmation || suggestions || connectionDecline + ? (connectionDecline ? ["reject"] as const : ["accept", "reject"] as const).map((decision) => ({ actionId: createChatConfirmationActionToken(), decision, })) @@ -339,31 +366,32 @@ export async function enqueueIssueInteractionChatPublications( } const actions: SafeExternalChatCardAction[] = formDraft ? [ + ...(customQuestion && !inlineSelection ? questionActionTokens.map(({ actionId, option }) => ({ type: "callback" as const, actionId, label: option.label })) : []), { type: "callback" as const, actionId: formDraft.openActionId, - label: "Respond", - style: "primary" as const, + label: customQuestion ? "Other…" : interaction.kind === "request_item_verdicts" ? "Review decisions" : "Respond", + style: customQuestion ? "default" as const : "primary" as const, }, ] : supportsCallbacks - ? questionActionTokens.map(({ actionId, option }) => ({ + ? (inlineSelection ? [] : questionActionTokens).map(({ actionId, option }) => ({ type: "callback" as const, actionId, label: option.label, })) - : confirmation - ? confirmationActionTokens.map(({ actionId, decision }) => ({ + : confirmation || suggestions || connectionDecline + ? confirmationActionTokens.filter(item => !(checklist || suggestedOptions.length > 1) || item.decision !== "accept").map(({ actionId, decision }) => ({ type: "callback" as const, actionId, label: decision === "accept" - ? (confirmation.payload.acceptLabel ?? "Accept") - : (confirmation.payload.rejectLabel ?? "Reject"), + ? (suggestions ? "Create task" : confirmation!.payload.acceptLabel ?? "Accept") + : (connectionDecline ? "Not now" : suggestions ? "Dismiss" : confirmation!.payload.rejectLabel ?? "Reject"), style: decision === "accept" ? ("primary" as const) - : ("danger" as const), + : (connectionDecline || suggestions ? "default" as const : "danger" as const), })) : taskUrl ? [ @@ -374,10 +402,9 @@ export async function enqueueIssueInteractionChatPublications( }, ] : []; - const text = - interaction.kind === "ask_user_questions" - ? textForQuestionInteraction(interaction, taskUrl) - : genericInteractionText(taskUrl); + if (connectionDecline && taskUrl) actions.unshift({ type: "link", label: "Review connection", url: taskUrl }); + if (suggestions && taskUrl) actions.push({ type: "link", label: "Revise in Paperclip", url: taskUrl }); + const text = [presentation.title, presentation.body, taskUrl ? `Open the task in Paperclip to respond: ${taskUrl}` : "Open the task in Paperclip to respond."].join("\n\n"); const payload = projectSafeChatPublication({ classification: "external", source: "issue_interaction", @@ -392,27 +419,29 @@ export async function enqueueIssueInteractionChatPublications( : interaction.kind === "request_confirmation" ? "confirmation" : "status", - title: - interaction.kind === "ask_user_questions" - ? (question?.prompt ?? - interaction.payload.title ?? - interaction.title ?? - "Input needed") - : interaction.kind === "request_confirmation" - ? interaction.payload.prompt - : "Response needed in Paperclip", - body: - interaction.kind === "ask_user_questions" - ? [...new Set([ - interaction.summary, - ...(question - ? [question.helpText] - : interaction.payload.questions.flatMap(item => [item.prompt, item.helpText])), - ].filter((value): value is string => Boolean(value?.trim())))].join("\n\n") || undefined - : interaction.kind === "request_confirmation" - ? (interaction.payload.detailsMarkdown ?? undefined) - : "Open the task in Paperclip to review and respond.", + title: interaction.kind === "ask_user_questions" && question ? question.prompt : presentation.title, + body: presentation.body, actions, + ...(suggestions && suggestedOptions.length > 1 ? { selection: { + actionId: confirmationActionTokens.find(item => item.decision === "accept")!.actionId, + label: "Select tasks to create", multiple: true, submitLabel: "Create selected", + options: suggestedOptions.map(({ actionId, option }) => ({ actionId, label: option.label, ...(option.description ? { description: option.description } : {}) })), + } } : {}), + ...(checklist ? { selection: { + actionId: confirmationActionTokens.find(item => item.decision === "accept")!.actionId, + label: "Select checks", multiple: true, submitLabel: checklist.payload.acceptLabel ?? "Save checks", + options: checklistOptions.map(({ actionId, option }) => ({ actionId, label: option.label, + ...(option.description ? { description: option.description } : {}), + selected: checklist.payload.defaultSelectedOptionIds?.includes(option.id) ?? false })), + } } : {}), + ...(inlineSelection && supportsCallbacks ? { selection: { + actionId: multipleActionId ?? `pcs:${interaction.id}`, + label: multipleQuestion ? "Choose one or more" : "Choose an answer", + ...(multipleQuestion ? { multiple: true, submitLabel: "Submit answer" } : {}), + options: questionActionTokens.map(({ actionId, option }) => ({ actionId, + label: option.label + (interaction.kind === "ask_user_questions" && interaction.payload.questionSet?.questions.find(item => item.id === question.id)?.options?.find(item => item.id === option.id)?.recommended ? " (recommended)" : ""), + ...(option.description ? { description: option.description } : {}) })), + } } : {}), }, }, }); @@ -447,6 +476,15 @@ export async function enqueueIssueInteractionChatPublications( publicationId: publication.id, }), ); + } + if (publication && supportsCallbacks && multipleQuestion && multipleActionId) { + await tx.insert(chatActions).values({ + companyId: interaction.companyId, endpointId: endpoint.id, conversationId: conversation.id, + kind: "question_answer", providerActionId: multipleActionId, status: "issued", + payload: { version: 1, publicationId: publication.id, interactionId: interaction.id, questionId: multipleQuestion.id, + selectionOptions: questionActionTokens.map(({ actionId, option }) => ({ value: actionId, optionId: option.id })), + expiresAt: new Date(publication.createdAt.getTime() + CHAT_QUESTION_ACTION_TOKEN_TTL_MS).toISOString() }, + }); } else if (publication && question && questionActionTokens.length > 0) { const expiresAt = new Date( publication.createdAt.getTime() + CHAT_QUESTION_ACTION_TOKEN_TTL_MS, @@ -471,7 +509,7 @@ export async function enqueueIssueInteractionChatPublications( ); } else if ( publication && - confirmation && + (confirmation || suggestions || connectionDecline) && confirmationActionTokens.length > 0 ) { const expiresAt = new Date( @@ -489,6 +527,8 @@ export async function enqueueIssueInteractionChatPublications( publicationId: publication.id, interactionId: interaction.id, decision, + ...(suggestions ? { selectionOptions: suggestedOptions.map(({ actionId, option }) => ({ value: actionId, optionId: option.id })) } : {}), + ...(checklist ? { selectionOptions: checklistOptions.map(({ actionId, option }) => ({ value: actionId, optionId: option.id })) } : {}), expiresAt, }, status: "issued", @@ -625,6 +665,7 @@ export async function enqueueTerminalIssueInteractionChatPublications( const resolutionOutcome = (interaction.result as { outcome?: unknown } | null) ?.outcome; const continuationWakeRequired = + (interaction.kind === "ask_user_questions" || interaction.kind === "request_confirmation" || interaction.kind === "request_item_verdicts") && interaction.status !== "expired" && resolutionOutcome !== "skipped" && !( diff --git a/server/src/services/chat-publication-projection.ts b/server/src/services/chat-publication-projection.ts index eee29362226..c51f0203fe6 100644 --- a/server/src/services/chat-publication-projection.ts +++ b/server/src/services/chat-publication-projection.ts @@ -106,6 +106,7 @@ export interface ChatPublicationProjectionInput { title: string; body?: string | null; actions?: readonly SafeExternalChatCardAction[] | null; + selection?: SafeExternalChatCard["selection"]; }; } | null; } @@ -323,6 +324,24 @@ function projectCard( ); } + const selection = input.card.selection; + if (selection && (typeof selection.actionId !== "string" || !SAFE_IDENTIFIER_RE.test(selection.actionId) || + !Array.isArray(selection.options) || selection.options.length < 1 || selection.options.length > 100 || + selection.options.some(option => !option || typeof option.actionId !== "string" || !SAFE_IDENTIFIER_RE.test(option.actionId)) || + new Set(selection.options.map(option => option.actionId)).size !== selection.options.length)) { + throw new UnsafeChatPublicationError("External chat selection is invalid"); + } + const safeSelection = selection ? { + actionId: selection.actionId, + ...(selection.multiple ? { multiple: true, submitLabel: truncateByCodePoint(projectSafeChatPublicationText(selection.submitLabel ?? "Submit"), 75) } : {}), + label: truncateByCodePoint(projectSafeChatPublicationText(selection.label), 150), + options: selection.options.map(option => ({ + ...(option.selected === true ? { selected: true } : {}), + actionId: option.actionId, + label: truncateByCodePoint(projectSafeChatPublicationText(option.label), 75), + ...(option.description ? { description: truncateByCodePoint(projectSafeChatPublicationText(option.description), 75) } : {}), + })), + } : undefined; const actions: SafeExternalChatCardAction[] = []; for (const action of rawActions) { const label = truncateByCodePoint( @@ -368,6 +387,7 @@ function projectCard( title, ...(body ? { body } : {}), ...(actions.length ? { actions } : {}), + ...(safeSelection ? { selection: safeSelection } : {}), }, }; } diff --git a/server/src/services/chat-question-forms.test.ts b/server/src/services/chat-question-forms.test.ts index d12610b951b..42dd5ae5524 100644 --- a/server/src/services/chat-question-forms.test.ts +++ b/server/src/services/chat-question-forms.test.ts @@ -99,6 +99,57 @@ function interaction( } describe("chat question forms", () => { + it("preserves context, complete help and editable starting text in a native form", () => { + const current = interaction(); + current.summary = "General checks passed; one detail is needed."; + current.payload.questionSet!.description = "The answer determines the migration test."; + current.payload.questionSet!.questions[1]!.initialText = "Editable draft"; + current.payload.questions[1]!.helpText = "Explain the expected behavior. ".repeat(12); + const draft = createChatQuestionFormDraft(current)!; + const payload = parseChatQuestionFormSubmitTokenPayload(chatQuestionFormActionRecords(draft, { + companyId: current.companyId, endpointId: "endpoint", conversationId: "conversation", publicationId: "publication", + })[1]!.payload)!; + const modal = buildChatQuestionFormModal(current, draft.submitActionId, payload)!; + const shown = JSON.stringify(modal); + expect(shown).toContain(current.summary); + expect(shown).toContain(current.payload.questionSet!.description); + expect(shown).toContain(current.payload.questions[1]!.helpText!.trim()); + expect(modal.children.find(child => child.type === "text_input")).toMatchObject({ initialValue: "Editable draft" }); + }); + + it.each([13, 100])("opens a native select for all %i choices", count => { + const current = interaction(); + current.payload.questions = [{ ...current.payload.questions[0]!, options: Array.from({ length: count }, (_, index) => ({ id: `choice-${index}`, label: `Choice ${index}` })) }]; + current.payload.questionSet!.questions = [{ ...current.payload.questionSet!.questions[0]!, options: current.payload.questions[0]!.options.map(({ id, label }) => ({ id, label })) }]; + expect(createChatQuestionFormDraft(current)?.fields[0]).toMatchObject({ kind: "single_select", options: expect.any(Array) }); + }); + + it("makes the original conversation audience explicit before a Slack modal answer", () => { + const current = interaction(); + const draft = createChatQuestionFormDraft(current, { nativeProvider: "slack" })!; + const payload = parseChatQuestionFormSubmitTokenPayload(chatQuestionFormActionRecords(draft, { + companyId: current.companyId, endpointId: "endpoint", conversationId: "conversation", publicationId: "publication", + })[1]!.payload)!; + const modal = buildChatQuestionFormModal(current, draft.submitActionId, payload)!; + expect(modal.children[0]).toMatchObject({ type: "text", content: "Your answers will be shared in this Slack conversation." }); + }); + + it.each([100, 101, 128])("keeps all %i custom-choice options reachable", count => { + const current = interaction(); + const options = Array.from({ length: count }, (_, index) => ({ id: `choice-${index}`, label: `Choice ${index}` })); + current.payload.questions = [{ ...current.payload.questions[0]!, allowOther: true, options: [...options, { id: "other", label: "Other", freeText: true }] }]; + current.payload.questionSet!.questions = [{ ...current.payload.questionSet!.questions[0]!, options, customAnswer: { enabled: true } }]; + const draft = createChatQuestionFormDraft(current, { nativeProvider: "slack" }); + if (count <= 100) expect(draft?.fields[0]).toMatchObject({ kind: "text" }); + else expect(draft).toBeNull(); + }); + + it("keeps an oversized editable starting value in the complete Paperclip form", () => { + const current = interaction(); + current.payload.questionSet!.questions[1]!.initialText = "a".repeat(3001); + expect(createChatQuestionFormDraft(current)).toBeNull(); + }); + it("keeps Discord's 4000-character contract explicit without changing legacy provider limits", () => { const current = interaction(); current.payload.questionSet!.questions[1]!.textValidation = { @@ -157,7 +208,7 @@ describe("chat question forms", () => { ), }, ]; - expect(createChatQuestionFormDraft(current)).toBeNull(); + expect(createChatQuestionFormDraft(current)?.fields).toHaveLength(1); const draft = createChatQuestionFormDraft(current, { nativeProvider: "discord", }); @@ -350,6 +401,12 @@ describe("chat question forms", () => { }, ); + it("keeps a credential-bearing starting draft in Paperclip instead of exposing it to a chat modal", () => { + const current = interaction(); + current.payload.questionSet!.questions[1]!.initialText = "xoxb-123456789012345678901234567890"; + expect(createChatQuestionFormDraft(current)).toBeNull(); + }); + it("issues opaque open, submit, field, and option tokens as durable action rows", () => { const now = new Date("2026-09-05T12:00:00.000Z"); const draft = createChatQuestionFormDraft(interaction(), { now }); @@ -422,6 +479,7 @@ describe("chat question forms", () => { { label: "Production", value: expect.stringMatching(/^pcfo:/) }, ], }, + { type: "text", content: "Describe the user-facing change" }, { type: "text_input", id: draft.fields[1]?.fieldId, @@ -455,6 +513,7 @@ describe("chat question forms", () => { { title: "Production", value: expect.stringMatching(/^pcfo:/) }, ], }, + { type: "TextBlock", text: "Describe the user-facing change" }, { type: "Input.Text", id: draft.fields[1]?.fieldId, diff --git a/server/src/services/chat-question-forms.ts b/server/src/services/chat-question-forms.ts index 715084693f0..d4093072cbe 100644 --- a/server/src/services/chat-question-forms.ts +++ b/server/src/services/chat-question-forms.ts @@ -1,3 +1,4 @@ +import { projectSafeChatPublicationText } from "./chat-publication-projection.js"; import { randomBytes } from "node:crypto"; import { and, eq, inArray } from "drizzle-orm"; import type { Db } from "@paperclipai/db"; @@ -10,7 +11,9 @@ import type { } from "@paperclipai/shared"; import { Modal, + CardText, Select, + RadioSelect, SelectOption, TextInput, type ModalElement, @@ -61,7 +64,7 @@ export type ChatQuestionFormField = ChatQuestionFormTextField | ChatQuestionFormSelectField; export interface ChatQuestionFormDraft { - nativeProvider?: "discord"; + nativeProvider?: "discord" | "slack"; expiresAt: string; fields: ChatQuestionFormField[]; interactionId: string; @@ -78,7 +81,7 @@ export interface ChatQuestionFormOpenTokenPayload { } export interface ChatQuestionFormSubmitTokenPayload { - nativeProvider?: "discord"; + nativeProvider?: "discord" | "slack"; expiresAt: string; fields: ChatQuestionFormField[]; formActionId: string; @@ -159,10 +162,9 @@ function opaqueToken(prefix: string): string { } function boundedLabel(value: string, maximum: number): string { - return value - .replace(/[\u0000-\u001f\u007f]/g, " ") - .trim() - .slice(0, maximum); + return Array.from(value.replace(/[\u0000-\u001f\u007f]/g, " ").trim()) + .slice(0, maximum) + .join(""); } function isRecord(value: unknown): value is Record { @@ -214,14 +216,21 @@ function questionSetQuestion( function formKind( interaction: AskUserQuestionsInteraction, question: AskUserQuestionsQuestion, + nativeProvider?: "discord" | "slack", ): "single_select" | "text" | null { const source = questionSetQuestion(interaction, question.id); if (source) { + if (nativeProvider === "slack" && source.answerMode === "single_select" && source.customAnswer && interaction.payload.questions.length === 1) { + // The text modal is the Other action beside native choices. Without all + // listed choices, keep the complete response path in Paperclip. + const choiceCount = question.options.filter(option => !option.freeText).length; + return choiceCount > 0 && choiceCount <= MAX_NATIVE_SELECT_OPTIONS ? "text" : null; + } if (source.answerMode === "text") { - // Regex evaluation supplied by an agent can be computationally unsafe. - // Keep those uncommon forms in Paperclip, whose canonical validator owns - // that policy, instead of evaluating a pattern inside a webhook callback. - return source.textValidation?.pattern ? null : "text"; + // Slack can show canonical validation errors without closing the modal. + // The canonical resolver evaluates patterns in its bounded worker, never + // synchronously on the webhook event loop. + return source.textValidation?.pattern && nativeProvider !== "slack" ? null : "text"; } return source.answerMode === "single_select" && !source.customAnswer ? "single_select" @@ -255,7 +264,7 @@ function formKind( */ export function createChatQuestionFormDraft( interaction: AskUserQuestionsInteraction, - options: { now?: Date; nativeProvider?: "discord" } = {}, + options: { now?: Date; nativeProvider?: "discord" | "slack" } = {}, ): ChatQuestionFormDraft | null { const maxTextLength = options.nativeProvider === "discord" ? 4000 : MAX_NATIVE_TEXT_LENGTH; @@ -270,14 +279,13 @@ export function createChatQuestionFormDraft( const classified = interaction.payload.questions.map((question) => ({ question, - kind: formKind(interaction, question), + kind: formKind(interaction, question, options.nativeProvider), })); if (classified.some(({ kind }) => kind === null)) return null; if ( classified.length === 1 && classified[0]?.kind === "single_select" && - (options.nativeProvider !== "discord" || - classified[0].question.options.length <= 12) + classified[0].question.options.length <= 12 ) { return null; } @@ -311,7 +319,8 @@ export function createChatQuestionFormDraft( const validation = source?.textValidation; const canonicalMax = validation?.maxLength ?? 100_000; const canonicalMin = validation?.minLength ?? 0; - if (options.nativeProvider === "discord" && canonicalMax < 1) return null; + if (canonicalMax < 1 || (source?.initialText?.length ?? 0) > Math.min(canonicalMax, maxTextLength)) return null; + if (source?.initialText?.trim() && projectSafeChatPublicationText(source.initialText) !== source.initialText.trim()) return null; if (canonicalMin > maxTextLength) return null; fields.push({ fieldId, @@ -331,7 +340,7 @@ export function createChatQuestionFormDraft( } const now = options.now ?? new Date(); - return { + const draft: ChatQuestionFormDraft = { ...(options.nativeProvider ? { nativeProvider: options.nativeProvider } : {}), @@ -343,6 +352,11 @@ export function createChatQuestionFormDraft( openActionId: opaqueToken(OPEN_ACTION_PREFIX), submitActionId: opaqueToken(SUBMIT_ACTION_PREFIX), }; + return buildChatQuestionFormModal(interaction, draft.submitActionId, { + version: 1, interactionId: interaction.id, publicationId: "preview", + formActionId: draft.submitActionId, expiresAt: draft.expiresAt, + fields: draft.fields, ...(draft.nativeProvider ? { nativeProvider: draft.nativeProvider } : {}), + }) ? draft : null; } /** Values ready for one durable chat_actions insert. */ @@ -475,7 +489,7 @@ export function parseChatQuestionFormSubmitTokenPayload( !isRecord(value) || value.version !== 1 || (value.nativeProvider !== undefined && - value.nativeProvider !== "discord") || + value.nativeProvider !== "discord" && value.nativeProvider !== "slack") || typeof value.publicationId !== "string" || typeof value.interactionId !== "string" || !isChatQuestionFormSubmitActionId(value.formActionId) || @@ -508,8 +522,8 @@ export function parseChatQuestionFormSubmitTokenPayload( return null; } return { - ...(value.nativeProvider === "discord" - ? { nativeProvider: "discord" as const } + ...((value.nativeProvider === "discord" || value.nativeProvider === "slack") + ? { nativeProvider: value.nativeProvider } : {}), version: 1, publicationId: value.publicationId, @@ -540,28 +554,49 @@ export function buildChatQuestionFormModal( return null; } - const children = []; + const title = interaction.payload.title ?? interaction.title ?? "Input needed"; + const titleLimit = payload.nativeProvider === "discord" ? 45 : 24; + const modalTitle = Array.from(title).length <= titleLimit ? boundedLabel(title, titleLimit) + : payload.fields.length === 1 ? "Answer question" : "Answer questions"; + const children: ModalElement["children"] = []; + const appendContext = (text: string | null | undefined) => { + if (payload.nativeProvider === "discord" || !text?.trim()) return; + const points = Array.from(projectSafeChatPublicationText(text)); + for (let offset = 0; offset < points.length; offset += 2000) { + children.push(CardText(points.slice(offset, offset + 2000).join(""))); + } + }; + if (payload.nativeProvider === "slack") appendContext("Your answers will be shared in this Slack conversation."); + if (modalTitle !== title && !interaction.payload.questions.some(question => question.prompt === title)) appendContext(title); + for (const text of new Set([interaction.summary, interaction.payload.questionSet?.description])) appendContext(text); for (const field of payload.fields) { const question = canonicalQuestion(interaction, field.questionId); - if (!question || formKind(interaction, question) !== field.kind) + if (!question || formKind(interaction, question, payload.nativeProvider) !== field.kind) return null; const label = boundedLabel( question.prompt, payload.nativeProvider === "discord" ? 45 : 2_000, ) || "Response"; + const source = questionSetQuestion(interaction, question.id); + if (source?.header && source.header !== question.helpText) appendContext(source.header); + if (question.prompt !== label) appendContext(question.prompt); + appendContext(question.helpText); if (field.kind === "text") { + if ((source?.initialText?.length ?? 0) > field.maxLength) return null; + if (source?.initialText?.trim() && projectSafeChatPublicationText(source.initialText) !== source.initialText.trim()) return null; children.push( TextInput({ + ...(source?.initialText !== undefined ? { initialValue: source.initialText } : {}), id: field.fieldId, - label, + label: source?.customAnswer?.label ?? label, maxLength: field.maxLength, multiline: field.inputType === "text", optional: !field.required, - ...(question.helpText + ...((source?.customAnswer?.placeholder ?? question.helpText) ? { placeholder: boundedLabel( - question.helpText, + source?.customAnswer?.placeholder ?? question.helpText!, payload.nativeProvider === "discord" ? 100 : 150, ), } @@ -570,6 +605,12 @@ export function buildChatQuestionFormModal( ); continue; } + for (const option of question.options) { + const recommended = source?.options?.find(item => item.id === option.id)?.recommended; + if (option.label !== boundedLabel(option.label, 75) || (option.description?.length ?? 0) > 75 || recommended) { + appendContext(`${option.label}${recommended ? " (recommended)" : ""}${option.description ? `: ${option.description}` : ""}`); + } + } const mappedOptions = field.options.map((mapping) => { const option = question.options.find( (candidate) => @@ -587,7 +628,7 @@ export function buildChatQuestionFormModal( }); if (mappedOptions.some((option) => option === null)) return null; children.push( - Select({ + (payload.nativeProvider === "slack" && mappedOptions.length <= 5 ? RadioSelect : Select)({ id: field.fieldId, label, optional: !field.required, @@ -597,13 +638,10 @@ export function buildChatQuestionFormModal( ); } + if (payload.nativeProvider !== "discord" && children.length > 100) return null; return Modal({ callbackId, - title: - boundedLabel( - interaction.payload.title ?? interaction.title ?? "Input needed", - payload.nativeProvider === "discord" ? 45 : 24, - ) || "Input needed", + title: modalTitle || "Input needed", submitLabel: boundedLabel(interaction.payload.submitLabel ?? "Submit", 24) || "Submit", closeLabel: "Cancel", @@ -661,7 +699,7 @@ export function validateChatQuestionFormSubmission(args: { const fieldErrors: Record = {}; for (const field of payload.fields) { const question = canonicalQuestion(interaction, field.questionId); - if (!question || formKind(interaction, question) !== field.kind) { + if (!question || formKind(interaction, question, payload.nativeProvider) !== field.kind) { return invalid("stale_interaction"); } const submitted = values[field.fieldId] ?? ""; diff --git a/server/src/services/chat-run-publications.ts b/server/src/services/chat-run-publications.ts index 74eb2ca3901..25ac411e74b 100644 --- a/server/src/services/chat-run-publications.ts +++ b/server/src/services/chat-run-publications.ts @@ -716,12 +716,17 @@ export async function enqueueChatRunMilestones( and continuation_wake.run_id = ${heartbeatRuns.id} and continuation_wake.agent_id = ${heartbeatRuns.agentId} and continuation_wake.status <> 'skipped' - and continuation_wake.idempotency_key = case + and ( + (interaction.kind = 'request_item_verdicts' + and continuation_wake.payload->>'interactionId' = interaction.id::text + and continuation_wake.payload->>'sourceRunId' = interaction.source_run_id::text + and continuation_wake.reason = 'issue_commented') + or continuation_wake.idempotency_key = case when interaction.kind = 'ask_user_questions' and interaction.status = 'answered' then 'question-response:' || interaction.id::text else 'interaction:' || interaction.id::text || ':' || interaction.status - end + end) where interaction.company_id = ${heartbeatRuns.companyId} and interaction.issue_id::text = ${issueIdFromContext} and interaction.id::text = ${heartbeatRuns.contextSnapshot} ->> 'interactionId' @@ -732,11 +737,29 @@ export async function enqueueChatRunMilestones( and interaction.status in ('answered', 'cancelled') ) or ( - interaction.kind = 'request_confirmation' + interaction.kind in ('request_confirmation', 'request_checkbox_confirmation', 'suggest_tasks') and interaction.status in ('accepted', 'rejected', 'cancelled') ) + or ( + interaction.kind = 'request_item_verdicts' + and interaction.status in ('pending', 'answered', 'cancelled') + ) ) )`; + const hasConnectionContinuation = sql`( + ${heartbeatRuns.contextSnapshot}->>'source' = 'connection_intent.resolved' and exists ( + select 1 from connection_intent_deliveries delivery + inner join issue_thread_interactions interaction on interaction.id = delivery.interaction_id + and interaction.company_id = delivery.company_id + inner join agent_wakeup_requests wake on wake.company_id = delivery.company_id + and wake.run_id = ${heartbeatRuns.id} and wake.agent_id = ${heartbeatRuns.agentId} + and wake.idempotency_key = 'connection-intent:' || interaction.id::text || ':' || interaction.status + and wake.status <> 'skipped' + where delivery.company_id = ${heartbeatRuns.companyId} + and interaction.issue_id::text = ${issueIdFromContext} + and interaction.id::text = ${heartbeatRuns.contextSnapshot}->>'interactionId' + ) + )`; const hasMonitorContinuation = sql`( ${heartbeatRuns.contextSnapshot}->>'source' = 'issue.monitor' and exists ( select 1 from agent_wakeup_requests monitor_wake @@ -839,6 +862,7 @@ export async function enqueueChatRunMilestones( "issue.interaction.respond", "issue.interaction.accept", "issue.interaction.reject", + "issue.interaction.verdicts", "issue.interaction.cancel", "issue.interaction.withdraw", "external_chat.interaction.resolve", @@ -847,6 +871,7 @@ export async function enqueueChatRunMilestones( hasDirectInteractionContinuation, ), hasQuestionContinuationTarget, + hasConnectionContinuation, hasMonitorContinuation, hasTaskContinuation, ), @@ -897,6 +922,7 @@ export async function enqueueChatRunMilestones( ), ), or( + hasConnectionContinuation, hasMonitorContinuation, hasTaskContinuation, sql`exists ( diff --git a/server/src/services/chat-sdk-runtime.ts b/server/src/services/chat-sdk-runtime.ts index 1adb53bf2dd..cffdd09f5e4 100644 --- a/server/src/services/chat-sdk-runtime.ts +++ b/server/src/services/chat-sdk-runtime.ts @@ -1,3 +1,4 @@ +import { isPassiveSlackAction, normalizeSlackSelectionAction, slackSelectionValues } from "./chat-channels/slack/cards.js"; import { PhotonChatAdapter, parsePhotonThreadId } from "./photon/adapter.js"; import { PhotonLineAuthentication } from "./photon/cloud.js"; import { PhotonState } from "./photon/state.js"; @@ -407,6 +408,8 @@ export interface ChatSdkMessageUpdatedCallbackEvent { export interface ChatSdkCallbackEvent { endpointId: string; event: T; + /** Provider-normalized selected opaque values from an explicit message submit. */ + selectionValues?: string[]; provider: ChatSdkProvider; /** Runtime-assigned ingress context; never read from provider payloads. */ transport?: "discord_gateway"; @@ -1917,7 +1920,10 @@ function registerCallbacks( }); } if (callbacks.onAction) { - chat.onAction(async (event) => { + chat.onAction(async (sourceEvent) => { + if (provider === "slack" && isPassiveSlackAction(sourceEvent)) return; + const event = provider === "slack" ? normalizeSlackSelectionAction(sourceEvent) : sourceEvent; + const selectionValues = provider === "slack" ? slackSelectionValues(sourceEvent) : undefined; const transport = actionTransport(); if (!acceptsProviderScope(event.raw)) { if (transport === "discord_gateway") { @@ -1937,6 +1943,7 @@ function registerCallbacks( provider, event, ...(transport ? { transport } : {}), + ...(selectionValues ? { selectionValues } : {}), ...(telegramCallback(event.raw) ? { telegramCallback: telegramCallback(event.raw) } : {}), diff --git a/server/src/services/chat-slack-native-modal.test.ts b/server/src/services/chat-slack-native-modal.test.ts index 80605c5dbce..b672d0001ef 100644 --- a/server/src/services/chat-slack-native-modal.test.ts +++ b/server/src/services/chat-slack-native-modal.test.ts @@ -31,7 +31,7 @@ const botUserId = "U-PAPERCLIP-BOT"; type SubmitCallback = NonNullable; type SubmitEvent = Parameters[0]; -function formFixture() { +function formFixture(configure?: (interaction: AskUserQuestionsInteraction) => void) { const interaction: AskUserQuestionsInteraction = { id: "11111111-1111-4111-8111-111111111111", companyId: "22222222-2222-4222-8222-222222222222", @@ -105,6 +105,7 @@ function formFixture() { }, }, }; + configure?.(interaction); const draft = createChatQuestionFormDraft(interaction)!; const payload = parseChatQuestionFormSubmitTokenPayload( chatQuestionFormActionRecords(draft, { @@ -182,10 +183,10 @@ interface SlackView { function submission(view: SlackView) { const select = view.blocks.find( - (block) => block.element.type === "static_select", + (block) => block.element?.type === "static_select", )!; const text = view.blocks.find( - (block) => block.element.type === "plain_text_input", + (block) => block.element?.type === "plain_text_input", )!; const selected = select.element.options!.find( (option) => option.text.text === "Production", @@ -239,13 +240,14 @@ describe("Slack native multi-question modal adapter-to-runtime boundary", () => async function harness( options: { + configureForm?: (interaction: AskUserQuestionsInteraction) => void; onSubmit?: SubmitCallback; persistence?: ChatSdkStatePersistence; endpointId?: string; companyId?: string; } = {}, ) { - const form = formFixture(); + const form = formFixture(options.configureForm); const views: SlackView[] = []; const openTriggers: Array = []; const apiMethods: string[] = []; @@ -386,6 +388,31 @@ describe("Slack native multi-question modal adapter-to-runtime boundary", () => }; } + it("sends the full prompt, context and editable draft through the real Slack adapter", async () => { + const test = await harness({ configureForm(current) { + current.summary = "The migration checks passed; one detail remains."; + current.payload.questionSet!.description = "Tell us which agent failed."; + current.payload.questionSet!.questions[1]!.header = "Reproduction details"; + current.payload.questions[0]!.options[0]!.description = "Complete option explanation. ".repeat(8); + current.payload.questionSet!.questions[0]!.options![0]!.recommended = true; + current.payload.questions[1]!.helpText = "Send the agent link and error text, if available. ".repeat(8); + current.payload.questionSet!.questions[1]!.initialText = "Editable starting answer"; + } }); + const view = await test.open(); + const wire = JSON.stringify(view); + expect(wire).toContain(test.form.interaction.summary); + expect(wire).toContain(test.form.interaction.payload.questionSet!.description); + expect(wire).toContain(test.form.interaction.payload.questions[1]!.helpText!.trim()); + expect(wire).toContain("Reproduction details"); + expect(wire).toContain(test.form.interaction.payload.questions[0]!.options[0]!.description!.trim()); + expect(wire).toContain("recommended"); + const text = view.blocks.find(block => block.element?.type === "plain_text_input"); + expect(text?.element).toMatchObject({ initial_value: "Editable starting answer" }); + const response = await test.runtime.handleWebhook(signedRequest(submission(view))); + expect(await response.json()).toEqual({ response_action: "clear" }); + expect(test.validations).toEqual([{ ok: true, answers: expect.any(Array) }]); + }); + it("round-trips the actual Paperclip modal, opaque metadata and Slack state into canonical answers", async () => { const test = await harness(); const view = await test.open(); @@ -463,7 +490,7 @@ describe("Slack native multi-question modal adapter-to-runtime boundary", () => const view = await test.open(); const submitted = submission(view); const field = view.blocks.find( - (block) => block.element.type === "plain_text_input", + (block) => block.element?.type === "plain_text_input", )!; submitted.view.state.values[field.block_id]![field.element.action_id] = { type: "plain_text_input", @@ -518,7 +545,7 @@ describe("Slack native multi-question modal adapter-to-runtime boundary", () => }; if (mode === "canonical_option") { const field = view.blocks.find( - (block) => block.element.type === "static_select", + (block) => block.element?.type === "static_select", )!; submitted.view.state.values[field.block_id]![field.element.action_id] = { diff --git a/server/src/services/connection-intents.ts b/server/src/services/connection-intents.ts index 442bf0155da..a6d07331c0c 100644 --- a/server/src/services/connection-intents.ts +++ b/server/src/services/connection-intents.ts @@ -53,7 +53,7 @@ import { import { instanceSettingsService } from "./instance-settings.js"; import { conflict, forbidden, notFound, unprocessable } from "../errors.js"; import type { RuntimeToolsTokenClaims } from "../runtime-tools-token.js"; -import { issueThreadInteractionService } from "./issue-thread-interactions.js"; +import { issueThreadInteractionService, type InteractionResolutionMutationOptions } from "./issue-thread-interactions.js"; import { lockToolConnectionRuntimeInputs, toolAccessService } from "./tool-access.js"; import { toolAccessPolicyService } from "./tool-access-policy.js"; import { captureRunIdentity } from "./run-identity.js"; @@ -1180,7 +1180,7 @@ export function connectionIntentService(db: Db) { interactionId: string, userId: string, reason?: string, - options: { bypassCurrentMembershipCheck?: boolean } = {}, + options: { bypassCurrentMembershipCheck?: boolean; mutationOptions?: InteractionResolutionMutationOptions } = {}, ) { const loaded = await loadIntent(interactionId); if (loaded.interaction.addresseeUserId !== userId) throw forbidden("Only the addressed user can decline this request"); @@ -1194,6 +1194,7 @@ export function connectionIntentService(db: Db) { interactionId, { version: 1, outcome: "declined", reason: reason?.trim() || null }, { userId }, + options.mutationOptions, ); } diff --git a/server/src/services/heartbeat-run-summary.ts b/server/src/services/heartbeat-run-summary.ts index eec17111280..25e0de11276 100644 --- a/server/src/services/heartbeat-run-summary.ts +++ b/server/src/services/heartbeat-run-summary.ts @@ -194,7 +194,8 @@ function record(value: unknown): Record { function requiresChatOriginProof(source: string): boolean { return source === "tool_action_review" || source === "issue.monitor" || source === "native_status_decision" || - source.startsWith("issue.comment") || source === "issue.update"; + source.startsWith("issue.comment") || source.startsWith("issue.interaction.") || + source === "external_chat.interaction.resolve" || source === "connection_intent.resolved" || source === "issue.update"; } export function isExternalChatPresentationContext( diff --git a/server/src/services/issue-thread-interactions.ts b/server/src/services/issue-thread-interactions.ts index 4e25c890615..9a4ed571a5b 100644 --- a/server/src/services/issue-thread-interactions.ts +++ b/server/src/services/issue-thread-interactions.ts @@ -197,7 +197,7 @@ export type IssueThreadInteractionServiceOptions = { }; type DbTransaction = Parameters[0]>[0]; -type InteractionResolutionMutationOptions = { +export type InteractionResolutionMutationOptions = { /** Confirmation accept/reject nested in an outer transaction must defer these * effects and flush them with the root database only after its commit. */ deferConfirmationCommitEffects?: (effect: (committedDb: Db) => Promise) => void; @@ -2634,7 +2634,9 @@ export function issueThreadInteractionService( }, ); } - return hydrateInteraction(existing) as ConnectionIntentInteraction; + const interaction = hydrateInteraction(existing) as ConnectionIntentInteraction; + await enqueueIssueInteractionChatPublications(db, interaction); + return interaction; } let inserted = false; @@ -2662,7 +2664,10 @@ export function issueThreadInteractionService( )); const reusable = pending.find((candidate) => connectionIntentPayloadSchema.parse(candidate.payload).serviceSlug === payload.serviceSlug && connectionIntentPayloadSchema.parse(candidate.payload).purpose === payload.purpose && isDeepStrictEqual(connectionIntentPayloadSchema.parse(candidate.payload).accessRequest, payload.accessRequest)); - if (reusable) return reusable; + if (reusable) { + await enqueueIssueInteractionChatPublications(tx as unknown as Db, hydrateInteraction(reusable)); + return reusable; + } const [sourceRun] = await tx.select({ context: heartbeatRuns.contextSnapshot }).from(heartbeatRuns) .where(and(eq(heartbeatRuns.id, input.sourceRunId), eq(heartbeatRuns.companyId, issue.companyId))); @@ -2723,7 +2728,7 @@ export function issueThreadInteractionService( await tx .delete(toolOauthStates) .where(inArray(toolOauthStates.interactionId, supersededIds)); - await tx + const superseded = await tx .update(issueThreadInteractions) .set({ status: "expired", @@ -2735,10 +2740,15 @@ export function issueThreadInteractionService( resolvedAt: now(), updatedAt: now(), }) - .where(inArray(issueThreadInteractions.id, supersededIds)); + .where(inArray(issueThreadInteractions.id, supersededIds)) + .returning(); + for (const previous of superseded) { + await enqueueTerminalIssueInteractionChatPublications(tx as unknown as Db, hydrateInteraction(previous)); + } } await touchIssue(tx, issue.id); inserted = true; + await enqueueIssueInteractionChatPublications(tx as unknown as Db, hydrateInteraction(row)); await notifyDeliveryWork(tx, DELIVERY_QUEUES.connection); return row; }); @@ -2790,6 +2800,7 @@ export function issueThreadInteractionService( ? NonNullable : never, actor: InteractionActor, + mutationOptions: InteractionResolutionMutationOptions = {}, ) => { const result = connectionIntentResultSchema.parse(resultInput); const current = await getPendingInteractionForResolution({ @@ -2812,6 +2823,7 @@ export function issueThreadInteractionService( : "expired"; const resolvedAt = now(); const updated = await db.transaction(async (tx) => { + await mutationOptions.beforeResolveInTransaction?.(tx); const [row] = await tx .update(issueThreadInteractions) .set({ @@ -2835,6 +2847,8 @@ export function issueThreadInteractionService( await notifyDeliveryWork(tx, DELIVERY_QUEUES.connection); await tx.insert(connectionIntentDeliveries).values({ interactionId, companyId: issue.companyId }).onConflictDoNothing(); } + await mutationOptions.afterResolveInTransaction?.(tx, hydrateInteraction(row)); + await enqueueTerminalIssueInteractionChatPublications(tx as unknown as Db, hydrateInteraction(row)); return row; }); if (!updated) throw interactionAlreadyResolvedError(); @@ -3867,6 +3881,7 @@ export function issueThreadInteractionService( interactionId, data, actor, + mutationOptions, ); case "request_confirmation": { await assertIssueWorkspaceFinalizedForAccept({ @@ -3924,6 +3939,7 @@ export function issueThreadInteractionService( interactionId: string, input: AcceptIssueThreadInteraction, actor: InteractionActor, + mutationOptions: InteractionResolutionMutationOptions = {}, ) => { assertIssueOpenForInteractionResolution(issue); const current = await db @@ -4007,6 +4023,7 @@ export function issueThreadInteractionService( const createdWakeTargets: IssueWakeTarget[] = []; await db.transaction(async (tx) => { + await mutationOptions.beforeResolveInTransaction?.(tx); await assertInteractionRunWriteAllowed(tx as unknown as Db, issue, actor); const resolvedAt = new Date(); const [claimed] = await tx @@ -4097,6 +4114,8 @@ export function issueThreadInteractionService( .returning(); await touchIssue(tx, issue.id); + await mutationOptions.afterResolveInTransaction?.(tx, hydrateInteraction(updated)); + await enqueueTerminalIssueInteractionChatPublications(tx as unknown as Db, hydrateInteraction(updated)); current.status = updated.status; current.result = updated.result; current.resolvedByAgentId = updated.resolvedByAgentId; @@ -4136,6 +4155,7 @@ export function issueThreadInteractionService( data, actor, current, + mutationOptions, ); case "request_confirmation": case "request_checkbox_confirmation": @@ -4158,6 +4178,7 @@ export function issueThreadInteractionService( interactionId: string, input: SubmitIssueThreadInteractionVerdicts, actor: InteractionActor, + mutationOptions: InteractionResolutionMutationOptions = {}, ): Promise<{ interaction: IssueThreadInteraction; newlyResolvedItemIds: string[]; @@ -4165,6 +4186,7 @@ export function issueThreadInteractionService( assertIssueOpenForInteractionResolution(issue); const data = submitIssueThreadInteractionVerdictsSchema.parse(input); const submission = await db.transaction(async (tx) => { + await mutationOptions.beforeResolveInTransaction?.(tx); await assertInteractionRunWriteAllowed(tx as unknown as Db, issue, actor); const current = await tx .select() @@ -4268,6 +4290,8 @@ export function issueThreadInteractionService( } await touchIssue(tx, issue.id); + await mutationOptions.afterResolveInTransaction?.(tx, hydrateInteraction(updated)); + if (complete) await enqueueTerminalIssueInteractionChatPublications(tx as unknown as Db, hydrateInteraction(updated)); return { interaction: hydrateInteraction(updated), newlyResolvedItemIds, @@ -4288,6 +4312,7 @@ export function issueThreadInteractionService( input: RejectIssueThreadInteraction, actor: InteractionActor, current: IssueThreadInteractionRow, + mutationOptions: InteractionResolutionMutationOptions = {}, ) => { assertIssueOpenForInteractionResolution(issue); if ( @@ -4304,8 +4329,9 @@ export function issueThreadInteractionService( } const [updated] = await db.transaction(async (tx) => { + await mutationOptions.beforeResolveInTransaction?.(tx); await assertInteractionRunWriteAllowed(tx as unknown as Db, issue, actor); - return tx.update(issueThreadInteractions) + const rows = await tx.update(issueThreadInteractions) .set({ status: "rejected", result: { @@ -4325,6 +4351,9 @@ export function issueThreadInteractionService( ), ) .returning(); + if (rows[0]) await mutationOptions.afterResolveInTransaction?.(tx, hydrateInteraction(rows[0])); + if (rows[0]) await enqueueTerminalIssueInteractionChatPublications(tx as unknown as Db, hydrateInteraction(rows[0])); + return rows; }); if (!updated) { @@ -4597,7 +4626,8 @@ export function issueThreadInteractionService( } for (const row of itemVerdictRows) { - const [updated] = await db + const updated = await db.transaction(async tx => { + const [retired] = await tx .update(issueThreadInteractions) .set({ status: "expired", @@ -4614,6 +4644,9 @@ export function issueThreadInteractionService( ), ) .returning(); + if (retired) await enqueueTerminalIssueInteractionChatPublications(tx as unknown as Db, hydrateInteraction(retired)); + return retired; + }); if (updated) expired.push(hydrateInteraction(updated)); } @@ -4783,7 +4816,10 @@ export function issueThreadInteractionService( eq(issueThreadInteractions.status, "pending"), )) .returning(); - if (updated) expired.push(updated); + if (updated) { + await enqueueTerminalIssueInteractionChatPublications(db, hydrateInteraction(updated)); + expired.push(updated); + } } if (expired.length) await db.delete(toolOauthStates).where(inArray(toolOauthStates.interactionId, expired.map((item) => item.id))); return expired; diff --git a/server/src/services/issues.ts b/server/src/services/issues.ts index b1cbdaa2fdb..7f3f78e9936 100644 --- a/server/src/services/issues.ts +++ b/server/src/services/issues.ts @@ -1,3 +1,4 @@ +import { resolveConnectionIntentContinuationSource, resolveItemVerdictContinuationWake } from "./chat-interaction-continuation.js"; import { insertIssueComment } from "./issue-comment-writes.js"; import { measureRunTransaction } from "./execution-transaction-timing.js"; import { readNativeMonitorSource } from "./native-runtime/native-monitor-delivery.js"; @@ -1395,6 +1396,22 @@ export async function resolveChatOriginPublicationBindings( contextSnapshot = snapshot; break; } + if (contextSource === "connection_intent.resolved") { + const interactionId = readStringFromRecord(snapshot, "interactionId"); + if (!interactionId || !isUuidLike(interactionId)) return []; + const sourceRunId = await resolveConnectionIntentContinuationSource(dbOrTx, { + companyId, issueId, interactionId, runId: originRunId, agentId: lineageAgentId!, + }); + if (!sourceRunId) return []; + // An automation can request access on an already-linked Slack task. + // Its validated receipt and published prompt preserve that conversation. + const promptBindings = await resolvePublishedInteractionPromptBindings( + dbOrTx, companyId, issueId, interactionId, lineageAgentId!, + ); + if (promptBindings.length > 0) return promptBindings; + originRunId = sourceRunId; + continue; + } if (contextSource === "issue.monitor") { const sourceRunId = await readNativeMonitorSource(dbOrTx, { companyId, issueId, runId: originRunId }); if (!sourceRunId) return []; @@ -1411,6 +1428,7 @@ export async function resolveChatOriginPublicationBindings( contextSource !== "issue.interaction.respond" && contextSource !== "issue.interaction.accept" && contextSource !== "issue.interaction.reject" && + contextSource !== "issue.interaction.verdicts" && contextSource !== "issue.interaction.cancel" && contextSource !== "issue.interaction.withdraw" && contextSource !== "external_chat.interaction.resolve" @@ -1430,6 +1448,7 @@ export async function resolveChatOriginPublicationBindings( .select({ kind: issueThreadInteractions.kind, status: issueThreadInteractions.status, + result: issueThreadInteractions.result, sourceRunId: issueThreadInteractions.sourceRunId, }) .from(issueThreadInteractions) @@ -1446,6 +1465,7 @@ export async function resolveChatOriginPublicationBindings( rows: Array<{ kind: string; status: string; + result: unknown; sourceRunId: string | null; }>, ) => rows[0] ?? null, @@ -1455,13 +1475,16 @@ export async function resolveChatOriginPublicationBindings( interaction.kind === "ask_user_questions" && interaction.status === "answered"; const isResolvedConfirmation = - interaction.kind === "request_confirmation" && + ["request_confirmation", "request_checkbox_confirmation", "suggest_tasks"].includes(interaction.kind) && (interaction.status === "accepted" || interaction.status === "rejected"); const isCancelledSupportedInteraction = interaction.status === "cancelled" && - (interaction.kind === "ask_user_questions" || - interaction.kind === "request_confirmation"); + ["ask_user_questions", "request_confirmation", "request_checkbox_confirmation", "request_item_verdicts", "suggest_tasks"].includes(interaction.kind); + const isItemVerdictResponse = interaction.kind === "request_item_verdicts" && + (interaction.status === "answered" || interaction.status === "pending") && + contextSource === "issue.interaction.verdicts"; if ( + !isItemVerdictResponse && !isAnsweredQuestion && !isResolvedConfirmation && !isCancelledSupportedInteraction @@ -1498,7 +1521,13 @@ export async function resolveChatOriginPublicationBindings( const continuationIdempotencyKey = isAnsweredQuestion ? `question-response:${interactionId}` : `interaction:${interactionId}:${interaction.status}`; - const durableWakeTarget = recordedTarget + const itemVerdictWake = isItemVerdictResponse + ? await resolveItemVerdictContinuationWake(dbOrTx, { + companyId, issueId, interactionId, sourceRunId, runId: originRunId, + agentId: lineageAgentId!, result: interaction.result, + }) + : null; + const durableWakeTarget = isItemVerdictResponse ? itemVerdictWake : recordedTarget ? null : await dbOrTx .select({ id: agentWakeupRequests.id }) diff --git a/server/src/services/native-runtime/external-chat-question-response.ts b/server/src/services/native-runtime/external-chat-question-response.ts index df45788684a..23875f181ec 100644 --- a/server/src/services/native-runtime/external-chat-question-response.ts +++ b/server/src/services/native-runtime/external-chat-question-response.ts @@ -75,6 +75,23 @@ const ids = (value: unknown): string[] => ? value.filter((id): id is string => typeof id === "string") : []; +function completedMultiChoiceMatches(question: Record, answer: Record, payload: Record): boolean { + const selected = ids(payload.selectionValues); + const answered = ids(answer.optionIds); + const mappings = Array.isArray(payload.selectionOptions) ? payload.selectionOptions.map(record) : []; + const options = Array.isArray(question.options) ? question.options.map(record) : []; + if (question.selectionMode !== "multi" || question.allowOther === true || + !Array.isArray(payload.selectionValues) || selected.length !== payload.selectionValues.length || + !Array.isArray(answer.optionIds) || answered.length !== answer.optionIds.length || + new Set(selected).size !== selected.length || new Set(answered).size !== answered.length || + mappings.length !== options.length || new Set(mappings.map(item => item.value)).size !== mappings.length || + new Set(mappings.map(item => item.optionId)).size !== mappings.length || + (question.required !== false && selected.length === 0) || + selected.length !== answered.length || + mappings.some(item => typeof item.value !== "string" || typeof item.optionId !== "string" || !options.some(option => option.id === item.optionId && option.freeText !== true))) return false; + return selected.every((value, index) => mappings.find(item => item.value === value)?.optionId === answered[index]); +} + function completedQuestionFormMatchesInteraction( interaction: AskUserQuestionsInteraction, action: typeof chatActions.$inferSelect, @@ -159,7 +176,7 @@ function completedQuestionFormMatchesInteraction( } /** - * Resolve a durable provider answer or GitHub's authenticated Board fallback, + * Resolve a durable provider answer or an authenticated Board fallback, * never a caller-supplied wake marker. This * is routing/reading authority only: it never checks out a task or resolves a * review. Callers retain their issue/run/actor and current destination checks. @@ -620,8 +637,8 @@ async function resolveQuestionResponseChain( sql`${chatActions.result}->>'interactionId' = ${interaction.id}`, ), ); - // GitHub has no executable question callback. Its published link leads to - // the ordinary authenticated Board answer route, whose pending→answered CAS + // GitHub and Slack forms without native controls use the ordinary + // authenticated Board answer route, whose pending→answered CAS // creates the response delivery above atomically. Do not fabricate a provider // action: bind that distinct receipt to the original linked person instead. const boardQuery = tx @@ -676,7 +693,7 @@ async function resolveQuestionResponseChain( and( eq(chatEndpoints.id, chatPublications.endpointId), eq(chatEndpoints.companyId, chatPublications.companyId), - eq(chatEndpoints.provider, "github"), + eq(chatEndpoints.provider, provider), ), ) .innerJoin( @@ -709,7 +726,12 @@ async function resolveQuestionResponseChain( ), ), ); - const evidenceQuery = provider === "github" ? boardQuery : actionQuery; + // Slack native actions remain authoritative when present. The Board query + // excludes every native answer token, including unfinished ones; its result + // is re-read under the same identity and row locks below. + const boardAnswer = provider === "github" || + (provider === "slack" && (await boardQuery).length === 1); + const evidenceQuery = boardAnswer ? boardQuery : actionQuery; let expectedPrincipalId: string | null = null; if (lockMode !== "read") { // Identity changes take this advisory lock before their row lock. Resolve @@ -773,7 +795,7 @@ async function resolveQuestionResponseChain( const card = record(record(publication.payload).card); const links = Array.isArray(card.actions) ? card.actions.map(record) : []; if ( - provider !== "github" || + !boardAnswer || interaction.resolvedByRunId !== null || publication.payload.progressState !== "waiting_for_input" || card.kind !== "question" || @@ -781,12 +803,14 @@ async function resolveQuestionResponseChain( links.some((link) => link.type !== "link") || !publication.publishedAt || publication.publishedAt > interaction.resolvedAt || - typeof boardGeneration !== "number" || - !Number.isSafeInteger(boardGeneration) || - boardGeneration < 0 || - boardRuntime.generation !== boardGeneration || - typeof boardRuntime.credentialFingerprint !== "string" || - !/^[a-f0-9]{64}$/.test(boardRuntime.credentialFingerprint) + (provider === "github" && ( + typeof boardGeneration !== "number" || + !Number.isSafeInteger(boardGeneration) || + boardGeneration < 0 || + boardRuntime.generation !== boardGeneration || + typeof boardRuntime.credentialFingerprint !== "string" || + !/^[a-f0-9]{64}$/.test(boardRuntime.credentialFingerprint) + )) ) return null; } else if (action.kind === "question_answer") { @@ -806,13 +830,16 @@ async function resolveQuestionResponseChain( record(action.result).interactionStatus !== "answered" || !selectedAnswer || !selectedQuestion || - selectedQuestion.selectionMode !== "single" || - ids(selectedAnswer.optionIds).length !== 1 || - ids(selectedAnswer.optionIds)[0] !== action.payload.optionId || !Array.isArray(selectedQuestion.options) || - !selectedQuestion.options.some( - (option) => record(option).id === action.payload.optionId, - ) + !Array.isArray(answers) || answers.length !== 1 || + !Array.isArray(questions) || questions.length !== 1 || + Boolean(selectedAnswer.otherText) || + (Array.isArray(action.payload.selectionOptions) + ? provider !== "slack" || !completedMultiChoiceMatches(selectedQuestion, selectedAnswer, action.payload) + : selectedQuestion.selectionMode !== "single" || + ids(selectedAnswer.optionIds).length !== 1 || + ids(selectedAnswer.optionIds)[0] !== action.payload.optionId || + !selectedQuestion.options.some(option => record(option).id === action.payload.optionId)) ) return null; } else if (action.kind === "photon_interaction") { @@ -892,10 +919,12 @@ async function resolveQuestionResponseChain( } : { boardResponse: { - schema: "paperclip.github_board_question_response.v1", + schema: `paperclip.${provider}_board_question_response.v1`, principalId: inbound.principalId, - runtimeGeneration: boardGeneration, - credentialFingerprint: boardRuntime.credentialFingerprint, + ...(provider === "github" ? { + runtimeGeneration: boardGeneration, + credentialFingerprint: boardRuntime.credentialFingerprint, + } : {}), }, }), publication: { diff --git a/server/src/services/native-runtime/external-chat-wait.integration.test.ts b/server/src/services/native-runtime/external-chat-wait.integration.test.ts index 1bbdd1380a3..b0ee8e0c5f6 100644 --- a/server/src/services/native-runtime/external-chat-wait.integration.test.ts +++ b/server/src/services/native-runtime/external-chat-wait.integration.test.ts @@ -467,7 +467,7 @@ describe("native external-chat response wait", () => { fixture: Awaited>; gate: Awaited>; }, - responseKind: "button" | "form" = "button", + responseKind: "button" | "form" | "multi" = "button", ) { const fixture = target?.fixture ?? await seedWaitTurn(provider); const gate = target?.gate ?? await seedPriorCompletionReview(fixture); @@ -520,7 +520,7 @@ describe("native external-chat response wait", () => { { id: "color", prompt: "Choose a color", - selectionMode: "single" as const, + selectionMode: responseKind === "multi" ? "multi" as const : "single" as const, required: true, allowOther: false, options: [ @@ -545,7 +545,7 @@ describe("native external-chat response wait", () => { } : { version: 1 as const, - answers: [{ questionId: "color", optionIds: ["cobalt"] }], + answers: [{ questionId: "color", optionIds: responseKind === "multi" ? ["cobalt", "amber"] : ["cobalt"] }], }; await db.insert(heartbeatRuns).values({ id: sourceRunId, @@ -641,7 +641,7 @@ describe("native external-chat response wait", () => { interactionId, publicationId, questionId: "color", - optionId: "cobalt", + ...(responseKind === "multi" ? { selectionOptions: [{ value: "opaque-cobalt", optionId: "cobalt" }, { value: "opaque-amber", optionId: "amber" }], selectionValues: ["opaque-cobalt", "opaque-amber"] } : { optionId: "cobalt" }), }, result: responseKind === "form" @@ -700,8 +700,12 @@ describe("native external-chat response wait", () => { }; } - async function seedGitHubBoardAnsweredTurn(withLink = true) { - const fixture = await seedWaitTurn("github"); + async function seedBoardAnsweredTurn(withLink = true, provider: "github" | "slack" = "github", oversized = false) { + const fixture = await seedWaitTurn(provider); + if (provider === "slack") { + await db.update(chatEndpointResources).set({ type: "channel" }).where(eq(chatEndpointResources.id, fixture.resourceId)); + await db.update(chatConversations).set({ isDirectMessage: false }).where(eq(chatConversations.id, fixture.conversationId)); + } const gate = await seedPriorCompletionReview(fixture); const [current] = await db .select() @@ -756,12 +760,16 @@ describe("native external-chat response wait", () => { { id: "color", prompt: "Choose a color", - selectionMode: "single", + // Multi-select plus a custom answer intentionally needs Board. + selectionMode: provider === "slack" ? "multi" : "single", required: true, - allowOther: false, + allowOther: provider === "slack" && !oversized, options: [ { id: "cobalt", label: "Cobalt" }, { id: "amber", label: "Amber" }, + ...(oversized ? Array.from({ length: 9 }, (_, index) => ({ + id: `option-${index}`, label: `Option ${index}`, description: "Detail ".repeat(550), + })) : []), ], }, ], @@ -779,7 +787,7 @@ describe("native external-chat response wait", () => { .update(chatPublications) .set({ state: "published", - providerMessageId: "github-question", + providerMessageId: `${provider}-question`, publishedAt: new Date(), }) .where(eq(chatPublications.idempotencyKey, publicationKey)) @@ -858,10 +866,24 @@ describe("native external-chat response wait", () => { }; } - it.each([true, false])( - "attests a native GitHub question answered in Board without inventing a provider action (link: %s)", - async (withLink) => { - const fixture = await seedGitHubBoardAnsweredTurn(withLink); + it("resumes an oversized Slack multi-select answered through its Paperclip handoff", async () => { + const fixture = await seedBoardAnsweredTurn(true, "slack", true); + const [publication] = await db.select().from(chatPublications).where(eq(chatPublications.id, fixture.publicationId)); + expect(publication!.payload.card?.actions).toEqual([ + { type: "link", label: "Open in Paperclip", url: expect.stringContaining(fixture.issueId) }, + ]); + expect(publication!.payload.card?.selection).toBeUndefined(); + await expect(db.select().from(chatActions).where(eq(chatActions.companyId, fixture.companyId))).resolves.toEqual([]); + await attestAnswer(fixture); + const responses = await materializeExternalChatQuestionResponseInput({ db, binding: fixture, contextSnapshot: fixture.context }); + expect(responses).toHaveLength(1); + expect(JSON.stringify(responses)).toContain("cobalt"); + }); + + it.each((["github", "slack"] as const).flatMap(provider => [true, false].map(withLink => ({ provider, withLink }))))( + "attests a native $provider question answered in Board without inventing a provider action (link: $withLink)", + async ({ provider, withLink }) => { + const fixture = await seedBoardAnsweredTurn(withLink, provider); await expect( db .select() @@ -879,7 +901,7 @@ describe("native external-chat response wait", () => { ).not.toBeNull(); await attestAnswer(fixture); expect(fixture.context.paperclipWake).toMatchObject({ - externalChatProvider: "github", + externalChatProvider: provider, }); await db .update(heartbeatRuns) @@ -923,7 +945,7 @@ describe("native external-chat response wait", () => { }, ); - it.each([ + it.each((["github", "slack"] as const).flatMap(provider => ([ "different_user", "viewer", "membership_revoked", @@ -938,10 +960,10 @@ describe("native external-chat response wait", () => { "endpoint_paused", "resource_revoked", "answer_hash", - ] as const)( - "rejects GitHub Board answer authority after %s", - async (change) => { - const fixture = await seedGitHubBoardAnsweredTurn(); + ] as const).filter(change => provider === "github" || (change !== "generation" && change !== "missing_runtime")).map(change => ({ provider, change }))))( + "rejects $provider Board answer authority after $change", + async ({ provider, change }) => { + const fixture = await seedBoardAnsweredTurn(true, provider); if (change === "different_user") { const otherUser = `other-${randomUUID()}`; await db @@ -1080,10 +1102,10 @@ describe("native external-chat response wait", () => { }, ); - it.each(["generation", "identity", "membership", "reach"] as const)( - "rechecks GitHub Board answer %s at publication after native completion", - async (change) => { - const fixture = await seedGitHubBoardAnsweredTurn(); + it.each((["github", "slack"] as const).flatMap(provider => (["generation", "identity", "membership", "reach"] as const).filter(change => provider === "github" || change !== "generation").map(change => ({ provider, change }))))( + "rechecks $provider Board answer $change at publication after native completion", + async ({ provider, change }) => { + const fixture = await seedBoardAnsweredTurn(true, provider); await attestAnswer(fixture); const resultJson = await finishReviewResponse(fixture); expect( @@ -1203,7 +1225,7 @@ describe("native external-chat response wait", () => { async function attestAnswer( fixture: | Awaited> - | Awaited>, + | Awaited>, ) { expect( await attestReviewedExternalChatRun({ @@ -1240,13 +1262,13 @@ describe("native external-chat response wait", () => { check: (input: { fixture: | Awaited> - | Awaited>; + | Awaited>; invoke: () => Promise; }) => Promise, ) { const fixture = provider === "github" - ? await seedGitHubBoardAnsweredTurn() + ? await seedBoardAnsweredTurn() : await seedAnsweredChatTurn(provider); await attestAnswer(fixture); const root = await mkdtemp(path.join(tmpdir(), "answered-chat-file-")); @@ -1327,7 +1349,7 @@ describe("native external-chat response wait", () => { const fixture = source === "direct" ? await seedWaitTurn("github") - : await seedGitHubBoardAnsweredTurn(); + : await seedBoardAnsweredTurn(); if (source === "direct") await seedPriorCompletionReview(fixture); // A previous run's failure projects `error` onto the agent. The next // already-claimed turn attests before execution-start changes it to @@ -1444,6 +1466,16 @@ describe("native external-chat response wait", () => { }, ); + it.each(["valid", "tampered_selection", "revoked_identity"])("attests only the committed Slack multiple-choice response: %s", async condition => { + const fixture = await seedAnsweredChatTurn("slack", undefined, "multi"); + if (condition === "tampered_selection") { + const [action] = await db.select().from(chatActions).where(eq(chatActions.id, fixture.actionId)); + await db.update(chatActions).set({ payload: { ...action!.payload, selectionValues: ["opaque-amber", "opaque-cobalt"] } }).where(eq(chatActions.id, fixture.actionId)); + } + if (condition === "revoked_identity") await db.update(chatIdentityLinks).set({ status: "revoked" }).where(eq(chatIdentityLinks.principalId, fixture.principalId)); + expect(await attestReviewedExternalChatRun({ db, ...fixture, contextSnapshot: fixture.context })).toBe(condition === "valid"); + }); + it("attests a genuine Slack mixed-question modal answer for its native continuation", async () => { const fixture = await seedAnsweredChatTurn("slack", undefined, "form"); await expect( diff --git a/server/src/services/satisfied-connection-intents.ts b/server/src/services/satisfied-connection-intents.ts index f6a3eb39ef4..61b7bb21783 100644 --- a/server/src/services/satisfied-connection-intents.ts +++ b/server/src/services/satisfied-connection-intents.ts @@ -1,3 +1,4 @@ +import { enqueueTerminalIssueInteractionChatPublications } from "./chat-interaction-publications.js"; import { and, asc, eq, gt, inArray, isNull, or } from "drizzle-orm"; import { approvals, companyMemberships, connectionIntentDeliveries, issueApprovals, issueThreadInteractions, issues, type Db } from "@paperclipai/db"; import { connectionIntentPayloadSchema } from "@paperclipai/shared"; @@ -111,10 +112,14 @@ export function satisfiedConnectionIntentService(db: Db) { if (!connection) return false; const now = new Date(); // Retire the obsolete request without inventing a human approval. - await tx.update(issueThreadInteractions).set({ status: "expired", resolvedAt: now, updatedAt: now, + const [retired] = await tx.update(issueThreadInteractions).set({ status: "expired", resolvedAt: now, updatedAt: now, result: { version: 1, outcome: "expired", connectionId: connection.id, reason: "An already authorized connection is available to the requesting agent." }, - }).where(and(eq(issueThreadInteractions.id, intent.id), eq(issueThreadInteractions.status, "pending"))); + }).where(and(eq(issueThreadInteractions.id, intent.id), eq(issueThreadInteractions.status, "pending"))).returning(); + if (!retired) return false; + const { issueThreadInteractionService } = await import("./issue-thread-interactions.js"); + const interaction = await issueThreadInteractionService(txDb).getById(retired.id); + if (interaction) await enqueueTerminalIssueInteractionChatPublications(txDb, interaction); await tx.update(issues).set({ updatedAt: now }).where(and(eq(issues.id, task.id), eq(issues.companyId, task.companyId))); await tx.insert(connectionIntentDeliveries).values({ interactionId: intent.id, companyId: task.companyId }).onConflictDoNothing(); await notifyDeliveryWork(tx, DELIVERY_QUEUES.connection); From 0eb2c964a71066698b8415edb005133a2d10196a Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sat, 24 Oct 2026 10:31:40 -0700 Subject: [PATCH 006/110] fix(agents): allow runner qualification with agent configuration permission (#17448) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Agent owners configure the harness and computer used for that work. > - A legacy runner upgrade must first qualify an unverified sandbox. > - The upgrade called an instance-admin probe, so a company owner with agent configuration permission received HTTP 403. > - This pull request qualifies the saved computer through the agent's existing configuration authorization. > - Company owners can complete the upgrade while general instance environment management stays restricted. ## Linked Issues or Issue Description Refs #17361. Related: #17122. **What happened?** Upgrade runner displayed for an existing Claude agent on a Daytona Paperclip Computer. Clicking it returned “Instance admin access required” for a cloud company owner. The agent remained on the legacy runner. **Expected behavior** A caller permitted to update the agent can qualify that agent's saved computer and upgrade. Instance-admin access is not required for this agent-scoped operation. **Steps to reproduce** 1. Sign in as a cloud company owner with `agents:configure` and no instance-admin role. 2. Open an existing legacy Claude agent on an unqualified Daytona snapshot. 3. Select Upgrade runner. ## What Changed - Add `POST /api/agents/{id}/qualify-runner` with the existing `agent_config:update` guard. - Reuse the server's effective environment resolver. The submitted environment ID only detects stale state; it cannot select a different computer. - Preserve company binding checks, check binding again at lease acquisition, and record agent-scoped audit activity. - Return qualification status and the lease receipt without instance-level provider metadata or raw provider errors. - Use the new endpoint for the existing-agent upgrade. Keep the generic environment probe restricted to instance admins. - Disable Upgrade runner when an unsaved computer change resolves to a different target, with a save-first explanation. Other draft settings still accompany an upgrade. - Add real-database authorization regression tests and update the API contract and access maps. ## Verification - Red: the existing UI called the instance-wide probe and failed the new agent-scoped call assertions in eight upgrade cases. - Green: 349 related route, provider qualification, runner selection, and UI tests passed. - Green: 12 authorization cases passed with real PostgreSQL, real HTTP routes, real saved role grants, and a simulated provider boot. They cover the cloud owner, removed grants, foreign agent/computer, inherited targets, stale target, invalid body, archived/local target, redacted failure, audit scope, and unchanged agent settings. - Review regression: two cases first reproduced the enabled upgrade button after an unsaved computer change; both now pass, along with all 168 related UI tests. Qualified/unqualified computers and restoring the saved selection are covered. - All 26 OpenAPI cases passed; the 12 real-database authorization cases also passed after rebase. - The host exhausted PostgreSQL semaphores. For the 12 cases, a temporary local-only setup used disposable PostgreSQL 18 in Docker instead of the embedded database launcher. The committed tests use the normal embedded database helper. No authorization decisions were mocked. - `pnpm -r typecheck`, `pnpm build`, `pnpm check:token-gates`, map validation, module-boundary validation, and `git diff --check` passed. - `pnpm test:run` was attempted but did not establish a full local pass: the host could not start embedded PostgreSQL clusters. All current-head CI gates passed, including the full suite in CI. The commitperclip review workflow timed out before reporting any executed steps on its first attempt and passed on one retry. - Fresh staging acceptance remains pending deployment. Verify persisted native configuration and a successful runtime test on the existing Daytona computer after merge. Earlier live Daytona proof from #17361 is separate evidence. ## Risks - Qualification can start a fresh, temporary sandbox. It uses the existing probe lifecycle and cleanup contract. - The new path must remain scoped to the saved agent and its company. Denial and redaction tests cover that boundary. General instance probe authorization is unchanged. - No migration, role change, credential change, or automatic agent upgrade is included. ## Model Used - OpenAI GPT-6 through Codex, with reasoning, code execution, and browser tools. The exact deployed model variant and context-window size were 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 (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 --- doc/PRODUCT.md | 5 + maps/agent-access-map/agents.md | 11 +- maps/feature-map/agents.md | 6 +- packages/shared/src/index.ts | 1 + packages/shared/src/validators/agent.ts | 4 + packages/shared/src/validators/index.ts | 1 + .../agent-runner-qualification-routes.test.ts | 123 ++++++++++++++++++ .../src/__tests__/environment-probe.test.ts | 4 +- server/src/routes/agents.ts | 21 +++ server/src/routes/openapi.ts | 11 ++ .../services/agent-runner-qualification.ts | 42 ++++++ server/src/services/agent-runner-selection.ts | 48 +++---- server/src/services/environment-probe.ts | 2 + ui/src/api/agents.ts | 3 + .../AgentConfigForm.render.test.tsx | 37 +++++- ui/src/components/AgentConfigForm.tsx | 54 +++++--- 16 files changed, 316 insertions(+), 57 deletions(-) create mode 100644 server/src/__tests__/agent-runner-qualification-routes.test.ts create mode 100644 server/src/services/agent-runner-qualification.ts diff --git a/doc/PRODUCT.md b/doc/PRODUCT.md index ffda2b04cd1..48086411897 100644 --- a/doc/PRODUCT.md +++ b/doc/PRODUCT.md @@ -56,6 +56,11 @@ while keeping the harness, selected model, account bindings, instructions, and history. Unsupported settings produce an actionable error without changing the saved agent. Future runs start fresh sessions. +Qualifying an existing agent's sandbox for that upgrade uses the same agent +configuration permission as saving the upgrade. The server checks the saved +computer and its company binding. Company owners do not need instance-admin +access for this step; general instance environment management remains restricted. + Paperclip supports several ways to run an agent's heartbeat: 1. **Local CLI/session adapters** — Paperclip starts or resumes local coding-tool sessions such as Claude Code, Codex, Gemini, OpenCode, Pi, and Cursor, then tracks the run. diff --git a/maps/agent-access-map/agents.md b/maps/agent-access-map/agents.md index 8599a70e397..efc593ec743 100644 --- a/maps/agent-access-map/agents.md +++ b/maps/agent-access-map/agents.md @@ -106,6 +106,7 @@ API: `present` — representative operation IDs: - `GET /api/agents/{id}/instructions-bundle/file`. - `PUT /api/agents/{id}/instructions-bundle/file`. - `PATCH /api/agents/{id}` with an explicit `runner: "paperclip"` upgrade. +- `POST /api/agents/{id}/qualify-runner` to qualify the saved effective sandbox before upgrading. - `PATCH /api/agents/{id}` with `runtimeSettings: { harness, model?, aiConnection?, expected: { model, aiConnection } }` for a narrow roster edit. Each request handles one agent; the UI batches at most four writes and collects per-agent outcomes. Agent access: `available` — Native read/update/history/restore instruction tools; REST / @@ -125,9 +126,13 @@ The existing-agent upgrade notice uses this configuration PATCH. It does not grant configuration, account, or environment access. The server resolves the saved settings under normal company/configuration authorization. Obsolete Claude tuning fields are removed with `configurationWarnings`; security incompatibilities -remain errors. Unqualified sandbox upgrades first use the existing -`POST /api/environments/{id}/probe?companyId=...`, retaining its instance-admin -authorization and company-scoped qualification. No probe runs merely on page load. Operator browser evidence does not +remain errors. Unqualified sandbox upgrades first use the agent-scoped +`POST /api/agents/{id}/qualify-runner` under the same `agent_config:update` +authorization as saving the upgrade. The server resolves the saved computer; +`expectedEnvironmentId` rejects stale state and cannot select another computer. +Qualification checks company binding, returns only its receipt, and audits within +the agent's company. General instance environment probes still require instance +admin. No probe runs merely on page load. Operator browser evidence does not qualify the agent permission paths for this operation. Evidence: `source-only` — [implementation](../../server/src/routes/agents.ts#L1395) at diff --git a/maps/feature-map/agents.md b/maps/feature-map/agents.md index 1d0f8edc0ab..95fed092ec1 100644 --- a/maps/feature-map/agents.md +++ b/maps/feature-map/agents.md @@ -138,8 +138,10 @@ recorded execution. Keep runner choice in Advanced and verify the next eligible run separately from historical transcripts. Existing legacy Claude and Codex agents on qualified default environments, or -probe-capable Daytona snapshots / immutable sandbox images, show **Upgrade runner** above their configuration. Exercise that action with -pending edits and an environment-variable draft; reopen the page and compare the +probe-capable Daytona snapshots / immutable sandbox images, show **Upgrade runner** above their configuration. Verify a company owner with `agents:configure` and no instance-admin role can qualify the saved computer and upgrade. A caller without configuration permission must be denied before a probe starts. Exercise that action with +pending edits and an environment-variable draft. An unsaved change to a different +effective computer must disable the action and explain that the computer change +must be saved first; restoring the saved target must re-enable it. Reopen the page and compare the saved harness, model, account bindings, instructions, and run policy. Check a saved `maxTurnsPerRun: 1000`: upgrade must warn and remove it. Test an initially unqualified Daytona Paperclip Computer: click must probe, record qualification, diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index 5fd101bbb9e..99f0a885507 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -1879,6 +1879,7 @@ export { wakeAgentSchema, resetAgentSessionSchema, testAdapterEnvironmentSchema, + qualifyAgentRunnerSchema, agentPermissionsSchema, updateAgentPermissionsSchema, type CreateAgent, diff --git a/packages/shared/src/validators/agent.ts b/packages/shared/src/validators/agent.ts index 80ad7076e6b..32d65555e6d 100644 --- a/packages/shared/src/validators/agent.ts +++ b/packages/shared/src/validators/agent.ts @@ -180,6 +180,10 @@ export const updateAgentSchema = objectWithoutDefaults( export type UpdateAgent = z.infer; +export const qualifyAgentRunnerSchema = z.object({ + expectedEnvironmentId: z.string().uuid(), +}).strict(); + export const updateAgentInstructionsPathSchema = z.object({ path: z.string().trim().min(1).nullable(), adapterConfigKey: z.string().trim().min(1).optional(), diff --git a/packages/shared/src/validators/index.ts b/packages/shared/src/validators/index.ts index b8fc304b7ce..05519dd262f 100644 --- a/packages/shared/src/validators/index.ts +++ b/packages/shared/src/validators/index.ts @@ -367,6 +367,7 @@ export { wakeAgentSchema, resetAgentSessionSchema, testAdapterEnvironmentSchema, + qualifyAgentRunnerSchema, agentPermissionsSchema, updateAgentPermissionsSchema, type CreateAgent, diff --git a/server/src/__tests__/agent-runner-qualification-routes.test.ts b/server/src/__tests__/agent-runner-qualification-routes.test.ts new file mode 100644 index 00000000000..3d50ad7d6af --- /dev/null +++ b/server/src/__tests__/agent-runner-qualification-routes.test.ts @@ -0,0 +1,123 @@ +import { randomUUID } from "node:crypto"; +import express from "express"; +import request from "supertest"; +import { eq } from "drizzle-orm"; +import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; +import { agents, authUsers, companies, companyMemberships, createDb, environments, principalPermissionGrants, activityLog, instanceSettings, builtInManagedResources, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS } from "@paperclipai/db"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; +import { grantsForHumanRole } from "../services/company-member-roles.js"; +import { agentRoutes } from "../routes/agents.js"; +import { environmentRoutes } from "../routes/environments.js"; +import { errorHandler } from "../middleware/error-handler.js"; + +const probe = vi.hoisted(() => vi.fn()); +vi.mock("../services/environment-probe.js", async original => ({ + ...await original(), probeEnvironment: probe, +})); + +const support = await getEmbeddedPostgresTestSupport(); +describe.skipIf(!support.supported)("agent-scoped runner qualification", () => { + let tempDb: Awaited>; + let db: ReturnType; + let companyId: string; + let agentId: string; + let environmentId: string; + let userId: string; + let app: express.Express; + + beforeAll(async () => { + tempDb = await startEmbeddedPostgresTestDatabase("runner-qualification-"); + db = createDb(tempDb.connectionString); + }, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS); + afterAll(async () => { await tempDb?.cleanup(); }); + beforeEach(async () => { + await db.delete(instanceSettings); + await db.delete(environments); + probe.mockReset().mockResolvedValue({ ok: true, driver: "sandbox", summary: "Connected", + details: { platformQualificationRecorded: true, leaseId: "probe-lease", metadata: { private: "provider-secret" }, providerLeaseId: "private-id" } }); + companyId = randomUUID(); agentId = randomUUID(); environmentId = randomUUID(); userId = randomUUID(); + await db.insert(companies).values({ id: companyId, name: "Qualification", issuePrefix: `Q${companyId.slice(0, 7)}` }); + await db.insert(authUsers).values({ id: userId, name: "Company owner", email: `${userId}@example.test`, emailVerified: true, createdAt: new Date(), updatedAt: new Date() }); + await db.insert(companyMemberships).values({ companyId, principalType: "user", principalId: userId, membershipRole: "owner", status: "active" }); + await db.insert(principalPermissionGrants).values(grantsForHumanRole("owner").map(grant => ({ ...grant, companyId, principalType: "user" as const, principalId: userId }))); + await db.insert(environments).values({ id: environmentId, name: `Paperclip Computer ${environmentId}`, driver: "sandbox", status: "active", config: { provider: "daytona", snapshot: "managed-snapshot" } }); + await db.insert(agents).values({ id: agentId, companyId, name: "Amy fixture", adapterType: "claude_local", defaultEnvironmentId: environmentId, + adapterConfig: { model: "claude-opus-5-5", effort: "high", maxTurnsPerRun: 1000, dangerouslySkipPermissions: true } }); + app = express(); app.use(express.json()); + app.use((req, _res, next) => { + req.actor = { type: "board", userId, companyIds: [companyId], source: "cloud_tenant", isInstanceAdmin: false, + memberships: [{ companyId, membershipRole: "owner", status: "active" }] }; + next(); + }); + app.use("/api", agentRoutes(db)); + app.use("/api", environmentRoutes(db)); + app.use(errorHandler); + }); + const qualify = () => request(app).post(`/api/agents/${agentId}/qualify-runner`).send({ expectedEnvironmentId: environmentId }); + + it("allows the company owner without instance admin and keeps the generic probe restricted", async () => { + const before = await db.select().from(agents).where(eq(agents.id, agentId)); + const res = await qualify(); + expect(res.status).toBe(200); + expect(res.body).toMatchObject({ ok: true, details: { platformQualificationRecorded: true, leaseId: "probe-lease" } }); + expect(JSON.stringify(res.body)).not.toMatch(/provider-secret|private-id/); + expect(probe).toHaveBeenCalledWith(db, expect.objectContaining({ id: environmentId }), expect.objectContaining({ companyId, assertCompanyBinding: true, acquireSandboxRuntimeLease: true, applyCustomImageTemplate: true })); + expect(await db.select().from(agents).where(eq(agents.id, agentId))).toEqual(before); + const audit = await db.select().from(activityLog).where(eq(activityLog.entityId, agentId)); + expect(audit).toEqual([expect.objectContaining({ companyId, actorId: userId, action: "agent.runner_qualification_tested" })]); + const generic = await request(app).post(`/api/environments/${environmentId}/probe?companyId=${companyId}`).send({}); + expect(generic.status).toBe(403); + expect(probe).toHaveBeenCalledTimes(1); + }); + it("rejects an owner whose configure grant is absent before any provider work", async () => { + await db.delete(principalPermissionGrants).where(eq(principalPermissionGrants.principalId, userId)); + expect((await qualify()).status).toBe(403); + expect(probe).not.toHaveBeenCalled(); + }); + it("hides a foreign agent before any provider work", async () => { + const other = randomUUID(); + await db.insert(companies).values({ id: other, name: "Other", issuePrefix: `F${other.slice(0, 7)}` }); + await db.update(agents).set({ companyId: other }).where(eq(agents.id, agentId)); + expect((await qualify()).status).toBe(404); + expect(probe).not.toHaveBeenCalled(); + }); + it("treats the submitted environment as a stale-state check, not a target override", async () => { + const res = await request(app).post(`/api/agents/${agentId}/qualify-runner`).send({ expectedEnvironmentId: randomUUID() }); + expect(res.status).toBe(409); + expect(probe).not.toHaveBeenCalled(); + }); + it("rejects a managed computer bound to a different company", async () => { + const other = randomUUID(); + await db.insert(companies).values({ id: other, name: "Other", issuePrefix: `F${other.slice(0, 7)}` }); + await db.insert(builtInManagedResources).values({ companyId: other, bundleKey: "test", resourceKind: "environment", resourceKey: "computer", resourceId: environmentId, stockVersion: "test", stockHash: "test" }); + expect((await qualify()).status).toBe(403); + expect(probe).not.toHaveBeenCalled(); + }); + it.each(["instance", "managed", "kubernetes"])("resolves the %s computer with the same policy as runner saving", async mode => { + await db.update(agents).set({ defaultEnvironmentId: null }).where(eq(agents.id, agentId)); + await db.update(environments).set({ metadata: { managedByPaperclip: true, managedKubernetesSandbox: mode === "kubernetes" }, + ...(mode === "kubernetes" ? { config: { provider: "kubernetes" } } : {}) }).where(eq(environments.id, environmentId)); + await db.insert(instanceSettings).values({ defaultEnvironmentId: mode === "instance" ? environmentId : null, + experimental: { enableManagedSandboxOnly: mode === "managed" }, general: { executionMode: mode === "kubernetes" ? "kubernetes" : "local" } }); + expect((await qualify()).status).toBe(200); + expect(probe).toHaveBeenCalledWith(db, expect.objectContaining({ id: environmentId }), expect.anything()); + }); + it("does not accept arbitrary provider config or a target override", async () => { + const res = await request(app).post(`/api/agents/${agentId}/qualify-runner`).send({ expectedEnvironmentId: environmentId, config: { image: "untrusted" } }); + expect(res.status).toBe(400); + expect(probe).not.toHaveBeenCalled(); + }); + it.each(["archived", "local"])("rejects an ineligible %s environment", async state => { + await db.update(environments).set(state === "archived" ? { status: "archived" } : { driver: "local", config: {} }).where(eq(environments.id, environmentId)); + expect((await qualify()).status).toBe(422); + expect(probe).not.toHaveBeenCalled(); + }); + it("returns a failed qualification without exposing provider diagnostics or changing the agent", async () => { + probe.mockResolvedValue({ ok: false, driver: "sandbox", summary: "provider-secret", details: { error: "provider-secret" } }); + const res = await qualify(); + expect(res.status).toBe(200); + expect(res.body.ok).toBe(false); + expect(JSON.stringify(res.body)).not.toContain("provider-secret"); + expect((await db.select().from(agents).where(eq(agents.id, agentId)))[0]?.adapterType).toBe("claude_local"); + }); +}); diff --git a/server/src/__tests__/environment-probe.test.ts b/server/src/__tests__/environment-probe.test.ts index 94d334fddaf..e00c2d3eb6f 100644 --- a/server/src/__tests__/environment-probe.test.ts +++ b/server/src/__tests__/environment-probe.test.ts @@ -56,9 +56,9 @@ describe("probeEnvironment", () => { vi.spyOn(configRuntime, "resolveEnvironmentDriverConfigForRuntime").mockResolvedValue({ driver: "sandbox", config: environment.config }); mockRuntimeAcquireRunLease.mockResolvedValue({ lease: { id: "lease", provider: "daytona", metadata: { snapshot: "managed-snapshot", snapshotIdentity: identity } } }); mockRuntimeExecute.mockResolvedValue({ exitCode: 0, stdout: "Linux\nx86_64\nglibc\nglibc 2.39\n" }); - const result = await probeEnvironment({} as any, environment, { companyId: "company", acquireSandboxRuntimeLease: true }); + const result = await probeEnvironment({} as any, environment, { companyId: "company", acquireSandboxRuntimeLease: true, assertCompanyBinding: true }); expect(result.details?.platformQualificationRecorded).toBe(true); - expect(mockRuntimeAcquireRunLease).toHaveBeenCalledWith(expect.objectContaining({ resolveSnapshotIdentity: true })); + expect(mockRuntimeAcquireRunLease).toHaveBeenCalledWith(expect.objectContaining({ resolveSnapshotIdentity: true, assertCompanyBinding: true })); const proof = mockRecordPlatformProbe.mock.calls[1]![0].proof; expect(proof).toMatchObject({ v: 2, snapshotIdentity: identity }); environment.metadata = { [SANDBOX_PLATFORM_PROBE_METADATA_KEY]: { company: proof } }; diff --git a/server/src/routes/agents.ts b/server/src/routes/agents.ts index 0a03946e7f2..540e1f7d8cc 100644 --- a/server/src/routes/agents.ts +++ b/server/src/routes/agents.ts @@ -4,6 +4,7 @@ import { cancellationRequestId } from "../services/native-runtime/native-cancell import { agentHarnessType, isEnvironmentDriverSupportedForAdapter, normalizeClaudeRunnerOptions, type AgentConfigurationWarning, type AgentRunnerChoice } from "@paperclipai/shared"; import { resolveNewAgentRunnerForCompany } from "../services/agent-runner-selection.js"; import { agentEnvironmentTestService } from "../services/agent-environment-test.js"; +import { qualifyAgentRunner } from "../services/agent-runner-qualification.js"; import { createAgentLifecycle } from "../services/agent-lifecycle.js"; import { agentIdentityService } from "../services/agent-identity.js"; @@ -65,6 +66,7 @@ import { normalizeIssueIdentifier, resetAgentSessionSchema, testAdapterEnvironmentSchema, + qualifyAgentRunnerSchema, type AgentDesiredSkillEntry, type AgentSkillAssignmentMode, type AgentSkillSnapshot, @@ -1800,6 +1802,25 @@ export function agentRoutes( await assertCanUpdateAgent(req, targetAgent); } + router.post("/agents/:id/qualify-runner", validate(qualifyAgentRunnerSchema), async (req, res) => { + const agent = await getAccessibleResource(req, res, svc.getById(req.params.id as string), "Agent not found"); + if (!agent) return; + await assertCanUpdateAgent(req, agent); + const result = await qualifyAgentRunner(db, agent, req.body.expectedEnvironmentId, options.pluginWorkerManager); + const actor = getActorInfo(req); + await logActivity(db, { + companyId: agent.companyId, + actorType: actor.actorType, + actorId: actor.actorId, + action: "agent.runner_qualification_tested", + entityType: "agent", + entityId: agent.id, + details: { environmentId: req.body.expectedEnvironmentId, ok: result.ok, + platformQualificationRecorded: result.details?.platformQualificationRecorded === true }, + }); + res.json(result); + }); + async function assertCanReadAgent(req: Request, targetAgent: { id: string; companyId: string }) { if (!hasCompanyAccess(req, targetAgent.companyId)) { throw notFound("Agent not found"); diff --git a/server/src/routes/openapi.ts b/server/src/routes/openapi.ts index 45fb61d3445..650eb0670eb 100644 --- a/server/src/routes/openapi.ts +++ b/server/src/routes/openapi.ts @@ -67,6 +67,7 @@ import { resetAgentSessionSchema, agentSkillSyncSchema, testAdapterEnvironmentSchema, + qualifyAgentRunnerSchema, // Issue createIssueSchema, setIssueTitleSchema, @@ -4130,6 +4131,16 @@ registry.registerPath({ responses: { 200: r.ok(), 400: r.badRequest, 401: r.unauthorized }, }); +registry.registerPath({ + method: "post", + path: "/api/agents/{id}/qualify-runner", + tags: ["agents"], + summary: "Qualify an existing agent's saved computer for a runner upgrade", + description: "Requires agent_config:update authorization, normally agents:configure. Resolves the saved agent's effective sandbox; expectedEnvironmentId only guards against stale UI state. Does not change the agent or grant instance environment access.", + request: { params: z.object({ id: z.string() }), body: jsonBody(qualifyAgentRunnerSchema) }, + responses: { 200: r.ok(), 400: r.badRequest, 401: r.unauthorized, 403: r.forbidden, 404: r.notFound, 409: r.conflict, 422: r.unprocessable }, +}); + registry.registerPath({ method: "get", path: "/api/companies/{companyId}/adapters/{type}/auth-signal", diff --git a/server/src/services/agent-runner-qualification.ts b/server/src/services/agent-runner-qualification.ts new file mode 100644 index 00000000000..f6b73618e2e --- /dev/null +++ b/server/src/services/agent-runner-qualification.ts @@ -0,0 +1,42 @@ +import type { Db } from "@paperclipai/db"; +import type { Agent, EnvironmentProbeResult } from "@paperclipai/shared"; +import { conflict, unprocessable } from "../errors.js"; +import { resolveAgentRunnerEnvironmentForCompany } from "./agent-runner-selection.js"; +import { probeEnvironment } from "./environment-probe.js"; +import type { PluginWorkerManager } from "./plugin-worker-manager.js"; + +export async function qualifyAgentRunner( + db: Db, + agent: Pick, + expectedEnvironmentId: string, + pluginWorkerManager?: PluginWorkerManager, +): Promise { + if (!["claude_local", "codex_local"].includes(agent.adapterType)) { + throw unprocessable("This agent does not need a runner upgrade."); + } + const { environment } = await resolveAgentRunnerEnvironmentForCompany(db, agent.companyId, agent.defaultEnvironmentId); + if (!environment || environment.id !== expectedEnvironmentId) { + throw conflict("The agent's computer changed. Save any environment changes, reload, and retry the upgrade."); + } + if (environment.driver !== "sandbox") { + throw unprocessable("This computer does not need sandbox qualification."); + } + const result = await probeEnvironment(db, environment, { + companyId: agent.companyId, + pluginWorkerManager, + applyCustomImageTemplate: true, + acquireSandboxRuntimeLease: true, + assertCompanyBinding: true, + }); + const qualified = result.ok === true && result.details?.platformQualificationRecorded === true; + return { + ok: result.ok, + driver: "sandbox", + summary: qualified ? "The agent's computer is qualified for runner selection." + : "Could not qualify the agent's computer. Retry the upgrade or keep Legacy runner.", + details: { + platformQualificationRecorded: qualified, + ...(typeof result.details?.leaseId === "string" ? { leaseId: result.details.leaseId } : {}), + }, + }; +} diff --git a/server/src/services/agent-runner-selection.ts b/server/src/services/agent-runner-selection.ts index 42347ccad20..7d87a5b9d89 100644 --- a/server/src/services/agent-runner-selection.ts +++ b/server/src/services/agent-runner-selection.ts @@ -290,28 +290,7 @@ export async function resolveNewAgentRunnerForCompany(db: Db, companyId: string, export async function resolveAgentRunnerTargetForCompany(db: Db, companyId: string, defaultEnvironmentId?: string | null): Promise { await waitForExternalAdapters(); - const { instanceSettingsService } = await import("./instance-settings.js"); - const { environmentService } = await import("./environments.js"); - const settings = await instanceSettingsService(db).get(); - const envs = environmentService(db); - const environmentId = defaultEnvironmentId ?? settings.defaultEnvironmentId; - let environment = environmentId ? await envs.getById(environmentId) : null; - if (settings.experimental?.enableManagedSandboxOnly && (!environment || environment.driver === "local")) { - environment = await envs.findManagedSandboxEnvironment(companyId); - if (!environment) throw unprocessable("The managed sandbox is unavailable. Restore Paperclip Computer and retry.", { code: "managed_sandbox_unavailable" }); - } - if (settings.general?.executionMode === "kubernetes") { - environment = await envs.findKubernetesEnvironment(companyId); - if (!environment) return { driver: "sandbox" }; - } - if (environmentId && !environment) throw unprocessable("Environment not found."); - if (environment) { - const boundCompanyIds = await envs.listBoundCompanyIds(environment.id); - if (boundCompanyIds.length > 0 && !boundCompanyIds.includes(companyId)) throw forbidden("The selected environment belongs to another company.", { code: "environment_company_mismatch" }); - if (environment.status === "archived") throw unprocessable("Environment is archived."); - if (environment.driver === "sandbox" && environment.config?.provider === "fake") throw unprocessable("The fake sandbox provider cannot execute runs."); - } - const driver = environment?.driver ?? "local"; + const { environment, driver } = await resolveAgentRunnerEnvironmentForCompany(db, companyId, defaultEnvironmentId); let target: RunnerTarget = driver === "local" ? localAgentRunnerTarget() : { driver }; if (driver === "plugin" && environment && await pluginEnvironmentRunsRunnerTasks(db, environment)) target = { driver, runnerTasks: true }; @@ -332,6 +311,31 @@ export async function resolveAgentRunnerTargetForCompany(db: Db, companyId: stri return target; } +export async function resolveAgentRunnerEnvironmentForCompany(db: Db, companyId: string, defaultEnvironmentId?: string | null) { + const { instanceSettingsService } = await import("./instance-settings.js"); + const { environmentService } = await import("./environments.js"); + const settings = await instanceSettingsService(db).get(); + const envs = environmentService(db); + const environmentId = defaultEnvironmentId ?? settings.defaultEnvironmentId; + let environment = environmentId ? await envs.getById(environmentId) : null; + if (settings.experimental?.enableManagedSandboxOnly && (!environment || environment.driver === "local")) { + environment = await envs.findManagedSandboxEnvironment(companyId); + if (!environment) throw unprocessable("The managed sandbox is unavailable. Restore Paperclip Computer and retry.", { code: "managed_sandbox_unavailable" }); + } + if (settings.general?.executionMode === "kubernetes") { + environment = await envs.findKubernetesEnvironment(companyId); + if (!environment) return { environment: null, driver: "sandbox" }; + } + if (environmentId && !environment) throw unprocessable("Environment not found."); + if (environment) { + const boundCompanyIds = await envs.listBoundCompanyIds(environment.id); + if (boundCompanyIds.length > 0 && !boundCompanyIds.includes(companyId)) throw forbidden("The selected environment belongs to another company.", { code: "environment_company_mismatch" }); + if (environment.status === "archived") throw unprocessable("Environment is archived."); + if (environment.driver === "sandbox" && environment.config?.provider === "fake") throw unprocessable("The fake sandbox provider cannot execute runs."); + } + return { environment, driver: environment?.driver ?? "local" }; +} + // The plugin's manifest declaration decides whether its environment runs // Runner tasks. Run admission separately verifies a ready plugin and a live // worker, so a plugin that is down still selects the Runner and fails its run. diff --git a/server/src/services/environment-probe.ts b/server/src/services/environment-probe.ts index c743e0f2950..7f15b03656e 100644 --- a/server/src/services/environment-probe.ts +++ b/server/src/services/environment-probe.ts @@ -76,6 +76,7 @@ export async function probeEnvironment( resolvedConfig?: ParsedEnvironmentConfig; applyCustomImageTemplate?: boolean; acquireSandboxRuntimeLease?: boolean; + assertCompanyBinding?: boolean; } = {}, ): Promise { const resolvedCompanyId = options.companyId ?? null; @@ -148,6 +149,7 @@ export async function probeEnvironment( persistedExecutionWorkspace: null, adapterType: null, resolveSnapshotIdentity: true, + assertCompanyBinding: options.assertCompanyBinding, applyCustomImageTemplate: options.applyCustomImageTemplate === true, }); const metadata = leaseRecord.lease.metadata ?? {}; diff --git a/ui/src/api/agents.ts b/ui/src/api/agents.ts index b1d0e32587c..5d31460ea38 100644 --- a/ui/src/api/agents.ts +++ b/ui/src/api/agents.ts @@ -1,6 +1,7 @@ import type { AgentPublicIdentity } from "@paperclipai/shared"; import type { Agent, + EnvironmentProbeResult, ConnectionIntentInteraction, AgentDesiredSkillEntry, AgentSkillAssignmentMode, @@ -110,6 +111,8 @@ function agentPath(id: string, companyId?: string, suffix = "") { } export const agentsApi = { + qualifyRunner: (id: string, expectedEnvironmentId: string, companyId?: string) => + api.post(agentPath(id, companyId, "/qualify-runner"), { expectedEnvironmentId }), setAvatar: (companyId: string, agentId: string, imageBase64: string | null) => api.put<{ agentId: string; appearance: import("@paperclipai/shared").AgentAppearance; avatarUrl: string }>(`/companies/${companyId}/agents/${agentId}/avatar`, { imageBase64 }), getIdentity: (id: string, companyId?: string) => diff --git a/ui/src/components/AgentConfigForm.render.test.tsx b/ui/src/components/AgentConfigForm.render.test.tsx index 244d13e83db..9ecfc4a9c83 100644 --- a/ui/src/components/AgentConfigForm.render.test.tsx +++ b/ui/src/components/AgentConfigForm.render.test.tsx @@ -27,6 +27,7 @@ const mockAgentsApi = vi.hoisted(() => ({ detectModel: vi.fn(), list: vi.fn(), testEnvironment: vi.fn(), + qualifyRunner: vi.fn(), startAdapterAuthLogin: vi.fn(), getAdapterAuthLoginStatus: vi.fn(), getActiveAdapterAuthLoginSession: vi.fn(), @@ -817,7 +818,7 @@ describe("AgentConfigForm environment selector", () => { { type: "paperclip_runner", supportedRunners: ["legacy"], defaultRunner: "legacy" }, ]; mockAdaptersApi.list.mockResolvedValue(inventory(false)); - mockEnvironmentsApi.probe.mockImplementation(async () => { + mockAgentsApi.qualifyRunner.mockImplementation(async () => { mockAdaptersApi.list.mockResolvedValue(inventory(true)); return { ok: true, driver: "sandbox", details: { platformQualificationRecorded: true, leaseId: "probe-lease" } }; }); @@ -829,7 +830,7 @@ describe("AgentConfigForm environment selector", () => { roots.push(result.root); expect(result.container.textContent).toContain("Upgrade to Paperclip Runner"); expect(result.container.textContent).toContain("Max turns per run"); - expect(mockEnvironmentsApi.probe).not.toHaveBeenCalled(); + expect(mockAgentsApi.qualifyRunner).not.toHaveBeenCalled(); if (mode === "env-draft") { await clickByText(result.container, "Add variable"); await act(async () => { @@ -839,19 +840,40 @@ describe("AgentConfigForm environment selector", () => { await flushReact(); } await clickByText(result.container, "Upgrade runner"); - expect(mockEnvironmentsApi.probe).toHaveBeenCalledWith(environment.id, "company-1"); + expect(mockAgentsApi.qualifyRunner).toHaveBeenCalledWith("agent-1", environment.id, "company-1"); expect(result.onSave).toHaveBeenCalledWith(mode === "env-draft" ? expect.objectContaining({ runner: "paperclip", replaceAdapterConfig: true, adapterConfig: expect.objectContaining({ env: { MIGRATION_MARKER: { type: "plain", value: "kept" } } }), }) : { runner: "paperclip" }); }); + it.each([false, true])("requires saving a changed computer before upgrading (qualified: %s)", async qualified => { + const environments = ["saved-computer", "draft-computer"].map(id => makeEnvironment({ id, driver: "sandbox", status: "active", + config: { provider: "daytona", snapshot: "managed-snapshot" } })); + mockAdaptersApi.list.mockResolvedValue([ + { type: "claude_local", supportedRunners: qualified ? ["paperclip", "legacy"] : ["legacy"], defaultRunner: qualified ? "paperclip" : "legacy" }, + { type: "paperclip_runner", supportedRunners: ["legacy"], defaultRunner: "legacy" }, + ]); + const result = await renderForm(environments, { adapterType: "claude_local", defaultEnvironmentId: "saved-computer" }); + roots.push(result.root); + expect(findButton(result.container, "Upgrade runner")?.disabled).toBe(false); + await selectEnvironment(result.container, "draft-computer"); + expect(findButton(result.container, "Upgrade runner")?.disabled).toBe(true); + expect(result.container.textContent).toContain("Save your computer change before upgrading the runner."); + await clickByText(result.container, "Upgrade runner"); + expect(mockAgentsApi.qualifyRunner).not.toHaveBeenCalled(); + expect(result.onSave).not.toHaveBeenCalled(); + await selectEnvironment(result.container, "saved-computer"); + expect(findButton(result.container, "Upgrade runner")?.disabled).toBe(false); + expect(result.container.textContent).not.toContain("Save your computer change before upgrading the runner."); + }); + it.each(["probe", "unsupported", "settings-changed"])("does not save after Daytona %s", async failure => { const environment = makeEnvironment({ id: "daytona-computer", name: "Paperclip Computer", driver: "sandbox", status: "active", config: { provider: "daytona", snapshot: "managed-snapshot" } }); mockAdaptersApi.list.mockResolvedValue([{ type: "claude_local", supportedRunners: ["legacy"], defaultRunner: "legacy" }, { type: "paperclip_runner", supportedRunners: ["legacy"], defaultRunner: "legacy" }]); let finish!: () => void; - mockEnvironmentsApi.probe.mockImplementation(() => new Promise(resolve => { finish = () => resolve({ ok: failure !== "probe", + mockAgentsApi.qualifyRunner.mockImplementation(() => new Promise(resolve => { finish = () => resolve({ ok: failure !== "probe", summary: "Could not verify this computer", details: { platformQualificationRecorded: failure !== "probe", leaseId: "lease" } }); })); const result = await renderForm([environment], { adapterType: "claude_local", defaultEnvironmentId: environment.id }); roots.push(result.root); @@ -874,7 +896,7 @@ describe("AgentConfigForm environment selector", () => { { type: "paperclip_runner", supportedRunners: ["legacy"], defaultRunner: "legacy" }, ]; mockAdaptersApi.list.mockResolvedValue(inventory(false)); - mockEnvironmentsApi.probe.mockImplementation(async () => { + mockAgentsApi.qualifyRunner.mockImplementation(async () => { mockAdaptersApi.list.mockResolvedValue(inventory(true)); return { ok: true, details: { platformQualificationRecorded: true, leaseId: "kubernetes-probe" } }; }); @@ -884,12 +906,12 @@ describe("AgentConfigForm environment selector", () => { roots.push(result.root); if (available) { await clickByText(result.container, "Upgrade runner"); - expect(mockEnvironmentsApi.probe).toHaveBeenCalledWith(kubernetes.id, "company-1"); + expect(mockAgentsApi.qualifyRunner).toHaveBeenCalledWith("agent-1", kubernetes.id, "company-1"); expect(mockAdaptersApi.list).toHaveBeenLastCalledWith({ companyId: "company-1", environmentId: kubernetes.id }); expect(result.onSave).toHaveBeenCalledWith({ runner: "paperclip" }); } else { expect(findButton(result.container, "Upgrade runner")).toBeUndefined(); - expect(mockEnvironmentsApi.probe).not.toHaveBeenCalled(); + expect(mockAgentsApi.qualifyRunner).not.toHaveBeenCalled(); } }); @@ -1023,6 +1045,7 @@ describe("AgentConfigForm environment selector", () => { beforeEach(() => { mockEnvironmentsApi.probe.mockReset(); + mockAgentsApi.qualifyRunner.mockReset(); mockAdaptersApi.list.mockReset().mockResolvedValue([{ type: "codex_local", supportedRunners: ["legacy", "paperclip"], defaultRunner: "legacy" }]); mockAgentsApi.adapterModels.mockResolvedValue([]); mockAgentsApi.detectModel.mockResolvedValue(null); diff --git a/ui/src/components/AgentConfigForm.tsx b/ui/src/components/AgentConfigForm.tsx index c8e2ceb60ca..fb5a0fc7abc 100644 --- a/ui/src/components/AgentConfigForm.tsx +++ b/ui/src/components/AgentConfigForm.tsx @@ -867,25 +867,33 @@ export function AgentConfigForm(props: AgentConfigFormProps) { // is on but no managed sandbox is available; a render must not throw, so this // resolution catches that case and resolves no login environment. The Test // mutation surfaces the same case as a fail-closed error. - const effectiveLoginEnvironmentId = useMemo(() => { - try { - return resolveAdapterTestEnvironmentId({ - agentDefaultEnvironmentId: rawCurrentDefaultEnvironmentId || null, - instanceDefaultEnvironmentId: instanceSettings?.defaultEnvironmentId ?? null, - localDefaultEnvironmentId: resolveLocalDefaultEnvironmentId(environments), - managedSandboxOnly: experimentalSettings?.enableManagedSandboxOnly === true, - managedSandboxEnvironmentId: resolveManagedSandboxEnvironmentId(environments), - // The policy hides the local environment, so an agent default that still - // points at the hidden local row names no visible environment. Pass the - // visible ids so the resolver redirects that stale local default to the - // managed sandbox instead of the hidden local id. - visibleEnvironmentIds: environments.map((environment) => environment.id), - }); - } catch { - return null; - } + const savedDefaultEnvironmentId = isCreate ? null : props.agent.defaultEnvironmentId ?? null; + const { effectiveLoginEnvironmentId, savedLoginEnvironmentId } = useMemo(() => { + const resolve = (agentDefaultEnvironmentId: string | null) => { + try { + return resolveAdapterTestEnvironmentId({ + agentDefaultEnvironmentId, + instanceDefaultEnvironmentId: instanceSettings?.defaultEnvironmentId ?? null, + localDefaultEnvironmentId: resolveLocalDefaultEnvironmentId(environments), + managedSandboxOnly: experimentalSettings?.enableManagedSandboxOnly === true, + managedSandboxEnvironmentId: resolveManagedSandboxEnvironmentId(environments), + // The policy hides the local environment, so an agent default that still + // points at the hidden local row names no visible environment. Pass the + // visible ids so the resolver redirects that stale local default to the + // managed sandbox instead of the hidden local id. + visibleEnvironmentIds: environments.map((environment) => environment.id), + }); + } catch { + return null; + } + }; + return { + effectiveLoginEnvironmentId: resolve(rawCurrentDefaultEnvironmentId || null), + savedLoginEnvironmentId: resolve(savedDefaultEnvironmentId), + }; }, [ rawCurrentDefaultEnvironmentId, + savedDefaultEnvironmentId, instanceSettings?.defaultEnvironmentId, environments, experimentalSettings?.enableManagedSandboxOnly, @@ -897,6 +905,8 @@ export function AgentConfigForm(props: AgentConfigFormProps) { const nativeRunnerAvailability = runnerDiscovery.data?.find(item => item.type === "paperclip_runner"); const upgradeEnvironment = forcedKubernetes ? kubernetesEnvironment : effectiveLoginEnvironment; const upgradeEnvironmentId = upgradeEnvironment?.id ?? null; + const upgradeEnvironmentChanged = !isCreate && !forcedKubernetes + && effectiveLoginEnvironmentId !== savedLoginEnvironmentId; const canQualifyRunnerUpgrade = upgradeEnvironment?.status === "active" && canQualifyRunnerEnvironment(upgradeEnvironment) && Boolean(runnerAvailability && !runnerAvailability.disabled && !runnerAvailability.overriddenBuiltin) @@ -913,7 +923,7 @@ export function AgentConfigForm(props: AgentConfigFormProps) { && !runnerDiscovery.isError && (runnerAvailability?.defaultRunner === "paperclip" || canQualifyRunnerUpgrade); const upgradeRunner = async () => { - if (isCreate || runnerUpgradePending) return; + if (isCreate || runnerUpgradePending || upgradeEnvironmentChanged) return; const agentId = props.agent.id; setRunnerUpgrade({ agentId, status: "pending" }); try { @@ -929,7 +939,7 @@ export function AgentConfigForm(props: AgentConfigFormProps) { const qualified = await qualifyRunnerEnvironment({ adapterType: harnessType, readAdapters: () => adaptersApi.list({ companyId: selectedCompanyId, environmentId: upgradeEnvironmentId }), - probeEnvironment: () => environmentsApi.probe(upgradeEnvironmentId, selectedCompanyId), + probeEnvironment: () => agentsApi.qualifyRunner(agentId, upgradeEnvironmentId, selectedCompanyId), isCurrent: () => upgradeTargetRef.current === pendingTarget, }); if (!qualified) throw new Error("Agent settings changed during verification. Retry the upgrade with the current settings."); @@ -1578,9 +1588,11 @@ export function AgentConfigForm(props: AgentConfigFormProps) {

The upgrade will verify your computer first. This can take a few minutes.

) : null} {upgradeWarnings.map(warning =>

{warning.message}

)} - {isDirty ?

Your unsaved changes will be included.

: null} + {upgradeEnvironmentChanged ? ( +

Save your computer change before upgrading the runner.

+ ) : isDirty ?

Your unsaved changes will be included.

: null} - From 988fe0180b966e84d19c481a752ff231eabaed07 Mon Sep 17 00:00:00 2001 From: Nicky Leach Date: Sat, 24 Oct 2026 10:54:28 -0700 Subject: [PATCH 007/110] fix(heartbeat): keep source-free project policy stable across turns (#17447) --- .../heartbeat-session-preparation.test.ts | 26 ++++++++++++++++++- server/src/services/heartbeat.ts | 2 +- 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/server/src/__tests__/heartbeat-session-preparation.test.ts b/server/src/__tests__/heartbeat-session-preparation.test.ts index 9bacb2c7fb1..784b3ff2df4 100644 --- a/server/src/__tests__/heartbeat-session-preparation.test.ts +++ b/server/src/__tests__/heartbeat-session-preparation.test.ts @@ -1,9 +1,10 @@ import { randomUUID } from "node:crypto"; import { eq } from "drizzle-orm"; import { afterAll, beforeAll, describe, expect, it } from "vitest"; -import { agents, agentTaskSessions, authUsers, companies, companyMemberships, createDb, heartbeatRuns, issues } from "@paperclipai/db"; +import { agents, agentTaskSessions, authUsers, companies, companyMemberships, createDb, heartbeatRuns, issues, plugins, projects } from "@paperclipai/db"; import { registerServerAdapter, unregisterServerAdapter, type AdapterExecutionContext } from "../adapters/index.js"; import { heartbeatService } from "../services/heartbeat.js"; +import { createPluginWorkspaceFixture } from "./helpers/plugin-workspaces.js"; import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; const support = await getEmbeddedPostgresTestSupport(); @@ -81,6 +82,29 @@ describePostgres("heartbeat session preparation through adapter dispatch", () => expect(resumed.finished.sessionIdBefore).toBe("saved-session"); }); + it("keeps inherited project policy stable after binding a repository-free workspace", 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)); + const [project] = await db.insert(projects).values({ companyId: f.companyId, name: "Directory project" }).returning(); + await db.update(issues).set({ projectId: project.id }).where(eq(issues.id, f.issueId)); + 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 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 }, + } }); + } finally { await db.delete(plugins).where(eq(plugins.id, storage.pluginId)); } + }); + 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 e6e41be53f3..543d96a97f8 100644 --- a/server/src/services/heartbeat.ts +++ b/server/src/services/heartbeat.ts @@ -2371,7 +2371,7 @@ export function heartbeatService( !boundSourceWorkspace && !taskWorkspaceIntentRow?.intent && !issueContext?.projectWorkspaceId ? taskProjectContext : null ); - const parsedProjectExecutionWorkspacePolicy = workspacePolicyContext && !boundSourceWorkspace + const parsedProjectExecutionWorkspacePolicy = workspacePolicyContext?.hasWorkspace && !boundSourceWorkspace ? await effectiveProjectWorkspacePolicy(db, agent.companyId, workspacePolicyContext.executionWorkspacePolicy, workspacePolicyContext.hasGitSource) : parseProjectExecutionWorkspacePolicy(workspacePolicyContext?.executionWorkspacePolicy); const projectExecutionWorkspacePolicy = From 410e5c6eedba98588a87e4104153898fb0437532 Mon Sep 17 00:00:00 2001 From: Nicky Leach Date: Sat, 24 Oct 2026 10:54:40 -0700 Subject: [PATCH 008/110] fix(native): use current authority for warm plugin completion (#17444) --- .../native-session-executor.test.ts | 25 ++++++++++++++++--- .../native-runtime/native-session-executor.ts | 7 +++++- 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/server/src/services/native-runtime/native-session-executor.test.ts b/server/src/services/native-runtime/native-session-executor.test.ts index 66a235cc2ba..51e0c3af818 100644 --- a/server/src/services/native-runtime/native-session-executor.test.ts +++ b/server/src/services/native-runtime/native-session-executor.test.ts @@ -1,5 +1,6 @@ import * as environmentTaskRuntime from "../environment-task-runtime.js"; import * as pluginTaskRuntime from "./plugin-runner-task.js"; +import * as completionFeedback from "./native-completion-feedback.js"; import { environmentTaskOperationSchema } from "@paperclipai/plugin-sdk"; import { trace } from "@opentelemetry/api"; import { InMemorySpanExporter, SimpleSpanProcessor, TracerProvider } from "@opentelemetry/sdk-trace"; @@ -119,6 +120,7 @@ type BackendFactoryOptions = { }; }) => unknown; dynamicToolHandler?: (call: unknown) => Promise; + completionFeedback?: (result: Parameters[2]) => Promise; onSpawn?: (meta: { pid: number; processGroupId: number | null; @@ -10521,15 +10523,32 @@ describe("runnerd provider runtime wiring", () => { await writeRunnerAuthority(root, identity, "suspended"); }) }; const nextSession = { close: vi.fn(async () => undefined) }; - const result = { result: { summary: "done" }, terminal: { runTerminalState: "succeeded" }, + const validated = validatePrpStructuredRunResult({ schema: "paperclip.run_result.v1", reportedWorkDisposition: "done", + summary: "done", completionClaim: { contractRevision: first.completionContract.contract.revision, objectiveSatisfied: true, + criteria: [], remainingWork: [] }, evidence: [], verification: [], artifacts: [], attentionRequests: [] }); + if (!validated.ok) throw new Error("Invalid completion fixture"); + const result = { result: validated.result, terminal: { runTerminalState: "succeeded" }, turnId: "turn", normalizedSessionId: first.session.normalizedSessionId, providerSessionId: "provider", driverKind: "test", driverVersion: "1", nativeEventCount: 1, highestContiguousSourceSeq: 1, usage: null }; + const feedback = vi.spyOn(completionFeedback, "nativeCompletionFeedback").mockResolvedValue("accepted"); + const firstDb = leaseDb(first); + let retainedFeedback: BackendFactoryOptions["completionFeedback"]; state.execute.mockReset().mockImplementationOnce(async options => { + retainedFeedback = state.createBackend.mock.calls.at(-1)![1].completionFeedback; await options.onSession?.(firstSession); return result; }).mockImplementationOnce(async options => { order.push("execute-next"); + if (reusable) { + await expect(retainedFeedback!(result.result)).resolves.toBe("accepted"); + expect(feedback).toHaveBeenLastCalledWith(firstDb, next.binding.runId, result.result); + expect(state.toolAuthorityDefinitions).toHaveBeenLastCalledWith(expect.objectContaining({ runId: next.binding.runId })); + feedback.mockClear(); + state.toolAuthorityDefinitions.mockRejectedValueOnce(new Error("current authority denied")); + await expect(retainedFeedback!(result.result)).rejects.toThrow("current authority denied"); + expect(feedback).not.toHaveBeenCalled(); + } expect(options.existingSession).toBe(reusable ? firstSession : undefined); await options.onSession?.(reusable ? firstSession : nextSession); return result; @@ -10542,7 +10561,7 @@ describe("runnerd provider runtime wiring", () => { ? priorNativeRunDb(scenario === "stale-owner" ? older : first, scenario === "active-owner" ? "running" : "succeeded").select(fields as never) : ordinarySelect(fields as never)) as Db["select"]; try { - await executePaperclipNativeSession({ db: leaseDb(first), execution: first, + await executePaperclipNativeSession({ db: firstDb, execution: first, runnerInstanceId: identity.runnerInstanceId, useRunnerd: true, runnerExecutionTarget: pluginTarget as never,...pluginOptions }); if (scenario === "stale-owner") await writeRunnerAuthority(root, { ...identity, runId: older.binding.runId }, "ready"); if (scenario === "missing-owner") { @@ -10598,7 +10617,7 @@ describe("runnerd provider runtime wiring", () => { } } finally { failRetirement = false; - resume?.mockRestore();owners?.mockRestore(); + resume?.mockRestore();owners?.mockRestore();feedback.mockRestore(); await closeWarmNativeSessionsForEnvironment({ environmentId, reason: "test cleanup" }); } }); diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index 61092b3ce54..fe6d4732e76 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -11916,7 +11916,12 @@ async function createRunnerdBackendWithinSessionClaim( // its host environment out of the plugin and records the prepared directory. runnerInstanceId: prior?.runnerInstanceId ?? effectiveRunnerInstanceId, environment: {}, workingDirectoryAuthority: "runner_prepared_launch", dynamicTools, dynamicToolHandler: executeTool, - completionFeedback: async result => { await authorityEpoch.definitions(); return nativeCompletionFeedback(input.db, input.execution.binding.runId, result); }, + completionFeedback: async result => { + const current = sessionToolAuthorityEpochs.get(sessionScopeId); + if (!current) throw new Error("native_session_tool_authority_unavailable"); + await current.definitions(); + return nativeCompletionFeedback(input.db, current.runId, result); + }, codexTransportFactory: recovery => createRunnerdCodexTransport({ provider: provider.kind, stateDirectory: root, ...owner.driver, runnerArtifact: description.runner, ...(provider.kind === "acpx" ? { acpxAgent: provider.agent, From 14e1f59fbf4d9cc7875ed35ebaa9e997f6e2ea7c Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Sat, 24 Oct 2026 12:07:45 -0700 Subject: [PATCH 009/110] fix(heartbeat): avoid large run reads during deferred-message recovery (#17460) ## Thinking Path > - Paperclip manages AI agents and their tasks. > - Deferred messages must survive restarts and execution cleanup. > - Periodic recovery checks the latest run before it attempts release. > - That check and two release checks load large execution records. > - These checks use only admission evidence and completion identity. > - This change selects those fields while keeping the release policy and fresh reads. > - Full execution records remain available for execution and detail reads. ## Linked Issues or Issue Description **What happened?** Deferred-message recovery repeatedly transfers stored context, Runner profiles, and output excerpts to make small admission and release decisions. **Expected behavior** Select the fields each decision consumes. Preserve queued messages, current admission checks, cleanup ownership, and fresh completion reads. **Steps to reproduce** 1. Save a terminal run with large context, profile, and output fields. 2. Leave an accepted message deferred after the issue lock is released. 3. Call `resumeQueuedRuns` and follow execution release. 4. Observe full-row reads before the admission decision. **Paperclip version or commit** Baseline: `410e5c6eedb`. Related read optimization: Refs #17405. Searched open and closed PRs for run projections and stranded-queue reads. Searched open issues for database transfer. No matching fix was found. **Deployment mode** External PostgreSQL. The regression tests use disposable real PostgreSQL. ## What Changed - Select seven admission fields for the stranded queue's latest-run lookup. - Select authentication classification evidence before execution release. - Read completion status and typed issue identifiers after post-commit effects. - Keep company scoping on both release reads. - Add large-payload and fresh-state regressions. Document the read contract. ## Verification - Focused PostgreSQL tests: 68 passed across queue, run control, and the new release-read suite. - Release reads return less than 2 KiB with three large synthetic execution fields. - Queue recovery passes less than 512 bytes to release, retaining the full stored message. - Coverage includes legacy/native owners, paused recipients, live successors, authentication repair, and fresh completion identity after post-commit effects. - Root recursive typecheck and full build pass. The full local stable suite remains in progress; no local full-suite pass is claimed. - All current-head CI checks pass on `c819fbb6b46bd5480a197407f06e02f245667792`. Greptile: **5/5, medium impact**, zero comments and zero unresolved threads on that head. - The first focused attempt found a syntax error in the new test; it was corrected before the 68-test passing run. A redundant standalone compiler was stopped while the required recursive check continued. - Hosted impact is not measured yet. Staging verification follows merge. ## Risks The projection must retain all admission evidence and preserve JSON types. The release policy still owns transactions, locks, cleanup, and promotion. There is no schema migration, polling change, message deletion, or API change. Configuration repair evidence is read directly, including when unrelated result output is large. ## Model Used OpenAI GPT-6 through Codex, with source inspection, code execution, and GitHub tools. The exact served model ID and context-window size 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 (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 --- doc/DEVELOPING.md | 7 ++ server/src/services/heartbeat/queue.test.ts | 8 ++ server/src/services/heartbeat/queue.ts | 10 ++- .../heartbeat/run-control-reads.test.ts | 87 +++++++++++++++++++ server/src/services/heartbeat/run-control.ts | 25 +++++- 5 files changed, 132 insertions(+), 5 deletions(-) create mode 100644 server/src/services/heartbeat/run-control-reads.test.ts diff --git a/doc/DEVELOPING.md b/doc/DEVELOPING.md index fd25491f0d4..a8c500a4387 100644 --- a/doc/DEVELOPING.md +++ b/doc/DEVELOPING.md @@ -2871,6 +2871,13 @@ package avatar PNGs using the API renderer; static hosting needs no API proxy. ### Investigating polling load +Deferred-message recovery reads run admission fields before calling the release +policy. The release coordinator reads authentication evidence and then refreshes +completion identity after post-commit effects. These checks do not load stored +prompts, Runner profiles, or output excerpts. Full execution and detail reads +retain those fields. Queue cadence, delivery admission, and cleanup ownership +remain unchanged. + Runtime progress updates recheck the persisted run status before publication. This check selects only the run ID, company ID, agent ID, and status through `createHeartbeatRunState().getRunStatus`. It does not fetch prompts, runner diff --git a/server/src/services/heartbeat/queue.test.ts b/server/src/services/heartbeat/queue.test.ts index 9af4a5ac956..5a31b5ee131 100644 --- a/server/src/services/heartbeat/queue.test.ts +++ b/server/src/services/heartbeat/queue.test.ts @@ -161,6 +161,9 @@ describe.skipIf(!support.supported)("heartbeat queue database wiring", () => { it.each(["legacy", "native"])("resumes an accepted non-assignee queue through its %s owner", async runtimeMode => { const { run, pending } = await strandedMention(runtimeMode); + await db.update(heartbeatRuns).set({ contextSnapshot: { ...run.contextSnapshot, prompt: "large context".repeat(20_000) }, + runnerProfileJson: { instructions: "large profile".repeat(20_000) }, stdoutExcerpt: "large output".repeat(20_000), + }).where(eq(heartbeatRuns.id, run.id)); const deps = callbacks(db); await createHeartbeatQueue(db, deps).resumeQueuedRuns(); expect(deps.releaseIssueExecutionAndPromote).toHaveBeenCalledExactlyOnceWith( @@ -170,6 +173,11 @@ describe.skipIf(!support.supported)("heartbeat queue database wiring", () => { status: "deferred_issue_execution", runId: null, payload: pending.payload, }); expect(deps.executeRun).not.toHaveBeenCalled(); + const selected = deps.releaseIssueExecutionAndPromote.mock.calls[0][0]; + expect(Buffer.byteLength(JSON.stringify(selected))).toBeLessThan(512); + expect(selected).not.toHaveProperty("contextSnapshot"); + expect(selected).not.toHaveProperty("runnerProfileJson"); + expect(selected).not.toHaveProperty("stdoutExcerpt"); }); it("preserves a former owner's ordinary messages for the assignment handoff", async () => { diff --git a/server/src/services/heartbeat/queue.ts b/server/src/services/heartbeat/queue.ts index c6ac63b6a53..515bd683fb3 100644 --- a/server/src/services/heartbeat/queue.ts +++ b/server/src/services/heartbeat/queue.ts @@ -1837,7 +1837,15 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende for (const { wake } of strandedQueues) { if (!queuedCommentIdsFromWakePayload(wake.payload).length && !await readQueuedInteractionResponse(db, wake.companyId, String(wake.payload?.issueId), wake.payload)) continue; - const [latest] = await db.select().from(heartbeatRuns).where(and( + const [latest] = await db.select({ + id: heartbeatRuns.id, + companyId: heartbeatRuns.companyId, + status: heartbeatRuns.status, + finishedAt: heartbeatRuns.finishedAt, + startedAt: heartbeatRuns.startedAt, + runtimeMode: heartbeatRuns.runtimeMode, + errorCode: heartbeatRuns.errorCode, + }).from(heartbeatRuns).where(and( eq(heartbeatRuns.companyId, wake.companyId), sql`${heartbeatRuns.contextSnapshot}->>'issueId' = ${String(wake.payload?.issueId)}`, or(isNull(heartbeatRuns.nativeIssueId), sql`${heartbeatRuns.nativeIssueId}::text = ${String(wake.payload?.issueId)}`), diff --git a/server/src/services/heartbeat/run-control-reads.test.ts b/server/src/services/heartbeat/run-control-reads.test.ts new file mode 100644 index 00000000000..eb0248cc46d --- /dev/null +++ b/server/src/services/heartbeat/run-control-reads.test.ts @@ -0,0 +1,87 @@ +import { randomBytes } from "node:crypto"; +import type { Db } from "@paperclipai/db"; +import { heartbeatRuns, issues } from "@paperclipai/db"; +import { eq } from "drizzle-orm"; +import { describe, expect, it, vi } from "vitest"; +import { isAiAuthenticationBlocked } from "../ai-auth-failure.js"; +import { settleSlackConversation } from "../slack-conversation-lifecycle.js"; +import { createHeartbeatRunControl } from "./run-control.js"; +import { callbacks, runControlPostgresSupport, setupRunControlDatabase } from "./__tests__/run-control-fixtures.js"; + +vi.mock("../local-service-supervisor.js", async importOriginal => ({ + ...await importOriginal(), + terminateLocalService: vi.fn(async () => undefined), +})); +vi.mock("../slack-conversation-lifecycle.js", () => ({ settleSlackConversation: vi.fn(async () => undefined) })); + +describe.skipIf(!runControlPostgresSupport.supported)("execution release reads", () => { + let db: Db; + const { fixture } = setupRunControlDatabase("heartbeat-release-reads-", value => { db = value; }); + + function recordRunReads() { + const reads: unknown[][] = []; + const database = new Proxy(db, { get(target, key) { + if (key !== "select") return Reflect.get(target, key); + return (...fields: Parameters) => { + const builder = target.select(...fields); + const from = builder.from.bind(builder); + builder.from = ((...args: Parameters) => { + const query = from(...args); + if (args[0] === heartbeatRuns) { + const execute = query.execute.bind(query); + query.execute = async (...executeArgs: Parameters) => { + const rows = await execute(...executeArgs); + reads.push(rows); + return rows; + }; + } + return query; + }) as typeof builder.from; + return builder; + }; + }}); + return { database, reads }; + } + + it.each([ + { errorCode: "codex_auth_required", livenessState: "blocked", resultJson: null }, + { errorCode: "codex_auth_required", livenessState: "advanced", resultJson: null }, + { errorCode: "configuration_incomplete", livenessState: "blocked", resultJson: { configurationIncomplete: { reason: "ai_connection_unavailable" } } }, + { errorCode: "configuration_incomplete", livenessState: "blocked", resultJson: { configurationIncomplete: { reason: "secret_binding_missing", agentId: "owner", missingBindings: [{ bindingType: "user_secret_ref", consumerType: "agent", consumerId: "owner", errorCode: "user_secret_missing", envKey: "OPENAI_API_KEY", configPath: "env.OPENAI_API_KEY" }] } } }, + { errorCode: "configuration_incomplete", livenessState: "blocked", resultJson: { configurationIncomplete: { reason: "workspace_unavailable" } } }, + ])("preserves authentication admission for %j without loading execution payloads", async failure => { + const { company, agent } = await fixture(); + const payload = randomBytes(128 * 1024).toString("base64"); + const [run] = await db.insert(heartbeatRuns).values({ companyId: company.id, agentId: agent.id, + status: "failed", ...failure, contextSnapshot: { prompt: payload }, runnerProfileJson: { prompt: payload }, stdoutExcerpt: payload, + }).returning(); + const { database, reads } = recordRunReads(); + const deps = callbacks(database); + await createHeartbeatRunControl(database, deps).releaseIssueExecutionAndPromote(run); + expect(deps.wakeQueue.releaseIssueExecution).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ + companyId: company.id, runId: run.id, suppressImmediateRecovery: isAiAuthenticationBlocked(run), + })); + expect(deps.getRun).not.toHaveBeenCalled(); + expect(reads).toHaveLength(2); + expect(Buffer.byteLength(JSON.stringify(reads))).toBeLessThan(2048); + const [stored] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, run.id)); + expect(stored).toEqual(run); + }); + + it("reads the completed identity after post-commit effects and preserves the full record", async () => { + const { company, agent } = await fixture(); + const [issue] = await db.insert(issues).values({ companyId: company.id, title: "Release destination" }).returning(); + const [run] = await db.insert(heartbeatRuns).values({ companyId: company.id, agentId: agent.id, + status: "running", contextSnapshot: { issueId: 42, taskId: "", prompt: "retained" }, + }).returning(); + const deps = callbacks(db); + vi.spyOn(deps, "applyWakeQueuePostCommitEffects").mockImplementationOnce(async () => { + await db.update(heartbeatRuns).set({ status: "succeeded", contextSnapshot: { issueId: 42, taskId: issue.id, prompt: "retained" } }).where(eq(heartbeatRuns.id, run.id)); + }); + vi.mocked(settleSlackConversation).mockClear(); + await createHeartbeatRunControl(db, deps).releaseIssueExecutionAndPromote(run, { resumeStrandedQueue: true }); + expect(settleSlackConversation).toHaveBeenCalledExactlyOnceWith(db, company.id, issue.id); + expect(deps.wakeQueue.releaseIssueExecution).toHaveBeenCalledWith(expect.objectContaining({ resumeStrandedQueue: true })); + expect(deps.getRun).not.toHaveBeenCalled(); + }); +}); diff --git a/server/src/services/heartbeat/run-control.ts b/server/src/services/heartbeat/run-control.ts index e9b21a98aa3..7f80f99321a 100644 --- a/server/src/services/heartbeat/run-control.ts +++ b/server/src/services/heartbeat/run-control.ts @@ -815,7 +815,15 @@ export function createHeartbeatRunControl(db: Db, dependencies: HeartbeatRunCont options: { suppressImmediateRecovery?: boolean; resumeStrandedQueue?: boolean; deferredPostCommitEffects?: WakeQueuePostCommitEffect[] } = {}, ) { try { - const source = await getRun(run.id); + const [source] = await db.select({ + errorCode: heartbeatRuns.errorCode, + livenessState: heartbeatRuns.livenessState, + resultJson: sql>`jsonb_build_object( + 'configurationIncomplete', ${heartbeatRuns.resultJson}->'configurationIncomplete' + )`, + }).from(heartbeatRuns).where(and( + eq(heartbeatRuns.id, run.id), eq(heartbeatRuns.companyId, run.companyId), + )); const sourceHandoff = await pendingCaseHandoffForRun(db, run.id, run.companyId); const { postCommitEffects } = await wakeQueue.releaseIssueExecution({ companyId: run.companyId, @@ -831,9 +839,18 @@ export function createHeartbeatRunControl(db: Db, dependencies: HeartbeatRunCont } else { await applyWakeQueuePostCommitEffects(postCommitEffects); } - const completed = await getRun(run.id); - const issueId = readNonEmptyString(completed?.contextSnapshot?.issueId) - ?? readNonEmptyString(completed?.contextSnapshot?.taskId) ?? completed?.nativeIssueId; + const [completed] = await db.select({ + id: heartbeatRuns.id, + status: heartbeatRuns.status, + startedAt: heartbeatRuns.startedAt, + nativeIssueId: heartbeatRuns.nativeIssueId, + contextIssueId: sql`${heartbeatRuns.contextSnapshot}->'issueId'`, + contextTaskId: sql`${heartbeatRuns.contextSnapshot}->'taskId'`, + }).from(heartbeatRuns).where(and( + eq(heartbeatRuns.id, run.id), eq(heartbeatRuns.companyId, run.companyId), + )); + const issueId = readNonEmptyString(completed?.contextIssueId) + ?? readNonEmptyString(completed?.contextTaskId) ?? completed?.nativeIssueId; if (sourceHandoff && completed?.status === "cancelled" && !completed.startedAt && issueId) { // A cancelled queue entry has no executeRun.finally. The canonical // bootstrap proof still needs to release and wake its durable handoff. From 60ca3a903aa705baf2a585b8c63e4735fdc8fda4 Mon Sep 17 00:00:00 2001 From: Nicky Leach Date: Sat, 24 Oct 2026 12:11:26 -0700 Subject: [PATCH 010/110] Keep warm sessions across project revision transitions (#17461) --- doc/DEVELOPING.md | 5 ++ .../heartbeat-workspace-session.test.ts | 51 +++++++++++++++++++ server/src/services/heartbeat/workspaces.ts | 1 + 3 files changed, 57 insertions(+) diff --git a/doc/DEVELOPING.md b/doc/DEVELOPING.md index a8c500a4387..0e44d7feb81 100644 --- a/doc/DEVELOPING.md +++ b/doc/DEVELOPING.md @@ -1776,6 +1776,11 @@ preparation. Both phases keep their original ordering in `heartbeat.ts`; they acquire no runtime resources. Public-path characterization tests live in `server/src/__tests__/heartbeat-session-preparation.test.ts`. +Session compatibility uses effective workspace policy and settings. Generic issue +and project row timestamps do not reset a session. This includes the first +project-owned directory binding. Changes to effective execution configuration +still require a fresh session. + Run-log formatting is in `server/src/services/heartbeat/run-log.ts`. It bounds stored event payloads, redacts and shortens log chunks, and caps stdout/stderr excerpts. `run-output.ts` owns per-attempt log handles, current-user redaction, diff --git a/server/src/__tests__/heartbeat-workspace-session.test.ts b/server/src/__tests__/heartbeat-workspace-session.test.ts index 5df8621bbb6..154a7ff0600 100644 --- a/server/src/__tests__/heartbeat-workspace-session.test.ts +++ b/server/src/__tests__/heartbeat-workspace-session.test.ts @@ -2427,6 +2427,57 @@ describe("effective run session config freshness", () => { }); }); + it.each([null, "2026-06-01T00:00:00.000Z"])("does not reset for project row timestamps (%s) but still resets for project policy", async (revision) => { + const base = await buildSessionConfigMetadata({ + workspaceConfig: { + requestedMode: "agent_default", + effectiveMode: "agent_default", + projectConfigRevisionAt: revision, + projectPolicy: null, + }, + }); + const projectTouched = await buildSessionConfigMetadata({ + workspaceConfig: { + requestedMode: "agent_default", + effectiveMode: "agent_default", + projectConfigRevisionAt: "2026-06-01T00:05:00.000Z", + projectPolicy: null, + }, + }); + const policyChanged = await buildSessionConfigMetadata({ + workspaceConfig: { + requestedMode: "agent_default", + effectiveMode: "agent_default", + projectConfigRevisionAt: "2026-06-01T00:05:00.000Z", + projectPolicy: { enabled: true, defaultMode: "isolated_workspace" }, + }, + }); + + expect( + resolveTaskSessionConfigFreshness({ + hasTaskSession: true, + configuredModel: "gpt-5.4-mini", + taskSessionParams: sessionParamsWithConfigMetadata(base), + configMetadata: projectTouched, + }), + ).toMatchObject({ + reset: false, + changedCategories: [], + reasons: [], + }); + expect( + resolveTaskSessionConfigFreshness({ + hasTaskSession: true, + configuredModel: "gpt-5.4-mini", + taskSessionParams: sessionParamsWithConfigMetadata(base), + configMetadata: policyChanged, + }), + ).toMatchObject({ + reset: true, + changedCategories: ["workspaceConfig"], + }); + }); + it("does not reset when a reusable execution workspace becomes realized", async () => { const base = await buildSessionConfigMetadata({ workspaceConfig: { diff --git a/server/src/services/heartbeat/workspaces.ts b/server/src/services/heartbeat/workspaces.ts index c607e2426e3..6b036657a8c 100644 --- a/server/src/services/heartbeat/workspaces.ts +++ b/server/src/services/heartbeat/workspaces.ts @@ -2800,6 +2800,7 @@ function buildSessionConfigCategoryValues(input: { // the timestamp here makes every comment invalidate an otherwise reusable // task session. delete workspaceConfig.issueConfigRevisionAt; + delete workspaceConfig.projectConfigRevisionAt; // This row is runtime state, not requested configuration. It is absent // before the first reusable run is realized and present on the next turn; // fingerprinting that transition would rotate the native session exactly From 7bd449dbb66473ccb3fc9965186eed495d7cc623 Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Sat, 24 Oct 2026 12:14:41 -0700 Subject: [PATCH 011/110] fix(recovery): project context evidence for latest-run checks (#17463) ## Thinking Path > - Paperclip manages AI agents and their tasks. > - Recovery sweeps decide whether tasks have a valid next step. > - Those decisions inspect saved run metadata. > - Latest-run queries also return full prompts and execution setup data. > - This repeats large responses when a sweep leaves a task unchanged. > - This change projects the context evidence recovery actually reads. > - A row-version check keeps stale evidence from changing a task. ## Linked Issues or Issue Description **What happened?** The latest-run recovery queries retrieve large stored contexts for each candidate. The decision usually consumes small recovery, message, or workspace-mode fields. **Expected behavior** Keep all decision evidence while selecting a small response. Preserve complete stored contexts and full execution reads. Detect concurrent source changes. **Steps to reproduce** 1. Store a terminal run with large task Markdown, wake, workspace, and continuation bodies. 2. Call `reconcileStrandedAssignedIssues` for its assigned task. 3. Observe the full context returned by the latest-run query on each sweep. **Paperclip version or commit** Baseline: `410e5c6eedba98588a87e4104153898fb0437532`. Related read optimization: Refs #17405. Complementary fix: Refs #17460. These PRs have no code dependency. Searched existing PRs and issues for run projections, recovery reads, and database transfer. No duplicate was found. **Deployment mode** External PostgreSQL. Verification uses disposable real PostgreSQL and synthetic data. ## What Changed - Project typed context evidence in all three latest-run recovery queries. - Keep only the used workspace mode and external-interaction flag from nested setup objects. - Preserve original JSON types, message references, retry evidence, and existing query scopes and order. - Read PostgreSQL `xmin` with the run. Require the same row version during native blocked-wait repair. - Retain the original full-context comparison for callers that supply a full run without a row version. - Test large payloads, malformed JSON shapes, review-message recovery, and concurrent source edits. ## Verification - Final-source integration checks: **450 passed** across context projections, native finalization recovery, and the assembled heartbeat recovery service. - Focused issue-lock race check: **9 passed** (401 outside the filter), including omitted-context and late-output edits and successful repair on a fresh sweep. - Final-source recursive typecheck and full build pass. The full local stable suite is still running; current-head CI must also pass before merge. - Real-service SQL capture against the baseline: one returned row falls from 699,724 to 573 serialized JSON bytes (99.918% smaller). - The fixture uses four 174,764-byte incompressible execution fields. All unaffected returned columns compare equal. Regression tests check the retained decision evidence and unchanged stored records. - Five alternating warm samples after two warmups: baseline median 1.479 ms, treatment 1.084 ms. Ranges overlap; no request-latency speedup is claimed. Plans were captured outside the timing interval. - An initial full-context hash projection cut bytes but raised the local median to 7.457 ms. The final row-version check removes that cost. - One integration run overlapped the hash-export rename and failed seven tests on the removed export. A fresh final-source run passed all 450 tests. The earlier mixed-source failure remains recorded and is not counted as a pass. - All current-head CI checks pass on `17add20e391c30ed0496f4b39eb9c59779efa6b4`. Greptile: **5/5, medium impact**, no findings or unresolved threads on that head. - Hosted transfer and product behavior remain to be verified on staging after merge. ## Risks The context selection must track its recovery consumers. Tests preserve typed flags, retry budgets, external-chat references, and malformed-input behavior. The row-version guard is conservative: any intervening run update defers native blocker repair to a fresh sweep. Concurrent omitted-context and output edits are covered through the real service and issue-lock wait; a fresh sweep must still repair. There is no migration, prompt truncation, history deletion, or authorization cache. ## Model Used OpenAI GPT-6 through Codex, with source inspection, code execution, and GitHub tools. The exact served model ID and context-window size 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 (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 --- doc/DATABASE.md | 7 ++ .../heartbeat-process-recovery.test.ts | 12 +++ .../recovery/run-context-read.test.ts | 84 +++++++++++++++++++ .../src/services/recovery/run-context-read.ts | 28 +++++++ server/src/services/recovery/service.ts | 22 +++-- 5 files changed, 147 insertions(+), 6 deletions(-) create mode 100644 server/src/services/recovery/run-context-read.test.ts create mode 100644 server/src/services/recovery/run-context-read.ts diff --git a/doc/DATABASE.md b/doc/DATABASE.md index 2698c899e51..3ab9490ee1f 100644 --- a/doc/DATABASE.md +++ b/doc/DATABASE.md @@ -49,6 +49,13 @@ and leaves all existing cases passive. Source identities are not grants. ### Task query performance +Recovery's latest-run queries return the context fields used by recovery +decisions. Prompts, execution continuation bodies, and workspace setup payloads +remain in the stored run and its full detail reads. These queries also return +the PostgreSQL row version. Native blocked-wait repair compares that version +against a fresh full source read before applying changes. Any intervening row +update, including an edit outside the projection, defers repair to a fresh sweep. + Run-context lookups use expression indexes for both `context_snapshot.issueId` and `context_snapshot.paperclipIssue.id`. Task creation provenance has its own company-scoped expression index that follows the query's native issue ID and diff --git a/server/src/__tests__/heartbeat-process-recovery.test.ts b/server/src/__tests__/heartbeat-process-recovery.test.ts index 3af86f73e77..ca2576a5b59 100644 --- a/server/src/__tests__/heartbeat-process-recovery.test.ts +++ b/server/src/__tests__/heartbeat-process-recovery.test.ts @@ -15676,6 +15676,8 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => { "comment", "wake", "run", + "run_context", + "run_metadata", "attention", ] as const)( "does not clobber a newer %s while native blocker repair waits on the issue lock", @@ -15750,6 +15752,12 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => { continuationPolicy: "wake_assignee", payload: { version: 1, questions: [] }, }); + if (change === "run_context") + await tx.update(heartbeatRuns).set({ + contextSnapshot: sql`jsonb_set(${heartbeatRuns.contextSnapshot}, '{paperclipTaskMarkdown}', '"Changed execution instructions"'::jsonb)`, + }).where(eq(heartbeatRuns.id, runId)); + if (change === "run_metadata") + await tx.update(heartbeatRuns).set({ stdoutExcerpt: "Late execution output" }).where(eq(heartbeatRuns.id, runId)); [snapshot] = await tx .select() .from(issues) @@ -15793,6 +15801,10 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => { ), ).toHaveLength(0); expect(mockAdapterExecute).not.toHaveBeenCalled(); + if (change === "run_context" || change === "run_metadata") { + expect((await heartbeat.reconcileStrandedAssignedIssues()).escalated).toBe(1); + expect(mockAdapterExecute).not.toHaveBeenCalled(); + } }, ); diff --git a/server/src/services/recovery/run-context-read.test.ts b/server/src/services/recovery/run-context-read.test.ts new file mode 100644 index 00000000000..682aea7ab96 --- /dev/null +++ b/server/src/services/recovery/run-context-read.test.ts @@ -0,0 +1,84 @@ +import { randomBytes, randomUUID } from "node:crypto"; +import { agents, companies, createDb, heartbeatRuns } from "@paperclipai/db"; +import { eq } from "drizzle-orm"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embedded-postgres.js"; +import { isExternalChatPresentationContext } from "../heartbeat-run-summary.js"; +import { legacyDispositionEpisode } from "./legacy-continuation.js"; +import { decideIssueReviewPathRecovery } from "./review-path-recovery.js"; +import { recoveryRunContextColumn, recoveryRunVersionColumn } from "./run-context-read.js"; + +const support = await getEmbeddedPostgresTestSupport(); + +describe.skipIf(!support.supported)("recovery context PostgreSQL projection", () => { + let database: Awaited>; + let db: ReturnType; + let companyId: string; + let agentId: string; + beforeAll(async () => { + database = await startEmbeddedPostgresTestDatabase("recovery-context-read-"); + db = createDb(database.connectionString); + const [company] = await db.insert(companies).values({ name: "Recovery fixture", issuePrefix: "RC" }).returning(); + const [agent] = await db.insert(agents).values({ companyId: company.id, name: "Recovery agent", adapterType: "process" }).returning(); + companyId = company.id; + agentId = agent.id; + }, 60_000); + afterAll(async () => { + await db?.$client.end(); + await database?.cleanup(); + }); + + async function read(contextSnapshot: unknown) { + const [run] = await db.insert(heartbeatRuns).values({ companyId, agentId, contextSnapshot: contextSnapshot as Record | null }).returning(); + const [selected] = await db.select({ context: recoveryRunContextColumn, version: recoveryRunVersionColumn }) + .from(heartbeatRuns).where(eq(heartbeatRuns.id, run.id)); + return { run, selected }; + } + + it("retains typed recovery evidence while excluding large execution data", async () => { + const issueId = randomUUID(); + const payload = randomBytes(128 * 1024).toString("base64"); + const evidence = { + issueId, taskId: issueId, retryReason: "issue_continuation_needed", source: "chat:slack", + wakeReason: "assignment", handoffReason: "successful_run_missing_state", handoffRequired: true, + handoffAttempt: 2, maxHandoffAttempts: 3, sourceRunId: randomUUID(), resumeFromRunId: randomUUID(), + missingDisposition: "clear_next_step", providerQuotaRetryNotBefore: "2099-01-01T00:00:00Z", + transientRetryNotBefore: "2099-01-02T00:00:00Z", dispositionRepairAttempt: 2, + dispositionRepairFingerprint: "fingerprint", legacyDispositionEpisode: { id: "episode", attempt: 1, maxAttempts: 2 }, + reviewPathRecoveryAttempt: 1, reviewPathConsumedRef: "reference", interactionId: randomUUID(), + approvalId: randomUUID(), clearReason: "resolved", monitorAttemptCount: 4, + wakeCommentIds: [randomUUID(), randomUUID()], wakeCommentId: randomUUID(), commentId: randomUUID(), + externalChatContinuation: true, + }; + const context = { ...evidence, paperclipWake: { externalInteractionContinuation: true, prompt: payload }, + paperclipWorkspace: { mode: "shared_workspace", instructions: payload }, executionContinuation: { prompt: payload }, paperclipTaskMarkdown: payload }; + const { run, selected } = await read(context); + expect(selected.context).toEqual({ ...evidence, paperclipWake: { externalInteractionContinuation: true }, paperclipWorkspace: { mode: "shared_workspace" } }); + expect(Buffer.byteLength(JSON.stringify(selected))).toBeLessThan(4096); + expect(isExternalChatPresentationContext(selected.context)).toBe(isExternalChatPresentationContext(context)); + expect(legacyDispositionEpisode({ ...run, contextSnapshot: selected.context })).toEqual(legacyDispositionEpisode(run)); + const [stored] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, run.id)); + expect(stored.contextSnapshot).toEqual(context); + const [serialized] = await db.$client.unsafe("SELECT xmin::text AS version FROM heartbeat_runs WHERE id = $1", [run.id]); + expect(selected.version).toBe(serialized.version); + await db.update(heartbeatRuns).set({ contextSnapshot: { ...context, paperclipTaskMarkdown: "changed" } }).where(eq(heartbeatRuns.id, run.id)); + const [changed] = await db.select({ context: recoveryRunContextColumn, version: recoveryRunVersionColumn }).from(heartbeatRuns).where(eq(heartbeatRuns.id, run.id)); + expect(changed.context).toEqual(selected.context); + expect(changed.version).not.toBe(selected.version); + }); + + it.each([null, [], ["unexpected"], "scalar", 42, { issueId: 42, taskId: false, paperclipWake: [], paperclipWorkspace: null }].map(context => ({ context })))("preserves decisions for malformed context $context", async ({ context }) => { + const { selected } = await read(context); + expect(isExternalChatPresentationContext(selected.context)).toBe(isExternalChatPresentationContext(context)); + expect(legacyDispositionEpisode({ id: "run", contextSnapshot: selected.context })).toEqual(legacyDispositionEpisode({ id: "run", contextSnapshot: context })); + }); + + it("retains external-chat review recovery message references and monitor identity", async () => { + const context = { source: "chat:slack", wakeReason: "issue_monitor_fired", clearReason: "fired", monitorAttemptCount: 3, + wakeCommentIds: [randomUUID(), randomUUID()], prompt: randomBytes(64 * 1024).toString("base64") }; + const { selected } = await read(context); + const input = { issueId: randomUUID(), sourceRunId: randomUUID(), assigneeAgentId: agentId, reviewAttention: { state: "stalled" } as Parameters[0]["reviewAttention"], existingWake: false }; + expect(decideIssueReviewPathRecovery({ ...input, contextSnapshot: selected.context })) + .toEqual(decideIssueReviewPathRecovery({ ...input, contextSnapshot: context })); + }); +}); diff --git a/server/src/services/recovery/run-context-read.ts b/server/src/services/recovery/run-context-read.ts new file mode 100644 index 00000000000..b453aa79d09 --- /dev/null +++ b/server/src/services/recovery/run-context-read.ts @@ -0,0 +1,28 @@ +import { heartbeatRuns } from "@paperclipai/db"; +import { sql } from "drizzle-orm"; + +const recoveryContextKeys = [ + "issueId", "taskId", "retryReason", "source", "wakeReason", + "handoffReason", "handoffRequired", "handoffAttempt", "maxHandoffAttempts", + "sourceRunId", "resumeFromRunId", "missingDisposition", + "providerQuotaRetryNotBefore", "transientRetryNotBefore", + "dispositionRepairAttempt", "dispositionRepairFingerprint", "legacyDispositionEpisode", + "reviewPathRecoveryAttempt", "reviewPathConsumedRef", "interactionId", "approvalId", + "clearReason", "monitorAttemptCount", "wakeCommentIds", "wakeCommentId", "commentId", + "externalChatContinuation", "paperclipWake", "paperclipWorkspace", +] as const; + +export const recoveryRunContextColumn = sql | null>` + case when ${heartbeatRuns.contextSnapshot} is null then null else ( + select coalesce(jsonb_object_agg(field.key, case field.key + when 'paperclipWake' then jsonb_build_object( + 'externalInteractionContinuation', field.value->'externalInteractionContinuation') + when 'paperclipWorkspace' then jsonb_build_object('mode', field.value->'mode') + else field.value end), '{}'::jsonb) + from jsonb_each(case when jsonb_typeof(${heartbeatRuns.contextSnapshot}) = 'object' + then ${heartbeatRuns.contextSnapshot} else '{}'::jsonb end) as field(key, value) + where field.key in (${sql.join(recoveryContextKeys.map(key => sql`${key}`), sql`, `)}) + ) end +`; + +export const recoveryRunVersionColumn = sql`${heartbeatRuns}.xmin::text`; diff --git a/server/src/services/recovery/service.ts b/server/src/services/recovery/service.ts index 42765bb3606..e517b69ec69 100644 --- a/server/src/services/recovery/service.ts +++ b/server/src/services/recovery/service.ts @@ -1,3 +1,4 @@ +import { recoveryRunContextColumn, recoveryRunVersionColumn } from "./run-context-read.js"; import { isAgentAwaitingSetup } from "../../modules/agent-lifecycle/index.js"; import { onboardingFirstTaskAwaitingUserSql } from "./onboarding-first-task-wait.js"; import { isAiAuthenticationBlocked } from "../ai-auth-failure.js"; @@ -25,6 +26,7 @@ import { desc, eq, gt, + getTableColumns, gte, inArray, isNotNull, @@ -247,6 +249,7 @@ type LatestIssueRun = | "createdAt" > & { resultJson?: unknown; + rowVersion?: string; }) | null; type SuccessfulLatestIssueRun = NonNullable & { @@ -977,7 +980,8 @@ export function recoveryService( status: heartbeatRuns.status, error: heartbeatRuns.error, errorCode: heartbeatRuns.errorCode, - contextSnapshot: heartbeatRuns.contextSnapshot, + contextSnapshot: recoveryRunContextColumn, + rowVersion: recoveryRunVersionColumn, livenessState: heartbeatRuns.livenessState, resultJson: heartbeatRuns.resultJson, startedAt: heartbeatRuns.startedAt, @@ -1007,7 +1011,8 @@ export function recoveryService( status: heartbeatRuns.status, error: heartbeatRuns.error, errorCode: heartbeatRuns.errorCode, - contextSnapshot: heartbeatRuns.contextSnapshot, + contextSnapshot: recoveryRunContextColumn, + rowVersion: recoveryRunVersionColumn, livenessState: heartbeatRuns.livenessState, resultJson: heartbeatRuns.resultJson, startedAt: heartbeatRuns.startedAt, @@ -1618,7 +1623,10 @@ export function recoveryService( return false; const source = await tx - .select() + .select({ + ...getTableColumns(heartbeatRuns), + rowVersion: recoveryRunVersionColumn, + }) .from(heartbeatRuns) .where( and( @@ -1634,8 +1642,9 @@ export function recoveryService( source.id !== latestRun.id || source.agentId !== current.assigneeAgentId || source.status !== "succeeded" || - JSON.stringify(source.contextSnapshot) !== - JSON.stringify(latestRun.contextSnapshot) + (latestRun.rowVersion !== undefined + ? source.rowVersion !== latestRun.rowVersion + : JSON.stringify(source.contextSnapshot) !== JSON.stringify(latestRun.contextSnapshot)) ) return false; const proof = await nativeBlockedUnblockAction( @@ -1903,7 +1912,8 @@ export function recoveryService( status: heartbeatRuns.status, error: heartbeatRuns.error, errorCode: heartbeatRuns.errorCode, - contextSnapshot: heartbeatRuns.contextSnapshot, + contextSnapshot: recoveryRunContextColumn, + rowVersion: recoveryRunVersionColumn, livenessState: heartbeatRuns.livenessState, resultJson: heartbeatRuns.resultJson, startedAt: heartbeatRuns.startedAt, From 6d46851920e2858d0f636a3dcbd7d5f0b6a464f8 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sat, 24 Oct 2026 12:16:26 -0700 Subject: [PATCH 012/110] test(e2e): add attended GitHub review bot journey (#17457) ## Thinking Path > - Paperclip manages agents and the work they perform. > - Product E2E checks verify real user paths through those agents. > - A recorded GitHub review-bot walkthrough had no repeatable registered case. > - App setup, automatic triggering, publication, and task completion need separate evidence. > - This pull request adds an explicit attended journey to the existing catalog and report tools. > - Reusable setup profiles and independent assertions preserve the same outcome across compatible targets. ## Linked Issues or Issue Description Refs: #17262. This case remains an explicit attended attached-target flow. It does not replace the shared deployment-target or paid-operations framework. **What existing behavior does this improve?** The Product E2E catalog can now select and retain evidence for GitHub review-bot setup and its first automatic review. **Current behavior** Recorded walkthroughs cannot be rerun as a fixed registered case. A published review alone can hide a failed run or unfinished task. **Proposed behavior** Create and install an owned App, save automatic new-PR settings, create a defective PR, and require correlated review delivery, an inline finding, a consistent check, a successful run, and a Done task. Retain failures and confirm owned-resource cleanup. **Reason and benefit** The case makes a useful external integration reproducible without treating setup, unit checks, or report rendering as proof of a completed live journey. ## What Changed - Add two explicit attended cells for an existing configured agent in local or Daytona execution. - Declare hosting, account, connection, and credential prerequisites through private setup bindings. - Add fixed browser controls, ownership checks, independent grading, and cleanup. - Package declared screenshots through the existing sanitizer, manifest, validator, and dashboard. - Reject operations-managed execution until budgeted routing is qualified. - Document hosted QA credential setup and evidence limits. ## Verification - Focused catalog, oracle, report, connection, and ownership checks: 127 tests passed. - Inherited-environment preflight regression failed against the previous commit and passed after the fix. Actual-run environment verification remains required. - Harness TypeScript check and full workspace typecheck passed. Full build passed. The local full-test attempt was interrupted after repeated embedded PostgreSQL startup failures; its exit code of zero does not establish a pass; Exact-head Linux CI passed the full test, typecheck, build, Runner, serialized, browser, and canary gates on `abbddeade848edefc8de75f11cc9008b2cd52764`. - A real hosted attempt published a rated review and inline finding. It failed when its native session timed out before the task reached Done. Cleanup passed. Full live qualification remains open. - Credential scan found no known credential values in the authored files or retained report corpus. ## Risks - The full case creates external test resources and uses the configured provider. It requires an explicit selection and current task authority. It is excluded from default and CI matrices. - Time and run limits are not a hard dollar cap. Missing dollar cost stays unknown. Fixture setup does not weaken budget policy. - Fresh personal OAuth, unattended authentication, runtime skill-read proof, and cross-host qualification are separate claims. - The selected live fixture needs environment/lifecycle recovery before it can adopt a longer provider deadline. ## Model Used OpenAI GPT-6 family through Codex, with reasoning, code execution, and browser tools. The exact deployment model ID and context-window size 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, including the available 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 described the issue in-PR following the enhancement template - [x] I have not referenced internal or instance-local Paperclip issues or links - [x] My branch name describes the change and contains no internal ticket ID - [x] I have run focused tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation - [x] I have considered and documented risks - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open findings - [x] I will address all Greptile and reviewer comments before merge --------- Co-authored-by: Paperclip --- .agents/skills/verify-paperclip/SKILL.md | 8 + .../references/hosted-qa-accounts.md | 128 ++++++++ doc/evals.md | 7 + tests/runner-e2e/GITHUB-REVIEW-JOURNEY.md | 120 +++++++ tests/runner-e2e/README.md | 4 + tests/runner-e2e/catalog.test.ts | 10 +- tests/runner-e2e/catalog.ts | 6 +- tests/runner-e2e/connection-launch.ts | 2 +- tests/runner-e2e/connection-target.ts | 8 +- tests/runner-e2e/github-review-attendance.ts | 31 ++ tests/runner-e2e/github-review-browser.ts | 181 ++++++++++ tests/runner-e2e/github-review-cases.ts | 23 ++ tests/runner-e2e/github-review-config.ts | 69 ++++ tests/runner-e2e/github-review-evidence.ts | 104 ++++++ tests/runner-e2e/github-review-flow.ts | 236 +++++++++++++ .../runner-e2e/github-review-journey.test.ts | 309 ++++++++++++++++++ tests/runner-e2e/github-review-launch.ts | 271 +++++++++++++++ tests/runner-e2e/github-review-ownership.ts | 43 +++ tests/runner-e2e/github-review-report.test.ts | 51 +++ tests/runner-e2e/github-review-report.ts | 62 ++++ tests/runner-e2e/journey-dependencies.ts | 62 ++++ tests/runner-e2e/launch.ts | 7 + tests/runner-e2e/result-validation.ts | 13 + tests/runner-e2e/selectors.ts | 9 +- tests/runner-e2e/types.ts | 2 + 25 files changed, 1754 insertions(+), 12 deletions(-) create mode 100644 .agents/skills/verify-paperclip/references/hosted-qa-accounts.md create mode 100644 tests/runner-e2e/GITHUB-REVIEW-JOURNEY.md create mode 100644 tests/runner-e2e/github-review-attendance.ts create mode 100644 tests/runner-e2e/github-review-browser.ts create mode 100644 tests/runner-e2e/github-review-cases.ts create mode 100644 tests/runner-e2e/github-review-config.ts create mode 100644 tests/runner-e2e/github-review-evidence.ts create mode 100644 tests/runner-e2e/github-review-flow.ts create mode 100644 tests/runner-e2e/github-review-journey.test.ts create mode 100644 tests/runner-e2e/github-review-launch.ts create mode 100644 tests/runner-e2e/github-review-ownership.ts create mode 100644 tests/runner-e2e/github-review-report.test.ts create mode 100644 tests/runner-e2e/github-review-report.ts create mode 100644 tests/runner-e2e/journey-dependencies.ts diff --git a/.agents/skills/verify-paperclip/SKILL.md b/.agents/skills/verify-paperclip/SKILL.md index 3bdc6e759e2..292fcf67c2a 100644 --- a/.agents/skills/verify-paperclip/SKILL.md +++ b/.agents/skills/verify-paperclip/SKILL.md @@ -54,6 +54,14 @@ npm install. Report only the combinations actually exercised. ## Deployment handoff +For hosted testing accounts, read [QA accounts and credentials](references/hosted-qa-accounts.md). +The testing environment has an AgentMail inbox on the allowed `paperclipbots.com` +domain and a persistent QA workspace at `https://qa.test.paperclip.app`. Use the +dedicated QA identity and normal email-code login. The expected 1Password service +account needs read and item-creation/update access; verify those capabilities +before promising that new credentials have been saved. Keep concrete secret +bindings and account receipts in the private eval configuration. + When a requested revision must first be built or deployed, use the skills in the private `paperclip-cloud` repo: diff --git a/.agents/skills/verify-paperclip/references/hosted-qa-accounts.md b/.agents/skills/verify-paperclip/references/hosted-qa-accounts.md new file mode 100644 index 00000000000..0e5426686ed --- /dev/null +++ b/.agents/skills/verify-paperclip/references/hosted-qa-accounts.md @@ -0,0 +1,128 @@ +# Hosted QA accounts and credentials + +Use this for testing Cloud login and tenant journeys. It is an environment setup +recipe, not a requirement for local or self-hosted verification. + +## Known testing setup + +- `https://test.paperclip.app` is the testing Cloud portal. The persistent tenant + is `https://qa.test.paperclip.app`. Keep testing distinct from staging and + production, including operator origins and secret namespaces. +- AgentMail supplies `qa@paperclipbots.com`. The custom `paperclipbots.com` domain + is admitted for testing sign-up. Verify admission through the actual customer + session when it matters; inbox access alone does not prove admission. +- A dedicated QA account and the persistent workspace already exist. Reuse them + for existing-user journeys. Account authentication, workspace creation, and + product onboarding are separate coverage claims. +- Hosted testing currently supports normal email-code authentication. A mailbox + key is an infrastructure credential; the short-lived sign-in code is not a + durable password. Do not fabricate a password for a passwordless account. +- The private Cloud Product E2E adapter owns the AgentMail and operator secret + references, registered stack/company IDs, leases, and cleanup. Locate its + `scripts/product-e2e/README.md` and reference-only target configuration. Use + that adapter for campaigns rather than inventing a second Cloud provisioner. + +The QA inbox credential can be inbox-scoped/read-only: domain listing or inbox +creation may return 403 while reading the configured QA inbox succeeds. An older +AgentMail key may expose only an `agentmail.to` inbox. That is not the allowed +custom-domain identity; do not silently substitute it. Read the configured inbox +directly. Create a new inbox only when the requested journey needs one and the +available account has that capability. + +The Cloud Product E2E credential is the rotation authority. A host-side 1Password +copy can become stale when that shared key rotates, even while browser cookies +still work. Probe the exact inbox and verify a fresh email-code session when +qualifying authentication. If the copy fails, reconcile it from the authorized +current source and verify read-back before creating another key. Record the +rotation owner and mirror refresh procedure in private setup; preserve the +original failed attempt. Use the declared staging AWS profile/region when a +one-time reconciliation reads the Cloud secret, and keep IAM access outside the +normal 1Password-only login dependency. + +For Dotta's QA journeys, reading the current verification email in the dedicated +test account's mailbox is an authorized part of sign-in, including Ralph's +GitHub device verification through existing AgentMail credentials. Do not ask +again for that same mailbox access on every run. Keep it scoped to the named QA +account, current login attempt, expected sender, and recipient; this does not +authorize reading unrelated mail. Declare the mailbox and its credential binding +as an explicit harness dependency rather than assuming the Paperclip QA inbox +also receives another account's codes. + +Ralph's dedicated verification binding is a separate, single-inbox, read-only +AgentMail key saved in 1Password, expiring **2027-10-23**. Resolve its current +item reference from the private Ponytail account registry; keep provider keys +out of this public reference. Normal GitHub password and current-device-email +verification worked without exporting a passkey. Use the supported ordinary +authentication flow; request assistance only if an additional factor actually +requires it. Expiry is a setup prerequisite and renewal responsibility, not a +reason to read another inbox or create credentials on every eval attempt. + +Cloud's shared GitHub OAuth App, the QA user's saved product connection, and a +journey-created review-bot App are separate resources. A 404 before GitHub consent +can be a registration prerequisite failure: compare the broker's actual client +ID/callback with the intended environment registration, then inspect whether the +App can be authorized by accounts outside its owner. A private App is not the +required public distribution for that setup. Verify the repaired OAuth handoff +and exact QA identity separately; changing visibility alone does not prove a +saved user connection or a working review bot. Keep one-time administrator repair +credentials outside normal per-attempt dependencies. Do not silently substitute +a personal token or another account for the requested connection route. + +## 1Password access and durable records + +The host is expected to supply `OP_SERVICE_ACCOUNT_TOKEN` for a designated QA +vault. It must permit reading required items and creating/updating credential +records when setup includes saving credentials. Successful reads do not prove +write permission. Save the intended account record and verify its returned item +ID; on denial, report the missing capability and retain the setup as incomplete. +Do not mark credentials saved, substitute a personal account, or change vault +permissions yourself. + +On Dotta's macOS host, the bootstrap token is stored in Keychain under service +`codex-1password`, account `$USER`. Read it with `/usr/bin/security +find-generic-password -a "$USER" -s "codex-1password" -w` inside a process that +captures stdout in memory and passes it only to the `op` child. A long-lived +shell's `OP_SERVICE_ACCOUNT_TOKEN` may be stale after rotation. Use the configured +bootstrap source; never run that command in a way that prints its result. CI +should inject its own service-account token through the runner's secret store. + +Use `op://` references in private setup profiles, with stable aliases such as +`paperclip-qa-user`, `agentmail-qa-inbox`, and `github-qa-user`. Bind each alias to +its account, consumer, required scopes, reference/field, and ownership. The +service-account token bootstraps the harness secret resolver; it never belongs +in a browser, product-agent environment, committed file, or evidence report. +Use the CLI's structured stdin input when creating an item. On macOS, `op` +may ignore Node socket-backed stdin; the private setup helper uses an actual +POSIX pipe and verifies saved fields rather than trusting an item ID. Keep secret values +out of shell arguments, transcripts, screenshots, and temporary handoff files. + +For a passwordless account, save the login URL, username, authentication method, +and reference to the approved mailbox credential. Save a real password only if +the product actually creates one. Preserve passkeys in their supported +authenticator and record that attended authentication may be required; a +1Password service account's ability to read a login item does not prove it can +exercise that item's passkey. + +## Authenticate, verify, and retain + +1. Read the exact QA inbox and credential bindings from private setup. Capture + message IDs already present before requesting a code. +2. Use the normal portal UI and dedicated QA identity. For a genuinely new + account, complete its sign-up flow and save its account record. For the + existing QA account, reuse normal sign-in without resetting credentials. +3. Read only the current attempt's verification mail. Match the configured + sender, exact recipient, unseen message ID, time window, and one unexpired + code. Keep the key and code in process memory; exclude authentication pages + and raw email from screenshots, traces, and reports. +4. Verify the authenticated principal and, if workspace creation is relevant, + `capabilities.canCreateOrganizations` through the customer session. Enter the + intended tenant and verify its actual company. A portal login alone does not + prove tenant access. +5. Record the account alias, credential-item reference, target, auth method, + fresh/reused state, and the observed outcome in private evidence. Keep pending + credential storage explicit. Retain the shared QA account, inbox, workspace, + and reusable repository; clean up only attempt-owned resources. + +Use the shared Product Journey target adapter for automated authentication and +ownership. Fixed UI scripts prove the actions they execute; an email login to an +existing account does not establish new-account onboarding coverage. diff --git a/doc/evals.md b/doc/evals.md index 9d89aa297eb..2c0af7e5ec7 100644 --- a/doc/evals.md +++ b/doc/evals.md @@ -1,5 +1,12 @@ # Paperclip evaluation guide +The explicit-only [GitHub review bot journey](../tests/runner-e2e/GITHUB-REVIEW-JOURNEY.md) +converts the Ponytail walkthrough into attended App setup, scoped installation, +automatic PR review, and independent two-service checks. It supports attached +self-hosted/Cloud targets and separately selected local/Daytona agents. Account +and credential bindings stay in the private eval repo; registration and oracle +tests do not establish a completed live pass or unattended CI qualification. + The explicit-only [necessary free-text question journey](../tests/runner-e2e/README.md#necessary-free-text-question) checks one essential input, the rendered prompt and context, the real answer, one bound continuation, and an exact saved confirmation. Its four development diff --git a/tests/runner-e2e/GITHUB-REVIEW-JOURNEY.md b/tests/runner-e2e/GITHUB-REVIEW-JOURNEY.md new file mode 100644 index 00000000000..ceeb56a95e0 --- /dev/null +++ b/tests/runner-e2e/GITHUB-REVIEW-JOURNEY.md @@ -0,0 +1,120 @@ +# GitHub review bot journey (explicit, attended) + +The `github-review-journey` suite converts the recorded Ponytail walkthrough into +fixed browser actions and an independent review oracle. It creates a GitHub App, +installs it on one private eval repository, saves automatic review configuration +with a selected skill and 5/5 passing threshold, opens a defective PR without a +bot mention, and checks the matching automatic task, review, GitHub delivery, +failed check, task completion, and persistence. + +The suite is applicable to self-hosted deployments with public GitHub webhook +ingress and to Paperclip Cloud with GitHub App support. Hosting is independent of +the configured agent's `local` or `daytona` execution environment. Both cells are +registered; select exactly one and bind it in the private setup profile. Browser +registration and oracle tests do not establish live qualification of either cell. + +## Dependencies and starting state + +Use a dedicated private browser profile outside the checkout. Supply the intended +company, serving SHA, deployment mode, existing agent/model/provider/runtime, +review skill, agent environment ID, GitHub account handle, App owner, and private +reusable repository. The GitHub login identifier may be an email; the handle is +separate. The agent and its provider connection must already be configured. +A matching existing GitHub user connection is required; fresh user OAuth and +agent hiring are outside this variant. App creation and installation remain +measured UI actions with attended consent/passkey boundaries. + +The browser, harness, and review agent need no external MCP tools. The agent uses +the task-bound GitHub review tools. The preexisting personal GitHub connection +is a separate product identity prerequisite; the product may store/expose it as +an MCP-backed connection. That does not supply MCP access to the harness or +review agent. The browser account controls the App and eval repository; the +agent consumes its own provider and task bindings. Harness access to 1Password +does not supply those product connections. + +Private setup profiles bind credential aliases to environment variable names or +selected `op://vault/item/field` references. A 1Password service-account token +goes only to the resolver's `op` child, and browser processes inherit a limited +environment. Never commit passwords, mailbox keys, passkeys, cookies, auth traces, +or browser profile contents. A private optional `authentication` module and +config file can prepare an ordinary hosted session before measured actions; +the private QA implementation reuses Cloud's email-code authentication helper. + +## Select and run + +```sh +pnpm test:e2e:runner -- --list --suite github-review-journey +pnpm test:e2e:runner -- \ + --id github-review-journey.configured-agent.daytona.setup-and-first-review \ + --github-review-config /private/ponytail-qa.json +``` + +The private definition, reference-only setup example, credential setup utilities, +and source-step mapping live in `paperclip-evals/evals/product-journeys/ponytail`. +Its wrapper supports the host's Keychain bootstrap without putting a token in +shell arguments. The suite is excluded from `--all` and generated CI matrices. +It has no scheduler, public upload, or automatic retry. A full setup needs +attended external authorization. Do not claim it is an unattended CI journey. +In a terminal, each creation/installation pause also accepts the exact displayed +action and unique App name. Inspect that attempt's permissions first. The setup +profile is not authorization: use the current task's actual authority, including +any explicitly granted standing permission for disposable QA resources. Do not +repeat an already covered approval; obey any required host approval boundary. + +## Oracle and ownership + +`cart-total.js` is a newly authored deterministic precision defect, not an +assertion that the source walkthrough had identical fixture bytes. A passing +eval requires a complete assessment of that path and head, a relevant inline +precision finding, a score below 5, and a correctly failed GitHub check. The +oracle rejects a stale/foreign company, endpoint, issue, PR, or head, manual +triggering, missing findings/delivery, and false completion. It does not require +the source's exact 3/5 score. Persisted skill selection proves binding; this +variant does not yet independently verify a runtime skill-read receipt. + +The rendered inline discussion must identify the created bot, `cart-total.js`, +the complete reviewed head, and the relevant precision finding. A summary that +mentions the defect does not substitute for inline publication. The review's +completed state alone is also insufficient: the actual run must succeed and the +associated task must reach Done. A native failure after publication fails the +journey and retains the publication evidence already observed. + +Each attempt records endpoint, App, PR/branch, task, and run ownership. Cleanup +removes the owned endpoint, closes the owned PR/deletes its branch, and asks for +the owned App's removal. App identity must match the created endpoint, company, +agent, exact name, GitHub-confirmed owner/slug, and immutable App ID. Installation +management is recorded separately: uninstalling alone does not prove App deletion. +It retains the shared repository, account, provider/user +connections, and completed task evidence. An unconfirmed cleanup fails the +attempt; retain the resource receipt for recovery. Read the receipt before any +manual cleanup. Never delete by a guessed name or broad account search. + +The configured deadline and observed run limit bound the attempt. They are not +a hard provider-dollar cap or proof that no request outlives cancellation. Use +the existing budgeted Cloud operations adapter before automated paid campaigns; +this attended attached-agent variant does not replace that infrastructure. +Effective company/agent budget policies are recorded when readable. A route +that reports tokens without a dollar cost can stop on `unpricedUsagePolicy: +block` despite a zero legacy spend counter. Any authorized exception is a +distinct tested setup condition; normal fixture setup must not silently grant +it. Restore temporary exceptions after verification and retain their receipts. + +The case declares a ten-minute provider-turn allowance within its fifteen-minute +body deadline. Read back the attached agent's effective timeout separately; +catalog metadata cannot increase a deployed agent's limit. If the target rejects +the required configuration or its lifecycle cannot settle, preserve that setup +failure and repair the fixture before claiming a qualified run. + +Private normalized results and the existing Product E2E dashboard retain actual +model/provider, selected environment, serving SHA, setup ID, source hash, +checkpoints, screenshots, observed usage, partial cost coverage, assistance, and +cleanup. Missing usage remains unknown. Authentication screens are excluded. + +`github-review-report.ts` uses the existing evidence sanitizer and manifest, +stages only declared screenshots, and verifies screenshot hashes and attempt +path ownership. The standard report inputs are `evidence/result.json`, +`evidence/evidence-manifest.json`, and `evidence/snapshots/`. Raw private operator +receipts are outside the manifest. Existing report tooling imports these files; +no second runner or report service is required. A presentation repair must use a +new directory, preserve the original result/hash and failure, and dispatch no +provider work. Rebuilding a dashboard never qualifies a failed live attempt. diff --git a/tests/runner-e2e/README.md b/tests/runner-e2e/README.md index 94b9f55ffa1..47853d3ba74 100644 --- a/tests/runner-e2e/README.md +++ b/tests/runner-e2e/README.md @@ -1,5 +1,9 @@ # Paid runner full-stack E2E +The explicit-only [GitHub review bot journey](GITHUB-REVIEW-JOURNEY.md) tests +attended bot setup and an automatic PR review against an attached deployment. +Private account bindings and setup receipts live in the private eval repository. + ## Dependable-work qualification checkpoint `dependable-qualification.ts` defines the six everyday journeys across Codie diff --git a/tests/runner-e2e/catalog.test.ts b/tests/runner-e2e/catalog.test.ts index 8fe1d5957fe..4f36708a091 100644 --- a/tests/runner-e2e/catalog.test.ts +++ b/tests/runner-e2e/catalog.test.ts @@ -219,10 +219,10 @@ describe("runner E2E catalog", () => { expect(localIntegrityTasks).toHaveLength(2); expect(openRouterBreadthTasks).toHaveLength(3); expect(runnerSuites.map((suite) => suite.expectedMatrixSize)).toEqual([ - 1, 3, 2, 2, 4, 4, 4, 4, 4, 4, 8, 10, 6, 63, 12, 6, 4, 2, 4, 2, 30, 3, 16, 16, 2, 6, 8, 46, 2, 23, 15, 52, 6, 6, 20, 26, 52, 28, 18, 2, 6, 6, 13, 10, 2, 48, 16, 10, 2, 1, 1, 4, 116, 2, + 1, 3, 2, 2, 4, 4, 4, 4, 4, 4, 8, 10, 6, 63, 12, 6, 4, 2, 4, 2, 30, 3, 16, 16, 2, 6, 8, 46, 2, 23, 15, 52, 6, 6, 20, 26, 52, 28, 18, 2, 6, 6, 13, 10, 2, 48, 16, 10, 2, 1, 1, 4, 116, 2, 2, ]); - expect(validateRunnerCatalog()).toHaveLength(763); - expect(new Set(runnerMatrix.map((entry) => entry.id)).size).toBe(763); + expect(validateRunnerCatalog()).toHaveLength(765); + expect(new Set(runnerMatrix.map((entry) => entry.id)).size).toBe(765); expect( runnerMatrix.filter((entry) => entry.suite.id === "core-compatibility"), ).toHaveLength(48); @@ -519,13 +519,13 @@ describe("runner E2E catalog", () => { it("uses only declared secret references in generated payloads", () => { expect( - runnerMatrix.filter(entry => entry.task.flow !== "provider_connection").every((entry) => + runnerMatrix.filter(entry => !["provider_connection", "github_review_journey"].includes(entry.task.flow)).every((entry) => entry.requiredCredentials.includes(entry.profile.credential), ), ).toBe(true); expect( runnerMatrix - .filter((entry) => entry.environment.id === "daytona" && entry.task.flow !== "provider_connection") + .filter((entry) => entry.environment.id === "daytona" && !["provider_connection", "github_review_journey"].includes(entry.task.flow)) .every((entry) => entry.requiredCredentials.includes("DAYTONA_API_KEY"), ), diff --git a/tests/runner-e2e/catalog.ts b/tests/runner-e2e/catalog.ts index c6bc7b4d292..84c733fe035 100644 --- a/tests/runner-e2e/catalog.ts +++ b/tests/runner-e2e/catalog.ts @@ -19,6 +19,7 @@ import { NATIVE_INSTRUCTION_SUITE, NATIVE_INSTRUCTION_BASE_SHA, nativeInstructio import { nativeCompletionProfile, NATIVE_COMPLETION_BUDGET_CENTS } from "./native-completion-defaults.js"; import { chatConfirmationTasks } from "./chat-cases.js"; import { buildConnectionSuite } from "./connection-cases.js"; +import { buildGitHubReviewJourneySuite } from "./github-review-cases.js"; import { hiringTemplateTasks, hiringTemplateProfile, hiringTemplateDefinitionDigest } from "./hiring-template-cases.js"; import { copilotProviderDeathTasks } from "./copilot-active-stop-tasks.js"; import { instructionPersistenceTask } from "./instruction-persistence.js"; @@ -1800,6 +1801,7 @@ export const runnerSuites: readonly RunnerSuiteFixture[] = [ } }, }, buildConnectionSuite(runnerProfiles, runnerEnvironments), + buildGitHubReviewJourneySuite(runnerProfiles, runnerEnvironments), { id: "repository-skills", label: "Repository skill packages", manualOnly: true, description: "Live private Poteto import and byte-for-byte delivery to local and Daytona agent runtimes.", @@ -1875,8 +1877,8 @@ export function buildRunnerMatrix( ]), ], requiredCredentials: [ - ...(task.flow === "provider_connection" ? [] : [profile.credential]), - ...(task.flow !== "provider_connection" && environment.credential ? [environment.credential] : []), + ...(["provider_connection", "github_review_journey"].includes(task.flow) ? [] : [profile.credential]), + ...(!["provider_connection", "github_review_journey"].includes(task.flow) && environment.credential ? [environment.credential] : []), ...(task.requiredCredentials ?? []), ], })) diff --git a/tests/runner-e2e/connection-launch.ts b/tests/runner-e2e/connection-launch.ts index 8781a2b4abd..99eb7a7a196 100644 --- a/tests/runner-e2e/connection-launch.ts +++ b/tests/runner-e2e/connection-launch.ts @@ -66,7 +66,7 @@ export async function cleanupConnectionCompany(input: { else for (const agent of fixtureAgents) await api.delete(`/api/agents/${agent.id}`); } -export async function openConnectionBrowser(config: ConnectionConfig, repositoryRoot: string, origin: string) { +export async function openConnectionBrowser(config: Pick, repositoryRoot: string, origin: string) { const temporary = config.browser.freshness === "signed-out" || !config.browser.profileDir; const profile = temporary ? await mkdtemp(path.join(os.tmpdir(), "paperclip-qa-browser-")) : path.resolve(config.browser.profileDir!); await assertOutsideRepository(profile, repositoryRoot); diff --git a/tests/runner-e2e/connection-target.ts b/tests/runner-e2e/connection-target.ts index 455c67d8c9e..fafecc2c0e4 100644 --- a/tests/runner-e2e/connection-target.ts +++ b/tests/runner-e2e/connection-target.ts @@ -92,11 +92,13 @@ export async function startConnectionTarget(config: ConnectionConfig, executions } catch (error) { await stop(); throw error; } } -export async function verifyConnectionTarget(origin: string, config: ConnectionConfig) { +export async function verifyConnectionTarget(origin: string, config: ConnectionConfig, request?: APIRequestContext) { let health: any; try { - const response = await fetch(`${targetOrigin(origin)}/api/health`, { redirect: "error", signal: AbortSignal.timeout(15_000) }); - if (!response.ok) throw new ConnectionFailure(); + const response = request + ? await request.get(`${targetOrigin(origin)}/api/health`, { maxRedirects: 0, timeout: 15_000 }) + : await fetch(`${targetOrigin(origin)}/api/health`, { redirect: "error", signal: AbortSignal.timeout(15_000) }); + if (!(typeof response.ok === "function" ? response.ok() : response.ok)) throw new ConnectionFailure(); health = await response.json(); } catch { throw new ConnectionBlock("blocked_target", "target_health_unavailable_or_redirected"); } if (typeof health.commit !== "string" || !/^[a-f0-9]{40}$/.test(health.commit)) throw new ConnectionBlock("blocked_target", "target_revision_unavailable"); diff --git a/tests/runner-e2e/github-review-attendance.ts b/tests/runner-e2e/github-review-attendance.ts new file mode 100644 index 00000000000..8bfcd067346 --- /dev/null +++ b/tests/runner-e2e/github-review-attendance.ts @@ -0,0 +1,31 @@ +import { createInterface } from "node:readline"; +import type { Readable } from "node:stream"; +import type { Locator } from "@playwright/test"; +import { ConnectionBlock } from "./connection-config.js"; +import { connectionDelay } from "./connection-target.js"; + +/** An attended operator can use the QA browser or confirm its displayed action + * in this run's terminal. Approval is never saved in the reusable profile. */ +export async function attendGitHubJourneyAction(input: { + control: Locator; action: "create-app" | "install-app"; appName: string; + signal: AbortSignal; timeoutMs: number; +}, operatorInput: Readable & { isTTY?: boolean } = process.stdin) { + const command = `${input.action} ${input.appName}`; + const terminal = operatorInput.isTTY ? createInterface({ input: operatorInput, terminal: false }) : undefined; + let confirmed = false; + terminal?.on("line", line => { if (line.trim() === command) confirmed = true; }); + console.log(`[github-review-journey] Inspect the displayed App permissions. Complete the action in the QA browser${terminal ? `, or type exactly: ${command}` : "."}`); + const deadline = Date.now() + input.timeoutMs; + try { + while (Date.now() < deadline) { + if (input.signal.aborted) throw new ConnectionBlock("blocked_target", "journey_interrupted"); + if (!await input.control.isVisible()) return; + if (confirmed) { + await input.control.click(); + return; + } + await connectionDelay(500); + } + throw new ConnectionBlock("awaiting_user", `${input.action.replaceAll("-", "_")}_consent_required`); + } finally { terminal?.close(); } +} diff --git a/tests/runner-e2e/github-review-browser.ts b/tests/runner-e2e/github-review-browser.ts new file mode 100644 index 00000000000..dffb516bcdd --- /dev/null +++ b/tests/runner-e2e/github-review-browser.ts @@ -0,0 +1,181 @@ +import { expect, type Page } from "@playwright/test"; +import { ConnectionBlock, ConnectionFailure } from "./connection-config.js"; +import { connectionDelay } from "./connection-target.js"; +import type { GitHubReviewJourneyConfig } from "./github-review-config.js"; + +export async function enterGitHubJourneyCompany(page: Page, origin: string, company: { issuePrefix: string }) { + if (!/^[A-Za-z0-9]+$/.test(company.issuePrefix)) throw new ConnectionFailure("invalid_journey_company_prefix"); + const pathname = `/${company.issuePrefix}/dashboard`; + await page.goto(`${origin}${pathname}`); + await page.waitForURL(url => url.origin === origin && url.pathname === pathname); +} + +/** Capture measured pages only, excluding authentication and unrelated GitHub data. */ +export function isGitHubJourneyEvidencePage(value: string, targetOrigin: string, repository: string, appSlug?: string) { + const url = new URL(value); + if ([...url.searchParams.keys()].some(key => /token|secret|code|state|password/i.test(key))) return false; + if (url.origin === targetOrigin) return !/connect|login|auth/.test(url.pathname); + if (url.origin !== "https://github.com") return false; + const prefix = `/${repository}/`; + if (url.pathname.startsWith(prefix) && /^(?:pull\/\d+(?:\/(?:files|commits|checks))?|runs\/\d+|actions\/runs\/\d+(?:\/job\/\d+)?)\/?$/.test(url.pathname.slice(prefix.length))) return true; + return Boolean(appSlug && (url.pathname === `/apps/${appSlug}/installations/new` || url.pathname === `/apps/${appSlug}/installations/new/permissions`)); +} + +export async function awaitJourneyCondition(check: () => Promise, timeoutMs: number, code: string, signal: AbortSignal, boundary: "awaiting_user" | "failed" = "awaiting_user") { + const end = Date.now() + timeoutMs; + while (Date.now() < end) { + if (signal.aborted) throw new ConnectionBlock("blocked_target", "journey_interrupted"); + if (await check()) return; + await connectionDelay(750); + } + if (boundary === "failed") throw new ConnectionFailure(code); + throw new ConnectionBlock("awaiting_user", code); +} + +export async function observeGitHubJourneyAccount(page: Page) { + const menu = page.getByRole("button", { name: /Open user navigation menu|View profile and more/i }); + const dialog = page.getByRole("dialog", { name: "User navigation", exact: true }); + await menu.click(); + try { await dialog.waitFor({ timeout: 3_000 }); } + catch (error) { + // GitHub can replace its server-rendered header during hydration. Retry + // once only when the observed control still explicitly says Open. + if (!await menu.isVisible() || await dialog.isVisible()) throw error; + await menu.click(); + await dialog.waitFor(); + } + const profile = dialog.getByRole("link", { name: "Profile", exact: true }); + const href = await profile.getAttribute("href"); + const url = new URL(href ?? "", "https://github.com"); + const account = url.origin === "https://github.com" ? /^\/([A-Za-z0-9-]+)\/?$/.exec(url.pathname)?.[1] : undefined; + if (!account) throw new ConnectionFailure("github_profile_identity_missing"); + await page.keyboard.press("Escape"); + return account; +} + +/** Prepare one repository grant; submitting Install remains a separate action. */ +export async function selectGitHubJourneyRepository(page: Page, repository: string) { + const selectedOnly = page.getByRole("radio", { name: /Only select repositories/i }); + await selectedOnly.check(); + await page.getByRole("button", { name: /Select repositories/i }).click(); + await page.getByRole("textbox", { name: "Search for a repository", exact: true }).fill(repository.split("/")[1]!); + const name = new RegExp(`^${repository.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?:\\s|$)`); + // GitHub nests the selectable repository item inside a containing menu item. + await page.getByRole("menuitem", { name }).last().click(); + await page.keyboard.press("Escape"); + await expect(selectedOnly).toBeChecked(); + await expect(page.getByRole("radio", { name: /^All repositories/ })).not.toBeChecked(); + await expect(page.getByRole("main")).toContainText("Selected 1 repository."); + await expect(page.getByRole("button", { name: `Remove ${repository.split("/")[1]}`, exact: true })).toBeVisible(); + await expect(page.getByRole("button", { name: "Install", exact: true })).toBeEnabled(); +} + +/** Login remains ordinary browser UI. Passkeys are never exported or emulated. */ +export async function ensureGitHubJourneyLogin(input: { + page: Page; config: GitHubReviewJourneyConfig; username: string; password?: () => Promise; signal: AbortSignal; + checkpoint(id: string): Promise; +}) { + const { page, config } = input; + const signedIn = () => page.getByRole("button", { name: /Open user navigation menu|View profile and more/i }).isVisible(); + if (!await signedIn()) { + const loginLink = page.getByRole("link", { name: /^Sign in$/ }); + if (await loginLink.isVisible()) await loginLink.click(); + if (config.github.login === "password") { + await page.getByLabel("Username or email address", { exact: true }).fill(input.username); + await page.getByLabel("Password", { exact: true }).fill(await input.password!()); + await page.getByRole("button", { name: "Sign in", exact: true }).click(); + } + await input.checkpoint("awaiting_github_sign_in"); + console.log("[github-review-journey] Complete Ralph QA GitHub sign-in/passkey in the dedicated QA browser. No credential needs to be pasted into chat."); + await awaitJourneyCondition(signedIn, config.browser.loginTimeoutMs, "github_login_required", input.signal); + } + // The login identifier can be an email address; verify the GitHub handle. + if ((await observeGitHubJourneyAccount(page)).toLowerCase() !== config.github.account.toLowerCase()) throw new ConnectionBlock("blocked_target", "github_account_mismatch"); +} + +/** Explicit one-time bootstrap. Later attempts reuse this private repository. */ +export async function createPrivateJourneyRepository(page: Page, repository: string) { + const [owner, name] = repository.split("/"); + await page.getByRole("button", { name: /Create new/i }).click(); + await page.getByRole("menuitem", { name: /New repository/i }).click(); + const ownerButton = page.getByRole("button", { name: /Owner|Choose an owner/i }); + await expect(ownerButton).toHaveText(owner!); + await page.getByRole("textbox", { name: /Repository name/i }).fill(name!); + await expect(page.getByText(`${name} is available.`, { exact: true })).toBeVisible(); + const privateChoice = page.getByRole("radio", { name: /Private/ }); + if (await privateChoice.isVisible()) await privateChoice.check(); + else { + await page.getByRole("button", { name: /Choose visibility|Public/i }).click(); + await page.getByRole("menuitemradio", { name: /Private/ }).click(); + } + await expect(page.getByRole("button", { name: "Choose visibility: Private", exact: true })).toBeVisible(); + const readme = page.getByRole("button", { name: "Add README", exact: true }); + if (await readme.getAttribute("aria-pressed") !== "true") await readme.click(); + await expect(readme).toHaveAttribute("aria-pressed", "true"); + await page.getByRole("button", { name: "Create repository", exact: true }).click(); + await page.waitForURL(url => url.origin === "https://github.com" && url.pathname === `/${repository}`); + await expect(page.getByRole("link", { name: name!, exact: true }).first()).toBeVisible(); + await expect(page.getByText("Private", { exact: true }).first()).toBeVisible(); +} + +export async function createGitHubJourneyPullRequest(input: { page: Page; branch: string; title: string; contents: string }) { + const { page } = input; + // The initial file list is server-rendered before GitHub's controls hydrate. + // Its loaded commit receipt provides a visible readiness signal. + await expect(page.getByRole("link", { name: /^Commit [a-f0-9]{7,40}$/ })).toBeVisible(); + await page.getByRole("button", { name: "Add file", exact: true }).click(); + await page.getByRole("menuitem", { name: "Create new file", exact: true }).click(); + await page.getByRole("textbox", { name: /Name your file|File name/i }).fill("cart-total.js"); + await page.getByRole("textbox", { name: /Editing cart-total.js file contents|File contents/i }).fill(input.contents); + await page.getByRole("button", { name: /Commit changes/i }).click(); + const dialog = page.getByRole("dialog"); + await dialog.getByRole("textbox", { name: /Commit message/i }).fill("Add isolated cart precision review fixture"); + await dialog.getByRole("radio", { name: /Create a new branch/i }).check(); + const branch = dialog.getByRole("textbox", { name: "PR target branch", exact: true }); + await branch.fill(input.branch); + await expect(branch).toHaveValue(input.branch); + await dialog.getByRole("button", { name: /Propose changes|Commit changes/i }).click(); + await page.getByRole("textbox", { name: /Add a title/i }).fill(input.title); + await page.getByRole("textbox", { name: /Add a description|Comment|Description/i }).fill("Disposable automated review fixture. This money-total helper promises exact cent totals. Review only; do not modify or merge the branch. No manual bot mention is used."); + await page.getByRole("button", { name: "Create pull request", exact: true }).click(); + await page.waitForURL(url => url.origin === "https://github.com" && /\/pull\/\d+$/.test(url.pathname)); + const match = /\/pull\/(\d+)$/.exec(new URL(page.url()).pathname); + if (!match) throw new ConnectionFailure("created_pr_url_missing"); + return Number(match[1]); +} + +export async function observeGitHubHead(page: Page) { + const pull = new URL(page.url()); + const repository = /^\/([^/]+\/[^/]+)\/pull\/\d+$/.exec(pull.pathname)?.[1]; + if (pull.origin !== "https://github.com" || !repository) throw new ConnectionFailure("github_pr_evidence_missing"); + const commits = page.getByRole("link", { name: /^Commits(?:\s*\(?\d+\)?)?$/ }); + await expect(commits).toBeVisible(); + const commitsUrl = new URL(await commits.getAttribute("href") ?? "", pull.origin); + if (commitsUrl.origin !== pull.origin || commitsUrl.pathname !== `${pull.pathname}/commits`) throw new ConnectionFailure("github_commits_navigation_missing"); + // Follow the rendered navigation link. A click immediately after PR creation + // can be swallowed when GitHub replaces its server-rendered navigation. + await page.goto(commitsUrl.href); + const commit = page.getByRole("link", { name: /^[a-f0-9]{7,40}$/ }).last(); + await expect(commit).toBeVisible(); + const url = new URL(await commit.getAttribute("href") ?? "", pull.origin); + const sha = /\/(?:commits?|changes)\/([a-f0-9]{40})$/.exec(url.pathname)?.[1]; + if (url.origin !== pull.origin || !sha || ![`/${repository}/commit/${sha}`, `${pull.pathname}/commits/${sha}`, `${pull.pathname}/changes/${sha}`].includes(url.pathname)) throw new ConnectionFailure("github_head_evidence_missing"); + const conversation = page.getByRole("link", { name: /^Conversation(?:\s*\(?\d+\)?)?$/ }); + await expect(conversation).toBeVisible(); + const conversationUrl = new URL(await conversation.getAttribute("href") ?? "", pull.origin); + if (conversationUrl.origin !== pull.origin || conversationUrl.pathname !== pull.pathname) throw new ConnectionFailure("github_conversation_navigation_missing"); + await page.goto(conversationUrl.href); + return sha; +} + +export async function closeOwnedGitHubPullRequest(page: Page) { + const closed = page.getByText("Closed", { exact: true }).first(); + if (!await closed.isVisible()) { + await expect(page.getByRole("button", { name: /^(?:Merge status|Status)$/ })).toBeEnabled(); + await page.getByRole("button", { name: "Close pull request", exact: true }).click(); + } + await expect(closed).toBeVisible({ timeout: 30_000 }); + const restored = page.getByRole("button", { name: "Restore branch", exact: true }); + if (!await restored.isVisible()) await page.getByRole("button", { name: "Delete branch", exact: true }).click(); + await expect(restored).toBeVisible({ timeout: 30_000 }); +} diff --git a/tests/runner-e2e/github-review-cases.ts b/tests/runner-e2e/github-review-cases.ts new file mode 100644 index 00000000000..614d11ba157 --- /dev/null +++ b/tests/runner-e2e/github-review-cases.ts @@ -0,0 +1,23 @@ +import { createHash } from "node:crypto"; +import { readFileSync } from "node:fs"; +import type { EnvironmentFixture, RunnerProfileFixture, RunnerSuiteFixture } from "./types.js"; + +export function buildGitHubReviewJourneySuite(profiles: readonly RunnerProfileFixture[], environments: readonly EnvironmentFixture[]): RunnerSuiteFixture { + const base = profiles.find(p => p.id === "runner-codex")!; + const profile: RunnerProfileFixture = { ...base, id: "configured-agent", label: "Existing review agent (profile-bound)", groups: [], + model: "configured-in-journey-profile", provider: "configured-in-journey-profile", supportedEnvironments: ["local", "daytona"], + modelQualification: { source: "candidate_runner_profile", qualificationId: "explicit-attached-agent-profile" }, + buildAgent: () => { throw new Error("GitHub review journey uses the explicitly bound existing agent"); } }; + const hash = createHash("sha256"); + for (const file of ["github-review-cases.ts", "github-review-config.ts", "github-review-browser.ts", "github-review-attendance.ts", "github-review-flow.ts", "github-review-launch.ts", "github-review-report.ts", "github-review-evidence.ts", "github-review-ownership.ts", "journey-dependencies.ts"]) hash.update(file).update(readFileSync(new URL(`./${file}`, import.meta.url))); + return { id: "github-review-journey", label: "GitHub review bot setup and first review", groups: [], manualOnly: true, + description: "Attended real GitHub App setup, repository-scoped installation, automatic PR review, independent publication and task checks. Reuses a private QA repository.", + profiles: [profile], environments, expectedMatrixSize: 2, + definitionMetadata: { version: 1, digest: hash.digest("hex"), scheduling: "explicit-only", sourceJourneySha256: "2a504ec0b68c42d597a20fad5fc3bb8d7086ab5c24d34fc75c2a031f8559ab40", + applicability: ["self-hosted-with-public-github-ingress", "paperclip-cloud-with-github-app-support"], mcpConnections: [], + dependencies: [{ alias: "github-user", consumer: "browser", required: true }, { alias: "github-verification-mailbox", consumer: "harness", phase: "setup-profile-dependent" }, { alias: "review-agent", consumer: "product-agent", required: true }, + { alias: "github-user-connection", consumer: "browser-identity-verification", required: true }, { alias: "review-bot-app", consumer: "product-agent", phase: "created-in-journey" }], authentication: "dedicated-browser-with-profile-bound-authentication", providerCredential: "existing-product-agent-binding" }, + tasks: [{ id: "setup-and-first-review", label: "Create App, configure Ponytail skill, open PR, verify automatic review", groups: [], flow: "github_review_journey", workMode: "standard", + expectedRunCount: 3, minimumExpectedRunCount: 1, automaticRetryPolicy: "single_attempt", attemptTimeoutMs: { local: 1_800_000, daytona: 1_800_000 }, turnTimeoutMs: 600_000, + expectedTerminalState: { issue: "done", run: "succeeded" }, buildTitle: n => `GitHub review journey ${n}`, buildPrompt: () => "Real GitHub opened event; never dispatched by fixture.", buildVisibleMarker: n => n, buildMatchers: () => [] }] }; +} diff --git a/tests/runner-e2e/github-review-config.ts b/tests/runner-e2e/github-review-config.ts new file mode 100644 index 00000000000..abbee09e79f --- /dev/null +++ b/tests/runner-e2e/github-review-config.ts @@ -0,0 +1,69 @@ +import { readFile } from "node:fs/promises"; +import path from "node:path"; +import os from "node:os"; +import { ConnectionBlock, parseConnectionConfig, targetOrigin, type ConnectionConfig } from "./connection-config.js"; +import { parseJourneyCredentialBinding, type JourneyCredentialBinding } from "./journey-dependencies.js"; + +export interface GitHubReviewJourneyConfig { + version: 1; + setupId: string; + hosting: "self-hosted" | "paperclip-cloud"; + executionEnvironment: "local" | "daytona"; + target: Extract & { companyId: string; environmentId: string }; + browser: ConnectionConfig["browser"]; + authentication?: { module: string; configFile: string }; + agent: { id: string; name: string; skill: string; model: string; provider: string; runtimeMode: "native" | "legacy" }; + github: { repository: string; ownerType: "personal" | "organization"; appOwner: string; account: string; login: "passkey" | "password"; username: JourneyCredentialBinding; password?: JourneyCredentialBinding }; + deadlineMs: number; + maximumRuns: number; +} + +const invalid = (): never => { throw new ConnectionBlock("blocked_target", "invalid_github_journey_configuration"); }; +function object(v: unknown, keys: string[]): Record { + if (!v || typeof v !== "object" || Array.isArray(v) || Object.keys(v).some(k => !keys.includes(k))) return invalid(); + return v as Record; +} +function text(v: unknown, pattern?: RegExp): string { + if (typeof v !== "string" || !v.trim() || v.length > 1024 || (pattern && !pattern.test(v))) return invalid(); + return v; +} +export function parseGitHubReviewJourneyConfig(input: unknown): GitHubReviewJourneyConfig { + try { + const v = object(input, ["version", "setupId", "hosting", "executionEnvironment", "target", "browser", "authentication", "agent", "github", "deadlineMs", "maximumRuns"]); + if (v.version !== 1 || !["self-hosted", "paperclip-cloud"].includes(v.hosting)) return invalid(); + if (v.executionEnvironment !== undefined && !["local", "daytona"].includes(v.executionEnvironment)) return invalid(); + const target = object(v.target, ["mode", "baseURL", "expectedCommit", "deploymentMode", "companyId", "environmentId"]); + if (target.mode !== "attach") return invalid(); + const common = parseConnectionConfig({ target, browser: v.browser }); + if (common.target.mode !== "attach" || !common.browser.profileDir) return invalid(); + const agent = object(v.agent, ["id", "name", "skill", "model", "provider", "runtimeMode"]); + const github = object(v.github, ["repository", "ownerType", "appOwner", "account", "login", "username", "password"]); + if (!["personal", "organization"].includes(github.ownerType) || !["passkey", "password"].includes(github.login) + || !["native", "legacy"].includes(agent.runtimeMode) || (github.login === "password" && !github.password)) return invalid(); + const deadlineMs = v.deadlineMs ?? 900_000; const maximumRuns = v.maximumRuns ?? 3; + if (!Number.isInteger(deadlineMs) || deadlineMs < 60_000 || deadlineMs > 1_800_000 + || !Number.isInteger(maximumRuns) || maximumRuns < 1 || maximumRuns > 5) return invalid(); + const uuid = /^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$/; + const authentication = v.authentication === undefined ? undefined : object(v.authentication, ["module", "configFile"]); + if (authentication && (!path.isAbsolute(text(authentication.module)) || !path.isAbsolute(text(authentication.configFile)))) return invalid(); + return { version: 1, setupId: text(v.setupId, /^[a-z0-9-]{1,80}$/), hosting: v.hosting, executionEnvironment: v.executionEnvironment ?? "local", + target: { ...common.target, baseURL: targetOrigin(common.target.baseURL), companyId: text(target.companyId, uuid), environmentId: text(target.environmentId, uuid) }, browser: common.browser, + ...(authentication ? { authentication: { module: authentication.module, configFile: authentication.configFile } } : {}), + agent: { id: text(agent.id, uuid), name: text(agent.name), skill: text(agent.skill, /^[a-z0-9-]+$/), model: text(agent.model), provider: text(agent.provider), runtimeMode: agent.runtimeMode }, + github: { repository: text(github.repository, /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/), ownerType: github.ownerType, appOwner: text(github.appOwner, /^[A-Za-z0-9-]+$/), + account: text(github.account ?? (github.ownerType === "personal" ? github.appOwner : undefined), /^[A-Za-z0-9-]+$/), login: github.login, + username: parseJourneyCredentialBinding(github.username), ...(github.password ? { password: parseJourneyCredentialBinding(github.password) } : {}) }, deadlineMs, maximumRuns }; + } catch { return invalid(); } +} + +export async function loadGitHubReviewJourneyConfig(file?: string) { + if (!file) throw new ConnectionBlock("blocked_target", "github_journey_config_required"); + try { + const value = JSON.parse(await readFile(file, "utf8")); + if (value.browser?.profileDir?.startsWith("~/")) value.browser.profileDir = path.join(os.homedir(), value.browser.profileDir.slice(2)); + // Profile paths are relative to the profile, not the invoking checkout. + if (value.browser?.profileDir && !path.isAbsolute(value.browser.profileDir)) value.browser.profileDir = path.resolve(path.dirname(file), value.browser.profileDir); + for (const key of ["module", "configFile"]) if (value.authentication?.[key] && !path.isAbsolute(value.authentication[key])) value.authentication[key] = path.resolve(path.dirname(file), value.authentication[key]); + return parseGitHubReviewJourneyConfig(value); + } catch { throw new ConnectionBlock("blocked_target", "invalid_github_journey_configuration"); } +} diff --git a/tests/runner-e2e/github-review-evidence.ts b/tests/runner-e2e/github-review-evidence.ts new file mode 100644 index 00000000000..f2f6cda9588 --- /dev/null +++ b/tests/runner-e2e/github-review-evidence.ts @@ -0,0 +1,104 @@ +import { GITHUB_REVIEW_EVENTS, type GitHubReviewPolicy, type GitHubTaskReview } from "../../packages/shared/src/types/chat-github.js"; +import type { Matcher } from "./types.js"; + +export const githubJourneyCheckpoints = ["target", "dependencies", "agent", "app_creation_consent", "app_created", "repository_scope", "identity", "configuration_saved", "configuration_reloaded", "pr_created", "automatic_task", "skill_binding", "review_completed", "github_delivery", "github_inline_delivery", "check_projection", "task_done", "persisted"] as const; +export interface GitHubReviewJourneyEvidence { + version: 1; + outcome: "running" | "passed" | "failed" | "awaiting_user" | "missing_credential" | "blocked_target"; + phase: string; + setupId: string; + hosting: "self-hosted" | "paperclip-cloud"; + targetCommit: string | null; + assisted: boolean; + dependencies: Array<{ alias: string; consumer: "harness" | "browser" | "product-agent"; status: "ready" | "unverified" | "created-in-journey"; source: "onepassword" | "environment" | "browser-session" | "product-connection" }>; + checkpoints: Partial>; + cleanup: { endpoint: boolean; pullRequest: boolean; branch: boolean; app: boolean }; + definitionHash?: string; + score?: number; + conclusion?: string; + budgetPolicyRead?: "verified" | "unavailable"; + budgetPolicies?: Array<{ scopeType: string; amount: number; hardStopEnabled: boolean; unpricedUsagePolicy: string }>; + execution?: { reviewId: string; issueId: string; runId: string | null; runStatus?: string; issueStatus?: string; runtimeMode?: string; environmentId?: string; provider?: string; model?: string }; + review?: { id: string; repository: string; pullNumber: number; headSha: string; state: string; score?: number; conclusion: string | null; summaryUrl: string | null; checkUrl: string | null }; + inlinePublication?: { url: string; fileUrl: string; path: string; author: string; text: string }; +} + +export function retainGitHubReview(review: GitHubTaskReview): NonNullable { + return { id: review.id, repository: review.repository, pullNumber: review.pullNumber, headSha: review.headSha, + state: review.state, score: review.assessment?.score, conclusion: review.conclusion, summaryUrl: review.summaryUrl, checkUrl: review.checkUrl }; +} + +export function gradeGitHubReviewJourney(evidence: GitHubReviewJourneyEvidence) { + return [...githubJourneyCheckpoints.map(id => ({ matcher: { kind: "json_path", path: `githubReviewJourney.checkpoints.${id}`, expected: true } as Matcher, + passed: evidence.checkpoints[id] === true, detail: `${id}: ${evidence.checkpoints[id] === true ? "verified" : "missing"}` })), + { matcher: { kind: "json_path", path: "githubReviewJourney.cleanup", expected: true } as Matcher, + passed: Object.values(evidence.cleanup).every(Boolean), detail: "All attempt-owned resources reconciled; reusable repository retained." }]; +} + +/** Mentions and comment replies are manual intake, separate from automatic PR events. */ +export function hasOnlyOpenedAutomaticReview(policy: Pick) { + const automatic = policy.events.filter(event => GITHUB_REVIEW_EVENTS.slice(0, 4).includes(event)); + return automatic.length === 1 && automatic[0] === "opened" && policy.issueOpened !== true; +} + +export function matchesGitHubJourneyEnvironment(environment: { id: string; driver: string; config: Record }, id: string, kind: "local" | "daytona") { + return environment.id === id && (kind === "local" ? environment.driver === "local" + : environment.driver === "sandbox" && environment.config.provider === "daytona"); +} + +export function verifyGitHubReviewRun(run: Record | undefined, expected: { + runId: string | null; companyId: string; agentId: string; issueId: string; + runtimeMode: string; environmentId: string; executionEnvironment: "local" | "daytona"; + environment: { id: string; driver: string; config: Record }; provider: string; model: string; +}) { + const provider = run?.runnerProfileJson?.nativeExecutionInput?.provider; + return Boolean(run && run.id === expected.runId && run.companyId === expected.companyId + && run.agentId === expected.agentId && run.issueId === expected.issueId + && run.status === "succeeded" && run.runtimeMode === expected.runtimeMode + && matchesGitHubJourneyEnvironment(expected.environment, expected.environmentId, expected.executionEnvironment) + && run.contextSnapshot?.paperclipEnvironment?.id === expected.environmentId + && run.contextSnapshot?.paperclipEnvironment?.driver === expected.environment.driver + && (expected.runtimeMode !== "native" || (provider?.kind === expected.provider && provider?.model === expected.model))); +} + +function ownedDeliveryUrl(value: string | null, repository: string, pullNumber: number, kind: "summary" | "check") { + if (!value) return false; + try { + const url = new URL(value); + if (url.origin !== "https://github.com" || url.username || url.password) return false; + const prefix = `/${repository}/`; + if (!url.pathname.startsWith(prefix)) return false; + const path = url.pathname.slice(prefix.length); + return kind === "summary" + ? (path === `pull/${pullNumber}` || path === `issues/${pullNumber}`) && /^#(?:issuecomment|pullrequestreview)-\d+$/.test(url.hash) + : /^(?:runs\/\d+|actions\/runs\/\d+(?:\/job\/\d+)?)$/.test(path); + } catch { return false; } +} + +/** Independent identity/cause/output gates; a Done task or success prose cannot satisfy them. */ +export function verifyGitHubReview(input: { + review: GitHubTaskReview; companyId: string; endpointId: string; issueId: string; repository: string; pullNumber: number; headSha: string; + issue: { id: string; companyId: string; assigneeAgentId: string; status: string }; agentId: string; +}) { + const { review: r } = input; const assessment = r.assessment; + return r.companyId === input.companyId && r.endpointId === input.endpointId && r.issueId === input.issueId + && r.repository === input.repository && r.pullNumber === input.pullNumber && r.headSha === input.headSha + && r.event.event === "opened" && r.event.headSha === input.headSha && r.event.repository === input.repository + && r.state === "completed" && assessment?.complete === true && assessment.reviewedCommit === input.headSha + && assessment.coverage.reviewedPaths.includes("cart-total.js") && assessment.findings.some(f => f.path === "cart-total.js" && f.side === "RIGHT" + && /precision|decimal|floating|cents/i.test(f.body) && f.line >= 1 && f.line <= 7) + && assessment.score < 5 && r.conclusion === "failure" + && ownedDeliveryUrl(r.summaryUrl, input.repository, input.pullNumber, "summary") && ownedDeliveryUrl(r.checkUrl, input.repository, input.pullNumber, "check") + && input.issue.id === input.issueId && input.issue.companyId === input.companyId && input.issue.assigneeAgentId === input.agentId && input.issue.status === "done"; +} + +/** New, versioned fixture: price precision is explicitly part of the repository's test contract. */ +export const githubCartFixture = [ + "// Prices are decimal currency units; totals must be exact to a cent.", + "export function calculateCartTotal(items) {", + " return items.reduce((total, item) => {", + " const price = Number(item.price);", + " return total + price * Number(item.quantity);", + " }, 0);", + "}", +].join("\n") + "\n"; diff --git a/tests/runner-e2e/github-review-flow.ts b/tests/runner-e2e/github-review-flow.ts new file mode 100644 index 00000000000..c580ed767fa --- /dev/null +++ b/tests/runner-e2e/github-review-flow.ts @@ -0,0 +1,236 @@ +import { expect, type Page } from "@playwright/test"; +import type { GitHubTaskReview } from "../../packages/shared/src/types/chat-github.js"; +import type { GitHubRepositoryPage } from "../../packages/shared/src/types/chat-channels.js"; +import { ConnectionBlock, ConnectionFailure } from "./connection-config.js"; +import { ConnectionApi } from "./connection-target.js"; +import { awaitJourneyCondition, createGitHubJourneyPullRequest, enterGitHubJourneyCompany, observeGitHubHead, selectGitHubJourneyRepository } from "./github-review-browser.js"; +import { githubCartFixture, hasOnlyOpenedAutomaticReview, matchesGitHubJourneyEnvironment, retainGitHubReview, verifyGitHubReview, verifyGitHubReviewRun, type GitHubReviewJourneyEvidence } from "./github-review-evidence.js"; +import type { GitHubReviewJourneyConfig } from "./github-review-config.js"; +import { captureOwnedGitHubApp, readOwnedGitHubReviewRuns, type GitHubJourneyResources } from "./github-review-ownership.js"; +import { attendGitHubJourneyAction } from "./github-review-attendance.js"; + +export async function runGitHubReviewFlow(input: { + page: Page; github: Page; githubUsername: string; api: ConnectionApi; config: GitHubReviewJourneyConfig; resources: GitHubJourneyResources; + evidence: GitHubReviewJourneyEvidence; signal: AbortSignal; + checkpoint(id: keyof GitHubReviewJourneyEvidence["checkpoints"], page: Page): Promise; + phase(id: string): Promise; + persistResources(): Promise; +}) { + const { page, github, api, config, resources, evidence } = input; + const capabilities = await api.get('/api/instance/settings/experimental'); + if (capabilities.enableGitHubReviewBots !== true) throw new ConnectionBlock("blocked_target", "github_review_capability_unavailable"); + const company = await api.get(`/api/companies/${config.target.companyId}`); + const agent = await api.get(`/api/agents/${config.agent.id}`); + if (company.id !== config.target.companyId || agent.companyId !== company.id || agent.name !== config.agent.name || !["idle", "running"].includes(agent.status)) throw new ConnectionBlock("blocked_target", "configured_review_agent_unavailable"); + const environment = await api.get(`/api/environments/${config.target.environmentId}`); + // Inheritance and task trust policy can select the environment without an + // agent override. Validate the declared target now; the actual run binding + // remains authoritative after dispatch. + if (environment.status !== "active" + || !matchesGitHubJourneyEnvironment(environment, config.target.environmentId, config.executionEnvironment)) throw new ConnectionBlock("blocked_target", "configured_review_environment_mismatch"); + // The profile is explicit about the provider/model it claims to qualify. + if (JSON.stringify(agent.adapterConfig ?? {}).includes(config.agent.model) === false) throw new ConnectionBlock("blocked_target", "configured_agent_model_mismatch"); + // Record effective accounting prerequisites without granting or changing them. + try { + const budgets = await api.get(`/api/companies/${company.id}/budgets/overview`); + evidence.budgetPolicies = budgets.policies.filter((p: any) => p.isActive && (p.scopeType === "company" || (p.scopeType === "agent" && p.scopeId === agent.id))) + .map((p: any) => ({ scopeType: p.scopeType, amount: p.amount, hardStopEnabled: p.hardStopEnabled, unpricedUsagePolicy: p.unpricedUsagePolicy })); + evidence.budgetPolicyRead = "verified"; + } catch { evidence.budgetPolicyRead = "unavailable"; } + await enterGitHubJourneyCompany(page, api.origin, company); + await input.checkpoint("agent", page); + await input.phase("connector_navigation"); + await page.getByRole("link", { name: "Connectors", exact: true }).click(); + const botCard = page.getByRole("listitem").filter({ has: page.getByRole("heading", { name: "GitHub Code Review Bot", exact: true }) }); + await botCard.getByRole("button", { name: /^(?:Connect|Add connection) GitHub Code Review Bot$/ }).click(); + await page.getByRole("button", { name: /Select agent/ }).click(); + await page.getByRole("button", { name: `Select ${config.agent.name}`, exact: true }).click(); + const creation = page.waitForResponse(r => new URL(r.url()).pathname === `/api/companies/${company.id}/chat-endpoints` && r.request().method() === "POST"); + await page.getByRole("button", { name: "Continue", exact: true }).click(); + const response = await creation; + if (!response.ok()) throw new ConnectionFailure("endpoint_creation_failed"); + const endpoint = await response.json(); + if (endpoint.companyId !== company.id || endpoint.assignedAgentId !== agent.id || endpoint.provider !== "github") throw new ConnectionFailure("created_endpoint_binding_mismatch"); + resources.endpointId = endpoint.id; + evidence.cleanup.endpoint = false; + await input.persistResources(); + // Check the declared existing-user prerequisite before creating an external + // App. A missing fixture must not leave an unnecessary GitHub installation. + const existingAccounts = await api.get>(`/api/chat-endpoints/${endpoint.id}/github/personal-connections`); + const expectedAccounts = existingAccounts.filter(a => a.status === "active" && a.enabled && a.login?.toLowerCase() === input.githubUsername.toLowerCase()); + if (expectedAccounts.length !== 1) throw new ConnectionBlock("blocked_target", "dedicated_github_user_connection_required"); + await input.phase("github_app_registration"); + if (config.github.ownerType === "organization") { + await page.getByLabel("GitHub account", { exact: true }).selectOption("organization"); + await page.getByLabel("Organization", { exact: true }).fill(config.github.appOwner); + } + await page.getByLabel("App name", { exact: true }).fill(resources.appName); + await page.getByRole("button", { name: "Continue to GitHub", exact: true }).click(); + // Manifest flow navigates the same tab. External App grants remain attended. + evidence.assisted = true; + await awaitJourneyCondition(async () => new URL(page.url()).hostname === "github.com", 30_000, "github_manifest_handoff_missing", input.signal); + const createApp = page.getByRole("button", { name: new RegExp(`^Create GitHub App(?: for ${config.github.appOwner})?$`) }); + await createApp.waitFor({ timeout: config.browser.loginTimeoutMs }); + await page.bringToFront(); + await input.checkpoint("app_creation_consent", page); + console.log(`[github-review-journey] Authorize creation of only ${resources.appName} in the dedicated QA browser. Install it only on ${config.github.repository}.`); + await attendGitHubJourneyAction({ control: createApp, action: "create-app", appName: resources.appName, signal: input.signal, timeoutMs: config.browser.loginTimeoutMs }); + await input.phase("github_repository_installation"); + await awaitJourneyCondition(async () => await page.getByRole("radio", { name: /Only select repositories/i }).isVisible(), config.browser.loginTimeoutMs, "github_app_creation_consent_required", input.signal); + await awaitJourneyCondition(async () => captureOwnedGitHubApp(resources, await api.get(`/api/chat-endpoints/${endpoint.id}`), config), 30_000, "created_github_app_identity_unavailable", input.signal, "failed"); + await input.checkpoint("app_created", page); + await selectGitHubJourneyRepository(page, config.github.repository); + await input.checkpoint("repository_scope", page); + await page.bringToFront(); + console.log(`[github-review-journey] The installation selects only ${config.github.repository}. Confirm Install in the QA browser.`); + await attendGitHubJourneyAction({ control: page.getByRole("button", { name: "Install", exact: true }), action: "install-app", appName: resources.appName, signal: input.signal, timeoutMs: config.browser.loginTimeoutMs }); + await awaitJourneyCondition(async () => new URL(page.url()).origin === api.origin, config.browser.loginTimeoutMs, "github_installation_consent_required", input.signal); + const savedAccount = page.getByLabel("Existing GitHub connection", { exact: true }); + await input.phase("github_identity_binding"); + // Returning to the tenant can precede signed-webhook verification and the + // asynchronously loaded identity choices. Wait for a usable wizard state. + await awaitJourneyCondition(async () => await savedAccount.isVisible() + || await page.getByRole("button", { name: "Connect my GitHub account", exact: true }).isVisible() + || await page.getByRole("button", { name: "Confirm my account", exact: true }).isVisible() + || await page.getByRole("button", { name: "Done", exact: true }).isVisible(), + 120_000, "github_identity_or_connection_state_missing", input.signal, "failed"); + if (await savedAccount.isVisible()) { + // Select only a single already configured account; ambiguity never picks a stranger's login. + const accounts = await api.get>(`/api/chat-endpoints/${endpoint.id}/github/personal-connections`); + const active = accounts.filter(a => a.status === "active" && a.enabled && a.login?.toLowerCase() === input.githubUsername.toLowerCase()); + if (active.length !== 1) throw new ConnectionBlock("blocked_target", "dedicated_github_user_connection_required"); + await savedAccount.selectOption(active[0]!.connectionId); + await page.getByRole("button", { name: "Check my account", exact: true }).click(); + await expect(page.getByText(`GitHub account: ${input.githubUsername}`, { exact: true })).toBeVisible(); + await page.getByRole("button", { name: "Confirm my account", exact: true }).click(); + } else if (await page.getByRole("button", { name: "Confirm my account", exact: true }).isVisible()) { + await expect(page.getByText(`Connect GitHub account ${input.githubUsername} to your Paperclip account.`, { exact: true })).toBeVisible(); + await page.getByRole("button", { name: "Confirm my account", exact: true }).click(); + } else if (await page.getByRole("button", { name: "Connect my GitHub account", exact: true }).isVisible()) { + throw new ConnectionBlock("blocked_target", "saved_github_user_connection_required"); + } + await page.getByRole("button", { name: "Done", exact: true }).click(); + await input.checkpoint("identity", page); + await input.phase("review_configuration"); + const configuredEndpoint = await api.get(`/api/chat-endpoints/${endpoint.id}`); + const repositories = await api.get(`/api/chat-endpoints/${endpoint.id}/github/repositories?limit=100&offset=0`); + if (configuredEndpoint.status !== "active" || configuredEndpoint.assignedAgentId !== config.agent.id + || repositories.totalCount !== 1 || repositories.enabledCount !== 1 + || repositories.items.length !== 1 || !repositories.items[0]!.enabled + || repositories.items[0]!.label !== config.github.repository) throw new ConnectionFailure("installation_repository_scope_mismatch"); + if (!captureOwnedGitHubApp(resources, configuredEndpoint, config)) throw new ConnectionFailure("created_github_app_identity_unavailable"); + const editor = page.getByRole("textbox", { name: "Agent instructions", exact: true }); + await editor.fill("/"); + await page.getByRole("button", { name: new RegExp(`/${config.agent.skill}.*SKILL`, "i") }).click(); + await editor.press("End"); + await page.keyboard.type("\nReview this pull request using the selected review skill. Post findings and a numeric rating out of 5. Review only; do not modify repository files."); + const automatic = page.getByRole("switch", { name: "Run automatically", exact: true }); + if (await automatic.getAttribute("aria-checked") !== "true") await automatic.click(); + for (const label of ["New pull request", "Updated commits", "Reopened", "Ready for review"]) await page.getByRole("checkbox", { name: label, exact: true }).setChecked(label === "New pull request"); + await page.getByRole("checkbox", { name: "New issues", exact: true }).setChecked(false); + await page.getByLabel("Passing score", { exact: true }).fill("5"); + const savedConfiguration = page.waitForResponse(r => new URL(r.url()).pathname === `/api/chat-endpoints/${endpoint.id}/github/configuration` && r.request().method() === "PUT"); + await page.getByRole("button", { name: "Save changes", exact: true }).click(); + if (!(await savedConfiguration).ok()) throw new ConnectionFailure("review_configuration_save_failed"); + await expect(page.getByText("Changes saved.", { exact: true })).toBeVisible(); + const record = await api.get(`/api/chat-endpoints/${endpoint.id}/github/configuration`); + const policy = record.configuration.defaults; + if (policy.invocation === "mentions_only") throw new ConnectionFailure("saved_review_invocation_mismatch"); + if (!hasOnlyOpenedAutomaticReview(policy)) throw new ConnectionFailure("saved_review_events_mismatch"); + if (policy.ratingThreshold !== 5) throw new ConnectionFailure("saved_review_threshold_mismatch"); + if (!policy.instructions.includes(config.agent.skill)) throw new ConnectionFailure("saved_review_skill_mismatch"); + await input.checkpoint("configuration_saved", page); + await page.reload(); + await expect(editor).toContainText(config.agent.skill); + await input.checkpoint("configuration_reloaded", page); + await input.checkpoint("skill_binding", page); + // A branch can persist even if PR submission or navigation later fails. + evidence.cleanup.branch = false; + await input.persistResources(); + resources.pullNumber = await createGitHubJourneyPullRequest({ page: github, branch: resources.branch, title: `Ponytail precision eval ${resources.branch}`, contents: githubCartFixture }); + evidence.cleanup.pullRequest = false; + await input.persistResources(); + await input.checkpoint("pr_created", github); + const headSha = await observeGitHubHead(github); + await page.getByRole("link", { name: "Reviews", exact: true }).click(); + let review: GitHubTaskReview | undefined; + await awaitJourneyCondition(async () => { + const rows = await api.get(`/api/chat-endpoints/${endpoint.id}/github/reviews`); + const matches = rows.filter(r => r.repository === config.github.repository && r.pullNumber === resources.pullNumber && r.headSha === headSha && r.event.event === "opened"); + if (matches.length > 1) throw new ConnectionFailure("duplicate_automatic_review"); + review = matches[0]; return Boolean(review); + }, config.deadlineMs, "automatic_review_missing", input.signal, "failed"); + resources.issueId = review!.issueId; + await page.getByRole("link").filter({ hasText: `#${resources.pullNumber}` }).click(); + await input.checkpoint("automatic_task", page); + await awaitJourneyCondition(async () => { + review = await api.get(`/api/chat-endpoints/${endpoint.id}/github/reviews/${review!.id}`); + const runs = await readOwnedGitHubReviewRuns(api, { companyId: company.id, agentId: agent.id, issueId: review!.issueId }); + resources.runIds = runs.map(r => r.id); + if (resources.runIds.length > config.maximumRuns) throw new ConnectionFailure("review_run_limit_exceeded"); + if (["error", "incomplete", "superseded", "manual_required"].includes(review!.state)) throw new ConnectionFailure("review_terminal_failure"); + return review!.state === "completed"; + }, config.deadlineMs, "review_completion_timeout", input.signal, "failed"); + await input.phase("review_execution_completion"); + evidence.review = retainGitHubReview(review!); + let issue: any; let completedRun: any; + // Submitting the assessment can precede publication and the agent's final + // task completion. A completed review record is not a settled heartbeat run. + await awaitJourneyCondition(async () => { + review = await api.get(`/api/chat-endpoints/${endpoint.id}/github/reviews/${review!.id}`); + evidence.review = retainGitHubReview(review!); + const runs = await readOwnedGitHubReviewRuns(api, { companyId: company.id, agentId: agent.id, issueId: review!.issueId }); + resources.runIds = runs.map(r => r.id); + if (resources.runIds.length > config.maximumRuns) throw new ConnectionFailure("review_run_limit_exceeded"); + issue = await api.get(`/api/issues/${review!.issueId}`); + completedRun = review!.runId ? await api.get(`/api/heartbeat-runs/${review!.runId}`) : undefined; + evidence.execution = { reviewId: review!.id, issueId: review!.issueId, runId: review!.runId, + runStatus: completedRun?.status, issueStatus: issue.status, runtimeMode: completedRun?.runtimeMode, + environmentId: completedRun?.contextSnapshot?.paperclipEnvironment?.id, + provider: completedRun?.runnerProfileJson?.nativeExecutionInput?.provider?.kind, + model: completedRun?.runnerProfileJson?.nativeExecutionInput?.provider?.model }; + if (completedRun && (completedRun.companyId !== company.id || completedRun.agentId !== agent.id + || completedRun.issueId !== review!.issueId)) throw new ConnectionFailure("review_run_owner_mismatch"); + if (completedRun && ["failed", "timed_out", "cancelled", "interrupted"].includes(completedRun.status)) throw new ConnectionFailure("review_run_terminal_failure"); + return completedRun?.status === "succeeded" && issue.status === "done"; + }, config.deadlineMs, "review_execution_completion_timeout", input.signal, "failed"); + if (!verifyGitHubReviewRun(completedRun, { runId: review!.runId, companyId: company.id, agentId: agent.id, issueId: review!.issueId, + runtimeMode: config.agent.runtimeMode, environmentId: config.target.environmentId, executionEnvironment: config.executionEnvironment, + environment: await api.get(`/api/environments/${config.target.environmentId}`), provider: config.agent.provider, model: config.agent.model })) throw new ConnectionFailure("review_run_binding_mismatch"); + evidence.dependencies.find(d => d.alias === "review-agent-provider")!.status = "ready"; + if (!verifyGitHubReview({ review: review!, issue, companyId: company.id, endpointId: endpoint.id, issueId: review!.issueId, repository: config.github.repository, + pullNumber: resources.pullNumber, headSha, agentId: agent.id })) throw new ConnectionFailure("review_oracle_failed"); + evidence.score = review!.assessment!.score; evidence.conclusion = review!.conclusion!; + await input.checkpoint("review_completed", page); + await github.reload(); + await expect(github.getByText(`${evidence.score}/5`, { exact: false }).first()).toBeVisible(); + await expect(github.getByText(/precision|decimal|floating|cents/i).first()).toBeVisible(); + await input.checkpoint("github_delivery", github); + const inline = github.locator(".review-thread-component") + .filter({ has: github.getByRole("link", { name: "cart-total.js", exact: true }) }) + .filter({ has: github.locator(".review-comment .comment-body").filter({ hasText: /precision|decimal|floating|cents/i }) }).first(); + await expect(inline).toBeVisible(); + await expect(inline.locator(`.review-comment a[href="/apps/${resources.appSlug}"]`).first()).toBeVisible(); + const fileUrl = new URL(await inline.getByRole("link", { name: "cart-total.js", exact: true }).getAttribute("href") ?? "", "https://github.com"); + const commentUrl = new URL(await inline.locator('a[href^="#discussion_r"]').first().getAttribute("href") ?? "", github.url()); + if (fileUrl.origin !== "https://github.com" || fileUrl.pathname !== `/${config.github.repository}/pull/${resources.pullNumber}/files/${headSha}` + || commentUrl.origin !== "https://github.com" || commentUrl.pathname !== `/${config.github.repository}/pull/${resources.pullNumber}` + || !/^#discussion_r\d+$/.test(commentUrl.hash)) throw new ConnectionFailure("inline_publication_binding_mismatch"); + evidence.inlinePublication = { url: commentUrl.href, fileUrl: fileUrl.href, path: "cart-total.js", author: resources.appSlug!, + text: await inline.locator(".review-comment .comment-body").filter({ hasText: /precision|decimal|floating|cents/i }).first().innerText() }; + await inline.scrollIntoViewIfNeeded(); + await input.checkpoint("github_inline_delivery", github); + const checkPopup = page.context().waitForEvent("page"); + await page.getByRole("link", { name: "Check", exact: true }).click(); + const check = await checkPopup; + await expect(check.getByText(`${evidence.score}/5`, { exact: false }).first()).toBeVisible(); + await expect(check.getByText(/failed/i).first()).toBeVisible(); + await input.checkpoint("check_projection", check); + await page.getByRole("link", { name: "Paperclip task", exact: true }).click(); + await expect(page.getByText("Done", { exact: true }).first()).toBeVisible(); + await input.checkpoint("task_done", page); + await page.reload(); await github.reload(); + await expect(page.getByText("Done", { exact: true }).first()).toBeVisible(); + await expect(github.getByText(`${evidence.score}/5`, { exact: false }).first()).toBeVisible(); + await input.checkpoint("persisted", page); +} diff --git a/tests/runner-e2e/github-review-journey.test.ts b/tests/runner-e2e/github-review-journey.test.ts new file mode 100644 index 00000000000..8489b4596b0 --- /dev/null +++ b/tests/runner-e2e/github-review-journey.test.ts @@ -0,0 +1,309 @@ +import { describe, expect, it, vi } from "vitest"; +import { parseJourneyCredentialBinding, resolveJourneyCredential } from "./journey-dependencies.js"; +import { parseGitHubReviewJourneyConfig } from "./github-review-config.js"; +import { githubJourneyCheckpoints, gradeGitHubReviewJourney, hasOnlyOpenedAutomaticReview, verifyGitHubReview, verifyGitHubReviewRun, type GitHubReviewJourneyEvidence } from "./github-review-evidence.js"; +import { runnerMatrix } from "./catalog.js"; +import { buildMatrixJobs, parseRunnerSelectors, selectRunnerExecutions } from "./selectors.js"; +import type { GitHubTaskReview } from "../../packages/shared/src/types/chat-github.js"; +import { verifyConnectionTarget } from "./connection-target.js"; +import { parseConnectionConfig } from "./connection-config.js"; +import type { APIRequestContext } from "@playwright/test"; +import { captureOwnedGitHubApp, readOwnedGitHubReviewRuns, type GitHubJourneyResources } from "./github-review-ownership.js"; +import type { ChatEndpoint } from "../../packages/shared/src/types/chat-channels.js"; +import { enterGitHubJourneyCompany, isGitHubJourneyEvidencePage } from "./github-review-browser.js"; +import { attendGitHubJourneyAction } from "./github-review-attendance.js"; +import { PassThrough } from "node:stream"; +import type { Locator, Page } from "@playwright/test"; +import { validateRetainedRunnerResult } from "./result-validation.js"; +import { runGitHubReviewCampaign } from "./github-review-launch.js"; +import type { ConnectionApi } from "./connection-target.js"; +import { runGitHubReviewFlow } from "./github-review-flow.js"; + +describe("reused target ownership", () => { + it("admits an inherited environment before setup and still leaves actual-run verification mandatory", async () => { + const setup = parseGitHubReviewJourneyConfig(config()); + const company = { id: setup.target.companyId, issuePrefix: "QA" }; + const rows: Record = { + "/api/instance/settings/experimental": { enableGitHubReviewBots: true }, + [`/api/companies/${company.id}`]: company, + [`/api/agents/${setup.agent.id}`]: { companyId: company.id, name: setup.agent.name, status: "idle", defaultEnvironmentId: null, adapterConfig: { model: setup.agent.model } }, + [`/api/environments/${setup.target.environmentId}`]: { id: setup.target.environmentId, driver: "local", status: "active", config: {} }, + [`/api/companies/${company.id}/budgets/overview`]: { policies: [] }, + }; + const api = { origin: setup.target.baseURL, get: async (route: string) => rows[route] }; + const page = { goto: async () => {}, waitForURL: async () => {} }; + await expect(runGitHubReviewFlow({ api: api as unknown as ConnectionApi, page: page as unknown as Page, github: {} as Page, + githubUsername: "fixture", config: setup, resources: { branch: "owned", appName: "owned", runIds: [] }, + evidence: { version: 1, setupId: "qa", hosting: "paperclip-cloud", targetCommit: null, assisted: false, outcome: "running", phase: "setup", dependencies: [], checkpoints: {}, cleanup: { endpoint: true, app: true, pullRequest: true, branch: true } }, + signal: new AbortController().signal, phase: async () => {}, persistResources: async () => {}, + checkpoint: async id => { if (id === "agent") throw new Error("preflight_admitted"); }, + })).rejects.toThrow("preflight_admitted"); + }); + it("enters the configured company before using its navigation despite remembered browser state", async () => { + let current = new URL("https://qa.example.test/OTHER/dashboard"); + const page = { goto: vi.fn(async (url: string) => { current = new URL(url); }), + waitForURL: vi.fn(async (predicate: (url: URL) => boolean) => { expect(predicate(current)).toBe(true); }) }; + await enterGitHubJourneyCompany(page as unknown as Page, current.origin, { issuePrefix: "QA" }); + expect(current.pathname).toBe("/QA/dashboard"); + }); + it("finds the owned run outside company history windows and excludes related foreign-task activity", async () => { + const get = vi.fn(async (route: string) => { + if (route === "/api/issues/issue/runs") return [{ runId: "old-owned" }, { runId: "related" }, { runId: "old-owned" }]; + if (route === "/api/heartbeat-runs/old-owned") return { id: "old-owned", companyId: "company", agentId: "agent", issueId: "issue" }; + if (route === "/api/heartbeat-runs/related") return { id: "related", companyId: "company", agentId: "agent", issueId: "other-issue" }; + throw new Error("company_history_must_not_be_used"); + }); + const runs = await readOwnedGitHubReviewRuns({ get } as unknown as Pick, { companyId: "company", agentId: "agent", issueId: "issue" }); + expect(runs.map(run => run.id)).toEqual(["old-owned"]); + expect(get).toHaveBeenCalledTimes(3); + }); + it("rejects a foreign company in hydrated run inventory", async () => { + const get = vi.fn(async (route: string) => route.endsWith("/runs") ? [{ runId: "foreign" }] : { id: "foreign", companyId: "other", agentId: "agent", issueId: "issue" }); + await expect(readOwnedGitHubReviewRuns({ get } as unknown as Pick, { companyId: "company", agentId: "agent", issueId: "issue" })).rejects.toThrow("issue_run_company_mismatch"); + }); +}); + +describe("governed campaign admission", () => { + it("rejects operations-managed selection before opening credentials or browsers", async () => { + const execution = runnerMatrix.find(entry => entry.id === "github-review-journey.configured-agent.daytona.setup-and-first-review")!; + vi.stubEnv("PAPERCLIP_E2E_OPERATIONS_MANIFEST", "/private/campaign.json"); + try { + await expect(runGitHubReviewCampaign({ executions: [execution], catalog: runnerMatrix, repositoryRoot: "/does-not-exist" })) + .rejects.toThrow("no budgeted routing qualification"); + } finally { vi.unstubAllEnvs(); } + }); +}); + +describe("automatic review event policy", () => { + it("accepts opened-only automation while ordinary mentions and comment replies remain available", () => { + expect(hasOnlyOpenedAutomaticReview({ events: ["opened", "mention", "comment"], issueOpened: false })).toBe(true); + }); + it("rejects missing opened events, other automatic triggers, and issue intake", () => { + for (const events of [["mention", "comment"], ["opened", "synchronize"], ["opened", "reopened"], ["opened", "ready_for_review"]] as const) { + expect(hasOnlyOpenedAutomaticReview({ events: [...events] })).toBe(false); + } + expect(hasOnlyOpenedAutomaticReview({ events: ["opened"], issueOpened: true })).toBe(false); + }); +}); + +describe("retained journey metadata", () => { + it("accepts actual budget/execution fields while rejecting unrelated private metadata", () => { + const evidence: GitHubReviewJourneyEvidence = { version: 1, outcome: "failed", phase: "review_execution_completion", setupId: "qa", hosting: "paperclip-cloud", targetCommit: "a".repeat(40), assisted: true, + dependencies: [], checkpoints: { automatic_task: true }, cleanup: { endpoint: true, app: true, branch: true, pullRequest: true }, budgetPolicyRead: "verified", + budgetPolicies: [{ scopeType: "agent", amount: 100, hardStopEnabled: true, unpricedUsagePolicy: "allow" }], + execution: { reviewId: "review", issueId: "issue", runId: "run", runStatus: "failed", issueStatus: "in_progress", runtimeMode: "native", environmentId: "sandbox", provider: "opencode", model: "configured-model" } }; + const result = { schema: "paperclip.runner-e2e.result/v2", executionId: "github-review-journey.configured-agent.local.setup-and-first-review", suiteId: "github-review-journey", suiteDefinitionHash: "definition", + attempt: 1, status: "failed", profileId: "configured-agent", environmentId: "local", caseId: "setup-and-first-review", provider: "opencode", model: "configured-model", runtimeMode: "native", + startedAt: "2026-10-24T00:00:00Z", finishedAt: "2026-10-24T00:01:00Z", durationMs: 60000, cleanup: "passed", githubReviewJourney: evidence }; + expect(() => validateRetainedRunnerResult(result)).not.toThrow(); + expect(() => validateRetainedRunnerResult({ ...result, githubReviewJourney: { ...evidence, execution: { ...evidence.execution, credential: "not-allowed" } } })).toThrow(/execution/); + expect(() => validateRetainedRunnerResult({ ...result, githubReviewJourney: { ...evidence, budgetPolicies: [{ ...evidence.budgetPolicies![0], credential: "not-allowed" }] } })).toThrow(/budgetPolicies/); + }); +}); + +describe("review execution attribution", () => { + const expected = { runId: "run", companyId: "company", agentId: "agent", issueId: "issue", runtimeMode: "native", environmentId: "sandbox", executionEnvironment: "daytona" as const, + environment: { id: "sandbox", driver: "sandbox", config: { provider: "daytona" } }, provider: "opencode", model: "configured-model" }; + const run = () => ({ id: "run", companyId: "company", agentId: "agent", issueId: "issue", status: "succeeded", runtimeMode: "native", + contextSnapshot: { paperclipEnvironment: { id: "sandbox", driver: "sandbox" } }, runnerProfileJson: { nativeExecutionInput: { provider: { kind: "opencode", model: "configured-model" } } } }); + it("rejects a mismatched environment kind or provider even when the ID matches", () => { + expect(verifyGitHubReviewRun(run(), { ...expected, executionEnvironment: "local" })).toBe(false); + expect(verifyGitHubReviewRun(run(), { ...expected, environment: { ...expected.environment, config: { provider: "fake" } } })).toBe(false); + expect(verifyGitHubReviewRun({ ...run(), contextSnapshot: { paperclipEnvironment: { id: "sandbox", driver: "local" } } }, expected)).toBe(false); + const local = { ...run(), contextSnapshot: { paperclipEnvironment: { id: "local", driver: "local" } } }; + expect(verifyGitHubReviewRun(local, { ...expected, executionEnvironment: "local", environmentId: "local", environment: { id: "local", driver: "local", config: {} } })).toBe(true); + }); + it("requires the actual successful native run, environment, provider, and model", () => { + expect(verifyGitHubReviewRun(run(), expected)).toBe(true); + expect(verifyGitHubReviewRun(undefined, expected)).toBe(false); + expect(verifyGitHubReviewRun({ ...run(), runnerProfileJson: {} }, expected)).toBe(false); + expect(verifyGitHubReviewRun(run(), { ...expected, model: "another-model" })).toBe(false); + expect(verifyGitHubReviewRun(run(), { ...expected, environmentId: "another-sandbox" })).toBe(false); + }); + it.each(["queued", "running", "failed", "cancelled"])("does not accept a %s run merely because a review record completed", status => { + expect(verifyGitHubReviewRun({ ...run(), status }, expected)).toBe(false); + }); + it.each(["runId", "companyId", "agentId", "issueId"] as const)("rejects foreign %s attribution", key => { + expect(verifyGitHubReviewRun(run(), { ...expected, [key]: "foreign" })).toBe(false); + }); +}); + +describe("attended terminal control", () => { + it("ignores another App/action, accepts the current action once, and does not retain consent", async () => { + const terminal = Object.assign(new PassThrough(), { isTTY: true }); + const control = { isVisible: vi.fn(async () => true), click: vi.fn(async () => {}) }; + const log = vi.spyOn(console, "log").mockImplementation(() => {}); + vi.useFakeTimers(); + try { + const first = attendGitHubJourneyAction({ control: control as unknown as Locator, action: "create-app", appName: "Ponytail QA one", signal: new AbortController().signal, timeoutMs: 5_000 }, terminal); + terminal.write("create-app Ponytail QA another\ninstall-app Ponytail QA one\n"); + await vi.advanceTimersByTimeAsync(500); + expect(control.click).not.toHaveBeenCalled(); + terminal.write("create-app Ponytail QA one\n"); + await vi.advanceTimersByTimeAsync(500); + await first; + expect(control.click).toHaveBeenCalledTimes(1); + const abort = new AbortController(); + const second = attendGitHubJourneyAction({ control: control as unknown as Locator, action: "install-app", appName: "Ponytail QA one", signal: abort.signal, timeoutMs: 5_000 }, terminal); + const stopped = expect(second).rejects.toThrow("journey_interrupted"); + abort.abort(); + await vi.advanceTimersByTimeAsync(500); + await stopped; + expect(control.click).toHaveBeenCalledTimes(1); + } finally { terminal.destroy(); vi.useRealTimers(); log.mockRestore(); } + }); + it("never treats piped input as attended confirmation", async () => { + const terminal = Object.assign(new PassThrough(), { isTTY: false }); + const control = { isVisible: vi.fn(async () => true), click: vi.fn(async () => {}) }; + const abort = new AbortController(); + const log = vi.spyOn(console, "log").mockImplementation(() => {}); + vi.useFakeTimers(); + try { + const pending = attendGitHubJourneyAction({ control: control as unknown as Locator, action: "create-app", appName: "Ponytail QA one", signal: abort.signal, timeoutMs: 5_000 }, terminal); + const stopped = expect(pending).rejects.toThrow("journey_interrupted"); + terminal.write("create-app Ponytail QA one\n"); + abort.abort(); + await vi.advanceTimersByTimeAsync(500); + await stopped; + expect(control.click).not.toHaveBeenCalled(); + } finally { terminal.destroy(); vi.useRealTimers(); log.mockRestore(); } + }); +}); + +describe("journey screenshot boundaries", () => { + it("captures owned PR, check and installation pages while excluding auth and foreign resources", () => { + const capture = (url: string) => isGitHubJourneyEvidencePage(url, "https://qa.example.test", "fixture/repo", "owned-app"); + for (const url of ["https://qa.example.test/QA/issues/QA-1", "https://github.com/fixture/repo/pull/7", "https://github.com/fixture/repo/runs/123", "https://github.com/apps/owned-app/installations/new"]) expect(capture(url)).toBe(true); + for (const url of ["https://qa.example.test/QA/apps/connect", "https://qa.example.test/callback?code=secret", "https://github.com/login", "https://github.com/apps/shared-app/installations/new", "https://github.com/foreign/repo/pull/7", "https://github.com/fixture/repo/settings/secrets"]) expect(capture(url)).toBe(false); + }); +}); + +describe("durable journey credential references", () => { + it("resolves one selected field through a service-account-only child environment", async () => { + const secret = vi.fn(); + const read = vi.fn(async () => "resolved-value"); + expect(await resolveJourneyCredential({ source: "onepassword", reference: "op://vault/item/username" }, { env: { PATH: "/bin", OP_SERVICE_ACCOUNT_TOKEN: "service-account", GITHUB_TOKEN: "unrelated", OP_SESSION_user: "personal-session", OPENAI_API_KEY: "foreign-provider" }, read, registerSecret: secret })).toBe("resolved-value"); + expect(read).toHaveBeenCalledWith("op://vault/item/username", { PATH: "/bin", OP_SERVICE_ACCOUNT_TOKEN: "service-account" }, undefined); + expect(secret.mock.calls.flat()).toEqual(["service-account", "resolved-value"]); + }); + it("does not fall back to a personal desktop login or another environment credential", async () => { + const read = vi.fn(); + await expect(resolveJourneyCredential({ source: "onepassword", reference: "op://vault/item/password" }, { env: { OP_SESSION_user: "personal" }, read, registerSecret: vi.fn() })).rejects.toThrow("service_account_unavailable"); + expect(read).not.toHaveBeenCalled(); + }); + it.each([{ source: "onepassword", reference: "op://vault/item/password", value: "raw-password" }, { source: "onepassword", reference: "$(cat secrets)" }, { source: "environment", variable: "OP_SERVICE_ACCOUNT_TOKEN" }])("rejects malformed or literal bindings", binding => { + expect(() => parseJourneyCredentialBinding(binding)).toThrow("invalid_dependency_binding"); + }); + it("retains only a closed failure code when op fails with sensitive stderr", async () => { + await expect(resolveJourneyCredential({ source: "onepassword", reference: "op://vault/item/password" }, { env: { OP_SERVICE_ACCOUNT_TOKEN: "secret" }, read: async () => { throw new Error("private token and item path"); }, registerSecret: vi.fn() })).rejects.toThrow(/^credential_unavailable$/); + }); +}); + +const config = () => ({ version: 1, setupId: "qa-test", hosting: "paperclip-cloud", target: { mode: "attach", baseURL: "https://qa.example.test", expectedCommit: "a".repeat(40), deploymentMode: "authenticated", companyId: "11111111-1111-4111-8111-111111111111", environmentId: "22222222-2222-4222-8222-222222222222" }, + browser: { headed: true, channel: "chrome", profileDir: "/private/qa-browser", accountAlias: "ralph-qa", freshness: "signed-in" }, + agent: { id: "22222222-2222-4222-8222-222222222222", name: "Ponytail QA", skill: "ponytail-review", model: "configured-model", provider: "openai", runtimeMode: "native" }, + github: { repository: "fixture/ponytail-evals", ownerType: "personal", appOwner: "fixture", login: "passkey", username: { source: "onepassword", reference: "op://vault/item/username" } } }); + +describe("setup profiles and selection", () => { + it("requires an actual environment binding for every selected cell", () => { + const value = config(); + const { environmentId: _environmentId, ...target } = value.target; + expect(() => parseGitHubReviewJourneyConfig({ ...value, target })).toThrow("invalid_github_journey_configuration"); + }); + it("verifies a protected hosted target through the authenticated session without following redirects", async () => { + const get = vi.fn(async () => ({ ok: () => true, json: async () => ({ commit: "a".repeat(40), deploymentMode: "authenticated" }) })); + await expect(verifyConnectionTarget("https://qa.example.test", parseConnectionConfig({ target: config().target }), { get } as unknown as APIRequestContext)).resolves.toMatchObject({ commit: "a".repeat(40) }); + expect(get).toHaveBeenCalledWith("https://qa.example.test/api/health", { maxRedirects: 0, timeout: 15_000 }); + get.mockResolvedValueOnce({ ok: () => false, json: async () => ({}) } as any); + await expect(verifyConnectionTarget("https://qa.example.test", parseConnectionConfig({ target: config().target }), { get } as unknown as APIRequestContext)).rejects.toThrow("target_health_unavailable_or_redirected"); + }); + it("keeps Cloud hosting separate from agent execution and declares passkey without requiring an exported password", () => { + expect(parseGitHubReviewJourneyConfig(config())).toMatchObject({ hosting: "paperclip-cloud", github: { login: "passkey" } }); + expect(parseGitHubReviewJourneyConfig({ ...config(), hosting: "self-hosted" }).hosting).toBe("self-hosted"); + expect(parseGitHubReviewJourneyConfig({ ...config(), executionEnvironment: "daytona" }).executionEnvironment).toBe("daytona"); + expect(parseGitHubReviewJourneyConfig(config()).github.account).toBe("fixture"); + expect(() => parseGitHubReviewJourneyConfig({ ...config(), github: { ...config().github, ownerType: "organization" } })).toThrow("invalid_github_journey_configuration"); + expect(() => parseGitHubReviewJourneyConfig({ ...config(), github: { ...config().github, password: "literal" } })).toThrow("invalid_github_journey_configuration"); + }); + it("discovers the exact journey and excludes it from all and CI paid matrices", () => { + const cells = runnerMatrix.filter(c => c.suite.id === "github-review-journey"); + expect(cells).toHaveLength(2); + const options = parseRunnerSelectors(["--suite", "github-review-journey", "--environment", "local", "--github-review-config", "/private/profile.json"]); + expect(selectRunnerExecutions(options).map(c => c.id)).toEqual(cells.filter(c => c.environment.id === "local").map(c => c.id)); + expect(selectRunnerExecutions(parseRunnerSelectors(["--all"])).some(c => c.suite.id === "github-review-journey")).toBe(false); + expect(() => buildMatrixJobs(cells)).toThrow(/Attended connection journeys/); + expect(cells[0]!.requiredCredentials).toEqual([]); + }); +}); + +describe("GitHub App cleanup ownership", () => { + const fixture = () => { + const profile = parseGitHubReviewJourneyConfig(config()); + const resources: GitHubJourneyResources = { endpointId: "endpoint", appName: "Ponytail QA nonce", branch: "owned", runIds: [] }; + const endpoint = { id: "endpoint", companyId: profile.target.companyId, provider: "github", assignedAgentId: profile.agent.id, + botExternalId: "12345", botUsername: "ponytail-qa-nonce[bot]", botLabel: resources.appName, + setup: { step: "provider_setup", github: { registrationStatus: "completed", appOwnerType: "personal", appOwnerLogin: "fixture", appSlug: "ponytail-qa-nonce", managementUrl: "https://github.com/settings/installations/67890" } } } as ChatEndpoint; + return { profile, resources, endpoint }; + }; + it("records the verified App registration separately from its installation", () => { + const f = fixture(); + expect(captureOwnedGitHubApp(f.resources, f.endpoint, f.profile)).toBe(true); + expect(f.resources).toMatchObject({ appId: "12345", appSlug: "ponytail-qa-nonce", appSettingsUrl: "https://github.com/settings/apps/ponytail-qa-nonce", installationSettingsUrl: "https://github.com/settings/installations/67890" }); + }); + it("cannot adopt the shared testing App, a foreign endpoint, or a renamed App", () => { + for (const mutate of [(e: ChatEndpoint) => { e.setup.github!.appOwnerLogin = "paperclipai"; }, (e: ChatEndpoint) => { e.id = "foreign"; }, + (e: ChatEndpoint) => { e.botLabel = "[Test] Paperclip"; }, (e: ChatEndpoint) => { e.botUsername = "foreign[bot]"; }]) { + const f = fixture(); mutate(f.endpoint); + expect(() => captureOwnedGitHubApp(f.resources, f.endpoint, f.profile)).toThrow("owned_github_app_binding_mismatch"); + expect(f.resources.appSettingsUrl).toBeUndefined(); + } + }); + it("rejects replacement of an already recorded immutable App ID", () => { + const f = fixture(); captureOwnedGitHubApp(f.resources, f.endpoint, f.profile); f.endpoint.botExternalId = "99999"; + expect(() => captureOwnedGitHubApp(f.resources, f.endpoint, f.profile)).toThrow("owned_github_app_binding_mismatch"); + expect(f.resources.appId).toBe("12345"); + }); + it("does not invent a cleanup URL while registration is incomplete", () => { + const f = fixture(); f.endpoint.setup.github!.registrationStatus = "pending"; + expect(captureOwnedGitHubApp(f.resources, f.endpoint, f.profile)).toBe(false); + expect(f.resources.appSettingsUrl).toBeUndefined(); + }); +}); + +const head = "d".repeat(40); +function oracleInput() { + const review = { id: "review", companyId: "company", endpointId: "endpoint", issueId: "issue", runId: "run", repositoryId: "repo", repository: "fixture/repo", pullNumber: 7, headSha: head, + event: { event: "opened", headSha: head, repository: "fixture/repo" }, state: "completed", conclusion: "failure", summaryUrl: "https://github.com/fixture/repo/pull/7#issuecomment-1", checkUrl: "https://github.com/fixture/repo/runs/1", + assessment: { complete: true, reviewedCommit: head, score: 3, summary: "Decimal prices lose precision.", rationale: "Reproduced currency error", coverage: { reviewedPaths: ["cart-total.js"], omittedPaths: [], limitations: [] }, findings: [{ path: "cart-total.js", side: "RIGHT", line: 5, body: "Decimal price precision fails", severity: "warning", category: "correctness" }] } } as unknown as GitHubTaskReview; + return { review, companyId: "company", endpointId: "endpoint", issueId: "issue", repository: "fixture/repo", pullNumber: 7, headSha: head, agentId: "agent", issue: { id: "issue", companyId: "company", assigneeAgentId: "agent", status: "done" } }; +} + +describe("independent GitHub review oracle", () => { + it("accepts a useful 3/5 review with a correctly failed check", () => expect(verifyGitHubReview(oracleInput())).toBe(true)); + it.each(["headSha", "repository", "issueId", "endpointId", "companyId"] as const)("rejects a stale or foreign %s", key => { + const input = oracleInput(); input.review[key] = "foreign"; + expect(verifyGitHubReview(input)).toBe(false); + }); + it("rejects manual triggering, false completion, missing delivery and a 5/5 score for the known defect", () => { + for (const mutate of [(r: GitHubTaskReview) => { r.event.event = "mention"; }, (r: GitHubTaskReview) => { r.assessment!.complete = false; }, + (r: GitHubTaskReview) => { r.summaryUrl = null; }, (r: GitHubTaskReview) => { r.assessment!.score = 5; }, (r: GitHubTaskReview) => { r.assessment!.findings = []; }]) { + const input = oracleInput(); mutate(input.review); expect(verifyGitHubReview(input)).toBe(false); + } + }); + it("rejects foreign delivery links even when the task and assessment match", () => { + for (const [field, value] of [["summaryUrl", "https://github.com/fixture/repo/pull/8#issuecomment-1"], ["summaryUrl", "https://github.com/foreign/repo/pull/7#issuecomment-1"], + ["checkUrl", "https://example.test/fixture/repo/runs/1"], ["checkUrl", "https://github.com/foreign/repo/runs/1"]] as const) { + const input = oracleInput(); input.review[field] = value; + expect(verifyGitHubReview(input)).toBe(false); + } + }); + it("fails missing checkpoint or cleanup evidence even when every other gate passed", () => { + const evidence: GitHubReviewJourneyEvidence = { version: 1, outcome: "passed", phase: "finished", hosting: "paperclip-cloud", setupId: "qa", targetCommit: head, assisted: true, dependencies: [], + checkpoints: Object.fromEntries(githubJourneyCheckpoints.map(id => [id, true])), cleanup: { endpoint: true, app: true, pullRequest: true, branch: true } }; + expect(gradeGitHubReviewJourney(evidence).every(c => c.passed)).toBe(true); + delete evidence.checkpoints.github_delivery; + expect(gradeGitHubReviewJourney(evidence).every(c => c.passed)).toBe(false); + evidence.checkpoints.github_delivery = true; evidence.cleanup.app = false; + expect(gradeGitHubReviewJourney(evidence).every(c => c.passed)).toBe(false); + }); +}); diff --git a/tests/runner-e2e/github-review-launch.ts b/tests/runner-e2e/github-review-launch.ts new file mode 100644 index 00000000000..a78365f6add --- /dev/null +++ b/tests/runner-e2e/github-review-launch.ts @@ -0,0 +1,271 @@ +import { randomBytes, createHash } from "node:crypto"; +import { execFileSync } from "node:child_process"; +import { mkdir, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { pathToFileURL } from "node:url"; +import type { Page } from "@playwright/test"; +import { expect } from "@playwright/test"; +import { ConnectionBlock, ConnectionFailure } from "./connection-config.js"; +import { ConnectionApi, verifyConnectionTarget } from "./connection-target.js"; +import { openConnectionBrowser, withConnectionCampaignCancellation } from "./connection-launch.js"; +import { createPrivateJourneyRepository, ensureGitHubJourneyLogin, closeOwnedGitHubPullRequest, awaitJourneyCondition, observeGitHubJourneyAccount, isGitHubJourneyEvidencePage } from "./github-review-browser.js"; +import { loadGitHubReviewJourneyConfig } from "./github-review-config.js"; +import { gradeGitHubReviewJourney, type GitHubReviewJourneyEvidence } from "./github-review-evidence.js"; +import { runGitHubReviewFlow } from "./github-review-flow.js"; +import { captureOwnedGitHubApp, readOwnedGitHubReviewRuns, type GitHubJourneyResources } from "./github-review-ownership.js"; +import { JourneyDependencyError, resolveJourneyCredential } from "./journey-dependencies.js"; +import { sanitizeJson, assertSecretFree } from "./redaction.js"; +import { writeGitHubReviewReport } from "./github-review-report.js"; +import { summarizeExecutionBilling, buildRuntimeUsage } from "./billing.js"; +import type { MatrixExecution, RunnerE2EResult } from "./types.js"; + +export async function runGitHubReviewCampaign(input: { executions: readonly MatrixExecution[]; catalog: readonly MatrixExecution[]; configFile?: string; repositoryRoot: string; provisionRepository?: boolean }) { + if (input.executions.length !== 1 || input.executions[0]!.task.flow !== "github_review_journey") throw new ConnectionFailure("Select exactly one GitHub review journey cell separately."); + if (process.env.PAPERCLIP_E2E_OPERATIONS_MANIFEST) throw new ConnectionFailure("GitHub review journey has no budgeted routing qualification"); + return withConnectionCampaignCancellation(async campaignSignal => { + const deadline = new AbortController(); + const signal = AbortSignal.any([campaignSignal, deadline.signal]); + const execution = input.executions[0]!; + const startedAt = new Date().toISOString(); + const nonce = randomBytes(5).toString("hex"); + const campaignId = `github-review-${startedAt.replace(/[:.]/g, "-")}-${nonce}`; + const output = path.join(input.repositoryRoot, "tests/runner-e2e/results", campaignId); + await mkdir(output, { recursive: true, mode: 0o700 }); + const secrets: string[] = []; + const save = async (name: string, value: unknown) => { + const text = JSON.stringify(sanitizeJson(value, secrets), null, 2) + "\n"; + assertSecretFree(text, secrets, name); await writeFile(path.join(output, name), text, { mode: 0o600 }); + }; + const evidence: GitHubReviewJourneyEvidence = { version: 1, setupId: "unresolved", hosting: "self-hosted", targetCommit: null, assisted: false, + outcome: "running", phase: "configuration", dependencies: [], checkpoints: {}, cleanup: { endpoint: true, pullRequest: true, branch: true, app: true } }; + const sha = execFileSync("git", ["rev-parse", "HEAD"], { cwd: input.repositoryRoot, encoding: "utf8" }).trim(); + const result: RunnerE2EResult = { schema: "paperclip.runner-e2e.result/v2", executionId: execution.id, suiteId: execution.suite.id, suiteDefinitionHash: execution.suiteDefinitionHash, + source: { sha, ref: "working-tree", workflowRunUrl: null }, attempt: 1, status: "failed", profileId: execution.profile.id, environmentId: execution.environment.id, caseId: execution.task.id, + provider: execution.profile.provider, model: execution.profile.model, runtimeMode: "native", startedAt, finishedAt: startedAt, durationMs: 0, cleanup: "not_started", githubReviewJourney: evidence, screenshots: [] }; + const resources: GitHubJourneyResources = { branch: `codex/ponytail-eval-${nonce}`, appName: `Ponytail QA ${nonce}`, runIds: [] }; + let browser: Awaited> | undefined; + let api: ConnectionApi | undefined; let github: Page | undefined; let page: Page | undefined; + let config: Awaited> | undefined; + const checkpoint = async (id: string) => { evidence.phase = id; await save("progress.json", { executionId: execution.id, ...evidence }); }; + const abort = () => { for (const tab of browser?.context.pages() ?? []) void tab.close().catch(() => {}); }; + signal.addEventListener("abort", abort, { once: true }); + let timer: ReturnType | undefined; + let repositoryCreated = false; + try { + config = await loadGitHubReviewJourneyConfig(input.configFile); + timer = setTimeout(() => deadline.abort(), config.deadlineMs); + const authentication = config.authentication ? await import(pathToFileURL(config.authentication.module).href) : undefined; + if (config.executionEnvironment !== execution.environment.id) throw new ConnectionBlock("blocked_target", "selected_execution_environment_mismatch"); + evidence.setupId = config.setupId; evidence.hosting = config.hosting; + result.provider = config.agent.provider; result.model = config.agent.model; result.runtimeMode = config.agent.runtimeMode; + evidence.definitionHash = createHash("sha256").update(execution.suiteDefinitionHash).update(JSON.stringify({ setup: config.setupId, hosting: config.hosting, agent: config.agent, repository: config.github.repository, login: config.github.login })).digest("hex"); + const common = { ...config, models: {}, routes: {}, credentials: {}, budgetCents: 1, maxRuns: config.maximumRuns, turnTimeoutMs: config.deadlineMs, retainCompany: true }; + const username = await resolveJourneyCredential(config.github.username, { signal, registerSecret: value => secrets.push(value) }); + evidence.dependencies.push({ alias: "github-user", consumer: "browser", status: "ready", source: config.github.username.source }); + evidence.dependencies.push({ alias: "review-agent-provider", consumer: "product-agent", status: "unverified", source: "product-connection" }); + evidence.checkpoints.dependencies = true; + browser = await openConnectionBrowser(common, input.repositoryRoot, config.target.baseURL); + page = await browser.context.newPage(); + github = await browser.context.newPage(); + await checkpoint("github_authentication"); + await github.goto(`https://github.com/${config.github.repository}`); + if (authentication?.authenticateGitHubJourneyUser) { + await authentication.authenticateGitHubJourneyUser({ page: github, configFile: config.authentication!.configFile, signal, + deadlineAt: Date.now() + config.browser.loginTimeoutMs, registerSecret: (value: string) => secrets.push(value), checkpoint: (id: string) => checkpoint(id) }); + } + await ensureGitHubJourneyLogin({ page: github, config, username, signal, checkpoint: async id => { evidence.assisted = true; await checkpoint(id); }, + ...(config.github.password ? { password: () => resolveJourneyCredential(config!.github.password!, { signal, registerSecret: value => secrets.push(value) }) } : {}) }); + if (input.provisionRepository) { + // Bootstrap is intentionally not graded as a setup-and-review attempt. + await createPrivateJourneyRepository(github, config.github.repository); + await save("repository-receipt.json", { version: 1, repository: config.github.repository, visibility: "private", createdAt: new Date().toISOString(), retained: true }); + repositoryCreated = true; + console.log("[github-review-journey] Private reusable QA repository created; receipt saved. Run the journey separately."); + return output; + } + // Authentication adapters can finish at GitHub home. Re-enter the declared + // repository before checking its visibility and preparing the measured PR. + await checkpoint("github_repository"); + await github.goto(`https://github.com/${config.github.repository}`); + await expect(github.getByText("Private", { exact: true }).first()).toBeVisible(); + await checkpoint("paperclip_authentication"); + await page.goto(config.target.baseURL); + if (config.authentication) { + if (typeof authentication?.authenticateGitHubJourney !== "function") throw new ConnectionBlock("blocked_target", "invalid_journey_authentication_adapter"); + await authentication.authenticateGitHubJourney({ page, origin: config.target.baseURL, configFile: config.authentication.configFile, signal, + deadlineAt: Date.now() + config.browser.loginTimeoutMs, registerSecret: (value: string) => secrets.push(value) }); + } + api = new ConnectionApi(browser.context.request, config.target.baseURL); + await checkpoint("awaiting_board_login"); + await awaitJourneyCondition(async () => { try { await api!.get(`/api/companies/${config!.target.companyId}`); return true; } catch { return false; } }, config.browser.loginTimeoutMs, "paperclip_login_required", signal); + const identity = await verifyConnectionTarget(config.target.baseURL, common, browser.context.request); + evidence.targetCommit = identity.commit; evidence.checkpoints.target = true; + await runGitHubReviewFlow({ page, github, githubUsername: config.github.account, api, config, resources, evidence, signal, + phase: checkpoint, persistResources: () => save("owned-resources.json", resources), checkpoint: async (id, tab) => { + evidence.checkpoints[id] = true; + // Authentication pages and forms are deliberately never captured. + const consentUrl = new URL(tab.url()); + const appCreation = id === "app_creation_consent" && consentUrl.origin === "https://github.com" + && await tab.getByRole("button", { name: new RegExp(`^Create GitHub App(?: for ${config!.github.appOwner})?$`) }).isVisible(); + if (id === "app_creation_consent") await save("app-creation-boundary.json", { origin: consentUrl.origin, path: consentUrl.pathname }); + if ((appCreation || isGitHubJourneyEvidencePage(tab.url(), config!.target.baseURL, config!.github.repository, resources.appSlug)) + && !await tab.locator('input[type="password"]:visible,input[autocomplete="one-time-code"]:visible').count()) { + const file = `${id}.png`; const bytes = await tab.screenshot({ path: path.join(output, file) }); + result.screenshots!.push({ id, label: id.replaceAll("_", " "), file, sha256: createHash("sha256").update(bytes).digest("hex") }); + } + await checkpoint(id); + await save("owned-resources.json", resources); + } }); + await verifyConnectionTarget(config.target.baseURL, common, browser.context.request); + result.issueId = resources.issueId; evidence.outcome = "passed"; + result.status = "passed"; + } catch (error) { + evidence.outcome = error instanceof ConnectionBlock ? error.reason : error instanceof JourneyDependencyError ? "missing_credential" : "failed"; + result.error = error instanceof ConnectionBlock ? error.code : error instanceof JourneyDependencyError ? error.code : error instanceof ConnectionFailure ? error.message : `${evidence.phase}_failed`; + result.failureClass = evidence.outcome === "failed" ? "candidate_failure" : "permanent_infrastructure"; + const frame = error instanceof Error ? error.stack?.match(/(?:github-review-(?:browser|flow|launch)|qa-authentication|github-authentication)\.(?:ts|mjs):\d+:\d+/)?.[0] : undefined; + if (frame) result.error += ` (${frame})`; + await save("attempt-error.json", { error: result.error, outcome: evidence.outcome, phase: evidence.phase }); + await save("progress.json", { executionId: execution.id, ...evidence }); + await save("owned-resources.json", resources); + if (github && config && !github.isClosed()) { + const url = new URL(github.url()); + await save("github-boundary.json", { origin: url.origin, path: url.pathname }); + const repositoryPath = config.github.repository.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + const pull = new RegExp(`^/${repositoryPath}/pull/(\\d+)$`).exec(url.pathname); + const title = `Ponytail precision eval ${resources.branch}`.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + if (!resources.pullNumber && pull && url.origin === "https://github.com" + && await github.getByRole("heading", { name: new RegExp(`^${title}(?:\\s|$)`) }).first().isVisible() + && await github.getByRole("link", { name: resources.branch, exact: true }).first().isVisible()) { + resources.pullNumber = Number(pull[1]); evidence.cleanup.pullRequest = false; + await save("owned-resources.json", resources); + } + if (url.origin === "https://github.com" && url.pathname === `/${config.github.repository}` + && !await github.locator('input[type="password"]:visible,input[autocomplete="one-time-code"]:visible').count()) { + await save("github-controls.json", { headings: await github.getByRole("heading").allTextContents(), buttons: await github.getByRole("button").allTextContents() }); + const bytes = await github.screenshot({ path: path.join(output, "github-failure.png") }).catch(() => null); + if (bytes) result.screenshots!.push({ id: "github-failure", label: evidence.phase, file: "github-failure.png", sha256: createHash("sha256").update(bytes).digest("hex") }); + } + } + if (page && config && !page.isClosed() && new URL(page.url()).origin === config.target.baseURL + && !/login|auth/.test(new URL(page.url()).pathname) && !await page.locator('input[type="password"]:visible,input[autocomplete="one-time-code"]:visible').count()) { + const bytes = await page.screenshot({ path: path.join(output, "failure.png") }).catch(() => null); + if (bytes) result.screenshots!.push({ id: "failure", label: evidence.phase, file: "failure.png", sha256: createHash("sha256").update(bytes).digest("hex") }); + await save("failure-controls.json", { phase: evidence.phase, + buttons: await page.getByRole("button").allTextContents().catch(() => []), + headings: await page.getByRole("heading").allTextContents().catch(() => []) }); + } + } finally { + if (timer) clearTimeout(timer); + signal.removeEventListener("abort", abort); + const cleanupSignal = AbortSignal.timeout(Math.min(config?.browser.loginTimeoutMs ?? 180_000, 600_000)); + const cleanupErrors: string[] = []; + if (resources.endpointId && api) { + evidence.cleanup.endpoint = false; + try { + const owned = await api.get(`/api/chat-endpoints/${resources.endpointId}`); + if (owned.companyId !== config!.target.companyId || owned.assignedAgentId !== config!.agent.id) throw new ConnectionFailure("cleanup_endpoint_owner_mismatch"); + if (owned.botExternalId) { + evidence.cleanup.app = false; + try { + if (!captureOwnedGitHubApp(resources, owned, config!)) cleanupErrors.push("owned_app_identity_unconfirmed"); + } catch { cleanupErrors.push("owned_app_binding_mismatch"); } + } + if (resources.issueId) { + const issue = await api.get(`/api/issues/${resources.issueId}`); + if (issue.companyId !== config!.target.companyId || issue.assigneeAgentId !== config!.agent.id) throw new ConnectionFailure("cleanup_issue_owner_mismatch"); + const boundRuns = await readOwnedGitHubReviewRuns(api, { companyId: config!.target.companyId, agentId: config!.agent.id, issueId: resources.issueId }); + resources.runIds = [...new Set([...resources.runIds, ...boundRuns.map(run => run.id)])]; + } + await save("owned-resources.json", resources); + await api.post(`/api/chat-endpoints/${resources.endpointId}/setup`, { action: "remove" }); + for (const runId of resources.runIds) { + const run = await api.get(`/api/heartbeat-runs/${runId}`); + if (run.companyId !== config!.target.companyId || run.agentId !== config!.agent.id) throw new ConnectionFailure("cleanup_run_owner_mismatch"); + if (["queued", "running"].includes(run.status)) { + await api.post(`/api/heartbeat-runs/${runId}/cancel`); + await awaitJourneyCondition(async () => !["queued", "running"].includes((await api!.get(`/api/heartbeat-runs/${runId}`)).status), 30_000, "owned_run_cancellation_unconfirmed", cleanupSignal, "failed"); + } + } + if (resources.issueId && result.status !== "passed") { + const issue = await api.get(`/api/issues/${resources.issueId}`); + if (issue.companyId !== config!.target.companyId || issue.assigneeAgentId !== config!.agent.id) throw new ConnectionFailure("cleanup_issue_owner_mismatch"); + if (!["done", "cancelled"].includes(issue.status)) { + await api.patch(`/api/issues/${issue.id}`, { status: "cancelled" }); + if ((await api.get(`/api/issues/${issue.id}`)).status !== "cancelled") throw new ConnectionFailure("owned_task_settlement_unconfirmed"); + await save("owned-task-cleanup.json", { issueId: issue.id, previousStatus: issue.status, status: "cancelled", reason: "failed_attempt" }); + } + } + evidence.cleanup.endpoint = (await api.get(`/api/chat-endpoints/${resources.endpointId}`)).status === "archived"; + } catch { cleanupErrors.push("endpoint_cleanup_failed"); } + } + if (resources.pullNumber && github && config) { + evidence.cleanup.pullRequest = false; evidence.cleanup.branch = false; + try { + if (github.isClosed() && browser) github = await browser.context.newPage(); + await github.goto(`https://github.com/${config.github.repository}/pull/${resources.pullNumber}`); + if ((await observeGitHubJourneyAccount(github)).toLowerCase() !== config.github.account.toLowerCase()) throw new ConnectionFailure("cleanup_github_account_mismatch"); + await closeOwnedGitHubPullRequest(github); + evidence.cleanup.pullRequest = true; evidence.cleanup.branch = true; + } catch { cleanupErrors.push("pull_request_cleanup_failed"); } + } else if (!evidence.cleanup.branch && github && config) { + try { + if (github.isClosed() && browser) github = await browser.context.newPage(); + await github.goto(`https://github.com/${config.github.repository}`); + const repository = await github.request.get(`https://github.com/${config.github.repository}`, { maxRedirects: 0 }); + const branch = await github.request.get(`https://github.com/${config.github.repository}/tree/${resources.branch}`, { maxRedirects: 0 }); + evidence.cleanup.branch = repository.status() === 200 && branch.status() === 404 + && (await observeGitHubJourneyAccount(github)).toLowerCase() === config.github.account.toLowerCase(); + if (!evidence.cleanup.branch) cleanupErrors.push("owned_branch_cleanup_required"); + } catch { cleanupErrors.push("owned_branch_cleanup_unconfirmed"); } + } + if (evidence.checkpoints.app_created || resources.appId || !evidence.cleanup.app) { + evidence.cleanup.app = false; + // App deletion is an explicit human action; never delete by an inferred name/URL. + if (resources.appSettingsUrl && github && config && new URL(resources.appSettingsUrl).origin === "https://github.com") { + try { + if (github.isClosed() && browser) github = await browser.context.newPage(); + await github.goto(resources.appSettingsUrl); + await github.bringToFront(); + console.log(`[github-review-journey] Remove only the disposable App named ${resources.appName} in the QA browser. The shared repository and existing user/provider credentials must remain.`); + await awaitJourneyCondition(async () => { + const response = await github!.request.get(resources.appSettingsUrl!, { maxRedirects: 0, timeout: 15_000 }); + if (response.status() !== 404) return false; + if ((await observeGitHubJourneyAccount(github!)).toLowerCase() !== config!.github.account.toLowerCase()) throw new ConnectionFailure("cleanup_github_account_mismatch"); + return true; + }, Math.min(config.browser.loginTimeoutMs, 600_000), "owned_app_cleanup_required", cleanupSignal); + evidence.cleanup.app = true; + } catch { cleanupErrors.push("app_cleanup_unconfirmed"); } + } else cleanupErrors.push("app_cleanup_unconfirmed"); + } + result.runIds = resources.runIds; + await save("owned-resources.json", resources); + if (api && resources.issueId && config) { + try { + const runs = await readOwnedGitHubReviewRuns(api, { companyId: config.target.companyId, agentId: config.agent.id, issueId: resources.issueId }); + result.runtimeUsage = buildRuntimeUsage({ environmentId: execution.environment.id, runs, fallbackFinishedAt: new Date().toISOString() }); + result.billing = summarizeExecutionBilling({ ...result, usage: { runs: runs.map(r => ({ usage: r.usageJson })) } }); + } catch { /* Missing billing remains unavailable; never substitute zero. */ } + } + if (result.billing) { result.billing.complete = false; result.billing.llm.costStatus = "partial"; } + await browser?.close().catch(() => cleanupErrors.push("browser_cleanup_failed")); + result.cleanup = cleanupErrors.length || !Object.values(evidence.cleanup).every(Boolean) ? "failed" : "passed"; + if (result.cleanup === "failed") { result.status = "failed"; result.failureClass = "cleanup_failure"; result.error = [result.error, ...cleanupErrors].filter(Boolean).join("; "); } + result.finishedAt = new Date().toISOString(); result.durationMs = Date.parse(result.finishedAt) - Date.parse(startedAt); + result.matcherResults = gradeGitHubReviewJourney(evidence); + if (!input.provisionRepository && result.status === "passed" && !result.matcherResults.every(check => check.passed)) { + result.status = "failed"; evidence.outcome = "failed"; result.failureClass = "candidate_failure"; result.error = "required_journey_evidence_missing"; + } + if (!input.provisionRepository) { + const reported = await writeGitHubReviewReport({ output, campaignId, result, resources, catalog: input.catalog, secrets }); + if (reported.status !== "passed" || reported.cleanup !== "passed") process.exitCode = 1; + } else { + await save("bootstrap-result.json", { created: repositoryCreated, outcome: repositoryCreated ? "passed" : evidence.outcome, error: result.error }); + if (!repositoryCreated) process.exitCode = 1; + } + await save("progress.json", evidence); + console.log(`[github-review-journey] ${evidence.outcome}; report directory: ${output}`); + } + return output; + }); +} diff --git a/tests/runner-e2e/github-review-ownership.ts b/tests/runner-e2e/github-review-ownership.ts new file mode 100644 index 00000000000..f1d15ee4855 --- /dev/null +++ b/tests/runner-e2e/github-review-ownership.ts @@ -0,0 +1,43 @@ +import type { ChatEndpoint } from "../../packages/shared/src/types/chat-channels.js"; +import { ConnectionFailure } from "./connection-config.js"; +import type { GitHubReviewJourneyConfig } from "./github-review-config.js"; +import type { ConnectionApi } from "./connection-target.js"; + +/** The issue run source includes history beyond company list windows. Related + * activity can name a run for another task, so hydrate and check direct ownership. */ +export async function readOwnedGitHubReviewRuns(api: Pick, scope: { companyId: string; agentId: string; issueId: string }) { + const rows = await api.get>(`/api/issues/${scope.issueId}/runs`); + if (!Array.isArray(rows) || rows.some(row => typeof row.runId !== "string" || !row.runId)) throw new ConnectionFailure("invalid_issue_run_inventory"); + const runs = await Promise.all([...new Set(rows.map(row => row.runId))].map(id => api.get>(`/api/heartbeat-runs/${id}`))); + if (runs.some(run => run.companyId !== scope.companyId)) throw new ConnectionFailure("issue_run_company_mismatch"); + return runs.filter(run => run.issueId === scope.issueId && run.agentId === scope.agentId); +} + +export interface GitHubJourneyResources { + endpointId?: string; pullNumber?: number; branch: string; appName: string; + appId?: string; appSlug?: string; appSettingsUrl?: string; installationSettingsUrl?: string; + issueId?: string; runIds: string[]; +} + +/** Bind cleanup to GitHub-confirmed identity on this attempt's owned endpoint. */ +export function captureOwnedGitHubApp(resources: GitHubJourneyResources, endpoint: ChatEndpoint, config: GitHubReviewJourneyConfig) { + if (!endpoint.botExternalId || endpoint.setup.github?.registrationStatus !== "completed") return false; + const app = endpoint.setup.github; + if (endpoint.id !== resources.endpointId || endpoint.companyId !== config.target.companyId || endpoint.provider !== "github" + || endpoint.assignedAgentId !== config.agent.id || endpoint.botLabel !== resources.appName + || !/^[1-9][0-9]*$/.test(endpoint.botExternalId) || !app.appSlug || !/^[a-z0-9-]+$/.test(app.appSlug) + || endpoint.botUsername !== `${app.appSlug}[bot]` || app.appOwnerType !== config.github.ownerType + || app.appOwnerLogin?.toLowerCase() !== config.github.appOwner.toLowerCase() + || (resources.appId && resources.appId !== endpoint.botExternalId) + || (resources.appSlug && resources.appSlug !== app.appSlug)) throw new ConnectionFailure("owned_github_app_binding_mismatch"); + resources.appId = endpoint.botExternalId; + resources.appSlug = app.appSlug; + const owner = encodeURIComponent(app.appOwnerLogin!); + resources.appSettingsUrl = app.appOwnerType === "organization" + ? `https://github.com/organizations/${owner}/settings/apps/${app.appSlug}` + : `https://github.com/settings/apps/${app.appSlug}`; + // Installation management is a different resource. Uninstalling is not proof + // that the owned App registration was deleted. + resources.installationSettingsUrl = app.managementUrl; + return true; +} diff --git a/tests/runner-e2e/github-review-report.test.ts b/tests/runner-e2e/github-review-report.test.ts new file mode 100644 index 00000000000..8840fcf171d --- /dev/null +++ b/tests/runner-e2e/github-review-report.test.ts @@ -0,0 +1,51 @@ +import { createHash } from "node:crypto"; +import { mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { afterEach, expect, it } from "vitest"; +import { runnerMatrix } from "./catalog.js"; +import { writeGitHubReviewReport } from "./github-review-report.js"; +import { validateRetainedRunnerResult } from "./result-validation.js"; +import type { RunnerE2EResult } from "./types.js"; + +const temporary: string[] = []; +afterEach(async () => { await Promise.all(temporary.splice(0).map(root => rm(root, { recursive: true, force: true }))); }); +const pixel = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jBv0AAAAASUVORK5CYII=", "base64"); +function fixture(): RunnerE2EResult { + const cell = runnerMatrix.find(row => row.id === "github-review-journey.configured-agent.local.setup-and-first-review")!; + return { schema: "paperclip.runner-e2e.result/v2", executionId: cell.id, suiteId: cell.suite.id, suiteDefinitionHash: cell.suiteDefinitionHash, + profileId: cell.profile.id, environmentId: "local", caseId: cell.task.id, provider: "opencode", model: "configured-model", runtimeMode: "native", + attempt: 1, status: "failed", error: "native_session_interrupted", cleanup: "passed", durationMs: 1000, + startedAt: "2026-10-24T00:00:00Z", finishedAt: "2026-10-24T00:00:01Z", + githubReviewJourney: { version: 1, outcome: "failed", phase: "review_execution_completion", setupId: "qa", hosting: "paperclip-cloud", targetCommit: "a".repeat(40), assisted: true, + dependencies: [], checkpoints: { github_delivery: true }, cleanup: { endpoint: true, app: true, branch: true, pullRequest: true }, + budgetPolicyRead: "verified", budgetPolicies: [{ scopeType: "agent", amount: 100, hardStopEnabled: true, unpricedUsagePolicy: "allow" }], + execution: { reviewId: "review", issueId: "issue", runId: "run", runStatus: "failed", runtimeMode: "native", provider: "opencode", model: "configured-model" } }, + screenshots: [{ id: "failure", label: "Failed native completion", file: "failure.png", sha256: createHash("sha256").update(pixel).digest("hex") }] }; +} + +it("packages an honest failed journey for the existing report pipeline without admitting other private files", async () => { + const output = await mkdtemp(path.join(os.tmpdir(), "github-report-test-")); temporary.push(output); + await writeFile(path.join(output, "failure.png"), pixel); + await writeFile(path.join(output, "auth.png"), pixel); + const result = await writeGitHubReviewReport({ output, campaignId: "retained-failure", result: fixture(), resources: { branch: "owned", appName: "owned", runIds: ["run"] }, catalog: runnerMatrix, secrets: [] }); + expect(result.status).toBe("failed"); + expect(() => validateRetainedRunnerResult(result)).not.toThrow(); + const manifest = JSON.parse(await readFile(path.join(output, "evidence/evidence-manifest.json"), "utf8")); + expect(manifest).toMatchObject({ leaks: [], missing: [] }); + expect(manifest.files).toContain("snapshots/failure.png"); + expect(manifest.files).toContain("snapshots/journey-resources.json"); + await expect(stat(path.join(output, "evidence/auth.png"))).rejects.toThrow(); + expect(await readFile(path.join(output, "evidence/snapshots/failure.png"))).toEqual(pixel); + const campaign = JSON.parse(await readFile(path.join(output, "campaign.json"), "utf8")); + expect(campaign).toMatchObject({ passed: 0, failed: 1 }); + const html = await readFile(path.join(output, "dashboard.html"), "utf8"); + expect(html).toContain("evidence/snapshots/failure.png"); +}); + +it("refuses an altered screenshot rather than retaining its claimed digest", async () => { + const output = await mkdtemp(path.join(os.tmpdir(), "github-report-test-")); temporary.push(output); + await writeFile(path.join(output, "failure.png"), "altered"); + await expect(writeGitHubReviewReport({ output, campaignId: "altered", result: fixture(), resources: { branch: "owned", appName: "owned", runIds: [] }, catalog: runnerMatrix, secrets: [] })) + .rejects.toThrow("journey_screenshot_digest_mismatch"); +}); diff --git a/tests/runner-e2e/github-review-report.ts b/tests/runner-e2e/github-review-report.ts new file mode 100644 index 00000000000..6ad2cc05149 --- /dev/null +++ b/tests/runner-e2e/github-review-report.ts @@ -0,0 +1,62 @@ +import { createHash } from "node:crypto"; +import { mkdir, mkdtemp, readFile, realpath, rm, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { packageEvidence } from "./evidence.js"; +import { buildRunnerCampaign } from "./history.js"; +import { renderRunnerE2EDashboard } from "./dashboard.js"; +import { stageDashboardBrandAssets } from "./report-assets.js"; +import { assertSecretFree, sanitizeJson } from "./redaction.js"; +import { validateRetainedRunnerResult } from "./result-validation.js"; +import type { GitHubJourneyResources } from "./github-review-ownership.js"; +import type { MatrixExecution, RunnerE2EResult } from "./types.js"; + +/** Use the normal sanitizer, artifact manifest, validator, and dashboard. Raw + * operator receipts stay in the private attempt; they are not auto-published. */ +export async function writeGitHubReviewReport(input: { + output: string; campaignId: string; result: RunnerE2EResult; resources: GitHubJourneyResources; + catalog: readonly MatrixExecution[]; secrets: readonly string[]; +}) { + const stage = await mkdtemp(path.join(os.tmpdir(), "github-journey-report-")); + const output = path.resolve(input.output); + const evidenceDir = path.join(output, "evidence"); + const realOutput = await realpath(output); + const save = async (root: string, name: string, value: unknown) => { + const text = JSON.stringify(sanitizeJson(value, input.secrets), null, 2) + "\n"; + assertSecretFree(text, input.secrets, name); + await writeFile(path.join(root, name), text, { mode: 0o600 }); + }; + try { + await mkdir(path.join(stage, "snapshots"), { mode: 0o700 }); + const result = structuredClone(input.result); + for (const shot of result.screenshots ?? []) { + const source = path.resolve(output, shot.file); + if (!source.startsWith(`${output}${path.sep}`) || !/^[a-z0-9_-]+$/.test(shot.id) || path.extname(source) !== ".png") throw new Error("unsafe_journey_screenshot_reference"); + if (!(await realpath(source)).startsWith(`${realOutput}${path.sep}`)) throw new Error("unsafe_journey_screenshot_reference"); + const bytes = await readFile(source); + if (shot.sha256 && createHash("sha256").update(bytes).digest("hex") !== shot.sha256) throw new Error("journey_screenshot_digest_mismatch"); + shot.file = `snapshots/${shot.id}.png`; + await writeFile(path.join(stage, shot.file), bytes, { mode: 0o600 }); + } + validateRetainedRunnerResult(result); + await save(stage, "result.json", result); + await save(stage, "snapshots/journey-resources.json", input.resources); + await save(stage, "snapshots/journey-evidence.json", result.githubReviewJourney); + const manifest = await packageEvidence({ privateDir: stage, uploadDir: evidenceDir, secrets: input.secrets, expectPassScreenshot: false }); + if (manifest.leaks.length || manifest.missing.length) { + result.status = "failed"; result.failureClass = "secret_leak"; result.error = "journey_evidence_packaging_failed"; + if (result.githubReviewJourney) result.githubReviewJourney.outcome = "failed"; + } + await save(evidenceDir, "result.json", result); + await save(evidenceDir, "evidence-manifest.json", manifest); + const campaign = buildRunnerCampaign({ campaignId: input.campaignId, generatedAt: result.finishedAt, expected: [result.executionId], results: [result] }); + await save(output, "campaign.json", campaign); + await save(output, "normalized-results.json", { ...campaign, results: [{ ...result, evidenceValid: !manifest.leaks.length && !manifest.missing.length, evidenceErrors: [] }] }); + await stageDashboardBrandAssets(output); + const html = renderRunnerE2EDashboard({ title: "Ponytail GitHub user journey", generatedAt: result.finishedAt, expected: [result.executionId], catalog: input.catalog, campaign, + entries: [{ result, valid: !manifest.leaks.length && !manifest.missing.length, errors: [], evidenceBaseHref: "evidence" }] }); + assertSecretFree(html, input.secrets, "dashboard.html"); + await writeFile(path.join(output, "dashboard.html"), html, { mode: 0o600 }); + return result; + } finally { await rm(stage, { recursive: true, force: true }); } +} diff --git a/tests/runner-e2e/journey-dependencies.ts b/tests/runner-e2e/journey-dependencies.ts new file mode 100644 index 00000000000..8adadae8fad --- /dev/null +++ b/tests/runner-e2e/journey-dependencies.ts @@ -0,0 +1,62 @@ +import { execFile } from "node:child_process"; + +/** Public requirements use aliases; deployment profiles bind these to private references. */ +export type JourneyCredentialBinding = + | { source: "environment"; variable: string } + | { source: "onepassword"; reference: string }; + +export class JourneyDependencyError extends Error { + constructor(readonly code: "invalid_dependency_binding" | "service_account_unavailable" | "credential_unavailable") { + super(code); + } +} + +export function parseJourneyCredentialBinding(input: unknown): JourneyCredentialBinding { + if (!input || typeof input !== "object" || Array.isArray(input)) throw new JourneyDependencyError("invalid_dependency_binding"); + const value = input as Record; + if (value.source === "environment" && Object.keys(value).sort().join() === "source,variable" + && typeof value.variable === "string" && /^[A-Z][A-Z0-9_]{1,100}$/.test(value.variable) + && value.variable !== "OP_SERVICE_ACCOUNT_TOKEN") return { source: value.source, variable: value.variable }; + // Resolve one selected field, never a vault/item dump or shell expression. + if (value.source === "onepassword" && Object.keys(value).sort().join() === "reference,source" + && typeof value.reference === "string" && value.reference.length < 1024 + && /^op:\/\/[^/?#\s]+\/[^/?#\s]+\/(?:[^/?#\r\n]+\/)?[^/?#\r\n]+(?:\?attribute=otp)?$/.test(value.reference) + && !/[`$\x00-\x1f]/.test(value.reference)) return { source: value.source, reference: value.reference }; + throw new JourneyDependencyError("invalid_dependency_binding"); +} + +export type SecretReader = (reference: string, env: NodeJS.ProcessEnv, signal?: AbortSignal) => Promise; +const readOnePassword: SecretReader = (reference, env, signal) => new Promise((resolve, reject) => { + execFile("op", ["read", "--no-newline", reference], { + env, encoding: "utf8", timeout: 30_000, maxBuffer: 64 * 1024, signal, + }, (error, stdout) => { + // CLI errors can contain private paths, item references or provider responses. + if (error || !stdout.trim()) reject(new JourneyDependencyError("credential_unavailable")); + else resolve(stdout); + }); +}); + +/** The service-account credential goes only to op, never the browser or product agent. */ +export async function resolveJourneyCredential(binding: JourneyCredentialBinding, options: { + env?: NodeJS.ProcessEnv; signal?: AbortSignal; read?: SecretReader; registerSecret(value: string): void; +}): Promise { + const checked = parseJourneyCredentialBinding(binding); + const env = options.env ?? process.env; + if (checked.source === "environment") { + const value = env[checked.variable]; + if (!value?.trim()) throw new JourneyDependencyError("credential_unavailable"); + options.registerSecret(value); + return value; + } + if (!env.OP_SERVICE_ACCOUNT_TOKEN?.trim()) throw new JourneyDependencyError("service_account_unavailable"); + options.registerSecret(env.OP_SERVICE_ACCOUNT_TOKEN); + const isolatedEnv: NodeJS.ProcessEnv = Object.fromEntries(["PATH", "HOME", "USER", "TMPDIR", "LANG", "SSL_CERT_FILE", "NODE_EXTRA_CA_CERTS"] + .flatMap(key => env[key] ? [[key, env[key]!]] : [])); + isolatedEnv.OP_SERVICE_ACCOUNT_TOKEN = env.OP_SERVICE_ACCOUNT_TOKEN; + try { + const value = await (options.read ?? readOnePassword)(checked.reference, isolatedEnv, options.signal); + if (!value.trim()) throw new JourneyDependencyError("credential_unavailable"); + options.registerSecret(value); + return value; + } catch { throw new JourneyDependencyError("credential_unavailable"); } +} diff --git a/tests/runner-e2e/launch.ts b/tests/runner-e2e/launch.ts index 934daa1dc86..69ea18c372f 100644 --- a/tests/runner-e2e/launch.ts +++ b/tests/runner-e2e/launch.ts @@ -1074,6 +1074,13 @@ async function main() { } if (process.env.PAPERCLIP_E2E_OPERATIONS_MANIFEST && executions.some(execution => execution.task.flow === "provider_connection")) throw new Error("Provider connection campaign has no budgeted routing qualification"); + if (executions.some(execution => execution.task.flow === "github_review_journey")) { + if (options.connectionConfig) throw new Error("Use --github-review-config for the GitHub journey."); + const { runGitHubReviewCampaign } = await import("./github-review-launch.js"); + await runGitHubReviewCampaign({ executions, catalog: runnerMatrix, configFile: options.githubReviewConfig, repositoryRoot, provisionRepository: options.provisionGitHubRepository }); + return; + } + if (options.githubReviewConfig || options.provisionGitHubRepository) throw new Error("GitHub journey options require an explicit GitHub review journey selection."); if (executions.some(execution => execution.task.flow === "provider_connection")) { const { runConnectionCampaign } = await import("./connection-launch.js"); await runConnectionCampaign({ executions, catalog: runnerMatrix, configFile: options.connectionConfig, repositoryRoot }); diff --git a/tests/runner-e2e/result-validation.ts b/tests/runner-e2e/result-validation.ts index ea99d9a1554..883d928c510 100644 --- a/tests/runner-e2e/result-validation.ts +++ b/tests/runner-e2e/result-validation.ts @@ -1,5 +1,6 @@ import { validateWorkerTiming } from "./worker-timing.js"; import { connectionCheckpoints, connectionEvidencePasses, connectionRunSignals } from "./connection-evidence.js"; +import { githubJourneyCheckpoints, gradeGitHubReviewJourney } from "./github-review-evidence.js"; import { STARTUP_REUSE_LAYERS, STARTUP_REUSE_REASONS } from "../../packages/adapter-utils/src/startup-reuse.js"; import type { RunnerE2ECampaignAccounting, RunnerE2EResult } from "./types.js"; import { DEPENDABLE_CELLS } from "./dependable-qualification.js"; @@ -379,6 +380,17 @@ const fields = { scores: array(shape({ dimension: oneOf("questionRelevance", "useOfFacts", "proposalUsefulness", "clarity", "lowFriction"), score: integer, rationale: string, evidence: array(string) })), inputTokens: nullable(integer), outputTokens: nullable(integer), estimatedCostUsd: nullable(number), reservedCostUsd: number, recordedAt: date, error: optional(string), })), + githubReviewJourney: optional(closedShape({ version: integer, outcome: oneOf("running", "passed", "failed", "awaiting_user", "missing_credential", "blocked_target"), + phase: string, setupId: string, hosting: oneOf("self-hosted", "paperclip-cloud"), targetCommit: nullable(string), assisted: boolean, + dependencies: array(closedShape({ alias: string, consumer: oneOf("harness", "browser", "product-agent"), status: oneOf("ready", "unverified", "created-in-journey"), source: oneOf("onepassword", "environment", "browser-session", "product-connection") })), + checkpoints: closedShape(Object.fromEntries(githubJourneyCheckpoints.map(id => [id, optional(boolean)]))), + cleanup: closedShape({ endpoint: boolean, pullRequest: boolean, branch: boolean, app: boolean }), definitionHash: optional(string), score: optional(integer), conclusion: optional(string), + budgetPolicyRead: optional(oneOf("verified", "unavailable")), + budgetPolicies: optional(array(closedShape({ scopeType: oneOf("agent", "company"), amount: number, hardStopEnabled: boolean, unpricedUsagePolicy: oneOf("allow", "block") }))), + execution: optional(closedShape({ reviewId: string, issueId: string, runId: nullable(string), runStatus: optional(string), issueStatus: optional(string), + runtimeMode: optional(string), environmentId: optional(string), provider: optional(string), model: optional(string) })), + review: optional(closedShape({ id: string, repository: string, pullNumber: integer, headSha: string, state: string, score: optional(integer), conclusion: nullable(string), summaryUrl: nullable(string), checkUrl: nullable(string) })), + inlinePublication: optional(closedShape({ url: string, fileUrl: string, path: string, author: string, text: string })) })), cleanup: oneOf("not_started", "passed", "failed"), } satisfies Record; const result = shape(fields); @@ -404,4 +416,5 @@ export function validateRetainedRunnerResult( if (checked.caseId === "cloud-onboarding" && (!checked.runIds?.length || !evidence.operations || !evidence.operations.requestCount || !evidence.operations.traceIds.length || evidence.operations.campaignId !== evidence.campaignId || evidence.operations.attemptId !== evidence.attemptId)) invalid("result.paidJourneyReceipt"); } if (checked.suiteId === "provider-connections" && checked.status === "passed" && (!checked.providerConnection || !connectionEvidencePasses(checked.providerConnection))) invalid("result.providerConnection"); + if (checked.suiteId === "github-review-journey" && checked.status === "passed" && (!checked.githubReviewJourney || checked.githubReviewJourney.outcome !== "passed" || !checked.githubReviewJourney.targetCommit || !gradeGitHubReviewJourney(checked.githubReviewJourney).every(check => check.passed))) invalid("result.githubReviewJourney"); } diff --git a/tests/runner-e2e/selectors.ts b/tests/runner-e2e/selectors.ts index 222b3eaf343..e40bf303794 100644 --- a/tests/runner-e2e/selectors.ts +++ b/tests/runner-e2e/selectors.ts @@ -18,6 +18,8 @@ export interface RunnerSelectorOptions { maxParallel: number; maxAutomaticRetries: number; connectionConfig?: string; + githubReviewConfig?: string; + provisionGitHubRepository?: boolean; } export class RunnerSelectorError extends Error {} @@ -62,6 +64,11 @@ export function parseRunnerSelectors( options.connectionConfig = valueFor(args, index, flag); index += 1; } + else if (flag === "--github-review-config") { + options.githubReviewConfig = valueFor(args, index, flag); + index += 1; + } + else if (flag === "--provision-github-repository") options.provisionGitHubRepository = true; else if (flag === "--max-parallel") { const value = valueFor(args, index, flag); index += 1; @@ -207,7 +214,7 @@ export function selectRunnerExecutions( export function buildMatrixJobs( executions: readonly MatrixExecution[], ): MatrixJob[] { - if (executions.some(e => e.task.flow === "provider_connection")) throw new RunnerSelectorError("Provider connection journeys use an explicit local/staging connection configuration; they are not admitted to paid CI matrix jobs yet."); + if (executions.some(e => ["provider_connection", "github_review_journey"].includes(e.task.flow))) throw new RunnerSelectorError("Attended connection journeys require explicit private setup profiles; they are not admitted to paid CI matrix jobs yet."); return executions .map((execution) => ({ executionId: execution.id, diff --git a/tests/runner-e2e/types.ts b/tests/runner-e2e/types.ts index f54348ef351..6cc59cbabda 100644 --- a/tests/runner-e2e/types.ts +++ b/tests/runner-e2e/types.ts @@ -26,6 +26,7 @@ export type RunnerTaskFlow = | "followup_stop_resume" | "repository_skills" | "provider_connection" + | "github_review_journey" | "plan_task_guidance" | "blocker_guidance" | "public_mcp" @@ -363,6 +364,7 @@ export interface RunnerE2EResult { productJourney?: import("./product-journeys/types.js").JourneyEvidence; firstTask?: import("./first-task-scoring.js").FirstTaskEvidence; providerConnection?: import("./connection-evidence.js").ConnectionEvidence; + githubReviewJourney?: import("./github-review-evidence.js").GitHubReviewJourneyEvidence; completionQuality?: import("./completion-quality.js").CompletionQualityRecord[]; firstTaskQuality?: import("./first-task-quality.js").FirstTaskQuality; /** External assistant API calls, separate from the team's heartbeat executions. */ From 3a2c56780c52ca6a9c2595f43c2443490bf906e2 Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Sat, 24 Oct 2026 12:25:33 -0700 Subject: [PATCH 013/110] fix(server): avoid execution payloads in run authority checks (#17467) ## Thinking Path > - Paperclip manages AI agents and their tasks. > - Each operation must use current task and user authority. > - Chat recovery also checks the exact source-run ancestry. > - These checks can repeatedly read full run payloads. > - Their decisions need identity fields and two typed task keys. > - This change selects those fields and keeps the current checks and locks. > - Complete execution context and output remain stored and available. ## Linked Issues or Issue Description **What happened?** Ancestry checks, instruction identity reads, task locks, and identity activation receipts transfer full execution context or full run rows for metadata decisions. **Expected behavior** Select only required identity and binding fields. Keep fresh membership and key revocation checks, task-before-run locking, native task precedence, and strict validation of legacy JSON task identifiers. **Steps to reproduce** 1. Store a run with large context, Runner profile, and output fields. 2. Read chat recovery ancestry or authorize an instruction operation. 3. Initialize or refresh its run identity. 4. Observe full context or full-row responses in these metadata paths. **Paperclip version or commit** Baseline: `14e1f59fbf4d9cc7875ed35ebaa9e997f6e2ea7c`. Complementary work: Refs #17460 and Refs #17463. Searched open and closed PRs for ancestry projections and run read optimizations. No duplicate was found. This PR has no dependency on #17463. **Deployment mode** External PostgreSQL. Tests and measurements use disposable real PostgreSQL. ## What Changed - Share a SQL projection of typed legacy issue/task keys with task-binding readers. - Select only source identity and retry links while checking chat ancestry. - Select current identity fields during instruction authorization. - Narrow identity task-lock reads and activation receipts to task binding fields. - Preserve existing authorization, ancestry proof, revocation checks, and lock order. ## Verification - **72 focused tests pass** across read projections, run identity, instruction authority, and chat admission retry. - **49 assembled heartbeat recovery tests pass** for chat and automatic ancestry; 359 unrelated tests were outside the filter. - Real PostgreSQL tests include large payloads, task/company/agent mismatch, current membership revocation, malformed JSON types, native binding precedence, and invalid legacy identifiers. - Real ancestry service SQL: 526,477 to 306 serialized response bytes (99.942% smaller) with three 174,764-byte incompressible execution fields. - Every selected non-context value matches the baseline. Both complete service calls return the same result. Typed binding cases are checked in PostgreSQL. - Five alternating warm samples after two warmups: median 2.152 ms before, 0.812 ms after. These are local query/client timings, not hosted request latency. - Full build and recursive typecheck pass. The full local stable suite is running; no full local pass is claimed. Current-head CI and review must pass before merge. - The first new-fixture run failed eight tests because it reused a unique company prefix. Each fixture now has its own prefix; the focused rerun passes all 72 tests. - All current-head CI checks pass on `ecc951b25d67fddc7dc2e0e3e2de861a40ee5ed0`. Greptile: **5/5, medium impact**, no findings or unresolved threads. - Staging effect is not measured yet. ## Risks Missing identity fields could change an authorization or recovery decision. The tests exercise current authority and fail-closed behavior. The change keeps full execution reads intact, preserves JSON types, and does not cache authority. There is no migration, message deletion, timing change, or data truncation. ## Model Used OpenAI GPT-6 through Codex, with source inspection, code execution, and GitHub tools. The exact served model ID and context-window size 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 (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 --- doc/DATABASE.md | 9 +- .../run-authority-read-projections.test.ts | 106 ++++++++++++++++++ .../agent-instruction-authorization.ts | 7 +- .../services/chat-control-recovery-stop.ts | 11 +- server/src/services/run-identity.ts | 10 +- server/src/services/run-task-binding.ts | 5 + 6 files changed, 142 insertions(+), 6 deletions(-) create mode 100644 server/src/__tests__/run-authority-read-projections.test.ts diff --git a/doc/DATABASE.md b/doc/DATABASE.md index 3ab9490ee1f..56e9736a66d 100644 --- a/doc/DATABASE.md +++ b/doc/DATABASE.md @@ -104,7 +104,14 @@ The initial agent JWT run lookup reads only the cancellation state and conversation flag from saved run JSON. It does not transfer the full context or result. Run status, responsible-user identity, company and agent boundaries, and the cancellation response remain unchanged. Later identity refreshes keep -their existing transaction and data reads. +their current authorization and transaction boundaries. + +Chat recovery ancestry selects task identifiers and source-run links instead +of full execution payloads. Instruction authorization selects current identity +fields and still rechecks accepted identity, key revocation, and membership. +Identity task locks and activation receipts project typed legacy task keys with +the native and first-class issue IDs. These projections preserve task binding +precedence and validation without transferring prompts or output. To measure authentication query responses on disposable synthetic data: diff --git a/server/src/__tests__/run-authority-read-projections.test.ts b/server/src/__tests__/run-authority-read-projections.test.ts new file mode 100644 index 00000000000..58f1de20aed --- /dev/null +++ b/server/src/__tests__/run-authority-read-projections.test.ts @@ -0,0 +1,106 @@ +import { randomBytes, randomUUID } from "node:crypto"; +import { agents, authUsers, companies, companyMemberships, createDb, heartbeatRuns, issues, type Db } from "@paperclipai/db"; +import { eq } from "drizzle-orm"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; +import { resolveInstructionActor } from "../services/agent-instruction-authorization.js"; +import { readChatControlRecoveryStop } from "../services/chat-control-recovery-stop.js"; +import { initializeRunIdentity } from "../services/run-identity.js"; +import { boundRunIssueId, runTaskContextColumn } from "../services/run-task-binding.js"; + +const support = await getEmbeddedPostgresTestSupport(); +describe.skipIf(!support.supported)("run authority read projections", () => { + let database: Awaited>; + let db: Db; + beforeAll(async () => { + database = await startEmbeddedPostgresTestDatabase("run-authority-read-"); + db = createDb(database.connectionString); + }, 60_000); + afterAll(async () => { await db?.$client.end(); await database?.cleanup(); }); + + async function fixture() { + const companyId = randomUUID(), agentId = randomUUID(), issueId = randomUUID(), userId = randomUUID(); + await db.insert(companies).values({ id: companyId, name: "Read fixture", issuePrefix: companyId.slice(0, 8) }); + await db.insert(agents).values({ id: agentId, companyId, name: "Read agent", adapterType: "process" }); + await db.insert(issues).values({ id: issueId, companyId, title: "Read task" }); + await db.insert(authUsers).values({ id: userId, name: "Fixture", email: `${userId}@example.invalid`, createdAt: new Date(), updatedAt: new Date() }); + await db.insert(companyMemberships).values({ companyId, principalType: "user", principalId: userId, status: "active" }); + const payload = randomBytes(128 * 1024).toString("base64"); + const [run] = await db.insert(heartbeatRuns).values({ companyId, agentId, status: "running", responsibleUserId: userId, + contextSnapshot: { issueId, prompt: payload }, runnerProfileJson: { instructions: payload }, stdoutExcerpt: payload, + }).returning(); + return { companyId, agentId, issueId, userId, run }; + } + + function recordRunReads() { + const reads: unknown[][] = []; + const recorded = new Proxy(db, { get(target, key) { + if (key !== "select") return Reflect.get(target, key); + return (...fields: Parameters) => { + const builder = target.select(...fields), from = builder.from.bind(builder); + builder.from = ((...args: Parameters) => { + const query = from(...args); + if (args[0] === heartbeatRuns) { + const execute = query.execute.bind(query); + query.execute = async (...executeArgs: Parameters) => { + const rows = await execute(...executeArgs); reads.push(rows); return rows; + }; + } + return query; + }) as typeof builder.from; + return builder; + }; + }}); + return { recorded, reads }; + } + + it("checks ancestry with small responses and still rejects task, agent, and company mismatches", async () => { + const f = await fixture(), { recorded, reads } = recordRunReads(); + const scope = { companyId: f.companyId, agentId: f.agentId, issueId: f.issueId, sourceRunId: f.run.id }; + expect(await readChatControlRecoveryStop(recorded, scope)).toEqual({ kind: "clear" }); + for (const field of ["companyId", "agentId", "issueId"] as const) { + expect(await readChatControlRecoveryStop(recorded, { ...scope, [field]: randomUUID() })).toEqual({ kind: "unresolved" }); + } + expect(reads).toHaveLength(4); + expect(Buffer.byteLength(JSON.stringify(reads))).toBeLessThan(2048); + expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.run.id)))[0]).toEqual(f.run); + }); + + it("refreshes instruction identity and membership without loading execution payloads", async () => { + const f = await fixture(); + await initializeRunIdentity(db, { companyId: f.companyId, runId: f.run.id, issueId: f.issueId, responsibleUserId: f.userId, messageIds: [], cause: "fixture" }); + const { recorded, reads } = recordRunReads(); + const actor = { type: "agent" as const, source: "agent_jwt" as const, companyId: f.companyId, agentId: f.agentId, runId: f.run.id }; + expect(await resolveInstructionActor(recorded, actor)).toMatchObject({ onBehalfOfUserId: f.userId }); + await db.update(companyMemberships).set({ status: "suspended" }).where(eq(companyMemberships.principalId, f.userId)); + await expect(resolveInstructionActor(recorded, actor)).rejects.toThrow(/responsible user is unavailable/); + await expect(resolveInstructionActor(recorded, { ...actor, agentId: randomUUID() })).rejects.toThrow(/does not match/); + expect(Buffer.byteLength(JSON.stringify(reads))).toBeLessThan(1024); + }); + + it.each([null, [], "scalar", 42, { issueId: false, taskId: 3 }, { issueId: "", taskId: "fallback" }].map(context => ({ context })))("preserves typed task binding for $context", async ({ context }) => { + const f = await fixture(); + await db.update(heartbeatRuns).set({ contextSnapshot: context as Record | null }).where(eq(heartbeatRuns.id, f.run.id)); + const [selected] = await db.select({ contextSnapshot: runTaskContextColumn }).from(heartbeatRuns).where(eq(heartbeatRuns.id, f.run.id)); + expect(boundRunIssueId(selected)).toBe(boundRunIssueId({ contextSnapshot: context as Record | null })); + expect(selected.contextSnapshot.issueId).toEqual((context as Record | null)?.issueId ?? null); + expect(selected.contextSnapshot.taskId).toEqual((context as Record | null)?.taskId ?? null); + }); + + it("keeps native task precedence and complete stored context during identity activation", async () => { + const f = await fixture(); + await db.update(heartbeatRuns).set({ nativeIssueId: f.issueId, contextSnapshot: { ...f.run.contextSnapshot, issueId: randomUUID() } }).where(eq(heartbeatRuns.id, f.run.id)); + const identity = await initializeRunIdentity(db, { companyId: f.companyId, runId: f.run.id, responsibleUserId: f.userId, cause: "fixture" }); + const [issue] = await db.select().from(issues).where(eq(issues.id, f.issueId)); + expect(issue.continuationIdentityContextId).toBe(identity.id); + expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.run.id)))[0].contextSnapshot?.prompt).toBe(f.run.contextSnapshot?.prompt); + }); + + it.each([42, false, {}, ["invalid"], "not-a-uuid"].map(issueId => ({ issueId })))("rejects malformed legacy identity $issueId even with a native task", async ({ issueId }) => { + const f = await fixture(); + await db.update(heartbeatRuns).set({ nativeIssueId: f.issueId, contextSnapshot: { issueId } }).where(eq(heartbeatRuns.id, f.run.id)); + await expect(initializeRunIdentity(db, { companyId: f.companyId, runId: f.run.id, responsibleUserId: f.userId, cause: "fixture" })).rejects.toThrow(/Run task identity is invalid/); + const [stored] = await db.select({ identity: heartbeatRuns.activeIdentityContextId }).from(heartbeatRuns).where(eq(heartbeatRuns.id, f.run.id)); + expect(stored.identity).toBeNull(); + }); +}); diff --git a/server/src/services/agent-instruction-authorization.ts b/server/src/services/agent-instruction-authorization.ts index fe98d26995e..fa3db14c4cf 100644 --- a/server/src/services/agent-instruction-authorization.ts +++ b/server/src/services/agent-instruction-authorization.ts @@ -61,7 +61,12 @@ export async function resolveInstructionActor( } if (actor.runId) { const [run] = await db - .select() + .select({ + id: heartbeatRuns.id, + companyId: heartbeatRuns.companyId, + responsibleUserId: heartbeatRuns.responsibleUserId, + activeIdentityContextId: heartbeatRuns.activeIdentityContextId, + }) .from(heartbeatRuns) .where( and( diff --git a/server/src/services/chat-control-recovery-stop.ts b/server/src/services/chat-control-recovery-stop.ts index 3a8fa375d2b..dff28753fcb 100644 --- a/server/src/services/chat-control-recovery-stop.ts +++ b/server/src/services/chat-control-recovery-stop.ts @@ -1,4 +1,5 @@ import { and, eq, inArray, or, sql } from "drizzle-orm"; +import { runTaskContextColumn } from "./run-task-binding.js"; import { agentWakeupRequests, chatActions, @@ -183,7 +184,15 @@ export async function readChatControlRecoveryStop( if (seen.has(runId)) return { kind: "unresolved" }; seen.add(runId); const [run] = await db - .select() + .select({ + id: heartbeatRuns.id, + companyId: heartbeatRuns.companyId, + agentId: heartbeatRuns.agentId, + nativeIssueId: heartbeatRuns.nativeIssueId, + wakeupRequestId: heartbeatRuns.wakeupRequestId, + retryOfRunId: heartbeatRuns.retryOfRunId, + contextSnapshot: runTaskContextColumn, + }) .from(heartbeatRuns) .where( and( diff --git a/server/src/services/run-identity.ts b/server/src/services/run-identity.ts index 19ac75989ce..cc75397a991 100644 --- a/server/src/services/run-identity.ts +++ b/server/src/services/run-identity.ts @@ -10,7 +10,7 @@ import { type Db, } from "@paperclipai/db"; import { conflict, forbidden } from "../errors.js"; -import { boundRunIssueId } from "./run-task-binding.js"; +import { boundRunIssueId, runTaskContextColumn } from "./run-task-binding.js"; import { isUuidLike } from "@paperclipai/shared"; import { queuedCommentIdsFromRunContext, queuedCommentIdsFromWakePayload } from "./issue-queued-comment-queue.js"; @@ -72,7 +72,7 @@ async function lockIdentityTask( ) { const [run] = await executor .select({ - contextSnapshot: heartbeatRuns.contextSnapshot, + contextSnapshot: runTaskContextColumn, nativeIssueId: heartbeatRuns.nativeIssueId, issueId: heartbeatRuns.issueId, }) @@ -150,7 +150,11 @@ async function activate(executor: Executor, context: RunIdentityContext) { eq(heartbeatRuns.companyId, context.companyId), ), ) - .returning(); + .returning({ + nativeIssueId: heartbeatRuns.nativeIssueId, + issueId: heartbeatRuns.issueId, + contextSnapshot: runTaskContextColumn, + }); const issueId = run ? boundRunIssueId(run) : null; if (typeof issueId === "string") await executor diff --git a/server/src/services/run-task-binding.ts b/server/src/services/run-task-binding.ts index 67b89336bd2..2711e9072df 100644 --- a/server/src/services/run-task-binding.ts +++ b/server/src/services/run-task-binding.ts @@ -1,6 +1,11 @@ import { sql } from "drizzle-orm"; import { heartbeatRuns } from "@paperclipai/db"; +export const runTaskContextColumn = sql>`jsonb_build_object( + 'issueId', ${heartbeatRuns.contextSnapshot}->'issueId', + 'taskId', ${heartbeatRuns.contextSnapshot}->'taskId' +)`; + type RunTaskBinding = { nativeIssueId?: string | null; issueId?: string | null; From fe85fd7ac45df92622b62205d94b2fbf52104a3c Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Sat, 24 Oct 2026 12:43:57 -0700 Subject: [PATCH 014/110] Expire closed workspaces that open descendants do not use (#17464) ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Git cache expiration removes closed issues' worktrees and saves restore points for unsaved work > - It treated a workspace as closed only when the source issue and every descendant were done or cancelled > - A routine that closes a parent and leaves children open for days therefore kept every parent worktree, although the children work in their own workspaces > - The idle path did not help, because the children are updated every day > - This pull request counts only the issues that use the workspace when it decides that a closed workspace can expire > - The benefit is that closed parent worktrees are removed while their children work elsewhere, and a child that later binds to the workspace gets it back from the restore point ## Linked Issues or Issue Description Refs #17271. Bug report described in-PR (bug report template). **What happened?** On one instance, an hourly routine creates a parent issue, works it in its own worktree, marks the parent done, and leaves child issues open (`blocked`, `in_review` or `in_progress`) for days. The children work in their own workspaces. They are not bound to the parent's workspace. Git cache expiration kept every parent worktree (about 300 MB each), because the closed-tree check and the workspace reaper required all descendants to be closed. In one project, 18 of 19 long-closed parent worktrees were kept only by open children that did not use them. The idle path never ran, because the children were updated daily. **Expected behavior** A closed issue's worktree expires while descendants are open, as long as no open descendant uses that workspace. **Steps to reproduce** 1. Enable git cache expiration and restore points. 2. Close an issue that has an isolated git worktree, and leave a child issue open that works in its own workspace (or has no workspace binding). 3. Wait past the terminal delay and run the workspace reaper: the parent worktree stays, and the reaper counts it as `skippedNonTerminalTree`. **Paperclip version or commit:** `master` at 410e5c6eedb. **Deployment mode:** any. **Agent adapter(s) involved:** not adapter-specific (core). ## What Changed - `isGitWorkspaceExpirationEligible` (closed path, not the idle path): the "tree closed for one day" check now covers only the issues in the tree that use the workspace. An issue uses the workspace when it is the source issue, when its `execution_workspace_id` is the workspace, or when its current `workspace_selection` or its `workspace_pending_selection` selects it as the `existing` workspace. Inheritance from a parent (`reuse_existing`) and `existing` selections are both stored as `execution_workspace_id`, and heartbeat workspace resolution reuses an existing workspace only through that binding or a run's persisted native binding. An open descendant without one of these references gets a new workspace on its next run, so it no longer keeps the parent's worktree. - All other checks stay the same: any open issue bound to the workspace, live or unsettled runs of any issue in the tree or of the workspace (including a run whose context names the workspace), finalizations, leases, recovery actions, runtime services, shared cwd and the reopen fence. - Workspace reaper: when the source issue is closed, git cache expiration applies, and no reopen is pending, the reaper routes the workspace by the same rule. It takes the restore point due time from the source issue and the descendants that use the workspace, also after every descendant is closed. A recently closed child that used the workspace still holds it for the terminal delay. The compaction delay and the archive cooldown still use the whole tree when it is closed. - Workspace reaper: compaction and the normal archive path keep their behavior. While any descendant is open, the reaper does not compact the worktree, and the expiration branch handles the workspace and continues. The archive path still requires a closed subtree. With expiration off, or a pending reopen, routing is unchanged. - New exported helper `listIssuesUsingGitWorkspace` shares the SQL "uses the workspace" predicate between eligibility and the reaper. - Docs: `doc/recoverable-disk-cleanup.md` and the `PAPERCLIP_GIT_RESTORE_POINT_TERMINAL_DELAY_DAYS` entry in `doc/DEVELOPING.md`. - The existing `preserves live descendants and pending reopening` case now binds its open child to the workspace. An unbound open child no longer keeps the worktree by design. ## Verification - `pnpm exec vitest run src/__tests__/git-restore-point-expiration.test.ts src/__tests__/git-workspace-expiration.test.ts src/__tests__/heartbeat-git-restore-point-resume.test.ts` in `server/`: all pass. - `pnpm exec vitest run src/__tests__/git-workspace-expiration src/__tests__/git-restore-point src/__tests__/execution-workspace src/__tests__/heartbeat-git-restore-point-resume src/services/heartbeat/environment-selection src/__tests__/isolated-repository` in `server/`: 15 of 17 files passed in one parallel run. The other failures were the updated descendant case (now fixed) and 45-second timeouts in restore point tests while 17 embedded Postgres files ran at the same time. Both files pass when run on their own. - `pnpm run typecheck` in `server/`: passes. - New embedded Postgres cases with real git repositories: - A closed parent with open `blocked`, `in_review`, `in_progress` and `todo` children and a grandchild in their own workspaces (or with none): the worktree expires with a restore point and the reopen restores it exactly. - The reaper archives it, timed from the issues that use the workspace. A child closed one minute ago with its own workspace does not delay it. - A recently closed child bound to the workspace holds it until its terminal delay passes. - When every child is closed and the most recent one used its own workspace, the reaper does not restart the restore point delay. - The worktree is kept when an open child is bound to it, when an open grandchild under a child with its own workspace is bound to it, when a child created later with `issueService.create` inherits it with `reuse_existing`, when an open child selects it through `workspace_selection` or `workspace_pending_selection`, when a child run that references it is live, and when the parent was closed inside the delay. - The reaper never compacts the worktree while children are open, with expiration on or off. A pending reopen keeps its current fence handling. - After expiry, an open child that binds to the workspace reopens it with the saved commits, index, working tree and untracked files. - Heartbeat: a queued run for an open child that binds to the expired workspace of a closed parent restores the workspace and runs the agent in it with the saved state. - Mutation checks (each run against the two restore point test files): - Closed-tree check restored to the whole tree: 7 tests fail. - `execution_workspace_id` removed from the rule: 3 fail. - `workspace_selection` removed from the rule: 1 fails. - `workspace_pending_selection` removed from the rule: 1 fails. - Reaper `latestTerminalAt` from the whole tree: 3 fail. - Reaper routing by the whole tree: 2 fail. - Reaper restore point due time from the whole tree once it is closed: 1 fails. - Pending-reopen gate removed: 1 fails. - Compaction gate (`!treeOpen`) removed: no test fails. Compaction's own guard under the lifecycle lock still rejects open trees, so the gate only skips work that cannot succeed. - Not run: the full server suite and the UI suites. CI covers them. ## Risks - Closed parent worktrees now expire while their children are open. A child that later binds to the workspace depends on the restore point and on the run-side reopen from #17271. The new tests cover this path. When restore points are off, only exactly reproducible worktrees expire. - An open child with no workspace binding no longer keeps the parent's worktree. Heartbeat resolution never reuses a workspace without a binding, so this does not change where the child runs. - The rule is conservative. A workspace selected only by an issue's current or pending selection is kept, and live runs of any issue in the tree still block. - The reaper runs one extra indexed query for each closed workspace when git cache expiration applies. No migration. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), 1M context, through Claude Code with tool use. ## 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 - [ ] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip --- doc/DEVELOPING.md | 4 +- doc/recoverable-disk-cleanup.md | 11 ++ .../git-restore-point-expiration.test.ts | 178 +++++++++++++++++- .../git-workspace-expiration.test.ts | 3 +- ...heartbeat-git-restore-point-resume.test.ts | 40 +++- server/src/services/execution-workspaces.ts | 20 +- .../src/services/git-workspace-expiration.ts | 23 ++- 7 files changed, 259 insertions(+), 20 deletions(-) diff --git a/doc/DEVELOPING.md b/doc/DEVELOPING.md index 0e44d7feb81..fea6694f2e8 100644 --- a/doc/DEVELOPING.md +++ b/doc/DEVELOPING.md @@ -2618,8 +2618,8 @@ Environment overrides: - `PAPERCLIP_GIT_RESTORE_POINTS_ENABLED=true` lets git cache expiration remove closed worktrees with unpushed or uncommitted work after saving an encrypted restore point (see `doc/recoverable-disk-cleanup.md`). It is off by default. - `PAPERCLIP_GIT_RESTORE_POINT_TERMINAL_DELAY_DAYS=` sets how long the issue tree - must be closed first. The default is `3`. A negative, empty, or non-numeric value falls + `PAPERCLIP_GIT_RESTORE_POINT_TERMINAL_DELAY_DAYS=` sets how long the issues that + use the workspace (the source issue and descendants bound to it) must be closed first. The default is `3`. A negative, empty, or non-numeric value falls back to the default. `PAPERCLIP_GIT_RESTORE_POINT_IDLE_DAYS=` sets how long an open issue tree's worktree must go untouched before it is removed the same way; runs restore it diff --git a/doc/recoverable-disk-cleanup.md b/doc/recoverable-disk-cleanup.md index 1fa8a1a892e..ea4aa982001 100644 --- a/doc/recoverable-disk-cleanup.md +++ b/doc/recoverable-disk-cleanup.md @@ -158,6 +158,17 @@ closed issue's worktree only when its remote can reproduce it exactly. With `PAPERCLIP_GIT_RESTORE_POINTS_ENABLED=true`, it can also remove a worktree that has unpushed commits, uncommitted or untracked files, or history-only commits, once its issue tree has been closed for `PAPERCLIP_GIT_RESTORE_POINT_TERMINAL_DELAY_DAYS` (default `3`). +For this, only the issues in the tree that use the workspace count: the source issue, and +each descendant that is bound to it (`execution_workspace_id`, which is how a child that +inherits the parent's workspace with `reuse_existing` is recorded) or that selects it as +its current or pending existing workspace. The delay runs from the latest close time among +those issues. A closed issue's worktree can therefore be removed while descendants that +work in their own workspaces stay open. Any issue still bound to the workspace, and any +live run, finalization, lease, recovery action or runtime service of an issue in the tree +or of the workspace, still keeps it. If an open descendant later binds to the removed +workspace, its next run or a comment reopens it from the restore point, as below. The +workspace reaper does not compact or archive such a worktree by its normal rules while +descendants are open; only expiration removes it. It also removes the worktree of an issue tree that is still open once nothing has touched it for `PAPERCLIP_GIT_RESTORE_POINT_IDLE_DAYS` (default `7`, `0` turns this off): no issue in the tree or bound to the workspace was updated and no run for those issues or diff --git a/server/src/__tests__/git-restore-point-expiration.test.ts b/server/src/__tests__/git-restore-point-expiration.test.ts index 510c9a536ed..49a05169abc 100644 --- a/server/src/__tests__/git-restore-point-expiration.test.ts +++ b/server/src/__tests__/git-restore-point-expiration.test.ts @@ -14,7 +14,8 @@ import { executionWorkspaceService } from "../services/execution-workspaces.js"; import { expireReconstructableGitWorkspace, gitWorkspaceLastActivityAt } from "../services/git-workspace-expiration.js"; import { getStorageService } from "../storage/index.js"; import { markGitRestorePointExpired } from "../services/git-restore-point-storage.js"; -import { GIT_RESTORE_POINT_EXPIRED_WARNING } from "../services/execution-workspaces.js"; +import { GIT_RESTORE_POINT_EXPIRED_WARNING, setMetadataReopenPendingConsumption } from "../services/execution-workspaces.js"; +import { issueService } from "../services/issues.js"; const gitEnv = { ...process.env, GIT_AUTHOR_NAME: "Fixture", GIT_AUTHOR_EMAIL: "fixture@example.test", GIT_COMMITTER_NAME: "Fixture", GIT_COMMITTER_EMAIL: "fixture@example.test", GIT_TERMINAL_PROMPT: "0" }; @@ -356,6 +357,181 @@ describeEmbeddedPostgres("git restore point expiration", () => { }); }); + describe("closed source issue with open descendants", () => { + async function child(f: Awaited>, values: Partial = {}) { + const id = randomUUID(); + await db.insert(issues).values({ id, companyId: f.companyId, parentId: f.issueId, title: "Follow-up", status: "blocked", ...values }); + return id; + } + async function ownWorkspace(f: Awaited>, sourceIssueId: string) { + const id = randomUUID(); + await db.insert(executionWorkspaces).values({ id, companyId: f.companyId, sourceIssueId, mode: "isolated_workspace", strategyType: "git_worktree", + name: "Child workspace", status: "active", providerType: "local_fs", cwd: path.join(root, "child-workspaces", id), providerRef: path.join(root, "child-workspaces", id) }); + await db.update(issues).set({ executionWorkspaceId: id, executionWorkspacePreference: "reuse_existing" }).where(eq(issues.id, sourceIssueId)); + return id; + } + const worker = (now = Date.now()) => executionWorkspaceService(db, { gitCacheExpirationEnabled: true, now: () => new Date(now), + gitRestorePoints: { storage: getStorageService(), terminalDelayMs: 3 * DAY_MS, keyDurable: true, idleMs: 7 * DAY_MS } }); + + it("expires the closed issue's worktree while open children work in their own workspaces", async () => { + const f = await fixture(); + const unpushed = await makeUnsavedWork(f.cwd); + const blocked = await child(f, { status: "blocked" }); + await ownWorkspace(f, blocked); + const reviewing = await child(f, { status: "in_review" }); + await ownWorkspace(f, reviewing); + const grandchild = await child(f, { parentId: reviewing, status: "in_progress" }); + await ownWorkspace(f, grandchild); + await child(f, { status: "todo" }); + expect(await f.expire()).toMatchObject({ candidate: true, expired: true, restorePoint: true, skipReason: null }); + expect(await exists(f.cwd)).toBe(false); + expect(await f.ledger()).toMatchObject([{ status: "active" }]); + expect(await f.reopen()).toMatchObject({ ok: true, reopened: true }); + expect(git(f.cwd, "rev-parse", "HEAD")).toBe(unpushed); + expect(await fs.readFile(path.join(f.cwd, "notes", "todo.md"), "utf8")).toBe("untracked work\n"); + }); + + it("lets the workspace reaper expire it, timed from the issues that use the workspace", async () => { + const f = await fixture(); + await makeUnsavedWork(f.cwd); + const open = await child(f, { status: "in_progress", updatedAt: new Date() }); + await ownWorkspace(f, open); + const closed = await child(f, { status: "done", completedAt: new Date(Date.now() - 60_000) }); + await ownWorkspace(f, closed); + expect(await worker().sweepTerminalWorkspaces()).toMatchObject({ archived: 1 }); + expect(await exists(f.cwd)).toBe(false); + expect((await f.row()).status).toBe("archived"); + expect(await f.ledger()).toMatchObject([{ status: "active" }]); + }); + + it("times the restore point from the issues that use the workspace once every child is closed", async () => { + const f = await fixture(); + await makeUnsavedWork(f.cwd); + const closed = await child(f, { status: "done", completedAt: new Date(Date.now() - 60_000) }); + await ownWorkspace(f, closed); + expect(await worker().sweepTerminalWorkspaces()).toMatchObject({ archived: 1 }); + expect(await exists(f.cwd)).toBe(false); + expect(await f.ledger()).toMatchObject([{ status: "active" }]); + }); + + it("waits for the terminal delay of a recently closed child that used the workspace", async () => { + const f = await fixture(); + await makeUnsavedWork(f.cwd); + await child(f, { status: "in_progress" }).then(id => ownWorkspace(f, id)); + const closedAt = new Date(Date.now() - DAY_MS); + await child(f, { status: "done", completedAt: closedAt, executionWorkspaceId: f.workspaceId }); + const early = worker(); + expect(await early.sweepTerminalWorkspaces()).toMatchObject({ archived: 0 }); + expect(await exists(f.cwd)).toBe(true); + expect(await worker(closedAt.getTime() + 3 * DAY_MS + 60_000).sweepTerminalWorkspaces()).toMatchObject({ archived: 1 }); + expect(await exists(f.cwd)).toBe(false); + }); + + it("never compacts a closed issue's worktree while children are open", async () => { + const f = await fixture(); + await makeUnsavedWork(f.cwd); + await db.update(executionWorkspaces).set({ providerType: "git_worktree" }).where(eq(executionWorkspaces.id, f.workspaceId)); + await db.update(issues).set({ completedAt: new Date(Date.now() - 2 * DAY_MS) }).where(eq(issues.id, f.issueId)); + await fs.mkdir(path.join(f.cwd, "node_modules", "pkg"), { recursive: true }); + await fs.writeFile(path.join(f.cwd, "node_modules", "pkg", "index.js"), "module.exports = 1;\n"); + await child(f, { status: "in_progress" }).then(id => ownWorkspace(f, id)); + for (const reaper of [executionWorkspaceService(db, { workspaceCompactionDelayMs: 0 }), + executionWorkspaceService(db, { workspaceCompactionDelayMs: 0, gitCacheExpirationEnabled: true, + gitRestorePoints: { storage: getStorageService(), terminalDelayMs: 3 * DAY_MS, keyDurable: true } })]) { + expect(await reaper.sweepTerminalWorkspaces()).toMatchObject({ archived: 0, compacted: 0 }); + expect(await exists(path.join(f.cwd, "node_modules", "pkg", "index.js"))).toBe(true); + } + }); + + it("keeps today's reopen fence handling while a reopen is pending", async () => { + const f = await fixture(); + await makeUnsavedWork(f.cwd); + await child(f, { status: "in_progress" }).then(id => ownWorkspace(f, id)); + await db.update(executionWorkspaces).set({ metadata: setMetadataReopenPendingConsumption((await f.row()).metadata, new Date()) }) + .where(eq(executionWorkspaces.id, f.workspaceId)); + expect(await worker().sweepTerminalWorkspaces()).toMatchObject({ archived: 0 }); + expect(await exists(f.cwd)).toBe(true); + expect((await f.row()).metadata?.reopenPendingConsumption).toBeUndefined(); + }); + + it("keeps the worktree while an open child is bound to it", async () => { + const f = await fixture(); + await makeUnsavedWork(f.cwd); + await child(f, { status: "blocked", executionWorkspaceId: f.workspaceId, executionWorkspacePreference: "reuse_existing" }); + expect(await f.expire()).toMatchObject({ expired: false, skipReason: "live_or_unresolved_consumer" }); + expect(await worker().sweepTerminalWorkspaces()).toMatchObject({ archived: 0, skippedNonTerminalTree: 1 }); + expect(await exists(f.cwd)).toBe(true); + }); + + it("keeps the worktree while an open grandchild is bound to it under a child with its own workspace", async () => { + const f = await fixture(); + const middle = await child(f, { status: "in_review" }); + await ownWorkspace(f, middle); + await child(f, { parentId: middle, status: "todo", executionWorkspaceId: f.workspaceId }); + expect(await f.expire()).toMatchObject({ expired: false, skipReason: "live_or_unresolved_consumer" }); + expect(await exists(f.cwd)).toBe(true); + }); + + it("keeps the worktree for a child created later that inherits it with reuse_existing", async () => { + const f = await fixture(); + const created = await issueService(db).create(f.companyId, { parentId: f.issueId, title: "Inherited follow-up", status: "todo" }); + expect(created).toMatchObject({ executionWorkspaceId: f.workspaceId, executionWorkspacePreference: "reuse_existing" }); + expect(await f.expire()).toMatchObject({ expired: false, skipReason: "live_or_unresolved_consumer" }); + expect(await worker().sweepTerminalWorkspaces()).toMatchObject({ archived: 0, skippedNonTerminalTree: 1 }); + expect(await exists(f.cwd)).toBe(true); + }); + + it("keeps the worktree while an open child selects it as its existing workspace", async () => { + const f = await fixture(); + const selection = { kind: "existing" as const, workspaceId: f.workspaceId }; + const selecting = await child(f, { status: "todo", workspaceSelection: { version: 1, selection, source: "explicit" } }); + expect(await f.expire()).toMatchObject({ expired: false, skipReason: "live_or_unresolved_consumer" }); + await db.update(issues).set({ workspaceSelection: null, workspacePendingSelection: { version: 1, requestKey: "fixture", + expectedBindingRevision: 0, intent: { version: 1, selection, source: "explicit" } } }).where(eq(issues.id, selecting)); + expect(await f.expire()).toMatchObject({ expired: false, skipReason: "live_or_unresolved_consumer" }); + await db.update(issues).set({ workspacePendingSelection: null }).where(eq(issues.id, selecting)); + expect(await f.expire()).toMatchObject({ expired: true }); + }); + + it("keeps the worktree while a child run referencing it is live", async () => { + const f = await fixture(); + const running = await child(f, { status: "in_progress" }); + await ownWorkspace(f, running); + const agentId = randomUUID(); + await db.insert(agents).values({ id: agentId, companyId: f.companyId, name: "Worker", adapterType: "process" }); + const [run] = await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId, status: "running", startedAt: new Date(), + contextSnapshot: { issueId: running, executionWorkspaceId: f.workspaceId } }).returning(); + expect(await f.expire()).toMatchObject({ expired: false, skipReason: "live_or_unresolved_consumer" }); + expect(await exists(f.cwd)).toBe(true); + await db.update(heartbeatRuns).set({ status: "succeeded", finishedAt: new Date() }).where(eq(heartbeatRuns.id, run!.id)); + expect(await f.expire()).toMatchObject({ expired: true }); + }); + + it("keeps the worktree while the closed issue was closed inside the terminal delay", async () => { + const f = await fixture(); + await db.update(issues).set({ completedAt: new Date(Date.now() - 60_000) }).where(eq(issues.id, f.issueId)); + await child(f, { status: "in_progress" }).then(id => ownWorkspace(f, id)); + expect(await f.expire()).toMatchObject({ expired: false, skipReason: "live_or_unresolved_consumer" }); + expect(await exists(f.cwd)).toBe(true); + }); + + it("restores the saved state when an open child later binds to the expired workspace", async () => { + const f = await fixture(); + const unpushed = await makeUnsavedWork(f.cwd); + const follower = await child(f, { status: "in_progress" }); + expect(await f.expire()).toMatchObject({ expired: true, restorePoint: true }); + await db.update(issues).set({ executionWorkspaceId: f.workspaceId, executionWorkspacePreference: "reuse_existing" }).where(eq(issues.id, follower)); + const reopened = await executionWorkspaceService(db).reopenClosedIsolatedExecutionWorkspaceForIssue({ workspaceId: f.workspaceId, + issue: { id: follower, companyId: f.companyId, projectId: null }, actor: { actorType: "user", agentId: null }, + authorizationActor: { type: "board", source: "local_implicit", isInstanceAdmin: true } }); + expect(reopened).toMatchObject({ ok: true, reopened: true }); + expect(git(f.cwd, "rev-parse", "HEAD")).toBe(unpushed); + expect(await fs.readFile(path.join(f.cwd, "marker.txt"), "utf8")).toBe("unstaged edit\n"); + expect(git(f.cwd, "show", ":marker.txt")).toBe("staged edit"); + expect(await fs.readFile(path.join(f.cwd, "notes", "todo.md"), "utf8")).toBe("untracked work\n"); + }); + }); + it("expires a worktree whose only extra files are ignored, and restores them on reopen", async () => { const f = await fixture(); await fs.mkdir(path.join(f.cwd, "ui"), { recursive: true }); diff --git a/server/src/__tests__/git-workspace-expiration.test.ts b/server/src/__tests__/git-workspace-expiration.test.ts index 7055ede59d1..80a1b510058 100644 --- a/server/src/__tests__/git-workspace-expiration.test.ts +++ b/server/src/__tests__/git-workspace-expiration.test.ts @@ -816,7 +816,8 @@ describeEmbeddedPostgres("reconstructable Git expiration", () => { it("preserves live descendants and pending reopening", async () => { const f = await fixture(); - await db.insert(issues).values({ companyId: f.companyId, title: "Active child", status: "in_progress", parentId: f.issueId }); + await db.insert(issues).values({ companyId: f.companyId, title: "Active child", status: "in_progress", parentId: f.issueId, + executionWorkspaceId: f.workspaceId, executionWorkspacePreference: "reuse_existing" }); expect((await f.expire()).expired).toBe(false); await db.delete(issues).where(eq(issues.parentId, f.issueId)); const row = await f.row(); diff --git a/server/src/__tests__/heartbeat-git-restore-point-resume.test.ts b/server/src/__tests__/heartbeat-git-restore-point-resume.test.ts index dc5ebb6d3f2..9620083333c 100644 --- a/server/src/__tests__/heartbeat-git-restore-point-resume.test.ts +++ b/server/src/__tests__/heartbeat-git-restore-point-resume.test.ts @@ -68,7 +68,7 @@ describe.skipIf(!support.supported)("heartbeat resume of an idle-expired workspa await fs.rm(root, { recursive: true, force: true }); }, 60_000); - async function seed() { + async function seed(options: { closedParent?: boolean } = {}) { const home = path.join(root, randomUUID()); vi.stubEnv("PAPERCLIP_HOME", home); vi.stubEnv("PAPERCLIP_INSTANCE_ID", "default"); @@ -108,24 +108,31 @@ describe.skipIf(!support.supported)("heartbeat resume of an idle-expired workspa isolatedRemoteSource: { schema: "paperclip.isolated-remote-source.v1", companyId, issueId, repoUrl } } }); await db.update(issues).set({ executionWorkspaceId: workspaceId, executionWorkspacePreference: "reuse_existing", updatedAt: idleSince }) .where(eq(issues.id, issueId)); + const childId = randomUUID(); + if (options.closedParent) { + await db.update(issues).set({ status: "done", completedAt: new Date(Date.now() - 4 * DAY_MS) }).where(eq(issues.id, issueId)); + await db.insert(issues).values({ id: childId, companyId, projectId, parentId: issueId, title: "Open follow-up", status: "in_progress", + workMode: "standard", assigneeAgentId: agentId, responsibleUserId: "responsible-user", issueNumber: 2, identifier: `${issuePrefix}-2`, + executionWorkspaceSettings: { mode: "isolated_workspace" } }); + } await fs.writeFile(path.join(realized.cwd, "marker.txt"), "commit B (unpushed)\n"); git(realized.cwd, "commit", "-qam", "B"); const unpushed = git(realized.cwd, "rev-parse", "HEAD"); await fs.writeFile(path.join(realized.cwd, "notes.md"), "uncommitted notes\n"); const workspace = () => db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, workspaceId)).then(rows => rows[0]!); const expiration = await expireReconstructableGitWorkspace(db, await workspace(), { - dryRun: false, expireBase: false, now: new Date(), idleCutoff: new Date(Date.now() - 7 * DAY_MS), + dryRun: false, expireBase: false, now: new Date(), idleCutoff: options.closedParent ? undefined : new Date(Date.now() - 7 * DAY_MS), restorePoint: { storage: getStorageService(), notBefore: new Date(Date.now() - DAY_MS), keyDurable: true }, }); - const queueRun = async () => { + const queueRun = async (target = issueId) => { await db.insert(agentWakeupRequests).values({ id: wakeupId, companyId, agentId, source: "assignment", triggerDetail: "system", - reason: "issue_assigned", payload: { issueId }, status: "queued", runId }); + reason: "issue_assigned", payload: { issueId: target }, status: "queued", runId }); await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, invocationSource: "assignment", triggerDetail: "system", status: "queued", - wakeupRequestId: wakeupId, responsibleUserId: "responsible-user", contextSnapshot: { issueId, taskId: issueId, wakeReason: "issue_assigned" } }); + wakeupRequestId: wakeupId, responsibleUserId: "responsible-user", contextSnapshot: { issueId: target, taskId: target, wakeReason: "issue_assigned" } }); await db.update(issues).set({ checkoutRunId: runId, executionRunId: runId, executionAgentNameKey: "resumer", executionLockedAt: new Date() }) - .where(eq(issues.id, issueId)); + .where(eq(issues.id, target)); }; - return { issueId, workspaceId, runId, cwd: realized.cwd, unpushed, expiration, workspace, queueRun }; + return { issueId, childId, workspaceId, runId, cwd: realized.cwd, unpushed, expiration, workspace, queueRun }; } async function waitForRun(heartbeat: ReturnType, runId: string) { @@ -159,4 +166,23 @@ describe.skipIf(!support.supported)("heartbeat resume of an idle-expired workspa const [issue] = await db.select().from(issues).where(eq(issues.id, seeded.issueId)); expect(issue.executionWorkspaceId).toBe(seeded.workspaceId); }); + + it("restores a closed parent's expired workspace when an open child binds to it", async () => { + const seeded = await seed({ closedParent: true }); + expect(seeded.expiration).toMatchObject({ expired: true, restorePoint: true }); + await expect(fs.access(seeded.cwd)).rejects.toMatchObject({ code: "ENOENT" }); + await db.update(issues).set({ executionWorkspaceId: seeded.workspaceId, executionWorkspacePreference: "reuse_existing" }) + .where(eq(issues.id, seeded.childId)); + await seeded.queueRun(seeded.childId); + const heartbeat = heartbeatService(db); + await heartbeat.resumeQueuedRuns(); + const run = await waitForRun(heartbeat, seeded.runId); + await heartbeat.waitForRunExecutionDrain(seeded.runId); + expect(run).toMatchObject({ status: "succeeded" }); + expect(adapterExecute.mock.calls[0]?.[0]).toMatchObject({ context: { executionWorkspaceId: seeded.workspaceId, + paperclipWorkspace: { cwd: seeded.cwd } } }); + expect(git(seeded.cwd, "rev-parse", "HEAD")).toBe(seeded.unpushed); + expect(await fs.readFile(path.join(seeded.cwd, "notes.md"), "utf8")).toBe("uncommitted notes\n"); + expect((await seeded.workspace()).status).not.toBe("archived"); + }); }); diff --git a/server/src/services/execution-workspaces.ts b/server/src/services/execution-workspaces.ts index 9d42edcc6e1..caf9a90511c 100644 --- a/server/src/services/execution-workspaces.ts +++ b/server/src/services/execution-workspaces.ts @@ -5,7 +5,7 @@ import { measureRunTransaction } from "./execution-transaction-timing.js"; import { measureRunPhase } from "./execution-preparation-timing.js"; import { assertExecutionWorkspaceRecordAccess, assertTaskWorkspaceExecutionAccess, assertTaskWorkspaceSourceProjectAccess } from "./task-workspace-access.js"; import { verifiedRecordedIsolatedRemoteSource, withIsolatedRepositorySourceLock } from "./isolated-remote-workspace-source.js"; -import { expireReconstructableGitWorkspace, gitWorkspaceLastActivityAt, hasPendingGitExpiration } from "./git-workspace-expiration.js"; +import { expireReconstructableGitWorkspace, gitWorkspaceLastActivityAt, hasPendingGitExpiration, listIssuesUsingGitWorkspace } from "./git-workspace-expiration.js"; import { hasPendingIsolatedRepositoryRehomeCleanup, isIsolatedRepositoryRehomeCandidate, rehomeExpiredIsolatedRestoration, rehomeIsolatedRepositoryWorkspace, sweepOrphanedIsolatedRepositorySources } from "./isolated-repository-rehome.js"; import { hasPendingNestedCloneMigration, isNestedCloneMigrationCandidate, nextNestedCloneMigrationBatch, pendingNestedCloneMigrationNames, listNestedCloneMigrationNames, migrateNestedRepositoryClone, NESTED_CLONE_MIGRATION_RETRY_REASONS, type NestedCloneMigrationRotation } from "./nested-clone-migration.js"; @@ -3434,7 +3434,14 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic workspace.metadata as Record | null, ); if (reopenPending) terminalWorkspaceDeadlines.set(workspace.id, now().getTime()); - if (!sourceIssue || issueTree.some(issue => !TERMINAL_ISSUE_STATUSES.has(issue.status))) { + const treeOpen = issueTree.some(issue => !TERMINAL_ISSUE_STATUSES.has(issue.status)); + const gitExpirationCandidate = workspace.providerType !== "plugin" && Boolean(opts.gitCacheExpirationEnabled) + && (hasPendingGitExpiration(workspace) || (workspace.mode === "isolated_workspace" && workspace.strategyType === "git_worktree")); + const usingIssueIds = sourceIssue && gitExpirationCandidate && !reopenPending + && TERMINAL_ISSUE_STATUSES.has(sourceIssue.status) + ? await listIssuesUsingGitWorkspace(db, workspace, issueTree.map(issue => issue.id)) : null; + const expirationTree = usingIssueIds ? issueTree.filter(issue => usingIssueIds.has(issue.id)) : issueTree; + if (!sourceIssue || expirationTree.some(issue => !TERMINAL_ISSUE_STATUSES.has(issue.status))) { if (reopenPending) { await clearReopenPendingConsumptionUnderLock(workspace.id, { expectedGeneration: readExecutionWorkspaceLifecycleGeneration( @@ -3473,11 +3480,13 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic result.skippedNonTerminalTree += 1; continue; } - const latestTerminalAt = Math.max(...issueTree.map(issue => issueTerminalTimestamp(issue)!.getTime())); + const expirationTerminalAt = Math.max(...expirationTree.map(issue => issueTerminalTimestamp(issue)!.getTime())); + const latestTerminalAt = treeOpen ? expirationTerminalAt : Math.max(...issueTree.map(issue => issueTerminalTimestamp(issue)!.getTime())); // Compaction runs once per terminal cycle, after its own delay and // before the archive cooldown, so a workspace the reaper cannot archive // yet (or ever) stops holding regenerable files. const compactionPending = workspaceCompactionDelayMs !== null + && !treeOpen && !isClosedExecutionWorkspaceStatus(workspace.status) && !reopenPending && compactedTerminalAt.get(workspace.id) !== latestTerminalAt; @@ -3503,14 +3512,13 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic ); } } - if (workspace.providerType !== "plugin" && opts.gitCacheExpirationEnabled && (hasPendingGitExpiration(workspace) - || (workspace.mode === "isolated_workspace" && workspace.strategyType === "git_worktree"))) { + if (gitExpirationCandidate) { const expiration = await expireReconstructableGitWorkspace(db, workspace, { dryRun: opts.gitCacheExpirationDryRun ?? false, expireBase: opts.gitBaseExpirationEnabled ?? false, now: now(), signal, beforeDelete: opts.beforeTerminalWorkspaceCleanup, restorePoint: opts.gitRestorePoints ? { storage: opts.gitRestorePoints.storage, - notBefore: new Date(latestTerminalAt + opts.gitRestorePoints.terminalDelayMs), + notBefore: new Date(expirationTerminalAt + opts.gitRestorePoints.terminalDelayMs), keyDurable: opts.gitRestorePoints.keyDurable, } : undefined, }); diff --git a/server/src/services/git-workspace-expiration.ts b/server/src/services/git-workspace-expiration.ts index ff9e6c7ffc5..c551f7471a5 100644 --- a/server/src/services/git-workspace-expiration.ts +++ b/server/src/services/git-workspace-expiration.ts @@ -3,7 +3,7 @@ import fs from "node:fs/promises"; import path from "node:path"; import { randomBytes } from "node:crypto"; import { acquireGitExpirationLocks } from "./git-workspace-expiration-locks.js"; -import { and, eq, ne, sql } from "drizzle-orm"; +import { and, eq, inArray, ne, sql } from "drizzle-orm"; import { executionWorkspaces, issues, heartbeatRuns, nativeRunFinalizations, environmentLeases, workspaceRuntimeServices, issueRecoveryActions, projectWorkspaces, withDedicatedDbConnection, type Db } from "@paperclipai/db"; import { createGitRemoteAuthProvider } from "./git-credentials.js"; @@ -124,6 +124,21 @@ export function expirationScope(workspace: Workspace) { )`; } +function issueUsesWorkspace(workspace: Pick) { + return sql`(${issues.id} = ${workspace.sourceIssueId} OR ${issues.executionWorkspaceId} = ${workspace.id} + OR (${issues.workspaceSelection}->'selection'->>'kind' = 'existing' + AND ${issues.workspaceSelection}->'selection'->>'workspaceId' = ${workspace.id}) + OR (${issues.workspacePendingSelection}->'intent'->'selection'->>'kind' = 'existing' + AND ${issues.workspacePendingSelection}->'intent'->'selection'->>'workspaceId' = ${workspace.id}))`; +} + +export async function listIssuesUsingGitWorkspace(db: Db | Tx, workspace: Pick, issueIds: string[]) { + if (issueIds.length === 0) return new Set(); + const rows = await db.select({ id: issues.id }).from(issues) + .where(and(eq(issues.companyId, workspace.companyId), inArray(issues.id, issueIds), issueUsesWorkspace(workspace))); + return new Set(rows.map(row => row.id)); +} + export async function gitWorkspaceLastActivityAt(db: Db | Tx, workspace: Workspace): Promise { if (!workspace.sourceIssueId) return null; const rows = await db.execute<{ at: string | Date | null }>(sql`${expirationScope(workspace)} @@ -142,8 +157,10 @@ export async function isGitWorkspaceExpirationEligible(tx: Tx, workspace: Worksp NOT EXISTS (SELECT 1 FROM tree WHERE updated_at > ${idleCutoff.toISOString()}::timestamptz) AND NOT EXISTS (SELECT 1 FROM bound WHERE updated_at > ${idleCutoff.toISOString()}::timestamptz) AND NOT EXISTS (SELECT 1 FROM relevant_runs WHERE greatest(created_at, started_at, finished_at) > ${idleCutoff.toISOString()}::timestamptz)` : sql` - NOT EXISTS (SELECT 1 FROM tree WHERE status NOT IN ('done', 'cancelled') - OR coalesce(CASE WHEN status = 'done' THEN completed_at ELSE cancelled_at END, updated_at) > ${new Date(now.getTime() - DAY_MS).toISOString()}::timestamptz) + NOT EXISTS (SELECT 1 FROM ${issues} WHERE ${issues.companyId} = ${workspace.companyId} + AND ${issues.id} IN (SELECT id FROM tree) AND ${issueUsesWorkspace(workspace)} + AND (${issues.status} NOT IN ('done', 'cancelled') + OR coalesce(CASE WHEN ${issues.status} = 'done' THEN ${issues.completedAt} ELSE ${issues.cancelledAt} END, ${issues.updatedAt}) > ${new Date(now.getTime() - DAY_MS).toISOString()}::timestamptz)) AND NOT EXISTS (SELECT 1 FROM ${issues} WHERE company_id = ${workspace.companyId} AND execution_workspace_id = ${workspace.id} AND status NOT IN ('done', 'cancelled'))`; const recoveryActionBlocks = idleCutoff ? sql`true` : sql`(cause = 'native_workspace_finalization_owner_unverified' From 991c47bc6e86509428544bbbc217c129c6f414e3 Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Sat, 24 Oct 2026 13:36:54 -0700 Subject: [PATCH 015/110] fix(server): project recovery result metadata (#17481) Keep full execution output in storage while selecting only recovery metadata for repeated latest-run and legacy eligibility checks. Retain complete results for provider-text classification and preserve all admission and write fences. Verified 456 focused PostgreSQL tests, full build and workspace typecheck, all 55 exact-head CI checks, and Greptile 5/5 with medium impact and no findings. Co-Authored-By: Paperclip --- doc/DATABASE.md | 8 ++ .../services/recovery/run-result-read.test.ts | 107 ++++++++++++++++++ .../src/services/recovery/run-result-read.ts | 25 ++++ server/src/services/recovery/service.ts | 20 ++-- 4 files changed, 153 insertions(+), 7 deletions(-) create mode 100644 server/src/services/recovery/run-result-read.test.ts create mode 100644 server/src/services/recovery/run-result-read.ts diff --git a/doc/DATABASE.md b/doc/DATABASE.md index 56e9736a66d..1dc73cbf9d5 100644 --- a/doc/DATABASE.md +++ b/doc/DATABASE.md @@ -113,6 +113,14 @@ Identity task locks and activation receipts project typed legacy task keys with the native and first-class issue IDs. These projections preserve task binding precedence and validation without transferring prompts or output. +Recovery's latest-run and legacy-continuation eligibility reads select structured +result fields for error families, +workspace/configuration receipts, cancellation attribution, retry deadlines, and +conversation finalization. The `adapter_failed`, `provider_quota`, and +`configuration_incomplete` classifiers retain full results because they inspect +arbitrary provider error text. Stored results and execution/detail reads remain +complete; no recovery decision is cached. + To measure authentication query responses on disposable synthetic data: ```sh diff --git a/server/src/services/recovery/run-result-read.test.ts b/server/src/services/recovery/run-result-read.test.ts new file mode 100644 index 00000000000..7f937c36f0a --- /dev/null +++ b/server/src/services/recovery/run-result-read.test.ts @@ -0,0 +1,107 @@ +import { randomBytes, randomUUID } from "node:crypto"; +import { agents, companies, createDb, heartbeatRuns, type Db } from "@paperclipai/db"; +import { eq } from "drizzle-orm"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embedded-postgres.js"; +import { isAiAuthenticationBlocked } from "../ai-auth-failure.js"; +import { recoveryRunResultColumn } from "./run-result-read.js"; +import { classifyAdapterFailureForRecovery, classifyContinuationFailure, recoveryService } from "./service.js"; + +const support = await getEmbeddedPostgresTestSupport(); +describe.skipIf(!support.supported)("recovery result PostgreSQL projection", () => { + let database: Awaited>; + let db: ReturnType; + let companyId: string; + let agentId: string; + beforeAll(async () => { + database = await startEmbeddedPostgresTestDatabase("recovery-result-read-"); + db = createDb(database.connectionString); + const [company] = await db.insert(companies).values({ name: "Recovery fixture", issuePrefix: "RR" }).returning(); + const [agent] = await db.insert(agents).values({ companyId: company.id, name: "Recovery agent", adapterType: "process" }).returning(); + companyId = company.id; + agentId = agent.id; + }, 60_000); + afterAll(async () => { await db?.$client.end(); await database?.cleanup(); }); + + async function read(resultJson: unknown, errorCode: string | null = null) { + const [run] = await db.insert(heartbeatRuns).values({ companyId, agentId, status: "succeeded", errorCode, + resultJson: resultJson as Record | null }).returning(); + const [selected] = await db.select({ resultJson: recoveryRunResultColumn }).from(heartbeatRuns).where(eq(heartbeatRuns.id, run.id)); + return { run, selected }; + } + + it("keeps typed recovery receipts without returning execution output or modifying history", async () => { + const evidence = { errorFamily: "transient_upstream", workspaceValidation: { fingerprint: "workspace" }, + configurationIncomplete: { reason: "workspace_unavailable", fingerprint: "configuration" }, + cancelledByActorType: "board", retryNotBefore: "2099-01-01T00:00:00Z", transientRetryNotBefore: 123, + providerQuotaRetryNotBefore: null, finalizationReasonCode: "conversation_turn_finished" }; + const payload = randomBytes(512 * 1024).toString("base64"); + const result = { ...evidence, summary: payload, output: payload, providerResponse: { output: payload } }; + const { run, selected } = await read(result); + expect(selected.resultJson).toEqual(evidence); + expect(Buffer.byteLength(JSON.stringify(selected))).toBeLessThan(1024); + expect(classifyContinuationFailure({ ...run, resultJson: selected.resultJson })).toEqual(classifyContinuationFailure(run)); + const [stored] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, run.id)); + expect(stored).toEqual(run); + }); + + it.each(["adapter_failed", "provider_quota", "configuration_incomplete"])("retains arbitrary provider evidence for %s classification", async errorCode => { + const now = new Date("2020-01-01T00:00:00Z"); + const result = { providerSpecificField: { nestedResponse: "Rate limit exceeded. Try again after 2099-01-01T00:00:00Z" }, + configurationIncomplete: { reason: "ai_connection_unavailable" }, + output: randomBytes(64 * 1024).toString("base64") }; + const { run, selected } = await read(result, errorCode); + expect(selected.resultJson).toEqual(result); + const projected = { ...run, livenessState: "blocked", resultJson: selected.resultJson }; + const complete = { ...run, livenessState: "blocked" }; + expect(classifyAdapterFailureForRecovery(projected, now)).toEqual(classifyAdapterFailureForRecovery(complete, now)); + expect(classifyContinuationFailure(projected)).toEqual(classifyContinuationFailure(complete)); + expect(isAiAuthenticationBlocked(projected)).toBe(isAiAuthenticationBlocked(complete)); + }); + + it("checks legacy eligibility and repair ancestry without returning large result bodies", async () => { + const result = { output: randomBytes(512 * 1024).toString("base64") }; + const { run: source } = await read(result); + const { run: queued } = await read(result); + await db.update(heartbeatRuns).set({ status: "queued", contextSnapshot: { + issueId: randomUUID(), dispositionRepairSourceRunId: source.id, + legacyDispositionEpisode: { id: source.id, attempt: 1, maxAttempts: 2 }, + } }).where(eq(heartbeatRuns.id, queued.id)); + const reads: unknown[][] = []; + const recorded = new Proxy(db, { get(target, key) { + if (key !== "select") return Reflect.get(target, key); + return (...fields: Parameters) => { + const builder = target.select(...fields), from = builder.from.bind(builder); + builder.from = ((...args: Parameters) => { + const query = from(...args); + if (args[0] === heartbeatRuns) { + const execute = query.execute.bind(query); + query.execute = async (...executeArgs: Parameters) => { + const rows = await execute(...executeArgs); reads.push(rows); return rows; + }; + } + return query; + }) as typeof builder.from; + return builder; + }; + }}); + const service = recoveryService(recorded, { enqueueWakeup: async () => { throw new Error("unexpected wake"); } }); + expect(await service.reconcileLegacyContinuation(source.id)).toBe("skipped"); + expect(await service.legacyRepairDispatchBlock(queued.id)).toBe("missing_issue"); + expect(reads).toHaveLength(3); + expect(Buffer.byteLength(JSON.stringify(reads))).toBeLessThan(16 * 1024); + const [stored] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, source.id)); + expect(stored).toEqual(source); + const [storedQueued] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, queued.id)); + expect(storedQueued.resultJson).toEqual(result); + }); + + it.each([null, [], ["unexpected"], "scalar", 42, false, {}, { errorFamily: false, cancelledByActorType: 3, + workspaceValidation: [], configurationIncomplete: null, retryNotBefore: { invalid: true }, finalizationReasonCode: "" }] + .map(result => ({ result })))("preserves structured evidence types for $result", async ({ result }) => { + const { run, selected } = await read(result); + const expected = result && typeof result === "object" && !Array.isArray(result) ? result : result === null ? null : {}; + expect(selected.resultJson).toEqual(expected); + expect(classifyContinuationFailure({ ...run, resultJson: selected.resultJson })).toEqual(classifyContinuationFailure(run)); + }); +}); diff --git a/server/src/services/recovery/run-result-read.ts b/server/src/services/recovery/run-result-read.ts new file mode 100644 index 00000000000..3f2b0ddecdd --- /dev/null +++ b/server/src/services/recovery/run-result-read.ts @@ -0,0 +1,25 @@ +import { heartbeatRuns } from "@paperclipai/db"; +import { sql } from "drizzle-orm"; + +const recoveryResultKeys = [ + "errorFamily", "workspaceValidation", "configurationIncomplete", + "cancelledByActorType", "retryNotBefore", "transientRetryNotBefore", + "providerQuotaRetryNotBefore", "finalizationReasonCode", +] as const; + +/** These three classifiers inspect arbitrary provider error text. Other + * recovery decisions consume the structured fields below, not model output. + * Keep the full stored result and all execution/detail reads unchanged. */ +export const recoveryRunResultColumn = sql | null>` + case + when ${heartbeatRuns.resultJson} is null then null + when ${heartbeatRuns.errorCode} in ('adapter_failed', 'provider_quota', 'configuration_incomplete') + then ${heartbeatRuns.resultJson} + else ( + select coalesce(jsonb_object_agg(field.key, field.value), '{}'::jsonb) + from jsonb_each(case when jsonb_typeof(${heartbeatRuns.resultJson}) = 'object' + then ${heartbeatRuns.resultJson} else '{}'::jsonb end) as field(key, value) + where field.key in (${sql.join(recoveryResultKeys.map(key => sql`${key}`), sql`, `)}) + ) + end +`; diff --git a/server/src/services/recovery/service.ts b/server/src/services/recovery/service.ts index e517b69ec69..e72811ec8d0 100644 --- a/server/src/services/recovery/service.ts +++ b/server/src/services/recovery/service.ts @@ -1,4 +1,5 @@ import { recoveryRunContextColumn, recoveryRunVersionColumn } from "./run-context-read.js"; +import { recoveryRunResultColumn } from "./run-result-read.js"; import { isAgentAwaitingSetup } from "../../modules/agent-lifecycle/index.js"; import { onboardingFirstTaskAwaitingUserSql } from "./onboarding-first-task-wait.js"; import { isAiAuthenticationBlocked } from "../ai-auth-failure.js"; @@ -235,6 +236,11 @@ type ResolvedDependencyWakeBackstopOptions = { source?: ResolvedDependencyWakeBackstopSource; }; +const recoveryRunFields = { + ...getTableColumns(heartbeatRuns), + resultJson: recoveryRunResultColumn, +}; + type LatestIssueRun = | (Pick< typeof heartbeatRuns.$inferSelect, @@ -983,7 +989,7 @@ export function recoveryService( contextSnapshot: recoveryRunContextColumn, rowVersion: recoveryRunVersionColumn, livenessState: heartbeatRuns.livenessState, - resultJson: heartbeatRuns.resultJson, + resultJson: recoveryRunResultColumn, startedAt: heartbeatRuns.startedAt, createdAt: heartbeatRuns.createdAt, }) @@ -1014,7 +1020,7 @@ export function recoveryService( contextSnapshot: recoveryRunContextColumn, rowVersion: recoveryRunVersionColumn, livenessState: heartbeatRuns.livenessState, - resultJson: heartbeatRuns.resultJson, + resultJson: recoveryRunResultColumn, startedAt: heartbeatRuns.startedAt, createdAt: heartbeatRuns.createdAt, }) @@ -1915,7 +1921,7 @@ export function recoveryService( contextSnapshot: recoveryRunContextColumn, rowVersion: recoveryRunVersionColumn, livenessState: heartbeatRuns.livenessState, - resultJson: heartbeatRuns.resultJson, + resultJson: recoveryRunResultColumn, startedAt: heartbeatRuns.startedAt, createdAt: heartbeatRuns.createdAt, }) @@ -3786,7 +3792,7 @@ export function recoveryService( episode: LegacyDispositionEpisode, dispatchRunId?: string, ) { - const [run] = await db.select().from(heartbeatRuns).where(and( + const [run] = await db.select(recoveryRunFields).from(heartbeatRuns).where(and( eq(heartbeatRuns.id, runId), eq(heartbeatRuns.companyId, issue.companyId), )).limit(1); if (!run) return { kind: "skip" as const, reason: "missing_run" }; @@ -3825,7 +3831,7 @@ export function recoveryService( } async function legacyRepairDispatchBlock(runId: string): Promise { - const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)).limit(1); + const [run] = await db.select(recoveryRunFields).from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)).limit(1); const context = parseObject(run?.contextSnapshot); if (!run || !parseObject(context.legacyDispositionEpisode).id) return null; if (!["queued", "running", "scheduled_retry"].includes(run.status)) return "repair_not_active"; @@ -3835,7 +3841,7 @@ export function recoveryService( const sourceId = readNonEmptyString(context.dispositionRepairSourceRunId) ?? readNonEmptyString(context.retryOfRunId); const issueId = readNonEmptyString(context.issueId); if (!sourceId || !issueId || episode.attempt < 1 || episode.attempt > episode.maxAttempts) return "invalid_repair_binding"; - const [source] = await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.id, sourceId), eq(heartbeatRuns.companyId, run.companyId))).limit(1); + const [source] = await db.select(recoveryRunFields).from(heartbeatRuns).where(and(eq(heartbeatRuns.id, sourceId), eq(heartbeatRuns.companyId, run.companyId))).limit(1); if (!source || source.agentId !== run.agentId || legacyDispositionEpisode(source).id !== episode.id) return "invalid_repair_source"; const [issue] = await db.select().from(issues).where(and(eq(issues.id, issueId), eq(issues.companyId, run.companyId))).limit(1); if (!issue) return "missing_issue"; @@ -3847,7 +3853,7 @@ export function recoveryService( } async function reconcileLegacyContinuation(runId: string) { - const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)).limit(1); + const [run] = await db.select(recoveryRunFields).from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)).limit(1); if (!run || run.runtimeMode === "native" || run.status !== "succeeded") return "skipped" as const; const context = parseObject(run.contextSnapshot); const issueId = readNonEmptyString(context.issueId) ?? readNonEmptyString(context.taskId); From 1cfaf973cdd100b1a13064b6ef4b9ea840861b57 Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Sat, 24 Oct 2026 14:01:41 -0700 Subject: [PATCH 016/110] Read release evidence and telemetry without unused output (#17485) Read execution release evidence and terminal telemetry without unused output. Keep full stored history, in-flight guards, and accepted messages. Validated with real PostgreSQL tests, build, typecheck, green CI, and Greptile 5/5. Co-Authored-By: Paperclip --- doc/DATABASE.md | 6 ++ .../agent-task-run-telemetry.test.ts | 56 +++++++++++++- .../wake-queue/adapters/postgres.test.ts | 75 ++++++++++++++++++- .../modules/wake-queue/adapters/postgres.ts | 12 ++- .../src/services/agent-task-run-telemetry.ts | 18 ++++- .../src/services/recovery/run-result-read.ts | 3 - 6 files changed, 157 insertions(+), 13 deletions(-) diff --git a/doc/DATABASE.md b/doc/DATABASE.md index 1dc73cbf9d5..28950218145 100644 --- a/doc/DATABASE.md +++ b/doc/DATABASE.md @@ -49,6 +49,12 @@ and leaves all existing cases passive. Source identities are not grants. ### Task query performance +The issue-lock adapter's release read omits `result_json.stdout` and +`result_json.stderr` before transferring a run to the controller. Every other result key, context field, and +stop, retry, lease, and workspace-recovery check stays intact. Full output remains +stored for execution history and detail reads. Terminal telemetry loads only its +run identity, timestamps, usage, and typed task identifier. + Recovery's latest-run queries return the context fields used by recovery decisions. Prompts, execution continuation bodies, and workspace setup payloads remain in the stored run and its full detail reads. These queries also return diff --git a/server/src/__tests__/agent-task-run-telemetry.test.ts b/server/src/__tests__/agent-task-run-telemetry.test.ts index ef036b73e46..87dbf7a26a3 100644 --- a/server/src/__tests__/agent-task-run-telemetry.test.ts +++ b/server/src/__tests__/agent-task-run-telemetry.test.ts @@ -1,6 +1,7 @@ -import { randomUUID } from "node:crypto"; +import { randomBytes, randomUUID } from "node:crypto"; import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; -import { agents, companies, createDb, heartbeatRuns } from "@paperclipai/db"; +import { agents, companies, createDb, heartbeatRuns, type Db } from "@paperclipai/db"; +import { eq } from "drizzle-orm"; import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase, @@ -23,7 +24,7 @@ vi.mock("@paperclipai/shared/telemetry", async () => { }; }); -import { emitAgentTaskRun } from "../services/agent-task-run-telemetry.ts"; +import { emitAgentTaskRun, emitAgentTaskRunById } from "../services/agent-task-run-telemetry.ts"; const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport(); const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip; @@ -104,6 +105,55 @@ describeEmbeddedPostgres("emitAgentTaskRun", () => { } }); + it("emits the same event from a small scoped run read without loading execution payloads", async () => { + await seedCompanyAndAgent(); + const payload = randomBytes(128 * 1024).toString("base64"); + const [run] = await db.insert(heartbeatRuns).values({ companyId, agentId, status: "succeeded", + startedAt: new Date("2020-01-01T00:00:00Z"), finishedAt: new Date("2020-01-01T00:00:07Z"), + contextSnapshot: { issueId: randomUUID(), prompt: payload }, runnerProfileJson: { instructions: payload }, + stdoutExcerpt: payload, resultJson: { stdout: payload }, usageJson: { model: "fixture", inputTokens: 12, outputTokens: 34, cachedInputTokens: 5 }, + }).returning(); + await emitAgentTaskRun(db, run); + const expected = mockTrackAgentTaskRun.mock.calls[0]; + mockTrackAgentTaskRun.mockClear(); + const reads: unknown[][] = []; + const recorded = new Proxy(db, { get(target, key) { + if (key !== "select") return Reflect.get(target, key); + return (...fields: Parameters) => { + const builder = target.select(...fields), from = builder.from.bind(builder); + builder.from = ((...args: Parameters) => { + const query = from(...args); + if (args[0] === heartbeatRuns) { + const execute = query.execute.bind(query); + query.execute = async (...executeArgs: Parameters) => { + const rows = await execute(...executeArgs); reads.push(rows); return rows; + }; + } + return query; + }) as typeof builder.from; + return builder; + }; + }}); + await emitAgentTaskRunById(recorded, { companyId, runId: run.id }); + expect(mockTrackAgentTaskRun).toHaveBeenCalledExactlyOnceWith(...expected); + expect(reads).toHaveLength(1); + expect(Buffer.byteLength(JSON.stringify(reads))).toBeLessThan(1024); + await emitAgentTaskRunById(recorded, { companyId: randomUUID(), runId: run.id }); + expect(mockTrackAgentTaskRun).toHaveBeenCalledTimes(1); + expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, run.id)))[0]).toEqual(run); + }); + + it.each([null, [], 42, { issueId: 42 }, { issueId: " fixture-task " }, { issueId: "" }].map(context => ({ context })))("preserves telemetry task identity for $context", async ({ context }) => { + await seedCompanyAndAgent(); + const [run] = await db.insert(heartbeatRuns).values({ companyId, agentId, status: "failed", + contextSnapshot: context as Record | null }).returning(); + await emitAgentTaskRun(db, run); + const expected = mockTrackAgentTaskRun.mock.calls[0]; + mockTrackAgentTaskRun.mockClear(); + await emitAgentTaskRunById(db, { companyId, runId: run.id }); + expect(mockTrackAgentTaskRun).toHaveBeenCalledExactlyOnceWith(...expected); + }); + it("omits durationSeconds when the run has no startedAt", async () => { await seedCompanyAndAgent(); const run = { diff --git a/server/src/modules/wake-queue/adapters/postgres.test.ts b/server/src/modules/wake-queue/adapters/postgres.test.ts index 24230989937..16479253a2f 100644 --- a/server/src/modules/wake-queue/adapters/postgres.test.ts +++ b/server/src/modules/wake-queue/adapters/postgres.test.ts @@ -1,5 +1,5 @@ import { instanceSettingsService } from "../../../services/instance-settings.js"; -import { randomUUID } from "node:crypto"; +import { randomBytes, randomUUID } from "node:crypto"; import { eq } from "drizzle-orm"; import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest"; import type { Db } from "@paperclipai/db"; @@ -177,6 +177,79 @@ describeEmbeddedPostgres("wake-queue postgres adapter", () => { return id; } + function recordReleaseRunReads() { + const rows: unknown[][] = []; + function recordSelects>(executor: T): T { + return new Proxy(executor, { get(target, key) { + if (key !== "select") return Reflect.get(target, key); + return (...fields: Parameters) => { + const builder = target.select(...fields), from = builder.from.bind(builder); + builder.from = ((...args: Parameters) => { + const query = from(...args); + if (args[0] === heartbeatRuns) { + const execute = query.execute.bind(query); + query.execute = async (...executeArgs: Parameters) => { + const result = await execute(...executeArgs); rows.push(result); return result; + }; + } + return query; + }) as typeof builder.from; + return builder; + }; + }}); + } + const transaction: Db["transaction"] = (callback, config) => + db.transaction(tx => callback(recordSelects(tx)), config); + const recorded = new Proxy(db, { get(target, key) { + return key === "transaction" ? transaction : Reflect.get(target, key); + }}); + return { recorded, rows }; + } + + it("keeps in-flight work and every recovery receipt while omitting output from release reads", async () => { + const companyId = await seedCompany(); + const agentId = await seedAgent({ companyId }); + const issueId = await seedIssue({ companyId, assigneeAgentId: agentId }); + const runId = await seedRun({ companyId, agentId, status: "running", contextSnapshot: { issueId } }); + const wakeId = await seedDeferredWake({ companyId, agentId, issueId }); + const payload = randomBytes(512 * 1024).toString("base64"); + const evidence = { cancellation: { source: "queued_message", expected: true, initiator: { type: "system" }, reason: "Fixture", recordedAt: "2020-01-01T00:00:00Z" }, + workspaceRestoreFailure: "restore_unsafe_archive", workspaceRestoreRecovery: { schema: "paperclip.workspace-restore-recovery.v1", leaseIds: [randomUUID()] }, + nativeCancellation: { schema: "paperclip.native-cancellation.v1", runId, companyId, issueId }, + executionCancellation: { state: "acknowledged" }, executionRecovery: { kind: "interrupted", providerStopped: true }, + configurationIncomplete: { reason: "workspace_unavailable" }, unknownFutureReceipt: { retained: true } }; + await db.update(heartbeatRuns).set({ resultJson: { ...evidence, stdout: payload.repeat(3), stderr: payload } }).where(eq(heartbeatRuns.id, runId)); + await db.update(issues).set({ executionRunId: runId, checkoutRunId: runId }).where(eq(issues.id, issueId)); + const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)); + const [issue] = await db.select().from(issues).where(eq(issues.id, issueId)); + const [wake] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, wakeId)); + const { recorded, rows } = recordReleaseRunReads(); + const result = await createPostgresWakeQueueAdapter(recorded, stubDeps).withIssueExecutionLock( + { companyId, runId, now: new Date(), resumeStrandedQueue: true }, + async () => { throw new Error("in-flight work must not drain"); }, + ); + expect(result.outcome.kind).toBe("released"); + expect(rows).toHaveLength(1); + expect(rows[0]).toEqual([{ ...run, resultJson: evidence }]); + expect(Buffer.byteLength(JSON.stringify(rows))).toBeLessThan(8 * 1024); + expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)))[0]).toEqual(run); + expect((await db.select().from(issues).where(eq(issues.id, issueId)))[0]).toEqual(issue); + expect((await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, wakeId)))[0]).toEqual(wake); + }); + + it.each([null, ["stdout", { stderr: "array evidence" }], "scalar", 42].map(result => ({ result })))("preserves non-object result evidence $result during release", async ({ result }) => { + const companyId = await seedCompany(), agentId = await seedAgent({ companyId }); + const runId = await seedRun({ companyId, agentId, status: "running" }); + await db.update(heartbeatRuns).set({ resultJson: result as Record | null }).where(eq(heartbeatRuns.id, runId)); + const { recorded, rows } = recordReleaseRunReads(); + await createPostgresWakeQueueAdapter(recorded, stubDeps).withIssueExecutionLock( + { companyId, runId, now: new Date(), resumeStrandedQueue: true }, + async () => { throw new Error("in-flight work must not drain"); }, + ); + expect(rows).toHaveLength(1); + expect((rows[0][0] as typeof heartbeatRuns.$inferSelect).resultJson).toEqual(result); + }); + it.each(["assignee", "mentioned"])("preserves a paused recipient's accepted message until resume (%s)", async kind => { const companyId = await seedCompany(); const ownerId = await seedAgent({ companyId }); diff --git a/server/src/modules/wake-queue/adapters/postgres.ts b/server/src/modules/wake-queue/adapters/postgres.ts index c4929f482ba..6db54a82725 100644 --- a/server/src/modules/wake-queue/adapters/postgres.ts +++ b/server/src/modules/wake-queue/adapters/postgres.ts @@ -5,7 +5,7 @@ import { isCompletedOnboardingHandoffWake } from "../../../services/chat-complet import { instanceSettingsService } from "../../../services/instance-settings.js"; import { currentConversationCommentCondition } from "../../../services/agent-conversations.js"; import { getExecutionBlocker, hasPendingRunCleanup } from "../../../services/execution-blocker.js"; -import { and, asc, eq, inArray, isNull, notInArray, or, sql } from "drizzle-orm"; +import { and, asc, eq, getTableColumns, inArray, isNull, notInArray, or, sql } from "drizzle-orm"; import type { Db } from "@paperclipai/db"; import { extractIssueReferenceIdentifiers, isUuidLike } from "@paperclipai/shared"; import { @@ -74,6 +74,14 @@ const EXECUTION_PATH_HEARTBEAT_RUN_STATUSES = ["queued", "running", "scheduled_r type HeartbeatRunRow = typeof heartbeatRuns.$inferSelect; type IssueRow = typeof issues.$inferSelect; +const releaseRunFields = { + ...getTableColumns(heartbeatRuns), + resultJson: sql | null>`case + when jsonb_typeof(${heartbeatRuns.resultJson}) = 'object' + then ${heartbeatRuns.resultJson} - 'stdout' - 'stderr' + else ${heartbeatRuns.resultJson} end`, +}; + function normalizeAgentNameKey(value: string | null | undefined): string | null { if (typeof value !== "string") return null; const normalized = value.trim().toLowerCase(); @@ -1051,7 +1059,7 @@ export function createPostgresWakeQueueAdapter(db: Db, deps: WakeQueuePostgresAd return db.transaction(async (rawTx) => { const tx = rawTx as unknown as Db; const run = await tx - .select() + .select(releaseRunFields) .from(heartbeatRuns) .where(and(eq(heartbeatRuns.id, input.runId), eq(heartbeatRuns.companyId, input.companyId))) .then((rows) => rows[0] ?? null); diff --git a/server/src/services/agent-task-run-telemetry.ts b/server/src/services/agent-task-run-telemetry.ts index c7fb031276a..d9df8afeeef 100644 --- a/server/src/services/agent-task-run-telemetry.ts +++ b/server/src/services/agent-task-run-telemetry.ts @@ -1,4 +1,4 @@ -import { and, eq } from "drizzle-orm"; +import { and, eq, sql } from "drizzle-orm"; import { agents, heartbeatRuns, type Db } from "@paperclipai/db"; import { trackAgentTaskRun } from "@paperclipai/shared/telemetry"; import { parseObject } from "../adapters/utils.js"; @@ -6,6 +6,8 @@ import { logger } from "../middleware/logger.js"; import { getTelemetryClient } from "../telemetry.js"; type HeartbeatRun = typeof heartbeatRuns.$inferSelect; +type TelemetryRun = Pick; function readNonEmptyString(value: unknown): string | null { return typeof value === "string" && value.trim().length > 0 @@ -27,7 +29,7 @@ function readUsageToken( } function resolveDurationSeconds( - run: HeartbeatRun, + run: Pick, now: Date, ): number | undefined { if (!run.startedAt) return undefined; @@ -52,7 +54,7 @@ function resolveDurationSeconds( * the caller's return on the slower of the two promises, so it does not * remove the delay. */ -export async function emitAgentTaskRun(db: Db, run: HeartbeatRun): Promise { +export async function emitAgentTaskRun(db: Db, run: TelemetryRun): Promise { try { const client = getTelemetryClient(); if (!client) return; @@ -130,7 +132,15 @@ export async function emitAgentTaskRunById( ): Promise { try { const run = await db - .select() + .select({ + id: heartbeatRuns.id, + agentId: heartbeatRuns.agentId, + status: heartbeatRuns.status, + startedAt: heartbeatRuns.startedAt, + finishedAt: heartbeatRuns.finishedAt, + usageJson: heartbeatRuns.usageJson, + contextSnapshot: sql>`jsonb_build_object('issueId', ${heartbeatRuns.contextSnapshot}->'issueId')`, + }) .from(heartbeatRuns) .where(and(eq(heartbeatRuns.id, input.runId), eq(heartbeatRuns.companyId, input.companyId))) .then((rows) => rows[0] ?? null); diff --git a/server/src/services/recovery/run-result-read.ts b/server/src/services/recovery/run-result-read.ts index 3f2b0ddecdd..93c519a3273 100644 --- a/server/src/services/recovery/run-result-read.ts +++ b/server/src/services/recovery/run-result-read.ts @@ -7,9 +7,6 @@ const recoveryResultKeys = [ "providerQuotaRetryNotBefore", "finalizationReasonCode", ] as const; -/** These three classifiers inspect arbitrary provider error text. Other - * recovery decisions consume the structured fields below, not model output. - * Keep the full stored result and all execution/detail reads unchanged. */ export const recoveryRunResultColumn = sql | null>` case when ${heartbeatRuns.resultJson} is null then null From 044628f59e8d057a25a1c2546962dcdeb42a66f7 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sat, 24 Oct 2026 14:07:28 -0700 Subject: [PATCH 017/110] Add explicit native tracing to the Runner eval CLI (#17483) ## Thinking Path > - Paperclip manages AI agents and their work. > - Runner Evals exercise real providers against a mock control plane. > - The controlled gateway route creates a disposable provider home. > - That route had no explicit native trace configuration. > - Codex skips normal home preparation for a preconfigured home. > - This change validates and applies the existing observability launch contract before provider creation. > - Operators can collect native evidence without passing vendor keys to the child. ## Linked Issues or Issue Description Refs #17440. Related: #17452 and #17469. This PR is based directly on master and does not include those pending controller changes. **Current behavior** The eval-session CLI cannot pass an explicit native observability launch. Passing environment alone cannot configure Codex in the disposable gateway home. **Proposed behavior** Accept an opt-in descriptor bound to the gateway attempt. Validate the existing provider launch contract, add a scoped relay token in memory, and apply it only to the owned provider home and environment. **Reason and benefit** A controller can route native evidence through its bounded local relay while the CLI keeps configuration distinct from verified ingestion. This is the CLI contract; hosted controller integration remains separate work. ## What Changed - Add a strict, bounded descriptor reader for native Codex and ACPX Claude. Bind campaign, execution, attempt, project, trace, span, and mock authority identifiers. - Reuse Runner observability materialization and redaction. Preserve the model gateway route. Reject upstream destinations, extra environment fields, credentials in headers, and unknown exporter settings. - Add `--observability-config`, requiring an explicit gateway. Keep direct and unconfigured paths unchanged. - Retain secret-free configured/unverified metadata in success and failure artifacts. - Document the contract and controller responsibilities. No workflow, runtime dependency, paid schedule, or public report changes. ## Verification - Eval CLI regression selection: 81 passed before the test-only relocation. The 17 new cross-package observability tests now pass from `tests/runner-e2e/runner-eval-observability.test.ts`; their integration-suite typecheck also passes. They use the actual shared launch generator, real disposable homes, CLI success/failure paths, and credential redaction. The first run exposed two test setup references introduced by a broad edit; both were corrected and its failure log remains retained. - Runner TypeScript build and release daemon build passed. Full `pnpm -r typecheck` passed. - Actual native Codex and ACPX Claude reached a local receiver with authenticated OTLP protobuf and the expected Braintrust parent. Codex sent four log and two trace batches; Claude sent three log and one trace batch. All recorded processes exited, disposable homes were removed, and 29 retained files contained neither synthetic credential. - The local model endpoint deliberately returned 401. Codex retained a failed terminal turn; Claude retained a provider timeout. These are route/export proofs, not semantic eval passes. Native retries reached only the fake endpoint. No paid provider or Braintrust request was made. - The first local probe failed before provider launch because its TypeScript loader path was wrong. It was corrected to the installed loader; both attempts remain retained. - Full repository build passed at initial head 7b75c0349f. The full local test suite encountered repeated embedded PostgreSQL startup failures before database-backed test bodies. It was stopped after five affected suites (exit 143), so it is incomplete. Its log remains retained. The same host had independently demonstrated PostgreSQL semaphore exhaustion earlier in this task; this run did not collect that lower-level error. Full hosted workflow 40131255078 passed on final head 23a172af328780c7eafb883fffa92dccf734db5b, including the database-backed suites, Runner, build, typecheck and browser checks. Greptile is 5/5 with zero open threads. The secondary Paperclip reviewer ended neutral without an assessment; it is not counted as a successful review. A follow-up header-validation repair uses a map without a prototype and passes the added negative regression. No exporter behavior changed. - The CLI still reports native ingestion as unverified. No complete capture, destination indexing, vendor billing bound, hosted admission, or paid recurrence qualification is claimed. - Package-boundary validation found two new imports from the standalone Runner tests into other repository packages. Those tests now live in the repository integration suite and use the actual launch generator there. Its first run failed on a TOML parser resolved from the wrong package; resolving that dependency from its Runner owner fixed the test. Three pre-existing boundary/tracked-import findings remain in unchanged files; this PR adds none. ## Risks - This descriptor is intentionally narrow. Changes to the shared launch contract must be reviewed against its validator and integration tests. - The local relay receives native content under the selected capture policy. Its controller must enforce ingestion quotas, shutdown, private retention, and qualified cost bounds. - Descriptor validation runs once before launch. It reads at most 128 KiB and refuses symlinks and non-regular files. Existing owned-home config writing remains synchronous and small. - Relay credentials are held in child memory. Persisted diagnostics and artifacts use the existing redactor. The descriptor itself must remain secret-free. ## Model Used OpenAI Codex, GPT-6 family, with reasoning, tool use, and code execution. This runtime does not expose the exact model ID or 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 `#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 --- .../docs/runner-protocol-live-evals.md | 39 ++++ .../src/cli/eval-observability-runtime.ts | 135 +++++++++++++ .../paperclip-runner/src/cli/eval-session.ts | 23 ++- .../runner-eval-observability.test.ts | 185 ++++++++++++++++++ 4 files changed, 376 insertions(+), 6 deletions(-) create mode 100644 packages/paperclip-runner/src/cli/eval-observability-runtime.ts create mode 100644 tests/runner-e2e/runner-eval-observability.test.ts diff --git a/packages/paperclip-runner/docs/runner-protocol-live-evals.md b/packages/paperclip-runner/docs/runner-protocol-live-evals.md index a7114ed7c31..6d3cf586e0b 100644 --- a/packages/paperclip-runner/docs/runner-protocol-live-evals.md +++ b/packages/paperclip-runner/docs/runner-protocol-live-evals.md @@ -159,6 +159,45 @@ change the hosted matrix. The controller must enforce request admission, deadlines, and limits before forwarding traffic. A local fake-API probe only proves routing; it does not qualify live provider or Braintrust behavior. +## Controller-assigned native observability + +The same CLI accepts `--observability-config /absolute/path/observability.json` +only with `--gateway-config`. This opt-in route supports native Codex and ACPX +Claude. Without that argument, the gateway route exports no native traces. + +The descriptor uses schema `paperclip.runner-eval.observability/v1`. It contains +`campaignId`, `executionId`, and `attemptId` matching the gateway and request; +`projectId` (UUID), `traceId` (32 lowercase hex characters), and `spanId` (16 +lowercase hex characters); `baseUrl` in the form +`http://127.0.0.1:PORT/otel`; and `launch`, the secret-free result from the existing +`buildProviderObservabilityLaunch` in `packages/adapter-utils`. The CLI accepts +only its known Codex/Claude exporter settings and the mock session's exact +company and agent attributes. Bind `revision` to `compatibilityKey`. Use a +compatibility key of at most 128 letters, digits, underscores, or hyphens. + +Build the launch with `/v1/logs` and `/v1/traces` under that base URL, a timeout +of at most 3 seconds, and only the `x-bt-parent` header from +`exportBraintrustAttemptParent` for those project/trace/span IDs. Do not include +upstream authorization in the file. Supply the attempt's separate 32-byte +hexadecimal relay credential through `PAPERCLIP_RUNNER_EVAL_OTLP_TOKEN`. The CLI +adds authorization to the provider environment and redacts it from diagnostics +and artifacts. Codex configuration is written only into the disposable gateway +home; the existing model route is preserved. The descriptor must be a regular +file, not a symlink, and fit within 128 KiB. + +Success and failure artifacts record `nativeObservability` with the declared +project/trace/span IDs, descriptor SHA-256, `configured: true`, and +`verification: "unverified"`. Configuration does not prove export, ingestion, +indexing, complete capture, or billing coverage. Relay receipts and destination +readback must establish those separate facts. Provider errors keep their +original outcome even when traces arrive. + +The controller owns the relay, credentials, ingestion quotas, deadline, drain, +and private receipt retention. This CLI option does not start a relay, set an +operating allowance, or enable a paid campaign. The existing Product E2E relay +and launch generator remain the integration owners; the hosted Runner workflow +still needs its own qualified controller integration. + ## Hosted campaign Use the `Runner Direct Live Protocol Evals` workflow. Dispatch the workflow diff --git a/packages/paperclip-runner/src/cli/eval-observability-runtime.ts b/packages/paperclip-runner/src/cli/eval-observability-runtime.ts new file mode 100644 index 00000000000..00e8b23a8b4 --- /dev/null +++ b/packages/paperclip-runner/src/cli/eval-observability-runtime.ts @@ -0,0 +1,135 @@ +import { createHash } from "node:crypto"; +import { constants } from "node:fs"; +import { open } from "node:fs/promises"; +import { CapabilityMockControlPlaneAdapter } from "../mock-core/capability-mock-control-plane-adapter.js"; +import { + applyProviderObservabilityEnvironment, + writeManagedCodexObservability, + type ProviderObservabilityLaunch, +} from "../drivers/agent-observability.js"; +import type { EvalSessionRequest } from "./eval-session-contract.js"; +import type { prepareEvalGatewayRuntime } from "./eval-gateway-runtime.js"; + +type Gateway = Awaited>; +const invalid = () => new Error("Invalid controlled eval observability configuration"); +function object(value: unknown, names: string[]): Record { + if (!value || typeof value !== "object" || Array.isArray(value) + || Object.keys(value).length !== names.length || Object.keys(value).some(key => !names.includes(key))) throw invalid(); + return value as Record; +} +function text(value: unknown): string { + if (typeof value !== "string" || !value || value.length > 4096 || /[\r\n\0]/.test(value)) throw invalid(); + return value; +} +function decodedMap(value: unknown): Record { + const result: Record = Object.create(null); + for (const item of text(value).split(",")) { + const index = item.indexOf("="); + if (index < 1) throw invalid(); + const key = item.slice(0, index); + if (Object.hasOwn(result, key)) throw invalid(); + result[key] = decodeURIComponent(item.slice(index + 1)); + } + return result; +} +function same(value: unknown, expected: Record) { + const actual = object(value, Object.keys(expected)); + if (Object.entries(expected).some(([key, item]) => actual[key] !== item)) throw invalid(); +} +function parentHeader(value: unknown, projectId: string, traceId: string, spanId: string): string { + const headers = decodedMap(value), parent = text(headers["x-bt-parent"]); + object(headers, ["x-bt-parent"]); + const bytes = Buffer.from(parent, "base64"); + if (bytes.toString("base64") !== parent || !bytes.subarray(0, 3).equals(Buffer.from([4, 2, 0]))) throw invalid(); + same(JSON.parse(bytes.subarray(3).toString("utf8")), { object_id: projectId, row_id: spanId, span_id: spanId, root_span_id: traceId }); + return parent; +} + +export async function prepareEvalObservabilityRuntime( + file: string, + request: EvalSessionRequest, + gateway: Gateway, + environment: NodeJS.ProcessEnv = process.env, +) { + let raw: Buffer; + const handle = await open(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); + try { + const stat = await handle.stat(); + if (!stat.isFile() || stat.size > 131_072) throw invalid(); + raw = Buffer.alloc(stat.size + 1); + const { bytesRead } = await handle.read(raw, 0, raw.length, 0); + if (bytesRead !== stat.size) throw invalid(); + raw = raw.subarray(0, bytesRead); + } finally { await handle.close(); } + let launch: ProviderObservabilityLaunch; + let projectId: string, traceId: string, spanId: string; + try { + const config = object(JSON.parse(raw.toString("utf8")), ["schema", "campaignId", "executionId", "attemptId", "projectId", "traceId", "spanId", "baseUrl", "launch"]); + projectId = text(config.projectId); traceId = text(config.traceId); spanId = text(config.spanId); + if (config.schema !== "paperclip.runner-eval.observability/v1" || config.attemptId !== request.attemptId + || config.campaignId !== gateway.evidence.campaignId || config.executionId !== gateway.evidence.executionId + || !/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(projectId) + || !/^[a-f0-9]{32}$/.test(traceId) || /^0+$/.test(traceId) || !/^[a-f0-9]{16}$/.test(spanId) || /^0+$/.test(spanId) + || !/^http:\/\/127\.0\.0\.1:[1-9][0-9]{0,4}\/otel$/.test(text(config.baseUrl)) + || Number(new URL(config.baseUrl as string).port) > 65535) throw invalid(); + const kind = request.provider === "codex" ? "codex" : request.provider === "acpx" && request.acpxAgent === "claude" ? "claude" : null; + if (!kind) throw invalid(); + const source = object(config.launch, ["kind", "compatibilityKey", "environment", ...(kind === "codex" ? ["otelConfig"] : [])]); + if (source.kind !== kind || !/^[A-Za-z0-9_-]{1,128}$/.test(text(source.compatibilityKey))) throw invalid(); + const state = new CapabilityMockControlPlaneAdapter(request.session.seed).snapshot(); + const attributes = { + "paperclip.company.id": request.session.companyId ?? state.company.id, + "paperclip.agent.id": request.session.actorId ?? state.actors[0]!.id, + "paperclip.observability.revision": source.compatibilityKey, + }; + const common = ["OTEL_EXPORTER_OTLP_LOGS_TIMEOUT", "OTEL_EXPORTER_OTLP_TRACES_TIMEOUT", "OTEL_EXPORTER_OTLP_LOGS_HEADERS", "OTEL_EXPORTER_OTLP_TRACES_HEADERS"]; + const env = object(source.environment, kind === "codex" ? common : [...common, + "CLAUDE_CODE_ENABLE_TELEMETRY", "CLAUDE_CODE_ENHANCED_TELEMETRY_BETA", "OTEL_LOGS_EXPORTER", "OTEL_TRACES_EXPORTER", "OTEL_METRICS_EXPORTER", + "OTEL_LOG_USER_PROMPTS", "OTEL_LOG_ASSISTANT_RESPONSES", "OTEL_LOG_TOOL_DETAILS", "OTEL_LOG_TOOL_CONTENT", "OTEL_LOG_RAW_API_BODIES", + "OTEL_EXPORTER_OTLP_LOGS_PROTOCOL", "OTEL_EXPORTER_OTLP_TRACES_PROTOCOL", "OTEL_EXPORTER_OTLP_LOGS_ENDPOINT", "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT", "OTEL_RESOURCE_ATTRIBUTES", + ]); + for (const value of Object.values(env)) text(value); + for (const signal of ["LOGS", "TRACES"]) { + if (!/^[1-9][0-9]{0,3}$/.test(env[`OTEL_EXPORTER_OTLP_${signal}_TIMEOUT`] as string) || Number(env[`OTEL_EXPORTER_OTLP_${signal}_TIMEOUT`]) > 3000) throw invalid(); + parentHeader(env[`OTEL_EXPORTER_OTLP_${signal}_HEADERS`], projectId, traceId, spanId); + } + if (kind === "codex") { + const otel = object(source.otelConfig, ["exporter", "trace_exporter", "metrics_exporter", "log_user_prompt", "log_agent_responses", "log_guardian_assessments", "tool_result", "span_attributes"]); + for (const [key, signal] of [["exporter", "logs"], ["trace_exporter", "traces"]]) { + const exporter = object(otel[key!], ["otlp-http"]); + const http = object(exporter["otlp-http"], ["endpoint", "protocol", "headers"]); + if (http.endpoint !== `${config.baseUrl}/v1/${signal}` || http.protocol !== "binary") throw invalid(); + object(http.headers, []); + } + const tool = object(otel.tool_result, ["max_bytes"]); + if (otel.metrics_exporter !== "none" || otel.log_guardian_assessments !== false + || typeof otel.log_user_prompt !== "boolean" || typeof otel.log_agent_responses !== "boolean" + || ![0, 65536].includes(tool.max_bytes as number)) throw invalid(); + same(otel.span_attributes, attributes); + } else { + const fixed: Record = { CLAUDE_CODE_ENABLE_TELEMETRY: "1", CLAUDE_CODE_ENHANCED_TELEMETRY_BETA: "1", + OTEL_LOGS_EXPORTER: "otlp", OTEL_TRACES_EXPORTER: "otlp", OTEL_METRICS_EXPORTER: "none", OTEL_LOG_RAW_API_BODIES: "0", + OTEL_EXPORTER_OTLP_LOGS_PROTOCOL: "http/protobuf", OTEL_EXPORTER_OTLP_TRACES_PROTOCOL: "http/protobuf", + OTEL_EXPORTER_OTLP_LOGS_ENDPOINT: `${config.baseUrl}/v1/logs`, OTEL_EXPORTER_OTLP_TRACES_ENDPOINT: `${config.baseUrl}/v1/traces` }; + if (Object.entries(fixed).some(([key, value]) => env[key] !== value) + || ["OTEL_LOG_USER_PROMPTS", "OTEL_LOG_ASSISTANT_RESPONSES", "OTEL_LOG_TOOL_DETAILS", "OTEL_LOG_TOOL_CONTENT"].some(key => !["0", "1"].includes(env[key] as string))) throw invalid(); + same(decodedMap(env.OTEL_RESOURCE_ATTRIBUTES), attributes); + } + launch = structuredClone(source) as unknown as ProviderObservabilityLaunch; + } catch { throw invalid(); } + const token = environment.PAPERCLIP_RUNNER_EVAL_OTLP_TOKEN; + if (typeof token !== "string" || !/^[a-f0-9]{64}$/.test(token)) throw new Error("Missing or invalid controlled eval OTLP token"); + const launchEnvironment = { ...launch.environment }; + for (const signal of ["LOGS", "TRACES"]) { + const key = `OTEL_EXPORTER_OTLP_${signal}_HEADERS`; + launchEnvironment[key] += `,authorization=${encodeURIComponent(`Bearer ${token}`)}`; + } + launch = { ...launch, environment: launchEnvironment }; + if (launch.kind === "codex") writeManagedCodexObservability(gateway.transportOptions.environment.CODEX_HOME!, launch.otelConfig!); + return { + transportOptions: { ...gateway.transportOptions, observability: launch, + environment: applyProviderObservabilityEnvironment(gateway.transportOptions.environment, launch) }, + evidence: { mode: "controller_otlp" as const, configured: true, verification: "unverified" as const, + projectId, traceId, spanId, descriptorSha256: createHash("sha256").update(raw).digest("hex") }, + }; +} diff --git a/packages/paperclip-runner/src/cli/eval-session.ts b/packages/paperclip-runner/src/cli/eval-session.ts index c42a22ec933..cae0b83a61b 100644 --- a/packages/paperclip-runner/src/cli/eval-session.ts +++ b/packages/paperclip-runner/src/cli/eval-session.ts @@ -37,6 +37,8 @@ import { } from "./eval-session-contract.js"; import { evalProviderTransportOptions } from "./eval-provider-runtime.js"; import { prepareEvalGatewayRuntime } from "./eval-gateway-runtime.js"; +import { prepareEvalObservabilityRuntime } from "./eval-observability-runtime.js"; +import { redactObservabilityDiagnostic } from "../drivers/agent-observability.js"; import { NativeSessionCloseUnrecoverableError } from "../contracts/native-session-backend.js"; interface EvalSessionCliOptions { @@ -45,6 +47,7 @@ interface EvalSessionCliOptions { candidateProfile?: EvalCandidateProfile; expectedAcpxProfile?: Record; gatewayConfigPath?: string; + observabilityConfigPath?: string; } function argument(args: string[], name: string): string { @@ -55,7 +58,7 @@ function argument(args: string[], name: string): string { } export function parseEvalSessionCliArgs(args: string[]): EvalSessionCliOptions { - const allowed = new Set(["--request", "--output", "--candidate-profile", "--expected-acpx-profile", "--gateway-config"]); + const allowed = new Set(["--request", "--output", "--candidate-profile", "--expected-acpx-profile", "--gateway-config", "--observability-config"]); const seen = new Set(); for (let index = 0; index < args.length; index += 2) { if (!allowed.has(args[index] ?? "")) { @@ -65,6 +68,7 @@ export function parseEvalSessionCliArgs(args: string[]): EvalSessionCliOptions { seen.add(args[index]!); if (args[index + 1] === undefined || args[index + 1]!.startsWith("--")) throw new Error(`missing ${args[index]}`); } + if (seen.has("--observability-config") && !seen.has("--gateway-config")) throw new Error("Eval observability requires an explicit controller gateway"); const candidateIndex = args.indexOf("--candidate-profile"); const candidateProfile = candidateIndex < 0 ? undefined : args[candidateIndex + 1]; if (candidateProfile !== undefined && candidateProfile !== "pi" && candidateProfile !== "cursor" && candidateProfile !== "copilot") { @@ -93,6 +97,7 @@ export function parseEvalSessionCliArgs(args: string[]): EvalSessionCliOptions { ...(candidateProfile === undefined ? {} : { candidateProfile }), ...(expectedAcpxProfile === undefined ? {} : { expectedAcpxProfile }), ...(seen.has("--gateway-config") ? { gatewayConfigPath: argument(args, "--gateway-config") } : {}), + ...(seen.has("--observability-config") ? { observabilityConfigPath: argument(args, "--observability-config") } : {}), requestPath: argument(args, "--request"), outputPath: argument(args, "--output"), }; @@ -406,11 +411,14 @@ export async function runEvalSessionCli( const gateway = cli.gatewayConfigPath ? await prepareEvalGatewayRuntime(cli.gatewayConfigPath, request) : undefined; + let observability: Awaited> | undefined; + const redact = (message: string) => redactObservabilityDiagnostic(message, observability?.transportOptions.environment, observability?.transportOptions.observability.otelConfig); let session: CapabilityLiveSession | null = null; let turn: CapabilityLiveTurnResult | null = null; let snapshot: CapabilityLiveSessionSnapshot | null = null; try { + if (cli.observabilityConfigPath) observability = await prepareEvalObservabilityRuntime(cli.observabilityConfigPath, request, gateway!); const runtimeContext = await prepareEvalRuntimeContext( resolve(request.session.workingDirectory ?? process.cwd()), ); @@ -422,8 +430,9 @@ export async function runEvalSessionCli( baseInstructions: evalRuntimeSystemInstructions(runtimeContext), environment: process.env, ...gateway?.transportOptions, + ...observability?.transportOptions, onDiagnostic: (message) => { - process.stderr.write(`[eval-session runnerd] ${message}\n`); + process.stderr.write(`[eval-session runnerd] ${redact(message)}\n`); }, }; const service = options.serviceFactory?.(runnerdPath, transportOptions) @@ -468,13 +477,14 @@ export async function runEvalSessionCli( await closeSession(session, "eval session complete"); snapshot = session.snapshot(); - await writeFile(cli.outputPath, `${JSON.stringify({ + await writeFile(cli.outputPath, redact(`${JSON.stringify({ schema: "paperclip-runner/eval-session-artifact/v1", attemptId: request.attemptId, build: PAPERCLIP_RUNNER_BUILD_METADATA, runnerd: { path: "[withheld]", sha256: `sha256:${actualDigest}` }, requestedModel: request.model, ...(gateway ? { requestRouting: gateway.evidence } : {}), + ...(observability ? { nativeObservability: observability.evidence } : {}), ...(cli.candidateProfile === undefined ? {} : { diagnosticCandidateProfile: cli.candidateProfile }), provider: requestedProvider, driver: requestedDriver, @@ -520,7 +530,7 @@ export async function runEvalSessionCli( finishedAt: new Date().toISOString(), durationMs: Date.now() - startedAtMs, }, - }, null, 2)}\n`); + }, null, 2)}\n`)); return accountingError === null ? 0 : 2; } catch (error) { if (session !== null) { @@ -546,7 +556,7 @@ export async function runEvalSessionCli( snapshot = session.snapshot(); } const usage = usageIfAvailable(request, snapshot); - await writeFile(cli.outputPath, `${JSON.stringify({ + await writeFile(cli.outputPath, redact(`${JSON.stringify({ schema: "paperclip-runner/eval-session-artifact/v1", attemptId: request.attemptId, infrastructureError: error instanceof Error ? error.message : String(error), @@ -555,6 +565,7 @@ export async function runEvalSessionCli( runnerd: { path: "[withheld]", sha256: `sha256:${actualDigest}` }, requestedModel: request.model, ...(gateway ? { requestRouting: gateway.evidence } : {}), + ...(observability ? { nativeObservability: observability.evidence } : {}), ...(cli.candidateProfile === undefined ? {} : { diagnosticCandidateProfile: cli.candidateProfile }), provider: requestedProvider, driver: requestedDriver, @@ -579,7 +590,7 @@ export async function runEvalSessionCli( finishedAt: new Date().toISOString(), durationMs: Date.now() - startedAtMs, }, - }, null, 2)}\n`); + }, null, 2)}\n`)); return 2; } finally { await gateway?.close(); diff --git a/tests/runner-e2e/runner-eval-observability.test.ts b/tests/runner-e2e/runner-eval-observability.test.ts new file mode 100644 index 00000000000..1ce5fca2f12 --- /dev/null +++ b/tests/runner-e2e/runner-eval-observability.test.ts @@ -0,0 +1,185 @@ +import { createHash } from "node:crypto"; +import { existsSync } from "node:fs"; +import { chmod, mkdtemp, readFile, readdir, rm, stat, symlink, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, expect, it, vi } from "vitest"; +import { createSanitizedAcpxSpawnInput } from "../../packages/paperclip-runner/src/drivers/acpx/environment.js"; +import { createCapabilityFixtureState } from "../../packages/paperclip-runner/src/mock-core/capability-control-plane-types.js"; +import type { CapabilityLiveSessionSnapshot } from "../../packages/paperclip-runner/src/live/live-session.js"; +import { parseEvalSessionRequest } from "../../packages/paperclip-runner/src/cli/eval-session-contract.js"; +import { prepareEvalGatewayRuntime } from "../../packages/paperclip-runner/src/cli/eval-gateway-runtime.js"; +import { prepareEvalObservabilityRuntime } from "../../packages/paperclip-runner/src/cli/eval-observability-runtime.js"; +import { buildProviderObservabilityLaunch } from "../../packages/adapter-utils/src/agent-observability.js"; +import { exportBraintrustAttemptParent } from "./braintrust.js"; +import { createRequire } from "node:module"; +import { parseEvalSessionCliArgs, runEvalSessionCli } from "../../packages/paperclip-runner/src/cli/eval-session.js"; + +const { parse } = createRequire(new URL("../../packages/paperclip-runner/package.json", import.meta.url))("smol-toml") as { parse(text: string): Record }; +const roots: string[] = []; +afterEach(async () => { + vi.unstubAllEnvs(); + for (const root of roots.splice(0)) { + for (const entry of await readdir(root).catch(() => [])) { + if (entry.startsWith(".paperclip-eval-runtime-context-")) await chmod(join(root, entry, "instructions"), 0o700).catch(() => undefined); + } + await rm(root, { recursive: true, force: true }); + } +}); +const token = "a".repeat(64); +async function fixture(provider = "codex", acpxAgent?: string) { + const root = await mkdtemp(join(tmpdir(), "runner-gateway-test-")); roots.push(root); + const model = acpxAgent === "claude" ? "claude-sonnet-5" : "gpt-5.6-sol"; + const binary = join(root, "runnerd"); + await writeFile(binary, "fake runnerd"); + const request = parseEvalSessionRequest({ + schema: "paperclip-runner/eval-session-request/v1", attemptId: "attempt-1", prompt: "Read the governed task.", + provider, ...(acpxAgent ? { acpxAgent } : {}), model, + runnerd: { path: binary, sha256: createHash("sha256").update("fake runnerd").digest("hex") }, + limits: { turnTimeoutMs: 120000, maxAgentTurns: 1, maxEstimatedCostNanodollars: 100000000 }, + session: { workingDirectory: root }, + }); + const descriptor = { schema: "paperclip.runner-eval.gateway/v1", provider: acpxAgent === "claude" ? "anthropic" : "openai", + model, baseUrl: "http://127.0.0.1:4567", campaignId: "campaign-1", executionId: "cell-1", attemptId: "attempt-1", upstreamRoute: "braintrust" }; + const descriptorPath = join(root, "gateway.json"); + await writeFile(descriptorPath, JSON.stringify(descriptor)); + return { root, request, descriptor, descriptorPath }; +} + +const otlpToken = "b".repeat(64); +async function observabilityFixture(f: Awaited>) { + const identity = { projectId: "11111111-1111-4111-8111-111111111111", traceId: "1".repeat(32), spanId: "2".repeat(16) }; + const baseUrl = "http://127.0.0.1:4568/otel"; + const descriptor = { + schema: "paperclip.runner-eval.observability/v1", campaignId: f.descriptor.campaignId, + executionId: f.descriptor.executionId, attemptId: f.request.attemptId, ...identity, baseUrl, + launch: buildProviderObservabilityLaunch({ kind: f.request.provider === "codex" ? "codex" : "claude", + companyId: "company-1", agentId: "actor-1", revision: "revision-1", compatibilityKey: "revision-1", enabled: true, + capture: { userPrompts: true, assistantResponses: true, toolDetails: true, toolContent: true }, + logsEndpoint: `${baseUrl}/v1/logs`, tracesEndpoint: `${baseUrl}/v1/traces`, + headers: { "x-bt-parent": exportBraintrustAttemptParent(identity) }, + }), + }; + const file = join(f.root, "observability.json"); + await writeFile(file, JSON.stringify(descriptor)); + return { descriptor, file }; +} + +it.each([["codex", undefined], ["acpx", "claude"]])("applies the existing %s/%s launch contract only to its owned gateway home", async (provider, agent) => { + const f = await fixture(provider, agent), observation = await observabilityFixture(f); + const gateway = await prepareEvalGatewayRuntime(f.descriptorPath, f.request, { PAPERCLIP_RUNNER_EVAL_GATEWAY_TOKEN: token }); + try { + const result = await prepareEvalObservabilityRuntime(observation.file, f.request, gateway, { PAPERCLIP_RUNNER_EVAL_OTLP_TOKEN: otlpToken, BRAINTRUST_API_KEY: "upstream-secret" }); + const launch = result.transportOptions.observability; + expect(result.evidence).toMatchObject({ mode: "controller_otlp", configured: true, verification: "unverified", projectId: observation.descriptor.projectId }); + expect(JSON.stringify(result.evidence)).not.toContain(otlpToken); + expect(JSON.stringify(result)).not.toContain("upstream-secret"); + expect(launch.environment.OTEL_EXPORTER_OTLP_LOGS_HEADERS).toContain(`authorization=Bearer%20${otlpToken}`); + expect(result.transportOptions.environment.BRAINTRUST_API_KEY).toBeUndefined(); + if (provider === "codex") { + const raw = await readFile(join(gateway.transportOptions.environment.CODEX_HOME!, "config.toml"), "utf8"), config = parse(raw); + expect(config.model_provider).toBe("paperclip_eval"); + expect(config.otel).toEqual(observation.descriptor.launch.otelConfig); + expect(raw).not.toContain(otlpToken); + expect((await stat(join(gateway.transportOptions.environment.CODEX_HOME!, "config.toml"))).mode & 0o777).toBe(0o600); + } else { + const sanitized = createSanitizedAcpxSpawnInput(result.transportOptions.environment, "claude").env; + expect(sanitized.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT).toBe(observation.descriptor.baseUrl + "/v1/traces"); + expect(sanitized.OTEL_EXPORTER_OTLP_TRACES_HEADERS).toContain(otlpToken); + expect(sanitized.ANTHROPIC_API_KEY).toBe(token); + } + } finally { await gateway.close(); } +}); + +it.each(["identity", "endpoint", "parent", "credential", "company", "rawBodies", "modelEnvironment", "extraField", "unknownExporter", "prototypeHeader"])("rejects observability %s drift before changing the gateway home", async fault => { + const f = await fixture(), observation = await observabilityFixture(f); + const descriptor = observation.descriptor as unknown as Record; + if (fault === "identity") descriptor.attemptId = "other"; + if (fault === "endpoint") descriptor.launch.otelConfig.exporter["otlp-http"].endpoint = "https://api.braintrust.dev/otel/v1/logs"; + if (fault === "parent") descriptor.traceId = "3".repeat(32); + if (fault === "prototypeHeader") descriptor.launch.environment.OTEL_EXPORTER_OTLP_LOGS_HEADERS += ",__proto__=ignored"; + if (fault === "credential") descriptor.launch.environment.OTEL_EXPORTER_OTLP_LOGS_HEADERS += ",authorization=Bearer%20upstream-secret"; + if (fault === "company") descriptor.launch.otelConfig.span_attributes["paperclip.company.id"] = "other"; + if (fault === "rawBodies") descriptor.launch.otelConfig.log_guardian_assessments = true; + if (fault === "modelEnvironment") descriptor.launch.environment.OPENAI_API_KEY = "upstream-secret"; + if (fault === "extraField") descriptor.extra = "unknown"; + if (fault === "unknownExporter") descriptor.launch.otelConfig.extra_exporter = "console"; + await writeFile(observation.file, JSON.stringify(descriptor)); + const gateway = await prepareEvalGatewayRuntime(f.descriptorPath, f.request, { PAPERCLIP_RUNNER_EVAL_GATEWAY_TOKEN: token }); + const config = join(gateway.transportOptions.environment.CODEX_HOME!, "config.toml"), before = await readFile(config); + try { + await expect(prepareEvalObservabilityRuntime(observation.file, f.request, gateway, { PAPERCLIP_RUNNER_EVAL_OTLP_TOKEN: otlpToken })).rejects.toThrow("Invalid controlled eval observability"); + expect(await readFile(config)).toEqual(before); + } finally { await gateway.close(); } +}); + +it("refuses missing relay credentials and oversized observability files before launch", async () => { + const f = await fixture(), observation = await observabilityFixture(f); + const gateway = await prepareEvalGatewayRuntime(f.descriptorPath, f.request, { PAPERCLIP_RUNNER_EVAL_GATEWAY_TOKEN: token }); + try { + await expect(prepareEvalObservabilityRuntime(observation.file, f.request, gateway, {})).rejects.toThrow("OTLP token"); + await writeFile(observation.file, " ".repeat(131073)); + await expect(prepareEvalObservabilityRuntime(observation.file, f.request, gateway, { PAPERCLIP_RUNNER_EVAL_OTLP_TOKEN: otlpToken })).rejects.toThrow("Invalid controlled eval observability"); + } finally { await gateway.close(); } +}); + +it.each([false, true])("the real CLI redacts native relay credentials and removes its home after failure=%s", async (fail) => { + const f = await fixture(); + const observation = await observabilityFixture(f); + vi.stubEnv("PAPERCLIP_RUNNER_EVAL_OTLP_TOKEN", otlpToken); + vi.stubEnv("PAPERCLIP_RUNNER_EVAL_GATEWAY_TOKEN", token); + vi.stubEnv("OPENAI_API_KEY", "upstream-must-not-reach-provider"); + const requestPath = join(f.root, "request.json"), outputPath = join(f.root, "artifact.json"); + await writeFile(requestPath, JSON.stringify(f.request)); + const state = JSON.stringify(createCapabilityFixtureState({})); + const snapshot = { + sessionId: "session-1", revision: 1, providerThreadId: "provider-1", providerSessionId: "provider-1", + providerModel: { id: f.request.model, provider: "openai" }, status: "idle", activeTurnId: null, + createdAt: "2026-10-24T00:00:00Z", updatedAt: "2026-10-24T00:00:01Z", + authority: { companyId: "company-1", actorId: "actor-1", taskId: "task-1", runId: "run-1", sessionId: "session-1", scenarioId: "gateway-test" }, + config: { provider: "codex", driver: "codex_app_server", seedState: state, workingDirectory: f.root, scenario: { id: "gateway-test" }, capabilities: [], explicitClaims: [], turnTimeoutMs: 1000 }, + mockState: state, process: null, networkEvidence: { realPaperclipRequests: 0, childPaperclipEnvironmentKeys: [] }, + transcript: [], evidence: [], authorizationRecords: [], attempts: [], terminalTurns: [{ turnId: "turn-1", status: "completed" }], + usageLedger: [{ receiptId: "receipt-1", turnId: "turn-1", providerCalls: 1, providerRequests: 1, inputTokens: 100, outputTokens: 10, cachedInputTokens: 0, reasoningTokens: 0, costNanodollars: 0 }], usageUnavailable: [], + } as unknown as CapabilityLiveSessionSnapshot; + let home: string | undefined; + const factory = vi.fn((_binary, options) => { + expect(options.homeMode).toBe("preconfigured"); + expect(options.observability).toBeDefined(); + expect(options.environment.OPENAI_API_KEY).toBeUndefined(); + expect(options.environment.PAPERCLIP_AI_PROVIDER_KEY).toBe(token); + home = options.environment.HOME; + expect(existsSync(home!)).toBe(true); + return { create: async () => ({ + sendMessage: async () => { if (fail) throw new Error(`simulated provider failure Bearer ${otlpToken}`); return { turnId: "turn-1", status: "completed", snapshot }; }, + completeAttempt: async () => undefined, shutdown: async () => { snapshot.status = "closed"; }, snapshot: () => snapshot, + }) } as never; + }); + const result = await runEvalSessionCli(["--request", requestPath, "--output", outputPath, "--gateway-config", f.descriptorPath, "--observability-config", observation.file], { serviceFactory: factory }); + expect(result).toBe(fail ? 2 : 0); + expect(factory).toHaveBeenCalledTimes(1); + expect(existsSync(home!)).toBe(false); + const raw = await readFile(outputPath, "utf8"), artifact = JSON.parse(raw); + expect(artifact.requestRouting).toMatchObject({ mode: "controller_gateway", provider: "openai", campaignId: "campaign-1", executionId: "cell-1", attemptId: "attempt-1" }); + expect(raw).not.toContain(token); + expect(raw).not.toContain(otlpToken); + expect(artifact.nativeObservability).toEqual(expect.objectContaining({ configured: true, verification: "unverified" })); + expect(raw).not.toContain("upstream-must-not-reach-provider"); + if (fail) expect(artifact.infrastructureError).toBe("simulated provider failure [REDACTED]"); +}); + + +it("requires gateway ownership before accepting observability", () => { + expect(() => parseEvalSessionCliArgs(["--request", "request.json", "--output", "artifact.json", "--observability-config", "otel.json"])) + .toThrow("requires an explicit controller gateway"); +}); + +it("rejects a symlinked observability descriptor", async () => { + const f = await fixture(), observation = await observabilityFixture(f); + const linked = join(f.root, "linked.json"); + await symlink(observation.file, linked); + const gateway = await prepareEvalGatewayRuntime(f.descriptorPath, f.request, { PAPERCLIP_RUNNER_EVAL_GATEWAY_TOKEN: token }); + try { + await expect(prepareEvalObservabilityRuntime(linked, f.request, gateway, { PAPERCLIP_RUNNER_EVAL_OTLP_TOKEN: otlpToken })).rejects.toThrow(); + } finally { await gateway.close(); } +}); From cb6c878c38274b13d7d8ae1013569d48223e6724 Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Sat, 24 Oct 2026 14:14:46 -0700 Subject: [PATCH 018/110] Read execution blocker evidence without full execution payloads (#17491) Read the lifecycle, process, and typed context evidence consumed by execution blockers. Preserve full result evidence, native workspace receipts, current state checks, and stored history. Validated with 458 real PostgreSQL and recovery tests, full build, recursive typecheck, all55 CI checks, and Greptile 5/5. Co-Authored-By: Paperclip --- doc/DATABASE.md | 6 + .../src/services/cancelled-native-startup.ts | 7 +- .../services/execution-blocker-read.test.ts | 115 ++++++++++++++++++ server/src/services/execution-blocker.ts | 48 +++++++- 4 files changed, 174 insertions(+), 2 deletions(-) create mode 100644 server/src/services/execution-blocker-read.test.ts diff --git a/doc/DATABASE.md b/doc/DATABASE.md index 28950218145..1ff88e3368d 100644 --- a/doc/DATABASE.md +++ b/doc/DATABASE.md @@ -62,6 +62,12 @@ the PostgreSQL row version. Native blocked-wait repair compares that version against a fresh full source read before applying changes. Any intervening row update, including an edit outside the projection, defers repair to a fresh sweep. +Execution-blocker reads select process, lifecycle, and task-binding fields rather +than full execution rows. Context retains typed task and pre-dispatch evidence; +Runner profiles retain the adapter type and complete native execution input and +workspace-sync receipts. Full result evidence stays available to the existing +retry and workspace checks. Stored context, profiles, and output are unchanged. + Run-context lookups use expression indexes for both `context_snapshot.issueId` and `context_snapshot.paperclipIssue.id`. Task creation provenance has its own company-scoped expression index that follows the query's native issue ID and diff --git a/server/src/services/cancelled-native-startup.ts b/server/src/services/cancelled-native-startup.ts index 53a17527f48..810c4d5939d 100644 --- a/server/src/services/cancelled-native-startup.ts +++ b/server/src/services/cancelled-native-startup.ts @@ -7,7 +7,12 @@ import { hasRemoteTerminationReceipt } from "./remote-execution-termination.js"; import { canContinueCancelledRun } from "./run-cancellation.js"; import { legacyControllerBootId } from "./legacy-controller-lease.js"; -type Run = typeof heartbeatRuns.$inferSelect; +type Run = Pick; type Coordinator = typeof nativeRunFinalizations.$inferSelect; /** Candidate for explicit user Retry only, never automatic replay after Stop. */ diff --git a/server/src/services/execution-blocker-read.test.ts b/server/src/services/execution-blocker-read.test.ts new file mode 100644 index 00000000000..309385a25cb --- /dev/null +++ b/server/src/services/execution-blocker-read.test.ts @@ -0,0 +1,115 @@ +import { randomBytes, randomUUID } from "node:crypto"; +import { agents, companies, createDb, heartbeatRuns, issueRecoveryActions, issues, type Db } from "@paperclipai/db"; +import { eq } from "drizzle-orm"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../__tests__/helpers/embedded-postgres.js"; +import { getExecutionBlocker } from "./execution-blocker.js"; + +const support = await getEmbeddedPostgresTestSupport(); +describe.skipIf(!support.supported)("execution blocker PostgreSQL read projection", () => { + let database: Awaited>; + let db: ReturnType; + beforeAll(async () => { + database = await startEmbeddedPostgresTestDatabase("execution-blocker-read-"); + db = createDb(database.connectionString); + }, 60_000); + afterAll(async () => { await db?.$client.end(); await database?.cleanup(); }); + + async function fixture(patch: Partial = {}, extraEvidence: Record = {}) { + const companyId = randomUUID(), agentId = randomUUID(), issueId = randomUUID(); + await db.insert(companies).values({ id: companyId, name: "Blocker fixture", issuePrefix: companyId.slice(0, 8) }); + await db.insert(agents).values({ id: agentId, companyId, name: "Blocker agent", adapterType: "process", status: "active" }); + await db.insert(issues).values({ id: issueId, companyId, title: "Blocker task", status: "blocked", assigneeAgentId: agentId }); + const payload = randomBytes(128 * 1024).toString("base64"); + const [run] = await db.insert(heartbeatRuns).values({ companyId, agentId, status: "failed", runtimeMode: "legacy", + startedAt: new Date("2020-01-01T00:00:00Z"), finishedAt: new Date("2020-01-01T00:01:00Z"), + errorCode: "adapter_failed", error: "Fixture failure", contextSnapshot: { issueId, prompt: payload }, + runnerProfileJson: { adapterDispatch: { adapterType: "paperclip_runner", adapterConfig: { instructions: payload } }, instructions: payload }, + stdoutExcerpt: payload, ...patch, + }).returning(); + await db.insert(issueRecoveryActions).values({ companyId, sourceIssueId: issueId, kind: "active_run_watchdog", + cause: "legacy_execution_requires_reconciliation", fingerprint: run.id, status: "active", nextAction: "Inspect the source run.", + evidence: { runId: run.id, ...extraEvidence } }); + return { companyId, agentId, issueId, run }; + } + + function recordRunReads(fullRows = false) { + const reads: unknown[][] = []; + const recorded = new Proxy(db, { get(target, key) { + if (key !== "select") return Reflect.get(target, key); + return (...fields: Parameters) => { + const builder = target.select(...fields), from = builder.from.bind(builder); + builder.from = ((...args: Parameters) => { + const query = args[0] === heartbeatRuns && fullRows ? target.select().from(heartbeatRuns) : from(...args); + if (args[0] === heartbeatRuns) { + const execute = query.execute.bind(query); + query.execute = async (...executeArgs: Parameters) => { + const rows = await execute(...executeArgs); reads.push(rows); return rows; + }; + } + return query; + }) as typeof builder.from; + return builder; + }; + }}); + return { recorded, reads }; + } + + async function compare(f: Awaited>) { + const baseline = recordRunReads(true), projected = recordRunReads(); + const expected = await getExecutionBlocker(baseline.recorded, f.companyId, f.issueId); + const result = await getExecutionBlocker(projected.recorded, f.companyId, f.issueId); + expect(expected).not.toBeNull(); + expect(result).toEqual(expected); + expect(projected.reads).toHaveLength(baseline.reads.length); + expect(projected.reads.flat()).toHaveLength(1); + expect(Buffer.byteLength(JSON.stringify(projected.reads))).toBeLessThan(4096); + expect(Buffer.byteLength(JSON.stringify(baseline.reads))).toBeGreaterThan(128 * 1024); + return result; + } + + it("preserves blocker and retry decisions without returning prompts, profiles, or output", async () => { + const f = await fixture(); + expect(await compare(f)).toMatchObject({ runId: f.run.id, agentId: f.agentId, canRetry: true, canContinue: false }); + expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.run.id)))[0]).toEqual(f.run); + expect(await getExecutionBlocker(db, randomUUID(), f.issueId)).toBeNull(); + }); + + it("retains the claimed adapter and startup receipts for a cancelled pre-provider run", async () => { + const f = await fixture({ status: "cancelled", startedAt: null, errorCode: "operator_interrupted", + resultJson: { startupCancellation: { beforeNativeSelection: true }, startupPreparationSettledAt: "2020-01-01T00:01:00Z" } }); + expect(await compare(f)).toMatchObject({ canRetry: true, canContinue: false }); + await db.update(heartbeatRuns).set({ processPid: 424242 }).where(eq(heartbeatRuns.id, f.run.id)); + expect(await getExecutionBlocker(db, f.companyId, f.issueId)).toMatchObject({ canRetry: false }); + }); + + it.each(["valid", "number", "missing"])("preserves typed pre-dispatch interaction evidence (%s)", async kind => { + const context = { source: "connection_intent.resolved", connectionIntentResolution: "existing_connection", + interactionKind: "connection_intent", interactionStatus: "expired", mutation: "interaction", + ...(kind === "missing" ? {} : { interactionId: kind === "valid" ? randomUUID() : 42 }) }; + const f = await fixture({ status: "cancelled", errorCode: "issue_waiting_for_response", contextSnapshot: context, + resultJson: { stopReason: "issue_waiting_for_response", timeoutSource: "stale_queued_run_gate", + preDispatchResponseWait: { version: 1, providerWorkStarted: false } } }); + expect(await compare(f)).toMatchObject({ canRetry: kind === "valid" }); + }); + + it.each([true, false])("preserves native no-workspace evidence and cwd presence (%s)", async hasCwd => { + const f = await fixture({ runtimeMode: "native", driverKind: "grok_bot_mcp" }, { + workspaceRestoreFailure: "restore_unsafe_archive", + workspaceRestoreRecovery: { schema: "paperclip.workspace-restore-recovery.v1", leaseIds: [] }, + }); + const input = { schema: "paperclip.native-execution-input.v6", + binding: { runId: f.run.id, companyId: f.companyId, agentId: f.agentId, issueId: f.issueId }, + provider: { kind: "grok_bot" }, workspace: { access: "none", ...(hasCwd ? { cwd: null } : {}) } }; + await db.update(heartbeatRuns).set({ nativeIssueId: f.issueId, + runnerProfileJson: { ...f.run.runnerProfileJson, nativeExecutionInput: input } }).where(eq(heartbeatRuns.id, f.run.id)); + expect(await compare(f)).toMatchObject({ workspaceRepairRequired: !hasCwd, canRetry: false }); + const [stored] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.run.id)); + expect(stored.runnerProfileJson?.nativeExecutionInput).toEqual(input); + }); + + it.each([null, [], "scalar", 42, { issueId: 42, taskId: false }].map(context => ({ context })))("preserves decisions for malformed context $context", async ({ context }) => { + const f = await fixture({ contextSnapshot: context as Record | null }); + expect(await compare(f)).toMatchObject({ canRetry: true }); + }); +}); diff --git a/server/src/services/execution-blocker.ts b/server/src/services/execution-blocker.ts index b1277e53f1e..4777d5947b3 100644 --- a/server/src/services/execution-blocker.ts +++ b/server/src/services/execution-blocker.ts @@ -14,6 +14,52 @@ import { hasRemoteTerminationReceipt } from "./remote-execution-termination.js"; import { readNativeWorkspaceSyncReference } from "./native-runtime/native-workspace-sync.js"; import { hasVerifiedWorkspaceRepair, workspaceRecoveryDisplay } from "./workspace-recovery-receipt.js"; +const blockerContextKeys = ["issueId", "taskId", "source", "connectionIntentResolution", + "interactionKind", "interactionStatus", "mutation", "interactionId"] as const; +const blockerProfileKeys = ["adapterDispatch", "nativeExecutionInput", "nativeWorkspaceSync"] as const; +const blockerContextColumn = sql | null>`case + when ${heartbeatRuns.contextSnapshot} is null then null else ( + select coalesce(jsonb_object_agg(field.key, field.value), '{}'::jsonb) + from jsonb_each(case when jsonb_typeof(${heartbeatRuns.contextSnapshot}) = 'object' + then ${heartbeatRuns.contextSnapshot} else '{}'::jsonb end) as field(key, value) + where field.key in (${sql.join(blockerContextKeys.map(key => sql`${key}`), sql`, `)}) + ) end`; +const blockerProfileColumn = sql | null>`case + when ${heartbeatRuns.runnerProfileJson} is null then null else ( + select coalesce(jsonb_object_agg(field.key, case field.key + when 'adapterDispatch' then jsonb_build_object('adapterType', field.value->'adapterType') + else field.value end), '{}'::jsonb) + from jsonb_each(case when jsonb_typeof(${heartbeatRuns.runnerProfileJson}) = 'object' + then ${heartbeatRuns.runnerProfileJson} else '{}'::jsonb end) as field(key, value) + where field.key in (${sql.join(blockerProfileKeys.map(key => sql`${key}`), sql`, `)}) + ) end`; +const blockerRunFields = { + id: heartbeatRuns.id, + companyId: heartbeatRuns.companyId, + agentId: heartbeatRuns.agentId, + status: heartbeatRuns.status, + startedAt: heartbeatRuns.startedAt, + finishedAt: heartbeatRuns.finishedAt, + error: heartbeatRuns.error, + errorCode: heartbeatRuns.errorCode, + issueId: heartbeatRuns.issueId, + nativeIssueId: heartbeatRuns.nativeIssueId, + nativeSessionId: heartbeatRuns.nativeSessionId, + runtimeMode: heartbeatRuns.runtimeMode, + runtimeModeResolvedAt: heartbeatRuns.runtimeModeResolvedAt, + driverKind: heartbeatRuns.driverKind, + processPid: heartbeatRuns.processPid, + processGroupId: heartbeatRuns.processGroupId, + processStartedAt: heartbeatRuns.processStartedAt, + sessionIdAfter: heartbeatRuns.sessionIdAfter, + controllerBootId: heartbeatRuns.controllerBootId, + controllerLeaseExpiresAt: heartbeatRuns.controllerLeaseExpiresAt, + executionStage: heartbeatRuns.executionStage, + resultJson: heartbeatRuns.resultJson, + contextSnapshot: blockerContextColumn, + runnerProfileJson: blockerProfileColumn, +}; + export async function hasPendingRunCleanup(db: Db, companyId: string, runId: string): Promise { const [state] = await db.execute<{ pending: boolean }>(sql`SELECT ${heartbeatRuns.runnerProfileJson}->>'nativeWorkspaceFinalizationOwner' IS NOT NULL @@ -99,7 +145,7 @@ export async function getExecutionBlocker(db: Db, companyId: string, issueId: st if (!action) return null; const parsedRunId = z.string().guid().safeParse(action.evidence.runId ?? action.evidence.sourceRunId); const runId = parsedRunId.success ? parsedRunId.data : null; - const [run] = runId ? await db.select().from(heartbeatRuns).where(and( + const [run] = runId ? await db.select(blockerRunFields).from(heartbeatRuns).where(and( eq(heartbeatRuns.companyId, companyId), eq(heartbeatRuns.id, runId), )).limit(1) : []; const withoutWorkspace = Boolean(run?.driverKind === "grok_bot_mcp" && nativeRunHasNoWorkspaceAccess(run)); From a7006a95063a85c10ce709193fe60c7095813bc0 Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Sat, 24 Oct 2026 14:16:58 -0700 Subject: [PATCH 019/110] Reclaim finished isolated task directories with restore points (#17472) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Agents do task work in execution workspaces on the instance disk > - A task without a project repository runs in a plain (non-Git) task directory under `/isolated-workspaces///` > - Nothing removes these directories after the work is done, so the disk fills up > - The directories can hold the only copy of agent work, so plain deletion is not safe > - This pull request saves each finished task directory in an encrypted restore point, removes it, and restores it when the work reopens. It also removes orphaned directories after a grace period > - The benefit is that finished task directories stop using disk, and no agent work is lost silently ## Linked Issues or Issue Description **What happened?** On one instance, `instances//isolated-workspaces/` held 251 task directories and 12 GB, and it grew every day. 61 directories belonged to open workspace rows whose issues closed more than 7 days before (3.9 GB). 12 belonged to issues closed 3 to 7 days before (0.7 GB). 4.0 GB were directories with no open workspace row (the row was archived or missing). The cause has two parts: 1. The terminal workspace reaper archives a workspace only when it proves delivery through Git (a merged pull request or a merged branch). A task directory is not a Git checkout, so the Git status inspection fails and the reaper always skips the row as "undelivered". Git cache expiration handles only `git_worktree` workspaces. 2. When a person archives such a workspace by hand, artifact cleanup removes a `local_fs` directory only when `metadata.createdByRuntime` is true. Task directory rows never set it, so the directory stays and the row becomes `cleanup_failed`. **Expected behavior** Paperclip reclaims the task directories of finished work by itself. It must not lose files that only exist in those directories. **Steps to reproduce** 1. Run an agent on an issue without a project repository (for example a low-trust sandbox task, or an issue with no project), so it works in `isolated-workspaces///`. 2. Let the agent write files there, then mark the issue `done`. 3. Wait any number of days. The directory and its workspace row stay. The reaper logs the row as skipped (undelivered). 4. Archive the workspace by hand. The directory still stays. **Paperclip version or commit** `master` at fe85fd7ac45 **Deployment mode** Self-hosted, local disk storage. **Agent adapter(s) involved** Any adapter that runs in a task directory (seen with local and sandbox runs). ## What Changed - Added `isolated-task-directory-snapshot.ts`: a deterministic snapshot of a plain directory (files with modes, directories, symbolic links as links). It never follows symbolic links, refuses special files, and enforces the restore point limits (20,000 files, 64 MiB per file, 256 MiB in total). A `node_modules` directory next to a `package.json` is left out. Restore writes to a staging directory, verifies the digest, then renames it into place. - Added `isolated-task-directory-retention.ts`: - `expireIsolatedTaskDirectory` saves the directory in a restore point, archives the workspace with the `isolatedTaskDirectoryRetention` state in one transaction, checks again that the directory did not change, renames it to trash and deletes it. A change after the capture rolls the workspace back to active and drops the restore point. An interrupted removal finishes on a later sweep. - It uses the git cache expiration consumer checks (`isGitWorkspaceExpirationEligible`): no live run, unsettled finalization, live lease, live runtime service, unresolved recovery action or reopen fence, and no other open workspace or project workspace in the directory. It also requires the source issue to be bound to the workspace, because reopen restores through that binding. - `restoreIsolatedTaskDirectory` restores the directory on reopen. It replaces an empty directory and fails closed on a non-empty directory that does not match. When the restore point expired, it reopens an empty directory and posts a system comment. - `sweepIsolatedTaskDirectories` walks `isolated-workspaces/` in bounded batches (8 per sweep, with a cursor). A closed workspace that its issue is still bound to is saved and removed like an open one. Other folders are orphans and are removed after a grace period when no live row, project workspace, runtime service, run, finalization, lease or recovery action refers to them. - Reused the git restore point ledger, storage and encryption. `storeSealedRestorePoint` and `readRestorePointObject` were extracted from `storeGitRestorePoint`. `markGitRestorePointExpired` now also marks a task directory restore point as expired. - `isGitWorkspaceExpirationEligible` takes `closedSiblingsAllowed`, so closed rows for the same issue directory do not block a task directory forever. Git expiration keeps its old behavior. - Terminal workspace reaper (`execution-workspaces.ts`): handles open task directory rows after the terminal delay and registers that moment as a deadline. It finishes pending removals, runs the folder walk at the start of a rotation (once per server start, then only at real deadlines), and saves at most 8 directories per sweep. - Reopen accepts a closed `shared_workspace` row that holds task directory state. The run path also reopens (and restores) a closed workspace with that state before preparing the run. - Settings: `PAPERCLIP_TASK_DIRECTORY_RETENTION_ENABLED` (default `false`), `PAPERCLIP_TASK_DIRECTORY_RETENTION_DRY_RUN` (default `true`), `PAPERCLIP_TASK_DIRECTORY_ORPHAN_GRACE_DAYS` (default `7`, minimum `1`). The delay is `PAPERCLIP_GIT_RESTORE_POINT_TERMINAL_DELAY_DAYS`. Removal needs `PAPERCLIP_GIT_RESTORE_POINTS_ENABLED=true`. - Logs: `execution_workspace.task_directory_retention`, `execution_workspace.task_directory_cleanup` and `execution_workspace.task_directory_restore`, with outcome, skip reason, candidate bytes and reclaimed bytes. - Documented the behavior in `doc/recoverable-disk-cleanup.md` and the settings in `doc/DEVELOPING.md`. **Preservation decision.** The code shows that these directories are not scratch space. Nothing pushes or copies their contents, and the next run of the same issue reuses the same path. So the files are saved before removal, with the same ledger, encryption and retention as git restore points, and restored on reopen. Orphans are not saved: no workspace row can reopen them. The docs and the Risks section state this. **Scheduling.** The work follows `rules/sleep-aware-background-work.mdc`. It adds no timer and no polling. Open rows use the existing reaper and its per-workspace deadlines (the end of the terminal delay, or one hour after a retryable skip). The folder walk runs once at startup. After that, workspace archive and issue close notifications (the existing terminal workspace hints) point the reaper at the affected folder, and a kept folder is checked again only at its own deadline (end of a grace period or terminal delay, or one hour after a busy lock or live consumer). When the tracked state is full, the reaper schedules another walk instead of dropping work. With nothing pending, it registers nothing. ## Verification - `cd server && pnpm exec vitest run src/__tests__/isolated-task-directory-retention.test.ts src/__tests__/isolated-task-directory-retention-config.test.ts src/__tests__/heartbeat-task-directory-restore.test.ts` (embedded Postgres): 48 tests pass. They cover: - a closed issue's task directory is archived and removed after the delay by the reaper, and reopen restores files, modes and symbolic links exactly; - the same through reopen for a `shared_workspace` row, and through a real heartbeat run (the run restores the files and runs in them); - the directory stays before the delay (and the deadline is the end of the delay), while the issue is open, and when retention is off; - the directory stays while each consumer check fails: live run, live runtime service, reopen fence, unsettled finalization, live lease, unresolved recovery action, issue bound elsewhere, live sibling workspace in the directory; - no removal without restore points, with a non-durable key, before `notBefore`, or over the limits; - dry run changes nothing; a change after the capture rolls back; an interrupted removal finishes on the next sweep; an expired restore point reopens empty with a warning; a diverged directory fails the reopen and stays untouched; - folder sweep: an orphan is removed after the grace period, kept when recently modified, in dry run, when a live row points into it, and when its issue is open; an archived unbound row's folder is removed; an archived bound row's folder is saved, removed and restored on reopen; the walk is bounded and continues from its cursor; - review follow-ups: a file name with a backslash saves and restores; after the startup walk, a workspace archived later is found through its change hint; an orphan used by a live run is retried; skipped rows do not starve later rows of the per-sweep budget; overflowing tracked deadlines schedule another walk instead of being dropped; a closing child sends the reaper back to its archived parent's folder; a pending lease cleanup on a closed workspace keeps an orphan; a deep path at the platform path limit restores; an expiry recorded during removal survives and the archive and removal are recorded as activity; a task closed beyond retention keeps its new restore point for the full period; - symbolic links: a task directory that is a link, an orphan that is a link, and a link inside a directory are never followed; the link targets stay untouched. - Mutation checks. Each change below made at least one of the tests above fail, and the test passed again after revert: - drop the run-path reopen condition; drop the skipped-row cache; drop hint tracking; reject backslashes again; drop the live-consumer retry for folders; evict overflowing folder deadlines; skip ancestor hints; ignore workspace-attached leases for orphans; stage restores under the old longer name; overwrite the whole metadata on the final write; retain task directory restore points from the tree close only; drop the removal activity; force `closedSiblingsAllowed` off; make live siblings not block; skip the digest recheck before rename; skip the issue binding check; remove both symbolic link refusals (task directory); remove the orphan symbolic link refusal; ignore live rows in the folder walk; skip the orphan modification grace; ignore dry run for orphans; skip the restore on reopen; skip the terminal delay; skip the restore points requirement; skip the orphan open-issue check. - Removing only one of the two task directory symbolic link checks did not fail a test, because the other check still refuses the link. Removing both fails the test. - Related suites: `pnpm exec vitest run execution-workspaces isolated-task-directory workspace-runtime git-restore-point git-workspace-expiration terminal-workspace workspace-reaper heartbeat-git-restore heartbeat-task-directory isolated-repository-rehome nested-clone-migration environment-selection` in `server/`: 34 files, 749 tests pass, 4 skipped. Two `workspace-runtime.test.ts` tests fail (`does not diagnose a missing remote branch as a rejected credential`, `rejects explicit main on a master-only remote ...`). They fail the same way on unchanged `master` on the local machine, so they are not caused by this change. - `pnpm run typecheck` in `server/`: passes. - Not run: the full server suite, a live instance rollout, and a check that the host disk usage drops after removal. ## Risks - The feature is off by default, and it starts as a dry run when enabled. It needs restore points to remove anything. Rollback: set `PAPERCLIP_TASK_DIRECTORY_RETENTION_ENABLED=false`. Saved restore points and restore on reopen keep working. - Orphan folders are removed without a restore point. This applies only when no workspace row is bound to the issue at that path. If such an issue is reopened later without another workspace, its next run starts in an empty directory. The grace period (default 7 days of a closed tree and no changes) and the dry run limit this risk. - A directory over the restore point limits stays on disk (logged with its reason). Special files keep a directory too. - `node_modules` next to a `package.json` is not saved. A reopened task must install its packages again. - The restore point lives as long as git restore points (90 days by default), counted from the later of the tree close and the removal. Only task directory restore points use the removal time; git restore points keep their retention. After that, reopen starts with an empty directory and posts a warning comment. - Reopen now accepts a closed `shared_workspace` row, but only when it holds task directory state written by this feature. - No schema migration. The ledger table and its columns are unchanged. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), 1M context, through Claude Code with tool use ## 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 - [ ] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip --- doc/DEVELOPING.md | 11 + doc/recoverable-disk-cleanup.md | 125 ++++ .../heartbeat-task-directory-restore.test.ts | 120 ++++ ...ed-task-directory-retention-config.test.ts | 29 + .../isolated-task-directory-retention.test.ts | 524 +++++++++++++++ server/src/config.ts | 7 + server/src/index.ts | 5 + server/src/services/execution-workspaces.ts | 173 ++++- .../src/services/git-restore-point-ledger.ts | 4 +- .../src/services/git-restore-point-storage.ts | 144 ++-- .../src/services/git-workspace-expiration.ts | 10 +- .../heartbeat/environment-selection.ts | 4 +- .../isolated-task-directory-retention.ts | 627 ++++++++++++++++++ .../isolated-task-directory-snapshot.ts | 265 ++++++++ 14 files changed, 1975 insertions(+), 73 deletions(-) create mode 100644 server/src/__tests__/heartbeat-task-directory-restore.test.ts create mode 100644 server/src/__tests__/isolated-task-directory-retention-config.test.ts create mode 100644 server/src/__tests__/isolated-task-directory-retention.test.ts create mode 100644 server/src/services/isolated-task-directory-retention.ts create mode 100644 server/src/services/isolated-task-directory-snapshot.ts diff --git a/doc/DEVELOPING.md b/doc/DEVELOPING.md index fea6694f2e8..e399790fbbb 100644 --- a/doc/DEVELOPING.md +++ b/doc/DEVELOPING.md @@ -2624,6 +2624,17 @@ Environment overrides: `PAPERCLIP_GIT_RESTORE_POINT_IDLE_DAYS=` sets how long an open issue tree's worktree must go untouched before it is removed the same way; runs restore it automatically. The default is `7`, and `0` turns this off. +- `PAPERCLIP_TASK_DIRECTORY_RETENTION_ENABLED=true` lets the terminal workspace reaper + save and remove plain task directories under `/isolated-workspaces/` once + their issue tree has been closed for `PAPERCLIP_GIT_RESTORE_POINT_TERMINAL_DELAY_DAYS`, + and remove orphaned ones (see `doc/recoverable-disk-cleanup.md`). It is off by default + and runs as a dry run until `PAPERCLIP_TASK_DIRECTORY_RETENTION_DRY_RUN=false`. Removal + needs `PAPERCLIP_GIT_RESTORE_POINTS_ENABLED=true`, because the files are saved in an + encrypted restore point first and restored on reopen. + `PAPERCLIP_TASK_DIRECTORY_ORPHAN_GRACE_DAYS=` sets how long an orphaned + directory's issue tree must be closed and its contents unchanged. The default is `7` + and the minimum is `1`. A negative, empty, or non-numeric value falls back to the + default. - `PAPERCLIP_GIT_RESTORE_POINT_RETENTION_DAYS=` sets how long a git workspace restore point is kept after its issue tree closes (see `doc/recoverable-disk-cleanup.md`). The default is `90` and the minimum is `1`. A diff --git a/doc/recoverable-disk-cleanup.md b/doc/recoverable-disk-cleanup.md index ea4aa982001..b33a0cc74fd 100644 --- a/doc/recoverable-disk-cleanup.md +++ b/doc/recoverable-disk-cleanup.md @@ -225,6 +225,131 @@ still keep a worktree from expiring. Restore points are refused when the file storage is `s3` and the secrets master key does not come from `PAPERCLIP_SECRETS_MASTER_KEY`. +## Isolated task directories + +Tasks without a project repository run in a plain (non-Git) directory at +`/isolated-workspaces///`. Its execution workspace row has +strategy `project_primary`, provider `local_fs` and that exact path as `cwd`, in +`isolated_workspace` or `shared_workspace` mode. Agents can leave the only copy of their +work there, such as reports or generated files, because nothing pushes it anywhere. + +Before this cleanup existed nothing removed these directories. The terminal workspace +reaper archives a workspace only after proving delivery through Git (a merged pull request +or a merged branch); for a directory that is not a Git checkout the status inspection fails, +so the row was always skipped as undelivered. A workspace archived by hand keeps its +directory too: artifact cleanup removes a `local_fs` directory only when the row says the +runtime created it, and task directory rows never say so. Deleting them on archive would +discard work silently, so retention saves the files first instead. + +With `PAPERCLIP_TASK_DIRECTORY_RETENTION_ENABLED=true` the terminal workspace reaper +handles an open task directory row once every issue in its tree has been `done` or +`cancelled` for `PAPERCLIP_GIT_RESTORE_POINT_TERMINAL_DELAY_DAYS` (default `3`), the same +delay git restore points use. It registers that moment as its deadline, so a closed tree +costs no checks before then. It removes the directory only when all of these hold, checked +under the issue's source lock and the workspace lifecycle lock: + +- the source issue is still bound to the workspace (`issue_not_bound` otherwise), because + reopening restores through that binding; +- no run of the tree or the workspace is queued, running or unfinished, no native run + finalization is unsettled, no environment lease or runtime service is live, no recovery + action is unresolved and the workspace is not waiting for a reopen to be consumed + (`live_or_unresolved_consumer`); these are the checks git cache expiration uses; +- no other open workspace or project workspace points into the directory (closed rows + for the same issue do not count); +- the directory is a real directory, not a symbolic link (`unsafe_task_directory`). + +It then saves a restore point of the directory: every file with its mode, every +directory and every symbolic link (the link itself; links are never followed). A +`node_modules` directory next to a `package.json` is left out, because installing the +package recreates it. Sockets, devices and other special files keep the directory +(`unsupported_filesystem_entry`), and so does a directory over the restore point limits +(`task_directory_too_many_files`, `task_directory_file_too_large`, +`task_directory_too_large`; 20,000 files, 64 MiB per file, 256 MiB in total). The +captured snapshot is decoded once before anything is removed; a directory whose snapshot +could not be restored stays (`task_directory_not_restorable`). The restore +point uses the git restore point ledger, storage and encryption: it is sealed with a +per-restore-point key wrapped by the instance secrets key, uploaded to file storage under +`git-restore-points///task-directory/`, read back and hash-checked, +and activated in the same transaction that archives the workspace and records the +`isolatedTaskDirectoryRetention` state in its metadata. It follows the git restore point +retention (`PAPERCLIP_GIT_RESTORE_POINT_RETENTION_DAYS`, default `90`), counted from the +later of the tree's close and the removal, so a task that closed long ago still keeps its +files for the full period. Restore points must be enabled (`PAPERCLIP_GIT_RESTORE_POINTS_ENABLED=true`, +`restore_points_disabled` otherwise), and they are refused when the file storage is `s3` +and the secrets master key does not come from `PAPERCLIP_SECRETS_MASTER_KEY`. + +Right before deletion the directory is read again. If anything changed since the capture, +the workspace is made active again, the restore point is dropped and the directory stays +(`task_directory_changed`). Otherwise the directory is renamed to a recorded +`.expired-` name beside it, no longer than the original name, and deleted. The +archive and the removal are recorded as `execution_workspace.task_directory_archived` and +`execution_workspace.task_directory_removed` activity. A removal the +server could not finish is finished by a later sweep. + +Reopening the workspace restores the directory before anything uses it: a comment or an +agent update on an issue bound to a closed `isolated_workspace`, or the next run of the +issue in either mode. The files are written to a `.restoring-` staging directory +beside it, whose name is no longer than the original, verified against the saved digest +and renamed into place. An empty directory in the way is replaced; a non-empty +one that does not match keeps the workspace closed and fails the reopen instead of +overwriting it. After a successful reopen the restore point is superseded and removed; the +next retention saves a new one. When the restore point has already expired, the reopen +starts with an empty directory and posts a system comment on the issue saying the earlier +files are no longer available. + +### Orphaned task directories + +The reaper also walks `isolated-workspaces/` once per server start, at most 8 issue +directories per sweep, continuing from that position in the next sweep. It never follows +symbolic links. For each directory: + +- an open execution workspace pointing at or into it keeps it (the reaper handles that + row as above); +- a closed workspace row that its issue is still bound to is handled like an open row: + the directory is saved in a restore point on that row and removed after the terminal + delay, and reopening restores it (outcome `preserved_and_removed`); +- any other directory is an orphan: its workspace row is missing, or archived or + `cleanup_failed` without the issue bound to it. An orphan is removed when its issue is + gone, or every issue in the tree has been closed for + `PAPERCLIP_TASK_DIRECTORY_ORPHAN_GRACE_DAYS` (default `7`), and nothing in it changed + during that period, and no project workspace, live runtime service, unsettled run, + finalization, live lease or unresolved recovery action of the issue refers to it. Leases +count when they belong to a run of the issue tree, to an issue in the tree, or to any +workspace row of the directory. An + orphan is not saved first: no workspace row can reopen it. If its issue is reopened + later without another workspace, its next run starts in an empty directory. + +After that first walk, the reaper looks only at the directories that changes point to: a +workspace row that becomes archived or `cleanup_failed`, or an issue that becomes `done` or +`cancelled`, sends the reaper to that issue's directory and the directories of its +ancestors, whose trees may have just closed. A directory it kept is checked +again at its own deadline: the end of the grace period or terminal delay, or an hour later +when a lock was busy or a live run, lease, service, finalization or recovery action still +used it. A directory whose issue is open waits for the issue to close. With nothing pending +it registers no work. The walk also deletes leftover `.expired-*` and `.restoring-*` +directories older than an hour; when deleting an orphan's trash fails, another walk is +scheduled an hour later. + +### Controls and logs + +| Environment variable | Default | Effect | +| --- | --- | --- | +| `PAPERCLIP_TASK_DIRECTORY_RETENTION_ENABLED` | `false` | Set `true` to let the reaper handle task directories | +| `PAPERCLIP_TASK_DIRECTORY_RETENTION_DRY_RUN` | `true` | Set `false` to save and remove; a dry run only reports candidates and needs no restore points | +| `PAPERCLIP_TASK_DIRECTORY_ORPHAN_GRACE_DAYS` | `7` | Days an orphan's issue tree must be closed and its contents unchanged before removal (minimum `1`) | + +Each open or pending workspace logs `event: "execution_workspace.task_directory_retention"` +with its outcome (`removed`, `dry_run` or `skipped`), skip reason, candidate bytes and +reclaimed bytes. Each directory the walk inspects logs +`event: "execution_workspace.task_directory_cleanup"` with its outcome (`removed`, +`preserved_and_removed`, `dry_run` or `skipped`), reason and bytes. Each reopen that +restores a directory logs `event: "execution_workspace.task_directory_restore"`. A sweep +saves and removes at most 8 open task directories; the rest continue in the next sweep. A +workspace that was skipped is inspected again only when it or its issue changes, or at its +retry deadline, so skipped workspaces do not use up that limit. +Roll out with the dry run, inspect the candidates and skip reasons, then set the dry run to +`false`. + ## Nested project repository worktrees Extra project repositories that have no configured local folder are no longer full diff --git a/server/src/__tests__/heartbeat-task-directory-restore.test.ts b/server/src/__tests__/heartbeat-task-directory-restore.test.ts new file mode 100644 index 00000000000..be964b6190d --- /dev/null +++ b/server/src/__tests__/heartbeat-task-directory-restore.test.ts @@ -0,0 +1,120 @@ +import { randomUUID } from "node:crypto"; +import { promises as fs } from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { eq, sql } from "drizzle-orm"; +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; +import { + agentWakeupRequests, + agents, + authUsers, + companies, + companyMemberships, + createDb, + EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, + executionWorkspaceRestorePoints, + executionWorkspaces, + heartbeatRuns, + issues, +} from "@paperclipai/db"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; +import { drainHeartbeatRunsToQuiescence } from "./helpers/drain-heartbeat-runs.js"; +import { heartbeatService } from "../services/heartbeat.ts"; +import { materializeIsolatedTaskDirectory } from "../services/isolated-task-directory.js"; +import { expireIsolatedTaskDirectory, readTaskDirectoryRetention } from "../services/isolated-task-directory-retention.js"; +import { getStorageService } from "../storage/index.js"; + +const adapterExecute = vi.hoisted(() => vi.fn(async (_input?: unknown) => ({ + exitCode: 0, signal: null, timedOut: false, summary: "Resumed restored files.", provider: "test", model: "test-model", +}))); + +vi.mock("../adapters/index.js", () => ({ + getServerAdapter: () => ({ type: "codex_local", execute: adapterExecute, supportsLocalAgentJwt: false }), + findActiveServerAdapter: () => ({ type: "codex_local", execute: adapterExecute, supportsLocalAgentJwt: false }), + runningProcesses: new Map(), +})); + +const DAY_MS = 24 * 60 * 60 * 1000; + +const support = await getEmbeddedPostgresTestSupport(); +describe.skipIf(!support.supported)("heartbeat resume of a removed task directory", () => { + let db: ReturnType; + let database: Awaited>; + let root: string; + beforeAll(async () => { + database = await startEmbeddedPostgresTestDatabase("heartbeat-task-directory-restore-"); + db = createDb(database.connectionString); + root = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-heartbeat-task-directory-"))); + }, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS); + afterEach(async () => { + await drainHeartbeatRunsToQuiescence(db, heartbeatService(db)); + adapterExecute.mockClear(); + await db.delete(executionWorkspaceRestorePoints); + await db.execute(sql`TRUNCATE TABLE companies CASCADE`); + await db.delete(authUsers).where(eq(authUsers.id, "responsible-user")); + vi.unstubAllEnvs(); + }); + afterAll(async () => { + await db.$client.end(); + await database.cleanup(); + await fs.rm(root, { recursive: true, force: true }); + }, 60_000); + + async function waitForRun(heartbeat: ReturnType, runId: string) { + const deadline = Date.now() + 20_000; + while (Date.now() < deadline) { + const run = await heartbeat.getRun(runId); + if (run && run.status !== "queued" && run.status !== "running") return run; + await new Promise(resolve => setTimeout(resolve, 50)); + } + return heartbeat.getRun(runId); + } + + it("restores a removed task directory before the run uses it", async () => { + const mode = "shared_workspace"; + vi.stubEnv("PAPERCLIP_HOME", path.join(root, randomUUID())); + vi.stubEnv("PAPERCLIP_INSTANCE_ID", "default"); + vi.stubEnv("PAPERCLIP_SECRETS_MASTER_KEY", "31".repeat(32)); + const companyId = randomUUID(), agentId = randomUUID(), issueId = randomUUID(), workspaceId = randomUUID(); + const runId = randomUUID(), wakeupId = randomUUID(); + const issuePrefix = `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`; + await db.insert(companies).values({ id: companyId, name: "Task directory resume", issuePrefix, status: "active", defaultResponsibleUserId: "responsible-user" }); + await db.insert(authUsers).values({ id: "responsible-user", name: "Fixture user", email: "responsible-user@example.test", createdAt: new Date(), updatedAt: new Date() }).onConflictDoNothing(); + await db.insert(companyMemberships).values({ companyId, principalType: "user", principalId: "responsible-user", status: "active", membershipRole: "member" }); + await db.insert(agents).values({ id: agentId, companyId, name: "Resumer", role: "engineer", status: "idle", adapterType: "codex_local", + adapterConfig: {}, runtimeConfig: { heartbeat: { wakeOnDemand: true, maxConcurrentRuns: 1 } }, permissions: {} }); + await db.insert(issues).values({ id: issueId, companyId, title: "Finished files", status: "done", workMode: "standard", + assigneeAgentId: agentId, responsibleUserId: "responsible-user", issueNumber: 1, identifier: `${issuePrefix}-1`, + completedAt: new Date(Date.now() - 4 * DAY_MS) }); + const cwd = await materializeIsolatedTaskDirectory({ companyId, issueId }); + await fs.mkdir(path.join(cwd, "out")); + await fs.writeFile(path.join(cwd, "out", "report.md"), "only copy of the report\n"); + await db.insert(executionWorkspaces).values({ id: workspaceId, companyId, sourceIssueId: issueId, mode, strategyType: "project_primary", + name: "Finished files", status: "active", providerType: "local_fs", cwd, metadata: { source: "task_session", createdByRuntime: false } }); + await db.update(issues).set({ executionWorkspaceId: workspaceId, executionWorkspacePreference: "reuse_existing", + executionWorkspaceSettings: { mode } }).where(eq(issues.id, issueId)); + const workspace = () => db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, workspaceId)).then(rows => rows[0]!); + expect(await expireIsolatedTaskDirectory(db, await workspace(), { dryRun: false, now: new Date(), notBefore: new Date(Date.now() - DAY_MS), + restorePoint: { storage: getStorageService(), keyDurable: true } })).toMatchObject({ expired: true }); + await expect(fs.access(cwd)).rejects.toMatchObject({ code: "ENOENT" }); + + await db.update(issues).set({ status: "in_progress", completedAt: null }).where(eq(issues.id, issueId)); + await db.insert(agentWakeupRequests).values({ id: wakeupId, companyId, agentId, source: "assignment", triggerDetail: "system", + reason: "issue_assigned", payload: { issueId }, status: "queued", runId }); + await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, invocationSource: "assignment", triggerDetail: "system", status: "queued", + wakeupRequestId: wakeupId, responsibleUserId: "responsible-user", contextSnapshot: { issueId, taskId: issueId, wakeReason: "issue_assigned" } }); + await db.update(issues).set({ checkoutRunId: runId, executionRunId: runId, executionAgentNameKey: "resumer", executionLockedAt: new Date() }) + .where(eq(issues.id, issueId)); + const heartbeat = heartbeatService(db); + await heartbeat.resumeQueuedRuns(); + const run = await waitForRun(heartbeat, runId); + await heartbeat.waitForRunExecutionDrain(runId); + expect(run).toMatchObject({ status: "succeeded" }); + expect(adapterExecute).toHaveBeenCalledTimes(1); + expect(adapterExecute.mock.calls[0]?.[0]).toMatchObject({ context: { executionWorkspaceId: workspaceId, paperclipWorkspace: { cwd } } }); + expect(await fs.readFile(path.join(cwd, "out", "report.md"), "utf8")).toBe("only copy of the report\n"); + const restored = await workspace(); + expect(restored.status).not.toBe("archived"); + expect(readTaskDirectoryRetention(restored)).toBeNull(); + }); +}); diff --git a/server/src/__tests__/isolated-task-directory-retention-config.test.ts b/server/src/__tests__/isolated-task-directory-retention-config.test.ts new file mode 100644 index 00000000000..f9a27b2dc8e --- /dev/null +++ b/server/src/__tests__/isolated-task-directory-retention-config.test.ts @@ -0,0 +1,29 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { loadConfig } from "../config.ts"; + +describe("isolated task directory retention config parsing", () => { + afterEach(() => { + vi.unstubAllEnvs(); + }); + + it("is disabled by default, dry run when enabled, with a seven-day orphan grace", () => { + vi.stubEnv("PAPERCLIP_TASK_DIRECTORY_RETENTION_ENABLED", undefined); + vi.stubEnv("PAPERCLIP_TASK_DIRECTORY_RETENTION_DRY_RUN", undefined); + vi.stubEnv("PAPERCLIP_TASK_DIRECTORY_ORPHAN_GRACE_DAYS", undefined); + expect(loadConfig()).toMatchObject({ taskDirectoryRetentionEnabled: false, taskDirectoryRetentionDryRun: true, + taskDirectoryOrphanGraceDays: 7 }); + }); + + it("accepts explicit settings", () => { + vi.stubEnv("PAPERCLIP_TASK_DIRECTORY_RETENTION_ENABLED", "true"); + vi.stubEnv("PAPERCLIP_TASK_DIRECTORY_RETENTION_DRY_RUN", "false"); + vi.stubEnv("PAPERCLIP_TASK_DIRECTORY_ORPHAN_GRACE_DAYS", "14"); + expect(loadConfig()).toMatchObject({ taskDirectoryRetentionEnabled: true, taskDirectoryRetentionDryRun: false, + taskDirectoryOrphanGraceDays: 14 }); + }); + + it.each([["0", 1], ["", 7], ["-1", 7], ["many", 7]])("clamps the orphan grace for %j", (value, expected) => { + vi.stubEnv("PAPERCLIP_TASK_DIRECTORY_ORPHAN_GRACE_DAYS", value); + expect(loadConfig()).toMatchObject({ taskDirectoryOrphanGraceDays: expected }); + }); +}); diff --git a/server/src/__tests__/isolated-task-directory-retention.test.ts b/server/src/__tests__/isolated-task-directory-retention.test.ts new file mode 100644 index 00000000000..bdaa1d97582 --- /dev/null +++ b/server/src/__tests__/isolated-task-directory-retention.test.ts @@ -0,0 +1,524 @@ +import { promises as fs } from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { randomUUID } from "node:crypto"; +import { execFileSync } from "node:child_process"; +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; +import { eq, sql } from "drizzle-orm"; +import { + activityLog, + agents, + companies, + createDb, + environmentLeases, + executionWorkspaceRestorePoints, + executionWorkspaces, + heartbeatRuns, + issueComments, + issueRecoveryActions, + issues, + nativeRunFinalizations, + workspaceRuntimeServices, +} from "@paperclipai/db"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; +import { executionWorkspaceService } from "../services/execution-workspaces.js"; +import { materializeIsolatedTaskDirectory } from "../services/isolated-task-directory.js"; +import { + expireIsolatedTaskDirectory, + readTaskDirectoryRetention, + sweepIsolatedTaskDirectories, + TASK_DIRECTORY_RESTORE_POINT_EXPIRED_WARNING, +} from "../services/isolated-task-directory-retention.js"; +import { markGitRestorePointExpired } from "../services/git-restore-point-storage.js"; +import { gitRestorePointRetentionService } from "../services/git-restore-point-ledger.js"; +import { getStorageService } from "../storage/index.js"; + +const DAY_MS = 24 * 60 * 60 * 1000; +const exists = (target: string) => fs.lstat(target).then(() => true, () => false); + +async function age(target: string, at: Date) { + const stat = await fs.lstat(target); + if (stat.isDirectory()) for (const name of await fs.readdir(target)) await age(path.join(target, name), at); + await (stat.isSymbolicLink() ? fs.lutimes(target, at, at) : fs.utimes(target, at, at)); +} + +const support = await getEmbeddedPostgresTestSupport(); +const describeEmbeddedPostgres = support.supported ? describe : describe.skip; +describeEmbeddedPostgres("isolated task directory retention", () => { + let db: ReturnType; + let database: Awaited>; + let root: string; + let outside: string; + const previousHome = process.env.PAPERCLIP_HOME; + const previousInstance = process.env.PAPERCLIP_INSTANCE_ID; + beforeAll(async () => { + database = await startEmbeddedPostgresTestDatabase("isolated-task-directory-retention-"); + db = createDb(database.connectionString); + root = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-task-directory-retention-"))); + process.env.PAPERCLIP_HOME = path.join(root, "home"); + process.env.PAPERCLIP_INSTANCE_ID = "default"; + vi.stubEnv("PAPERCLIP_SECRETS_MASTER_KEY", "31".repeat(32)); + outside = path.join(root, "outside"); + await fs.mkdir(outside); + await fs.writeFile(path.join(outside, "keep.txt"), "outside\n"); + }); + afterEach(async () => { + await db.delete(executionWorkspaceRestorePoints); + await db.execute(sql`TRUNCATE TABLE companies CASCADE`); + await fs.rm(path.join(root, "home", "instances", "default", "isolated-workspaces"), { recursive: true, force: true }); + }); + afterAll(async () => { + vi.unstubAllEnvs(); + if (previousHome === undefined) delete process.env.PAPERCLIP_HOME; else process.env.PAPERCLIP_HOME = previousHome; + if (previousInstance === undefined) delete process.env.PAPERCLIP_INSTANCE_ID; else process.env.PAPERCLIP_INSTANCE_ID = previousInstance; + await db.$client.end({ timeout: 1 }); await database.cleanup(); await fs.rm(root, { recursive: true, force: true }); + }); + + const settings = { dryRun: false, terminalDelayMs: 3 * DAY_MS, orphanGraceMs: 7 * DAY_MS }; + const restorePoints = (overrides: Partial<{ keyDurable: boolean }> = {}) => ({ storage: getStorageService(), terminalDelayMs: 3 * DAY_MS, keyDurable: true, ...overrides }); + + async function fixture(options: { closedDaysAgo?: number | null; mode?: string; status?: string } = {}) { + const companyId = randomUUID(), issueId = randomUUID(), workspaceId = randomUUID(), agentId = randomUUID(); + const closedDaysAgo = options.closedDaysAgo === undefined ? 4 : options.closedDaysAgo; + await db.insert(companies).values({ id: companyId, name: "Task directory fixture", issuePrefix: `TD${companyId.slice(0, 6)}` }); + await db.insert(agents).values({ id: agentId, companyId, name: "Fixture agent" }); + await db.insert(issues).values({ id: issueId, companyId, title: "Finished task", + status: closedDaysAgo === null ? "in_progress" : "done", completedAt: closedDaysAgo === null ? null : new Date(Date.now() - closedDaysAgo * DAY_MS) }); + const cwd = await materializeIsolatedTaskDirectory({ companyId, issueId }); + await fs.writeFile(path.join(cwd, "report.md"), "final report\n"); + await fs.mkdir(path.join(cwd, "nested", "deeper"), { recursive: true }); + await fs.writeFile(path.join(cwd, "nested", "deeper", "data.json"), "{\"value\":1}\n"); + await fs.writeFile(path.join(cwd, "run.sh"), "#!/bin/sh\necho ok\n", { mode: 0o755 }); + await fs.symlink(outside, path.join(cwd, "outside-link")); + await fs.writeFile(path.join(cwd, "package.json"), "{\"name\":\"fixture\"}\n"); + await fs.mkdir(path.join(cwd, "node_modules", "dep"), { recursive: true }); + await fs.writeFile(path.join(cwd, "node_modules", "dep", "index.js"), "module.exports = 1;\n"); + await db.insert(executionWorkspaces).values({ id: workspaceId, companyId, sourceIssueId: issueId, mode: options.mode ?? "isolated_workspace", + strategyType: "project_primary", name: "Fixture", status: options.status ?? "active", providerType: "local_fs", cwd, + closedAt: options.status === "archived" ? new Date(Date.now() - closedDaysAgo! * DAY_MS) : null, + metadata: { source: "task_session", createdByRuntime: false } }); + await db.update(issues).set({ executionWorkspaceId: workspaceId }).where(eq(issues.id, issueId)); + const row = () => db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, workspaceId)).then(rows => rows[0]!); + const ledger = () => db.select().from(executionWorkspaceRestorePoints).where(eq(executionWorkspaceRestorePoints.executionWorkspaceId, workspaceId)); + const service = (overrides: Parameters[1] = {}) => executionWorkspaceService(db, { + taskDirectoryRetention: settings, gitRestorePoints: restorePoints(), ...overrides }); + const expire = async (overrides: Partial[2]> = {}) => expireIsolatedTaskDirectory(db, await row(), { + dryRun: false, now: new Date(), notBefore: new Date(Date.now() - DAY_MS), restorePoint: { storage: getStorageService(), keyDurable: true }, ...overrides }); + const reopen = () => executionWorkspaceService(db).reopenClosedIsolatedExecutionWorkspaceForIssue({ workspaceId, + issue: { id: issueId, companyId, projectId: null }, actor: { actorType: "user", agentId: null }, + authorizationActor: { type: "board", source: "local_implicit", isInstanceAdmin: true } }); + return { companyId, issueId, workspaceId, agentId, cwd, row, ledger, service, expire, reopen }; + } + + async function expectRestored(cwd: string) { + expect(await fs.readFile(path.join(cwd, "report.md"), "utf8")).toBe("final report\n"); + expect(await fs.readFile(path.join(cwd, "nested", "deeper", "data.json"), "utf8")).toBe("{\"value\":1}\n"); + expect((await fs.stat(path.join(cwd, "run.sh"))).mode & 0o777).toBe(0o755); + expect((await fs.lstat(path.join(cwd, "outside-link"))).isSymbolicLink()).toBe(true); + expect(await fs.readlink(path.join(cwd, "outside-link"))).toBe(outside); + expect(await exists(path.join(cwd, "package.json"))).toBe(true); + expect(await exists(path.join(cwd, "node_modules"))).toBe(false); + } + + it("archives and removes a closed issue's task directory after the delay and restores it on reopen", async () => { + const f = await fixture(); + const result = await f.service().sweepTerminalWorkspaces(); + expect(result).toMatchObject({ archived: 1 }); + expect(await exists(f.cwd)).toBe(false); + expect(await fs.readFile(path.join(outside, "keep.txt"), "utf8")).toBe("outside\n"); + const archived = await f.row(); + expect(archived).toMatchObject({ status: "archived", cleanupReason: "isolated task directory retention" }); + const state = readTaskDirectoryRetention(archived)!; + expect(state).toMatchObject({ removed: true, restorePoint: { files: 4, excluded: 1 } }); + expect(await f.ledger()).toMatchObject([{ status: "active", objectKey: state.restorePoint.objectKey }]); + + expect(await f.reopen()).toMatchObject({ ok: true, reopened: true }); + await expectRestored(f.cwd); + const reopened = await f.row(); + expect(reopened.status).toBe("active"); + expect(readTaskDirectoryRetention(reopened)).toBeNull(); + expect(await f.ledger()).toMatchObject([{ status: "superseded" }]); + }); + + it("restores a shared-workspace task directory through reopen", async () => { + const f = await fixture({ mode: "shared_workspace" }); + expect(await f.expire()).toMatchObject({ expired: true, restorePoint: true }); + expect(await exists(f.cwd)).toBe(false); + const [issue] = await db.select().from(issues).where(eq(issues.id, f.issueId)); + expect(issue.executionWorkspaceId).toBe(f.workspaceId); + expect(await f.reopen()).toMatchObject({ ok: true, reopened: true }); + await expectRestored(f.cwd); + }); + + it("keeps the directory until the terminal delay and registers that deadline", async () => { + const f = await fixture({ closedDaysAgo: 1 }); + const service = f.service(); + expect(await service.sweepTerminalWorkspaces()).toMatchObject({ archived: 0 }); + expect(await exists(f.cwd)).toBe(true); + expect((await f.row()).status).toBe("active"); + const [issue] = await db.select().from(issues).where(eq(issues.id, f.issueId)); + const deadline = await service.nextTerminalWorkspaceSweepAt(); + expect(deadline).toBe(issue.completedAt!.getTime() + 3 * DAY_MS); + expect(await f.ledger()).toEqual([]); + }); + + it("keeps the directory while the issue is open", async () => { + const f = await fixture({ closedDaysAgo: null }); + expect(await f.service().sweepTerminalWorkspaces()).toMatchObject({ archived: 0, skippedNonTerminalTree: 1 }); + expect(await exists(f.cwd)).toBe(true); + expect(await f.ledger()).toEqual([]); + }); + + it("does nothing when retention is not configured", async () => { + const f = await fixture(); + await executionWorkspaceService(db, { gitRestorePoints: restorePoints() }).sweepTerminalWorkspaces(); + expect(await exists(f.cwd)).toBe(true); + expect((await f.row()).status).toBe("active"); + }); + + type Consumer = (f: Awaited>) => Promise; + const consumers: Array<[string, Consumer, string]> = [ + ["a live run", f => db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, status: "running", contextSnapshot: { issueId: f.issueId } }), + "live_or_unresolved_consumer"], + ["a live runtime service", f => db.insert(workspaceRuntimeServices).values({ id: randomUUID(), companyId: f.companyId, scopeType: "execution_workspace", + serviceName: "web", status: "running", lifecycle: "shared", provider: "local_process", executionWorkspaceId: f.workspaceId, cwd: f.cwd }), + "live_or_unresolved_consumer"], + ["a reopen fence", f => db.update(executionWorkspaces).set({ metadata: { source: "task_session", reopenPendingConsumption: true } }) + .where(eq(executionWorkspaces.id, f.workspaceId)), "live_or_unresolved_consumer"], + ["an unsettled finalization", async f => { + const runId = randomUUID(); + await db.insert(heartbeatRuns).values({ id: runId, companyId: f.companyId, agentId: f.agentId, status: "succeeded", + finishedAt: new Date(Date.now() - 4 * DAY_MS), nativeIssueId: f.issueId }); + await db.insert(nativeRunFinalizations).values({ runId, companyId: f.companyId, issueId: f.issueId, phase: "observed", leaseOwner: "native-finalizer:live" }); + }, "live_or_unresolved_consumer"], + ["a live environment lease", f => db.insert(environmentLeases).values({ companyId: f.companyId, executionWorkspaceId: f.workspaceId, status: "active" }), + "live_or_unresolved_consumer"], + ["an unresolved recovery action", f => db.insert(issueRecoveryActions).values({ companyId: f.companyId, sourceIssueId: f.issueId, + kind: "active_run_watchdog", status: "active", ownerType: "board", ownerAgentId: null, cause: "native_workspace_finalization_owner_unverified", + fingerprint: randomUUID(), evidence: {}, nextAction: "Verify the owner." }), "live_or_unresolved_consumer"], + ["an issue bound to another workspace", f => db.update(issues).set({ executionWorkspaceId: null }).where(eq(issues.id, f.issueId)), "issue_not_bound"], + ["a sibling live workspace in the directory", f => db.insert(executionWorkspaces).values({ companyId: f.companyId, mode: "shared_workspace", + strategyType: "project_primary", name: "Sibling", status: "active", providerType: "local_fs", cwd: path.join(f.cwd, "nested") }), + "live_or_unresolved_consumer"], + ]; + + it.each(consumers)("keeps the directory while %s exists", async (_label, add, reason) => { + const f = await fixture(); + await add(f); + expect(await f.expire()).toMatchObject({ expired: false, skipReason: reason }); + expect(await exists(f.cwd)).toBe(true); + expect((await f.row()).status).toBe("active"); + expect(await f.ledger()).toEqual([]); + }); + + it("removes the directory despite closed sibling rows at the same path", async () => { + const f = await fixture(); + await db.insert(executionWorkspaces).values({ companyId: f.companyId, sourceIssueId: f.issueId, mode: "isolated_workspace", + strategyType: "project_primary", name: "Old", status: "archived", closedAt: new Date(Date.now() - 10 * DAY_MS), providerType: "local_fs", cwd: f.cwd }); + expect(await f.expire()).toMatchObject({ expired: true }); + }); + + it("refuses to remove without restore points or with a non-durable key", async () => { + const f = await fixture(); + expect(await f.expire({ restorePoint: undefined })).toMatchObject({ expired: false, skipReason: "restore_points_disabled" }); + expect(await f.expire({ restorePoint: { storage: getStorageService(), keyDurable: false } })) + .toMatchObject({ expired: false, skipReason: "restore_point_key_not_durable" }); + expect(await f.expire({ notBefore: new Date(Date.now() + DAY_MS) })).toMatchObject({ expired: false, skipReason: "not_due" }); + expect(await exists(f.cwd)).toBe(true); + expect(await f.ledger()).toEqual([]); + }); + + it("keeps files it cannot save", async () => { + const f = await fixture(); + expect(await f.expire({ restorePoint: { storage: getStorageService(), keyDurable: true, limits: { maxFiles: 2, maxFileBytes: 1024, maxTotalBytes: 4096 } } })) + .toMatchObject({ expired: false, skipReason: "task_directory_too_many_files" }); + expect(await exists(f.cwd)).toBe(true); + expect((await f.row()).status).toBe("active"); + expect(await f.ledger()).toEqual([]); + }); + + it("reports candidates in dry run without changing anything", async () => { + const f = await fixture(); + const result = await f.service({ taskDirectoryRetention: { ...settings, dryRun: true }, gitRestorePoints: undefined }).sweepTerminalWorkspaces(); + expect(result).toMatchObject({ eligible: 1, archived: 0 }); + expect(await exists(f.cwd)).toBe(true); + expect((await f.row()).status).toBe("active"); + expect(await f.ledger()).toEqual([]); + }); + + it("rolls back when the directory changes after it was saved", async () => { + const f = await fixture(); + const result = await f.expire({ beforeDelete: async () => { await fs.writeFile(path.join(f.cwd, "late.txt"), "late work\n"); } }); + expect(result, JSON.stringify(result.failure)).toMatchObject({ expired: false, skipReason: "task_directory_changed" }); + expect(await fs.readFile(path.join(f.cwd, "late.txt"), "utf8")).toBe("late work\n"); + const row = await f.row(); + expect(row.status).toBe("active"); + expect(readTaskDirectoryRetention(row)).toBeNull(); + expect(await f.ledger()).toMatchObject([{ status: "superseded" }]); + }); + + it("finishes an interrupted removal on the next sweep", async () => { + const f = await fixture(); + await expect(f.expire({ beforeDelete: async () => { throw new Error("simulated_crash"); } })) + .resolves.toMatchObject({ expired: false, skipReason: "simulated_crash" }); + expect(await exists(f.cwd)).toBe(true); + expect(readTaskDirectoryRetention(await f.row())).toMatchObject({ removed: false }); + expect(await f.service().sweepTerminalWorkspaces()).toMatchObject({ archived: 1 }); + expect(await exists(f.cwd)).toBe(false); + expect(readTaskDirectoryRetention(await f.row())).toMatchObject({ removed: true }); + }); + + it("never follows a task directory that is a symbolic link", async () => { + const f = await fixture(); + const moved = path.join(root, `moved-${f.issueId}`); + await fs.rename(f.cwd, moved); + await fs.symlink(moved, f.cwd); + expect(await f.expire()).toMatchObject({ expired: false, skipReason: "unsafe_task_directory" }); + expect(await fs.readFile(path.join(moved, "report.md"), "utf8")).toBe("final report\n"); + expect(await f.ledger()).toEqual([]); + await fs.rm(f.cwd); + await fs.rm(moved, { recursive: true }); + }); + + it("reopens an empty directory with a warning when the saved files expired", async () => { + const f = await fixture(); + expect(await f.expire()).toMatchObject({ expired: true }); + const [ledger] = await f.ledger(); + await markGitRestorePointExpired(db, ledger!); + expect(readTaskDirectoryRetention(await f.row())?.restorePoint.expiredAt).toEqual(expect.any(String)); + expect(await f.reopen()).toMatchObject({ ok: true, reopened: true, warning: TASK_DIRECTORY_RESTORE_POINT_EXPIRED_WARNING }); + expect(await fs.readdir(f.cwd)).toEqual([]); + const comments = await db.select().from(issueComments).where(eq(issueComments.issueId, f.issueId)); + expect(comments.map(comment => comment.body)).toContain(TASK_DIRECTORY_RESTORE_POINT_EXPIRED_WARNING); + }); + + it("refuses to restore over a directory that diverged after removal", async () => { + const f = await fixture(); + expect(await f.expire()).toMatchObject({ expired: true }); + await fs.mkdir(f.cwd); + await fs.writeFile(path.join(f.cwd, "other.txt"), "unrelated\n"); + expect(await f.reopen()).toMatchObject({ ok: false, code: "rebuild_failed" }); + expect(await fs.readFile(path.join(f.cwd, "other.txt"), "utf8")).toBe("unrelated\n"); + expect((await f.row()).status).toBe("archived"); + }); + + it("saves and restores file names that contain a backslash", async () => { + const f = await fixture(); + await fs.writeFile(path.join(f.cwd, "report\\final.txt"), "backslash name\n"); + expect(await f.expire()).toMatchObject({ expired: true }); + expect(await f.reopen()).toMatchObject({ ok: true, reopened: true }); + expect(await fs.readFile(path.join(f.cwd, "report\\final.txt"), "utf8")).toBe("backslash name\n"); + }); + + it("restores a deep path that fills the platform path length", async () => { + const f = await fixture(); + let deep = f.cwd; + while (deep.length < 1000) deep = path.join(deep, "d".repeat(Math.min(60, 1000 - deep.length))); + await fs.mkdir(deep, { recursive: true }); + const file = path.join(deep, "z".repeat(Math.max(1, 1015 - deep.length))); + await fs.writeFile(file, "deep\n"); + expect(await f.expire()).toMatchObject({ expired: true }); + expect(await f.reopen()).toMatchObject({ ok: true, reopened: true }); + expect(await fs.readFile(file, "utf8")).toBe("deep\n"); + }); + + it("keeps an expiry recorded while the directory was being removed, and records activity", async () => { + const f = await fixture(); + const result = await f.expire({ beforeDelete: async () => { + const [ledger] = await f.ledger(); + await markGitRestorePointExpired(db, ledger!); + } }); + expect(result).toMatchObject({ expired: true }); + expect(readTaskDirectoryRetention(await f.row())).toMatchObject({ removed: true, restorePoint: { expiredAt: expect.any(String) } }); + const actions = await db.select({ action: activityLog.action }).from(activityLog).where(eq(activityLog.entityId, f.workspaceId)); + expect(actions.map(row => row.action).sort()).toEqual(["execution_workspace.task_directory_archived", "execution_workspace.task_directory_removed"]); + }); + + it("keeps a new restore point for the full retention even when the task closed long ago", async () => { + const f = await fixture({ closedDaysAgo: 120 }); + expect(await f.expire()).toMatchObject({ expired: true }); + const retention = gitRestorePointRetentionService(db, { storage: getStorageService(), retentionDays: 90 }); + await retention.tick(); + expect(await f.ledger()).toMatchObject([{ status: "active" }]); + expect(readTaskDirectoryRetention(await f.row())?.restorePoint.expiredAt).toBeUndefined(); + expect(await f.reopen()).toMatchObject({ ok: true, reopened: true }); + await expectRestored(f.cwd); + }); + + it("does not let skipped rows starve later rows of the per-sweep budget", async () => { + const blocked = await fixture(); + execFileSync("mkfifo", [path.join(blocked.cwd, "pipe")]); + const ready = await fixture(); + await db.update(executionWorkspaces).set({ updatedAt: new Date(Date.now() - 60_000) }).where(eq(executionWorkspaces.id, blocked.workspaceId)); + const service = blocked.service({ taskDirectoryRetention: { ...settings, perSweep: 1 } }); + expect(await service.sweepTerminalWorkspaces()).toMatchObject({ archived: 0 }); + expect(await exists(ready.cwd)).toBe(true); + expect(await service.sweepTerminalWorkspaces()).toMatchObject({ archived: 1 }); + expect(await exists(ready.cwd)).toBe(false); + expect(await exists(blocked.cwd)).toBe(true); + }); + + describe("folder sweep", () => { + const sweep = (overrides: Partial[1]> = {}) => sweepIsolatedTaskDirectories(db, { + dryRun: false, now: new Date(), orphanGraceMs: 7 * DAY_MS, terminalDelayMs: 3 * DAY_MS, + restorePoint: { storage: getStorageService(), keyDurable: true }, ...overrides }); + + async function orphan(options: { modifiedDaysAgo?: number } = {}) { + const companyId = randomUUID(), issueId = randomUUID(); + const cwd = await materializeIsolatedTaskDirectory({ companyId, issueId }); + await fs.writeFile(path.join(cwd, "left.txt"), "left behind\n"); + await fs.symlink(outside, path.join(cwd, "outside-link")); + await age(cwd, new Date(Date.now() - (options.modifiedDaysAgo ?? 10) * DAY_MS)); + return { companyId, issueId, cwd }; + } + + it("removes an orphan whose issue is gone after the grace period", async () => { + const o = await orphan(); + const batch = await sweep(); + expect(batch.results).toMatchObject([{ issueId: o.issueId, outcome: "removed", reason: null }]); + expect(batch.results[0]!.reclaimedBytes).toBeGreaterThan(0); + expect(await exists(o.cwd)).toBe(false); + expect(await fs.readFile(path.join(outside, "keep.txt"), "utf8")).toBe("outside\n"); + }); + + it("keeps a recently modified orphan and schedules its deadline", async () => { + const o = await orphan({ modifiedDaysAgo: 2 }); + const batch = await sweep(); + expect(batch.results).toMatchObject([{ issueId: o.issueId, outcome: "skipped", reason: "recently_modified" }]); + expect(batch.results[0]!.retryAt).toBeGreaterThan(Date.now() + 4 * DAY_MS); + expect(await exists(o.cwd)).toBe(true); + }); + + it("keeps an orphan in dry run", async () => { + const o = await orphan(); + const batch = await sweep({ dryRun: true }); + expect(batch.results).toMatchObject([{ issueId: o.issueId, outcome: "dry_run" }]); + expect(await exists(o.cwd)).toBe(true); + }); + + it("keeps a folder that a live workspace points into", async () => { + const o = await orphan(); + await db.insert(companies).values({ id: o.companyId, name: "Live", issuePrefix: `LV${o.companyId.slice(0, 6)}` }); + await db.insert(executionWorkspaces).values({ companyId: o.companyId, mode: "shared_workspace", strategyType: "project_primary", + name: "Live", status: "active", providerType: "local_fs", cwd: path.join(o.cwd, "sub") }); + const batch = await sweep(); + expect(batch.results).toEqual([]); + expect(await exists(o.cwd)).toBe(true); + }); + + it("removes a folder whose archived row is unbound and whose issue closed long ago", async () => { + const o = await orphan(); + await db.insert(companies).values({ id: o.companyId, name: "Archived", issuePrefix: `AR${o.companyId.slice(0, 6)}` }); + await db.insert(issues).values({ id: o.issueId, companyId: o.companyId, title: "Old", status: "done", completedAt: new Date(Date.now() - 10 * DAY_MS) }); + await db.insert(executionWorkspaces).values({ companyId: o.companyId, sourceIssueId: o.issueId, mode: "shared_workspace", strategyType: "project_primary", + name: "Archived", status: "archived", closedAt: new Date(Date.now() - 10 * DAY_MS), providerType: "local_fs", cwd: o.cwd }); + expect((await sweep()).results).toMatchObject([{ outcome: "removed" }]); + expect(await exists(o.cwd)).toBe(false); + }); + + it("keeps an orphan whose issue is still open", async () => { + const o = await orphan(); + await db.insert(companies).values({ id: o.companyId, name: "Open", issuePrefix: `OP${o.companyId.slice(0, 6)}` }); + await db.insert(issues).values({ id: o.issueId, companyId: o.companyId, title: "Open", status: "todo" }); + expect((await sweep()).results).toMatchObject([{ outcome: "skipped", reason: "issue_open" }]); + expect(await exists(o.cwd)).toBe(true); + }); + + it("never follows an orphan that is a symbolic link", async () => { + const companyId = randomUUID(), issueId = randomUUID(); + const parent = path.dirname(await materializeIsolatedTaskDirectory({ companyId, issueId })); + await fs.rmdir(path.join(parent, issueId)); + await fs.symlink(outside, path.join(parent, issueId)); + expect((await sweep()).results).toMatchObject([{ outcome: "skipped", reason: "unsafe_task_directory" }]); + expect(await fs.readFile(path.join(outside, "keep.txt"), "utf8")).toBe("outside\n"); + }); + + it("preserves an archived bound workspace's surviving folder before removing it, and reopen restores it", async () => { + const f = await fixture({ status: "archived" }); + const batch = await sweep(); + expect(batch.results).toMatchObject([{ issueId: f.issueId, outcome: "preserved_and_removed", executionWorkspaceId: f.workspaceId }]); + expect(await exists(f.cwd)).toBe(false); + expect(await f.ledger()).toMatchObject([{ status: "active" }]); + expect(await f.reopen()).toMatchObject({ ok: true, reopened: true }); + await expectRestored(f.cwd); + }); + + it("retries an orphan that a live run still uses", async () => { + const o = await orphan(); + const agentId = randomUUID(); + await db.insert(companies).values({ id: o.companyId, name: "Busy", issuePrefix: `BS${o.companyId.slice(0, 6)}` }); + await db.insert(agents).values({ id: agentId, companyId: o.companyId, name: "Busy agent" }); + await db.insert(issues).values({ id: o.issueId, companyId: o.companyId, title: "Old", status: "done", completedAt: new Date(Date.now() - 10 * DAY_MS) }); + await db.insert(heartbeatRuns).values({ companyId: o.companyId, agentId, status: "running", contextSnapshot: { issueId: o.issueId } }); + const batch = await sweep(); + expect(batch.results).toMatchObject([{ outcome: "skipped", reason: "live_run" }]); + expect(batch.results[0]!.retryAt).toBeGreaterThan(Date.now()); + expect(await exists(o.cwd)).toBe(true); + }); + + it("finds a folder left by a later archive through workspace change hints", async () => { + const service = executionWorkspaceService(db, { taskDirectoryRetention: settings, gitRestorePoints: restorePoints() }); + await service.sweepTerminalWorkspaces(); + expect(await service.nextTerminalWorkspaceSweepAt()).toBeNull(); + const f = await fixture({ status: "archived" }); + await service.sweepTerminalWorkspaces(); + expect(await exists(f.cwd)).toBe(true); + service.terminalWorkspaceWorkSettled(new Set([`workspace:${f.workspaceId}`])); + expect(await service.nextTerminalWorkspaceSweepAt()).toBeLessThanOrEqual(Date.now()); + await service.sweepTerminalWorkspaces(); + expect(await exists(f.cwd)).toBe(false); + expect(readTaskDirectoryRetention(await f.row())).toMatchObject({ removed: true }); + expect(await service.nextTerminalWorkspaceSweepAt()).toBeNull(); + }); + + it("keeps overflowing folder deadlines discoverable through another walk", async () => { + const folders = [await orphan({ modifiedDaysAgo: 1 }), await orphan({ modifiedDaysAgo: 1 })]; + let clock = Date.now(); + const service = executionWorkspaceService(db, { taskDirectoryRetention: { ...settings, trackedLimit: 1 }, + gitRestorePoints: restorePoints(), now: () => new Date(clock) }); + await service.sweepTerminalWorkspaces(); + for (const folder of folders) expect(await exists(folder.cwd)).toBe(true); + const deadline = await service.nextTerminalWorkspaceSweepAt(); + expect(deadline).toBeGreaterThan(clock); + clock = deadline! + 1000; + await service.sweepTerminalWorkspaces(); + for (const folder of folders) expect(await exists(folder.cwd)).toBe(false); + }); + + it("returns to a parent's folder when its last open child closes", async () => { + const service = executionWorkspaceService(db, { taskDirectoryRetention: settings, gitRestorePoints: restorePoints() }); + const f = await fixture({ status: "archived" }); + const childId = randomUUID(); + await db.insert(issues).values({ id: childId, companyId: f.companyId, parentId: f.issueId, title: "Open child", status: "todo" }); + await service.sweepTerminalWorkspaces(); + expect(await exists(f.cwd)).toBe(true); + await db.update(issues).set({ status: "done", completedAt: new Date(Date.now() - 4 * DAY_MS) }).where(eq(issues.id, childId)); + service.terminalWorkspaceWorkSettled(new Set([`issue:${childId}`])); + await service.sweepTerminalWorkspaces(); + expect(await exists(f.cwd)).toBe(false); + expect(readTaskDirectoryRetention(await f.row())).toMatchObject({ removed: true }); + }); + + it("keeps an orphan whose closed workspace still has a lease cleanup pending", async () => { + const o = await orphan(); + await db.insert(companies).values({ id: o.companyId, name: "Lease", issuePrefix: `LS${o.companyId.slice(0, 6)}` }); + const [row] = await db.insert(executionWorkspaces).values({ companyId: o.companyId, mode: "shared_workspace", strategyType: "project_primary", + name: "Closed", status: "archived", closedAt: new Date(Date.now() - 10 * DAY_MS), providerType: "local_fs", cwd: o.cwd }).returning(); + await db.insert(environmentLeases).values({ companyId: o.companyId, executionWorkspaceId: row!.id, status: "pending_cleanup", + releasedAt: new Date(Date.now() - 10 * DAY_MS) }); + expect((await sweep()).results).toMatchObject([{ outcome: "skipped", reason: "live_lease" }]); + expect(await exists(o.cwd)).toBe(true); + }); + + it("bounds the work per sweep and continues from its cursor", async () => { + const folders = [await orphan(), await orphan(), await orphan()]; + const first = await sweep({ limit: 2 }); + expect(first.results).toHaveLength(2); + expect(first.next).not.toBeNull(); + const second = await sweep({ limit: 2, after: first.next }); + expect(second.results).toHaveLength(1); + expect(second.next).toBeNull(); + for (const folder of folders) expect(await exists(folder.cwd)).toBe(false); + }); + }); +}); diff --git a/server/src/config.ts b/server/src/config.ts index e63b66ee0b0..74e80c77ee1 100644 --- a/server/src/config.ts +++ b/server/src/config.ts @@ -102,6 +102,9 @@ export interface Config { gitRestorePointsEnabled: boolean; gitRestorePointTerminalDelayDays: number; gitRestorePointIdleDays: number; + taskDirectoryRetentionEnabled: boolean; + taskDirectoryRetentionDryRun: boolean; + taskDirectoryOrphanGraceDays: number; serveUi: boolean; uiDevMiddleware: boolean; secretsProvider: SecretProvider; @@ -352,6 +355,7 @@ export function loadConfig(): Config { const gitRestorePointRetentionDays = Math.max(1, nonNegativeIntegerEnv("PAPERCLIP_GIT_RESTORE_POINT_RETENTION_DAYS", 90)); const gitRestorePointTerminalDelayDays = nonNegativeIntegerEnv("PAPERCLIP_GIT_RESTORE_POINT_TERMINAL_DELAY_DAYS", 3); const gitRestorePointIdleDays = nonNegativeIntegerEnv("PAPERCLIP_GIT_RESTORE_POINT_IDLE_DAYS", 7); + const taskDirectoryOrphanGraceDays = Math.max(1, nonNegativeIntegerEnv("PAPERCLIP_TASK_DIRECTORY_ORPHAN_GRACE_DAYS", 7)); const bindValidationErrors = validateConfiguredBindMode({ deploymentMode, deploymentExposure, @@ -420,6 +424,9 @@ export function loadConfig(): Config { gitRestorePointsEnabled: process.env.PAPERCLIP_GIT_RESTORE_POINTS_ENABLED === "true", gitRestorePointTerminalDelayDays, gitRestorePointIdleDays, + taskDirectoryRetentionEnabled: process.env.PAPERCLIP_TASK_DIRECTORY_RETENTION_ENABLED === "true", + taskDirectoryRetentionDryRun: process.env.PAPERCLIP_TASK_DIRECTORY_RETENTION_DRY_RUN !== "false", + taskDirectoryOrphanGraceDays, serveUi: process.env.SERVE_UI !== undefined ? process.env.SERVE_UI === "true" diff --git a/server/src/index.ts b/server/src/index.ts index 905605d2e65..584e9e67697 100644 --- a/server/src/index.ts +++ b/server/src/index.ts @@ -1481,6 +1481,11 @@ async function startServerWithDatabaseTeardown( idleMs: config.gitRestorePointIdleDays > 0 ? config.gitRestorePointIdleDays * 24 * 60 * 60 * 1000 : null, keyDurable: config.storageProvider !== "s3" || Boolean(process.env.PAPERCLIP_SECRETS_MASTER_KEY?.trim()), } : undefined, + taskDirectoryRetention: config.taskDirectoryRetentionEnabled ? { + dryRun: config.taskDirectoryRetentionDryRun, + terminalDelayMs: config.gitRestorePointTerminalDelayDays * 24 * 60 * 60 * 1000, + orphanGraceMs: config.taskDirectoryOrphanGraceDays * 24 * 60 * 60 * 1000, + } : undefined, workspaceReaperCooldownDays: config.workspaceReaperCooldownDays, workspaceCompactionDelayMs: config.workspaceCompactionDelayHours === null ? null diff --git a/server/src/services/execution-workspaces.ts b/server/src/services/execution-workspaces.ts index caf9a90511c..63800f66b9e 100644 --- a/server/src/services/execution-workspaces.ts +++ b/server/src/services/execution-workspaces.ts @@ -6,10 +6,15 @@ import { measureRunPhase } from "./execution-preparation-timing.js"; import { assertExecutionWorkspaceRecordAccess, assertTaskWorkspaceExecutionAccess, assertTaskWorkspaceSourceProjectAccess } from "./task-workspace-access.js"; import { verifiedRecordedIsolatedRemoteSource, withIsolatedRepositorySourceLock } from "./isolated-remote-workspace-source.js"; import { expireReconstructableGitWorkspace, gitWorkspaceLastActivityAt, hasPendingGitExpiration, listIssuesUsingGitWorkspace } from "./git-workspace-expiration.js"; +import { expireIsolatedTaskDirectory, hasPendingTaskDirectoryRetention, isIsolatedTaskDirectoryWorkspace, isRetryableTaskDirectorySkip, + mayBeIsolatedTaskDirectoryWorkspace, readTaskDirectoryRetention, restoreIsolatedTaskDirectory, supersedeTaskDirectoryRestorePoint, + sweepIsolatedTaskDirectories, inspectIsolatedTaskDirectoryFolders, taskDirectoryFoldersForHints, taskDirectoryCandidateFilter, TASK_DIRECTORY_RESTORE_POINT_EXPIRED_WARNING, TASK_DIRECTORY_RETENTION_KEY, + TASK_DIRECTORY_RETRY_MS } from "./isolated-task-directory-retention.js"; import { hasPendingIsolatedRepositoryRehomeCleanup, isIsolatedRepositoryRehomeCandidate, rehomeExpiredIsolatedRestoration, rehomeIsolatedRepositoryWorkspace, sweepOrphanedIsolatedRepositorySources } from "./isolated-repository-rehome.js"; import { hasPendingNestedCloneMigration, isNestedCloneMigrationCandidate, nextNestedCloneMigrationBatch, pendingNestedCloneMigrationNames, listNestedCloneMigrationNames, migrateNestedRepositoryClone, NESTED_CLONE_MIGRATION_RETRY_REASONS, type NestedCloneMigrationRotation } from "./nested-clone-migration.js"; import type { StorageService } from "../storage/types.js"; +import { getStorageService } from "../storage/index.js"; import { readGitCacheRestoration, restoreGitCacheBase, recoverGitCacheExpirationLocks, GitCacheRestorationFailure, gitRestorePointExpired } from "./git-workspace-restoration.js"; export const GIT_RESTORE_POINT_EXPIRED_WARNING = "The saved state of this workspace expired, so it was reopened as a fresh workspace on its branch. Unpushed and uncommitted work from before it was cleaned up is no longer available."; @@ -181,6 +186,11 @@ export function bumpExecutionWorkspaceLifecycleGeneration( }; } +function reopenableWorkspaceMode() { + return or(eq(executionWorkspaces.mode, "isolated_workspace"), + sql`(${executionWorkspaces.metadata}->${TASK_DIRECTORY_RETENTION_KEY}) IS NOT NULL`); +} + function isClosedExecutionWorkspaceStatus(status: string | null | undefined): boolean { return status === "archived" || status === "cleanup_failed"; } @@ -309,6 +319,7 @@ export type ExecutionWorkspaceServiceOptions = { nestedCloneMigrationEnabled?: boolean; nestedCloneMigrationDryRun?: boolean; gitRestorePoints?: { storage: StorageService; terminalDelayMs: number; keyDurable: boolean; idleMs?: number | null }; + taskDirectoryRetention?: { dryRun: boolean; terminalDelayMs: number; orphanGraceMs: number; perSweep?: number; trackedLimit?: number }; terminalWorkspaceInspectionBackoffMs?: number; resolvePullRequestDetails?: PullRequestMergeDetailsResolver; now?: () => Date; @@ -1760,6 +1771,80 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic let isolatedOrphanSweepDueAt = 0; let isolatedOrphanCursor: string | null = null; let isolatedOrphanKept = false; + const taskDirectoryDeadlines = new Map(); + let taskDirectoryWalkDueAt = 0; + let taskDirectoryWalkCursor: string | null = null; + let taskDirectoryWalkRetryAt: number | null = null; + const taskDirectoryFolderDue = new Map(); + const taskDirectoryHints = new Set(); + const taskDirectoryRowSkips = new Map(); + const TASK_DIRECTORY_FOLDERS_PER_SWEEP = 8; + const TASK_DIRECTORY_HINTS_PER_SWEEP = 64; + const remember = (map: Map, key: K, value: V) => { + if (!map.has(key) && map.size >= 4096) map.delete(map.keys().next().value!); + map.set(key, value); + }; + const TASK_DIRECTORY_TRACKED_LIMIT = opts.taskDirectoryRetention?.trackedLimit ?? 4096; + const rememberFolder = (key: string, dueAt: number) => { + if (!taskDirectoryFolderDue.has(key) && taskDirectoryFolderDue.size >= TASK_DIRECTORY_TRACKED_LIMIT) { + taskDirectoryWalkDueAt = Math.min(taskDirectoryWalkDueAt, dueAt); + return; + } + taskDirectoryFolderDue.set(key, dueAt); + }; + async function runTaskDirectoryFolderWork(signal?: AbortSignal) { + const settings = opts.taskDirectoryRetention!; + const options = { dryRun: settings.dryRun, now: now(), orphanGraceMs: settings.orphanGraceMs, terminalDelayMs: settings.terminalDelayMs, + signal, beforeDelete: opts.beforeTerminalWorkspaceCleanup, + restorePoint: opts.gitRestorePoints ? { storage: opts.gitRestorePoints.storage, keyDurable: opts.gitRestorePoints.keyDurable } : undefined }; + const nowMs = options.now.getTime(); + let results: Awaited> = []; + try { + if (taskDirectoryWalkDueAt <= nowMs) { + const batch = await sweepIsolatedTaskDirectories(db, { ...options, after: taskDirectoryWalkCursor, limit: TASK_DIRECTORY_FOLDERS_PER_SWEEP }); + results = batch.results; + if (batch.retryAt !== null) taskDirectoryWalkRetryAt = Math.min(taskDirectoryWalkRetryAt ?? Infinity, batch.retryAt); + taskDirectoryWalkCursor = batch.next; + if (taskDirectoryWalkCursor) taskDirectoryWalkDueAt = nowMs; + else { + taskDirectoryWalkDueAt = taskDirectoryWalkRetryAt ?? Number.POSITIVE_INFINITY; + taskDirectoryWalkRetryAt = null; + } + } else { + const hints = [...taskDirectoryHints].slice(0, TASK_DIRECTORY_HINTS_PER_SWEEP); + for (const hint of hints) taskDirectoryHints.delete(hint); + const hinted = hints.length === 0 ? [] : await taskDirectoryFoldersForHints(db, { + workspaceIds: hints.filter(hint => hint.startsWith("workspace:")).map(hint => hint.slice("workspace:".length)), + issueIds: hints.filter(hint => hint.startsWith("issue:")).map(hint => hint.slice("issue:".length)), + }); + const folders = new Map(hinted.map(folder => [`${folder.companyId}/${folder.issueId}`, folder])); + for (const [key, dueAt] of taskDirectoryFolderDue) { + if (dueAt > nowMs) continue; + const [companyId, issueId] = key.split("/"); + folders.set(key, { companyId: companyId!, issueId: issueId! }); + } + const batch = [...folders.entries()].slice(0, TASK_DIRECTORY_FOLDERS_PER_SWEEP); + for (const [key] of batch) taskDirectoryFolderDue.delete(key); + for (const [key] of [...folders.entries()].slice(TASK_DIRECTORY_FOLDERS_PER_SWEEP)) rememberFolder(key, nowMs); + results = await inspectIsolatedTaskDirectoryFolders(db, batch.map(([, folder]) => folder), options); + } + } catch (error) { + signal?.throwIfAborted(); + logger.warn({ err: error }, "isolated task directory sweep failed; it retries later"); + taskDirectoryWalkDueAt = Math.min(taskDirectoryWalkDueAt, nowMs + TASK_DIRECTORY_RETRY_MS); + } + for (const folder of results) { + const key = `${folder.companyId}/${folder.issueId}`; + if (folder.walkRetryAt !== undefined) taskDirectoryWalkDueAt = Math.min(taskDirectoryWalkDueAt, folder.walkRetryAt); + if (folder.retryAt !== undefined) rememberFolder(key, folder.retryAt); + else taskDirectoryFolderDue.delete(key); + logger.info({ event: "execution_workspace.task_directory_cleanup", dryRun: settings.dryRun, ...folder }, "Isolated task directory inspected"); + } + taskDirectoryDeadlines.clear(); + if (Number.isFinite(taskDirectoryWalkDueAt)) taskDirectoryDeadlines.set("walk", taskDirectoryWalkDueAt); + if (taskDirectoryHints.size > 0) taskDirectoryDeadlines.set("hints", now().getTime()); + if (taskDirectoryFolderDue.size > 0) taskDirectoryDeadlines.set("folders", Math.min(...taskDirectoryFolderDue.values())); + } let terminalSweepRescanRequested = false; // The reaper freezes an upper bound on updatedAt at the start of each // rotation. The scan only reads candidates at or below the bound, so a steady @@ -3258,6 +3343,7 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic terminalSweepInProgress = true; try { if (options.compact !== false) await purgeDeferredCompactionTrash(signal); + if (opts.taskDirectoryRetention) await runTaskDirectoryFolderWork(signal); const baseCandidateFilter = and( sql`${executionWorkspaces.sourceIssueId} IS NOT NULL`, or(and(inArray(executionWorkspaces.status, ["active", "idle", "in_review"]), isNull(executionWorkspaces.closedAt)), @@ -3269,7 +3355,8 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic sql`(${executionWorkspaces.metadata}->'nestedCloneMigrationPending') IS NOT NULL`) : undefined, opts.gitCacheExpirationEnabled && opts.isolatedSourceRehomeEnabled ? and(inArray(executionWorkspaces.status, ["archived", "cleanup_failed"]), sql`(${executionWorkspaces.metadata}->'isolatedRepositoryRehome') IS NOT NULL`, - sql`(${executionWorkspaces.metadata}->'isolatedRepositoryRehome'->>'cleanedAt') IS NULL`) : undefined), + sql`(${executionWorkspaces.metadata}->'isolatedRepositoryRehome'->>'cleanedAt') IS NULL`) : undefined, + opts.taskDirectoryRetention ? taskDirectoryCandidateFilter() : undefined), ); // Continue the scan after the previous sweep's last row. The keyset // predicate uses the same (updatedAt, id) order as the query, so each @@ -3354,6 +3441,34 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic compactionFailed: 0, }; const readinessByWorkingTree = new Map>(); + let taskDirectoryBudget = opts.taskDirectoryRetention?.perSweep ?? 8; + const expireTaskDirectory = async (workspace: ExecutionWorkspaceRow, notBefore: Date) => { + const settings = opts.taskDirectoryRetention!; + const skipped = taskDirectoryRowSkips.get(workspace.id); + if (skipped && skipped.updatedAt === workspace.updatedAt.getTime() && (skipped.retryAt === null || skipped.retryAt > now().getTime())) { + if (skipped.retryAt !== null) terminalWorkspaceDeadlines.set(workspace.id, skipped.retryAt); + return; + } + if (taskDirectoryBudget <= 0) { + terminalWorkspaceDeadlines.set(workspace.id, now().getTime()); + return; + } + taskDirectoryBudget -= 1; + const expiration = await expireIsolatedTaskDirectory(db, workspace, { dryRun: settings.dryRun, now: now(), notBefore, signal, + beforeDelete: opts.beforeTerminalWorkspaceCleanup, + restorePoint: opts.gitRestorePoints ? { storage: opts.gitRestorePoints.storage, keyDurable: opts.gitRestorePoints.keyDurable } : undefined }); + if (expiration.candidate) result.eligible += 1; + if (expiration.expired) result.archived += 1; + const retryAt = !expiration.expired && isRetryableTaskDirectorySkip(expiration.skipReason) ? now().getTime() + TASK_DIRECTORY_RETRY_MS : null; + if (retryAt !== null) terminalWorkspaceDeadlines.set(workspace.id, retryAt); + else terminalWorkspaceDeadlines.delete(workspace.id); + if (expiration.expired) taskDirectoryRowSkips.delete(workspace.id); + else remember(taskDirectoryRowSkips, workspace.id, { updatedAt: workspace.updatedAt.getTime(), retryAt, issueId: workspace.sourceIssueId }); + logger.info({ event: "execution_workspace.task_directory_retention", executionWorkspaceId: workspace.id, + companyId: workspace.companyId, sourceIssueId: workspace.sourceIssueId, dryRun: settings.dryRun, + outcome: expiration.expired ? "removed" : settings.dryRun && expiration.candidate ? "dry_run" : "skipped", ...expiration }, + "Isolated task directory retention inspected"); + }; for (let workspace of candidates) { signal?.throwIfAborted(); @@ -3428,6 +3543,10 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic } if (nestedOnly) continue; } + if (opts.taskDirectoryRetention && hasPendingTaskDirectoryRetention(workspace)) { + await expireTaskDirectory(workspace, now()); + continue; + } const issueTree = await listWorkspaceIssueTree(workspace); const sourceIssue = issueTree.find((issue) => issue.id === workspace.sourceIssueId); const reopenPending = metadataHasReopenPendingConsumption( @@ -3482,6 +3601,15 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic } const expirationTerminalAt = Math.max(...expirationTree.map(issue => issueTerminalTimestamp(issue)!.getTime())); const latestTerminalAt = treeOpen ? expirationTerminalAt : Math.max(...issueTree.map(issue => issueTerminalTimestamp(issue)!.getTime())); + if (opts.taskDirectoryRetention && !treeOpen && !reopenPending && !isClosedExecutionWorkspaceStatus(workspace.status) + && mayBeIsolatedTaskDirectoryWorkspace(workspace) && await isIsolatedTaskDirectoryWorkspace(workspace)) { + const dueAt = latestTerminalAt + opts.taskDirectoryRetention.terminalDelayMs; + if (dueAt > now().getTime()) { + terminalWorkspaceDeadlines.set(workspace.id, dueAt); + result.skippedCooldown += 1; + } else await expireTaskDirectory(workspace, new Date(dueAt)); + continue; + } // Compaction runs once per terminal cycle, after its own delay and // before the archive cooldown, so a workspace the reaper cannot archive // yet (or ever) stops holding regenerable files. @@ -3862,6 +3990,17 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic terminalWorkspaceWorkSettled: (hints?: ReadonlySet) => { if (terminalSweepInProgress || terminalSweepCursor !== null) terminalSweepRescanRequested = true; pullRequestStateCache.clear(); + if (opts.taskDirectoryRetention) { + if (!hints) taskDirectoryRowSkips.clear(); + for (const hint of hints ?? []) { + if (!hint.startsWith("workspace:") && !hint.startsWith("issue:")) continue; + if (taskDirectoryHints.size < TASK_DIRECTORY_TRACKED_LIMIT) taskDirectoryHints.add(hint); + else taskDirectoryWalkDueAt = Math.min(taskDirectoryWalkDueAt, now().getTime()); + taskDirectoryDeadlines.set("hints", now().getTime()); + if (hint.startsWith("workspace:")) taskDirectoryRowSkips.delete(hint.slice("workspace:".length)); + else for (const [id, skip] of taskDirectoryRowSkips) if (`issue:${skip.issueId}` === hint) taskDirectoryRowSkips.delete(id); + } + } if (!hints) { terminalInspections.clear(); return; } for (const [id, inspection] of terminalInspections) { if (hints.has(`workspace:${id}`) || [...inspection.issueIds].some(issueId => hints.has(`issue:${issueId}`))) { @@ -3871,8 +4010,10 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic }, nextTerminalWorkspaceSweepAt: async () => { - if (terminalWorkspaceDeadlines.size === 0 && isolatedRehomeDeadlines.size === 0 && nestedCloneMigrationDeadlines.size === 0) return null; - const next = [...terminalWorkspaceDeadlines.values(), ...isolatedRehomeDeadlines.values(), ...nestedCloneMigrationDeadlines.values()].reduce((earliest, deadline) => Math.min(earliest, deadline), Infinity); + if (terminalWorkspaceDeadlines.size === 0 && isolatedRehomeDeadlines.size === 0 && nestedCloneMigrationDeadlines.size === 0 + && taskDirectoryDeadlines.size === 0) return null; + const next = [...terminalWorkspaceDeadlines.values(), ...isolatedRehomeDeadlines.values(), ...nestedCloneMigrationDeadlines.values(), + ...taskDirectoryDeadlines.values()].reduce((earliest, deadline) => Math.min(earliest, deadline), Infinity); const nowMs = now().getTime(); if (next <= nowMs && opts.terminalWorkspaceInspectionBackoffMs) { return Math.min(nowMs + opts.terminalWorkspaceInspectionBackoffMs, @@ -3931,7 +4072,7 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic )); const authorizedSnapshot = boundSnapshot ? await db.select().from(executionWorkspaces).where(and( eq(executionWorkspaces.id, input.workspaceId), eq(executionWorkspaces.companyId, issue.companyId), - eq(executionWorkspaces.mode, "isolated_workspace"), + reopenableWorkspaceMode(), )).then(rows => rows[0] ?? null) : null; if (!authorizedSnapshot) return { ok: false, code: "not_reopenable", message: "Execution workspace is not reopenable" }; await assertTaskWorkspaceExecutionAccess(db, input.authorizationActor, issue.companyId, { issueId: issue.id, workspaceId: authorizedSnapshot.id }); @@ -3939,7 +4080,7 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic const reopen = async (): Promise => { const freshSnapshot = await db.select().from(executionWorkspaces).where(and( eq(executionWorkspaces.id, input.workspaceId), eq(executionWorkspaces.companyId, issue.companyId), - eq(executionWorkspaces.mode, "isolated_workspace"), + reopenableWorkspaceMode(), )).then(rows => rows[0] ?? null); if (!freshSnapshot || freshSnapshot.sourceIssueId !== sourceIssueId) { return { ok: false, code: "not_reopenable", message: "Execution workspace source changed during reopen" }; @@ -4068,7 +4209,7 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic .where(and( eq(executionWorkspaces.id, input.workspaceId), eq(executionWorkspaces.companyId, issue.companyId), - eq(executionWorkspaces.mode, "isolated_workspace"), + reopenableWorkspaceMode(), )) .then((rows) => rows[0] ?? null); if (!row) { @@ -4148,7 +4289,15 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic }); let rebuildError: string | null = null; + let taskDirectoryWarning: string | null = null; + const taskDirectoryState = readTaskDirectoryRetention(row); try { + if (taskDirectoryState) { + const restored = await restoreIsolatedTaskDirectory({ storage: opts.gitRestorePoints?.storage ?? getStorageService(), workspace: row }); + if (restored.expired) taskDirectoryWarning = TASK_DIRECTORY_RESTORE_POINT_EXPIRED_WARNING; + logger.info({ event: "execution_workspace.task_directory_restore", executionWorkspaceId: row.id, companyId: row.companyId, + issueId: issue.id, ...restored }, "Isolated task directory restored for reopen"); + } const [assignee, organization, sourceProject] = await Promise.all([ boundTask.assigneeAgentId ? tx.select({ companyId: agents.companyId, permissions: agents.permissions }).from(agents) .where(and(eq(agents.id, boundTask.assigneeAgentId), eq(agents.companyId, row.companyId))) @@ -4324,6 +4473,10 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic // receive newer task commits; the next expiration records a fresh recipe. if (freshStart) delete nextMetadata.gitCacheRestoration; else if (recipe) nextMetadata.gitCacheRestoration = { ...nextMetadata.gitCacheRestoration as Record, restoredAt: now().toISOString() }; + if (taskDirectoryState) { + delete nextMetadata[TASK_DIRECTORY_RETENTION_KEY]; + await supersedeTaskDirectoryRestorePoint(tx, row); + } const activeMetadata = setMetadataReopenPendingConsumption(nextMetadata, now()); await measureRunPhase("workspace.notification", () => notifyTerminalWorkspaceWork(tx, `workspace:${row.id}`)); const activeRow = await tx @@ -4369,14 +4522,16 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic outcome: "reopened", generation: nextGeneration, ...(freshStart ? { restorePointExpired: true, warning: GIT_RESTORE_POINT_EXPIRED_WARNING } : {}), + ...(taskDirectoryWarning ? { restorePointExpired: true, warning: taskDirectoryWarning } : {}), }, }); - if (freshStart) { + const reopenWarning = freshStart ? GIT_RESTORE_POINT_EXPIRED_WARNING : taskDirectoryWarning; + if (reopenWarning) { const { issueService } = await import("./issues.js"); - await issueService(db).addComment(issue.id, GIT_RESTORE_POINT_EXPIRED_WARNING, {}, { authorType: "system" }, tx); + await issueService(db).addComment(issue.id, reopenWarning, {}, { authorType: "system" }, tx); } return { ok: true, reopened: true, workspace: toExecutionWorkspace(activeRow), generation: nextGeneration, - ...(freshStart ? { warning: GIT_RESTORE_POINT_EXPIRED_WARNING } : {}) }; + ...(reopenWarning ? { warning: reopenWarning } : {}) }; }).catch((error): ReopenClosedIsolatedExecutionWorkspaceResult => { logger.warn({ error, executionWorkspaceId: snapshot.id }, "Execution workspace reopen failed"); return { ok: false, code: "rebuild_failed", message: recipe ? new GitCacheRestorationFailure().message : "Failed to rebuild the execution workspace" }; diff --git a/server/src/services/git-restore-point-ledger.ts b/server/src/services/git-restore-point-ledger.ts index 2070e2f1b1e..04e7c6333f7 100644 --- a/server/src/services/git-restore-point-ledger.ts +++ b/server/src/services/git-restore-point-ledger.ts @@ -77,7 +77,9 @@ export function gitRestorePointRetentionService(db: Db, options: GitRestorePoint eq(executionWorkspaceRestorePoints.status, "active"), eq(executionWorkspaceRestorePoints.reviewGeneration, row.reviewGeneration), ); - const deleteAfter = !tree.exists || tree.open || !tree.closedAt ? null : new Date(tree.closedAt.getTime() + retentionMs); + const retainedFrom = tree.closedAt && row.activatedAt && row.objectKey.includes("/task-directory/") + ? Math.max(tree.closedAt.getTime(), row.activatedAt.getTime()) : tree.closedAt?.getTime(); + const deleteAfter = !tree.exists || tree.open || retainedFrom === undefined ? null : new Date(retainedFrom + retentionMs); if (!tree.exists || (deleteAfter && deleteAfter.getTime() <= at.getTime())) { const claimed = await db.update(executionWorkspaceRestorePoints) .set({ status: tree.exists ? "expiring" : "delete_requested", lastError: null, updatedAt: at }) diff --git a/server/src/services/git-restore-point-storage.ts b/server/src/services/git-restore-point-storage.ts index 87bcae36578..bb32379d92a 100644 --- a/server/src/services/git-restore-point-storage.ts +++ b/server/src/services/git-restore-point-storage.ts @@ -18,6 +18,7 @@ import { } from "./git-restore-point.js"; import { notifyGitRestorePointWork } from "./git-restore-point-ledger.js"; import { gitCacheCommand } from "./git-workspace-restoration.js"; +import { TASK_DIRECTORY_RETENTION_KEY } from "./isolated-task-directory-snapshot.js"; export const GIT_RESTORE_POINT_SCHEMA = "paperclip.git-restore-point.v1"; const NAMESPACE = "git-restore-points"; @@ -99,45 +100,11 @@ export async function storeGitRestorePoint(input: { const identity = { companyId: input.workspace.companyId, workspaceId: input.workspace.id, restorePointId: id, generation: input.generation }; const sealed = await sealRestorePoint(captured.payload, identity); const objectKey = restorePointObjectKey(input.workspace.companyId, input.workspace.id, input.generation, id, input.checkout); - const [ledger] = await input.db.transaction(async (tx) => { - await notifyGitRestorePointWork(tx, `workspace:${input.workspace.id}`); - await tx.update(executionWorkspaceRestorePoints).set({ status: "superseded", updatedAt: new Date() }) - .where(and(eq(executionWorkspaceRestorePoints.executionWorkspaceId, input.workspace.id), - eq(executionWorkspaceRestorePoints.generation, input.generation), - eq(executionWorkspaceRestorePoints.checkoutName, input.checkout ?? ""), - eq(executionWorkspaceRestorePoints.status, "pending"))); - return tx.insert(executionWorkspaceRestorePoints).values({ - companyId: input.workspace.companyId, - executionWorkspaceId: input.workspace.id, - sourceIssueId: input.workspace.sourceIssueId, - generation: input.generation, - checkoutName: input.checkout ?? "", - objectKey, - sha256: sealed.sha256, - byteSize: sealed.ciphertext.length, - status: "pending", - }).returning({ id: executionWorkspaceRestorePoints.id }); - }); - try { - await input.storage.putFile({ - objectKey, - companyId: input.workspace.companyId, - namespace: NAMESPACE, - originalFilename: null, - contentType: "application/octet-stream", - body: sealed.ciphertext, - }); - const stored = await readObject(input.storage, input.workspace.companyId, objectKey, input.signal); - if (createHash("sha256").update(stored).digest("hex") !== sealed.sha256) { - throw new RestorePointRestoreFailure("stored_restore_point_mismatch"); - } - } catch (error) { - await abandonGitRestorePoint(input.db, ledger!.id).catch(() => undefined); - throw error; - } + const ledgerId = await storeSealedRestorePoint({ db: input.db, storage: input.storage, workspace: input.workspace, + generation: input.generation, checkoutName: input.checkout ?? "", objectKey, sealed, signal: input.signal }); const { manifest } = captured; return { - ledgerId: ledger!.id, + ledgerId, manifest, ref: { schema: GIT_RESTORE_POINT_SCHEMA, @@ -159,6 +126,55 @@ export async function storeGitRestorePoint(input: { }; } +export async function storeSealedRestorePoint(input: { + db: Db; + storage: StorageService; + workspace: { companyId: string; id: string; sourceIssueId: string | null }; + generation: number; + checkoutName: string; + objectKey: string; + sealed: { ciphertext: Buffer; sha256: string }; + signal?: AbortSignal; +}): Promise { + const [ledger] = await input.db.transaction(async (tx) => { + await notifyGitRestorePointWork(tx, `workspace:${input.workspace.id}`); + await tx.update(executionWorkspaceRestorePoints).set({ status: "superseded", updatedAt: new Date() }) + .where(and(eq(executionWorkspaceRestorePoints.executionWorkspaceId, input.workspace.id), + eq(executionWorkspaceRestorePoints.generation, input.generation), + eq(executionWorkspaceRestorePoints.checkoutName, input.checkoutName), + eq(executionWorkspaceRestorePoints.status, "pending"))); + return tx.insert(executionWorkspaceRestorePoints).values({ + companyId: input.workspace.companyId, + executionWorkspaceId: input.workspace.id, + sourceIssueId: input.workspace.sourceIssueId, + generation: input.generation, + checkoutName: input.checkoutName, + objectKey: input.objectKey, + sha256: input.sealed.sha256, + byteSize: input.sealed.ciphertext.length, + status: "pending", + }).returning({ id: executionWorkspaceRestorePoints.id }); + }); + try { + await input.storage.putFile({ + objectKey: input.objectKey, + companyId: input.workspace.companyId, + namespace: NAMESPACE, + originalFilename: null, + contentType: "application/octet-stream", + body: input.sealed.ciphertext, + }); + const stored = await readRestorePointObject(input.storage, input.workspace.companyId, input.objectKey, input.signal); + if (createHash("sha256").update(stored).digest("hex") !== input.sealed.sha256) { + throw new RestorePointRestoreFailure("stored_restore_point_mismatch"); + } + } catch (error) { + await abandonGitRestorePoint(input.db, ledger!.id).catch(() => undefined); + throw error; + } + return ledger!.id; +} + export async function activateGitRestorePoints(tx: Tx, input: { ledgerIds: string[]; workspaceId: string; at: Date }) { if (input.ledgerIds.length === 0) return; await notifyGitRestorePointWork(tx, `workspace:${input.workspaceId}`); @@ -200,7 +216,7 @@ export async function abandonGitRestorePoint(db: Db, ledgerId: string) { .where(and(eq(executionWorkspaceRestorePoints.id, ledgerId), inArray(executionWorkspaceRestorePoints.status, ["pending", "active"]))); } -async function readObject(storage: StorageService, companyId: string, objectKey: string, signal?: AbortSignal) { +export async function readRestorePointObject(storage: StorageService, companyId: string, objectKey: string, signal?: AbortSignal) { const { stream } = await storage.getObject(companyId, objectKey); const chunks: Buffer[] = []; let total = 0; @@ -221,7 +237,7 @@ export async function loadGitRestorePoint(input: { signal?: AbortSignal; }): Promise<{ payload: Buffer; manifest: RestorePointManifest }> { if (input.ref.expiredAt) throw new RestorePointRestoreFailure("restore_point_expired"); - const ciphertext = await readObject(input.storage, input.workspace.companyId, input.ref.objectKey, input.signal) + const ciphertext = await readRestorePointObject(input.storage, input.workspace.companyId, input.ref.objectKey, input.signal) .catch((error) => { if (error instanceof RestorePointRestoreFailure) throw error; throw new RestorePointRestoreFailure("restore_point_unavailable"); @@ -278,28 +294,36 @@ export async function applyGitRestorePointToWorktree(input: { if (!matches) await applyRestorePoint({ cwd: input.worktreePath, manifest, signal: input.signal }); } +function expireRestorePointRecipe(key: string, recipe: Record, objectKey: string, at: string) { + const expire = (ref: Record | undefined) => ref?.objectKey === objectKey ? { ...ref, expiredAt: at } : ref; + if (key === TASK_DIRECTORY_RETENTION_KEY) return recipe.restorePoint ? { ...recipe, restorePoint: expire(recipe.restorePoint) } : recipe; + return { + ...recipe, + ...(recipe.restorePoint ? { restorePoint: expire(recipe.restorePoint) } : {}), + ...(recipe.contents ? { contents: { ...recipe.contents, checkouts: (recipe.contents.checkouts ?? []).map((checkout: Record) => + checkout.restorePoint ? { ...checkout, restorePoint: expire(checkout.restorePoint) } : checkout) } } : {}), + }; +} + export async function markGitRestorePointExpired(db: Db, restorePoint: { companyId: string; executionWorkspaceId: string; objectKey: string }) { const at = new Date().toISOString(); - for (let attempt = 0; attempt < 3; attempt += 1) { - const [row] = await db.select({ metadata: executionWorkspaces.metadata }).from(executionWorkspaces) - .where(and(eq(executionWorkspaces.id, restorePoint.executionWorkspaceId), eq(executionWorkspaces.companyId, restorePoint.companyId))); - const recipe = row?.metadata?.gitCacheRestoration as Record | undefined; - if (!recipe) return; - const expire = (ref: Record | undefined) => ref?.objectKey === restorePoint.objectKey ? { ...ref, expiredAt: at } : ref; - const next = { - ...recipe, - ...(recipe.restorePoint ? { restorePoint: expire(recipe.restorePoint) } : {}), - ...(recipe.contents ? { contents: { ...recipe.contents, checkouts: (recipe.contents.checkouts ?? []).map((checkout: Record) => - checkout.restorePoint ? { ...checkout, restorePoint: expire(checkout.restorePoint) } : checkout) } } : {}), - }; - if (JSON.stringify(next) === JSON.stringify(recipe)) return; - const updated = await db.update(executionWorkspaces).set({ - metadata: sql`jsonb_set(${executionWorkspaces.metadata}, '{gitCacheRestoration}', ${JSON.stringify(next)}::jsonb)`, - updatedAt: new Date(), - }).where(and(eq(executionWorkspaces.id, restorePoint.executionWorkspaceId), eq(executionWorkspaces.companyId, restorePoint.companyId), - sql`${executionWorkspaces.metadata}->'gitCacheRestoration' = ${JSON.stringify(recipe)}::jsonb`)) - .returning({ id: executionWorkspaces.id }); - if (updated.length === 1) return; + for (const key of ["gitCacheRestoration", TASK_DIRECTORY_RETENTION_KEY]) { + let settled = false; + for (let attempt = 0; attempt < 3 && !settled; attempt += 1) { + const [row] = await db.select({ metadata: executionWorkspaces.metadata }).from(executionWorkspaces) + .where(and(eq(executionWorkspaces.id, restorePoint.executionWorkspaceId), eq(executionWorkspaces.companyId, restorePoint.companyId))); + const recipe = row?.metadata?.[key] as Record | undefined; + if (!recipe) { settled = true; break; } + const next = expireRestorePointRecipe(key, recipe, restorePoint.objectKey, at); + if (JSON.stringify(next) === JSON.stringify(recipe)) { settled = true; break; } + const updated = await db.update(executionWorkspaces).set({ + metadata: sql`jsonb_set(${executionWorkspaces.metadata}, ${`{${key}}`}::text[], ${JSON.stringify(next)}::jsonb)`, + updatedAt: new Date(), + }).where(and(eq(executionWorkspaces.id, restorePoint.executionWorkspaceId), eq(executionWorkspaces.companyId, restorePoint.companyId), + sql`${executionWorkspaces.metadata}->${key} = ${JSON.stringify(recipe)}::jsonb`)) + .returning({ id: executionWorkspaces.id }); + settled = updated.length === 1; + } + if (!settled) throw new RestorePointRestoreFailure("restore_point_expiry_conflict"); } - throw new RestorePointRestoreFailure("restore_point_expiry_conflict"); } diff --git a/server/src/services/git-workspace-expiration.ts b/server/src/services/git-workspace-expiration.ts index c551f7471a5..12cb8e52dda 100644 --- a/server/src/services/git-workspace-expiration.ts +++ b/server/src/services/git-workspace-expiration.ts @@ -8,6 +8,7 @@ import { executionWorkspaces, issues, heartbeatRuns, nativeRunFinalizations, env workspaceRuntimeServices, issueRecoveryActions, projectWorkspaces, withDedicatedDbConnection, type Db } from "@paperclipai/db"; import { createGitRemoteAuthProvider } from "./git-credentials.js"; import type { StorageService } from "../storage/types.js"; +import { TASK_DIRECTORY_RETENTION_KEY } from "./isolated-task-directory-snapshot.js"; import { currentRestorePointSnapshot, RestorePointSkip, type RestorePointLimits } from "./git-restore-point.js"; import { abandonGitRestorePoint, abandonGitRestorePointsByKey, activateGitRestorePoints, restorePointHistoryUnchanged, restorePointSnapshotMatches, storeGitRestorePoint } from "./git-restore-point-storage.js"; import { withIsolatedRepositorySourceLock, verifiedRecordedIsolatedRemoteSource } from "./isolated-remote-workspace-source.js"; @@ -151,8 +152,13 @@ export async function gitWorkspaceLastActivityAt(db: Db | Tx, workspace: Workspa return at ? new Date(at) : null; } -export async function isGitWorkspaceExpirationEligible(tx: Tx, workspace: Workspace, now: Date, idleCutoff?: Date) { +export async function isGitWorkspaceExpirationEligible(tx: Tx, workspace: Workspace, now: Date, idleCutoff?: Date, + options: { closedSiblingsAllowed?: boolean } = {}) { if (workspace.metadata?.reopenPendingConsumption === true) return false; + const siblingBlocks = options.closedSiblingsAllowed + ? sql`AND (other.status NOT IN ('archived', 'cleanup_failed') OR other.closed_at IS NULL + OR other.metadata->${TASK_DIRECTORY_RETENTION_KEY}->>'removed' = 'false')` + : sql``; const closedTree = idleCutoff ? sql` NOT EXISTS (SELECT 1 FROM tree WHERE updated_at > ${idleCutoff.toISOString()}::timestamptz) AND NOT EXISTS (SELECT 1 FROM bound WHERE updated_at > ${idleCutoff.toISOString()}::timestamptz) @@ -172,7 +178,7 @@ export async function isGitWorkspaceExpirationEligible(tx: Tx, workspace: Worksp SELECT CASE WHEN EXISTS (SELECT 1 FROM ${executionWorkspaces} other WHERE other.id <> ${workspace.id} AND (other.cwd = ${workspace.cwd} OR other.provider_ref = ${workspace.cwd} - OR left(other.cwd, length(${workspace.cwd}) + 1) = ${workspace.cwd} || '/')) + OR left(other.cwd, length(${workspace.cwd}) + 1) = ${workspace.cwd} || '/') ${siblingBlocks}) OR EXISTS (SELECT 1 FROM ${projectWorkspaces} WHERE cwd = ${workspace.cwd} OR left(cwd, length(${workspace.cwd}) + 1) = ${workspace.cwd} || '/') THEN false ELSE ( diff --git a/server/src/services/heartbeat/environment-selection.ts b/server/src/services/heartbeat/environment-selection.ts index 959a352902a..9910ab0b5b7 100644 --- a/server/src/services/heartbeat/environment-selection.ts +++ b/server/src/services/heartbeat/environment-selection.ts @@ -18,6 +18,7 @@ import { } from "../execution-workspace-policy.js"; import { assertTaskWorkspaceExecutionAccess, assertTaskWorkspaceSourceProjectAccess } from "../task-workspace-access.js"; import { shouldUseIsolatedTaskDirectory } from "../isolated-task-directory.js"; +import { readTaskDirectoryRetention } from "../isolated-task-directory-retention.js"; import { findNativeChatWorkspaceScope, nativeChatWorkspaceCwd, @@ -116,7 +117,8 @@ export async function selectHeartbeatEnvironment(db: Db, input: HeartbeatEnviron if (existingExecutionWorkspace && issueId && !isDotRun && !fresh && existingExecutionWorkspace.id === readNonEmptyString(issueRef?.executionWorkspaceId) && (existingExecutionWorkspace.status === "archived" || existingExecutionWorkspace.status === "cleanup_failed") - && readGitCacheExpiration(existingExecutionWorkspace as Parameters[0])?.workspaceRemoved) { + && (readGitCacheExpiration(existingExecutionWorkspace as Parameters[0])?.workspaceRemoved + || readTaskDirectoryRetention(existingExecutionWorkspace) !== null)) { const [boundIssue] = await db.select({ id: issues.id, companyId: issues.companyId, projectId: issues.projectId }) .from(issues).where(and(eq(issues.id, issueId), eq(issues.companyId, agent.companyId))); if (!boundIssue) throw new Error("Execution workspace issue is unavailable"); diff --git a/server/src/services/isolated-task-directory-retention.ts b/server/src/services/isolated-task-directory-retention.ts new file mode 100644 index 00000000000..cb5a8dc8a37 --- /dev/null +++ b/server/src/services/isolated-task-directory-retention.ts @@ -0,0 +1,627 @@ +import { randomUUID } from "node:crypto"; +import fs from "node:fs/promises"; +import path from "node:path"; +import { and, eq, inArray, or, sql } from "drizzle-orm"; +import { environmentLeases, executionWorkspaceRestorePoints, executionWorkspaces, issueRecoveryActions, issues, nativeRunFinalizations, + projectWorkspaces, withDedicatedDbConnection, workspaceRuntimeServices, type Db } from "@paperclipai/db"; +import type { StoredSecretVersionMaterial } from "../secrets/types.js"; +import type { StorageService } from "../storage/types.js"; +import { resolvePaperclipInstanceRoot } from "../home-paths.js"; +import { openRestorePoint, sealRestorePoint } from "./git-restore-point.js"; +import { notifyGitRestorePointWork } from "./git-restore-point-ledger.js"; +import { abandonGitRestorePoint, activateGitRestorePoints, readRestorePointObject, storeSealedRestorePoint } from "./git-restore-point-storage.js"; +import { allocatedBytes, describeGitExpirationFailure, expirationScope, isGitWorkspaceExpirationEligible, type GitExpirationFailure } from "./git-workspace-expiration.js"; +import { IsolatedRepositorySourceBusy, withIsolatedRepositorySourceLock } from "./isolated-remote-workspace-source.js"; +import { logActivity } from "./activity-log.js"; +import { + captureTaskDirectorySnapshot, + inspectTaskDirectory, + materializeTaskDirectorySnapshot, + newestTaskDirectoryMtime, + removeTaskDirectoryTree, + shortSiblingName, + TASK_DIRECTORY_RETENTION_KEY, + TaskDirectoryRestoreFailure, + TaskDirectorySnapshotSkip, + type TaskDirectorySnapshotLimits, +} from "./isolated-task-directory-snapshot.js"; + +export { TASK_DIRECTORY_RETENTION_KEY } from "./isolated-task-directory-snapshot.js"; +export const TASK_DIRECTORY_RETENTION_SCHEMA = "paperclip.task-directory-retention.v1"; +export const TASK_DIRECTORY_RESTORE_POINT_SCHEMA = "paperclip.task-directory-restore-point.v1"; +export const TASK_DIRECTORY_RETENTION_REASON = "isolated task directory retention"; +export const TASK_DIRECTORY_RESTORE_POINT_EXPIRED_WARNING = "The saved files of this task directory expired, so it was reopened as an empty directory. Files from before it was cleaned up are no longer available."; +export const TASK_DIRECTORY_RETRY_MS = 60 * 60 * 1000; +export const TASK_DIRECTORY_RECHECK_MS = 24 * 60 * 60 * 1000; +const TRASH_GRACE_MS = 60 * 60 * 1000; +const NAMESPACE = "git-restore-points"; +const MAX_RESTORE_POINT_BYTES = 512 * 1024 * 1024; +const IDENTITY = /^[a-zA-Z0-9_-]+$/; +const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; +const TRASH = /^\.(expired|restoring)-[0-9a-f]{8,}$/; +const RETRYABLE_SKIPS = new Set(["source_busy", "lifecycle_busy", "workspace_changed", "live_or_unresolved_consumer", + "task_directory_changed", "inspection_failed"]); + +type Workspace = typeof executionWorkspaces.$inferSelect; + +export type TaskDirectoryRestorePointRef = { + schema: typeof TASK_DIRECTORY_RESTORE_POINT_SCHEMA; + id: string; + objectKey: string; + sha256: string; + byteSize: number; + key: StoredSecretVersionMaterial; + generation: number; + digest: string; + files: number; + excluded: number; + expiredAt?: string; +}; + +export type TaskDirectoryRetention = { + schema: typeof TASK_DIRECTORY_RETENTION_SCHEMA; + generation: number; + removed: boolean; + trash: string; + restorePoint: TaskDirectoryRestorePointRef; + removedAt?: string; +}; + +export type TaskDirectoryRestorePointOptions = { storage: StorageService; keyDurable: boolean; limits?: TaskDirectorySnapshotLimits }; + +export type TaskDirectoryRetentionResult = { + candidate: boolean; + expired: boolean; + restorePoint: boolean; + candidateBytes: number; + reclaimedBytes: number; + skipReason: string | null; + failure?: GitExpirationFailure; +}; + +export function readTaskDirectoryRetention(workspace: { metadata?: Record | null }): TaskDirectoryRetention | null { + const state = workspace.metadata?.[TASK_DIRECTORY_RETENTION_KEY] as TaskDirectoryRetention | undefined; + return state?.schema === TASK_DIRECTORY_RETENTION_SCHEMA ? state : null; +} + +export function hasPendingTaskDirectoryRetention(workspace: Pick) { + const state = readTaskDirectoryRetention(workspace); + return Boolean(state && !state.removed && ["archived", "cleanup_failed"].includes(workspace.status)); +} + +export function isRetryableTaskDirectorySkip(reason: string | null) { + return reason !== null && RETRYABLE_SKIPS.has(reason); +} + +async function instanceRoot() { + return fs.realpath(resolvePaperclipInstanceRoot()).catch(() => null); +} + +export async function isolatedTaskDirectoriesRoot() { + const root = await instanceRoot(); + return root ? path.join(root, "isolated-workspaces") : null; +} + +export async function canonicalTaskDirectory(companyId: string, issueId: string) { + if (!IDENTITY.test(companyId) || !IDENTITY.test(issueId)) return null; + const root = await isolatedTaskDirectoriesRoot(); + return root ? path.join(root, companyId, issueId) : null; +} + +export function mayBeIsolatedTaskDirectoryWorkspace(workspace: Pick) { + return Boolean(workspace.sourceIssueId && workspace.cwd) && workspace.strategyType === "project_primary" + && workspace.providerType === "local_fs" && !workspace.repoUrl && !workspace.branchName + && (workspace.providerRef === null || workspace.providerRef === workspace.cwd) + && (workspace.mode === "isolated_workspace" || workspace.mode === "shared_workspace"); +} + +export async function isIsolatedTaskDirectoryWorkspace(workspace: Pick) { + if (!mayBeIsolatedTaskDirectoryWorkspace(workspace)) return false; + return workspace.cwd === await canonicalTaskDirectory(workspace.companyId, workspace.sourceIssueId!); +} + +function restorePointObjectKey(companyId: string, workspaceId: string, generation: number, id: string) { + return `${companyId}/${NAMESPACE}/${workspaceId}/${generation}/task-directory/${id}.pcrp`; +} + +function validateRestorePointRef(ref: TaskDirectoryRestorePointRef | null | undefined, workspace: { companyId: string; id: string }) { + if (!ref || ref.schema !== TASK_DIRECTORY_RESTORE_POINT_SCHEMA || typeof ref.id !== "string" || !UUID.test(ref.id) + || !Number.isSafeInteger(ref.generation) || ref.generation < 1 + || ref.objectKey !== restorePointObjectKey(workspace.companyId, workspace.id, ref.generation, ref.id) + || !/^[0-9a-f]{64}$/.test(ref.sha256) || !/^[0-9a-f]{64}$/.test(ref.digest) + || !Number.isSafeInteger(ref.byteSize) || ref.byteSize <= 0 || ref.byteSize > MAX_RESTORE_POINT_BYTES + || !ref.key || typeof ref.key !== "object" || Array.isArray(ref.key)) { + throw new TaskDirectoryRestoreFailure("invalid_restore_point_reference"); + } + return ref; +} + +function skipReason(error: unknown) { + if (error instanceof TaskDirectorySnapshotSkip) return error.reason; + if (error instanceof IsolatedRepositorySourceBusy) return "source_busy"; + if (error instanceof Error && (error as NodeJS.ErrnoException).code === "ENOENT") return "task_directory_changed"; + return error instanceof Error && /^[a-z][a-z_]+$/.test(error.message) ? error.message : "inspection_failed"; +} + +function recordSkip(result: { skipReason: string | null; failure?: GitExpirationFailure }, error: unknown) { + result.skipReason = skipReason(error); + if (result.skipReason === "inspection_failed") result.failure = describeGitExpirationFailure(error); +} + +async function directoryState(target: string) { + const stat = await fs.lstat(target).catch((error: NodeJS.ErrnoException) => { + if (error.code === "ENOENT") return null; + throw error; + }); + if (!stat) return "missing" as const; + if (stat.isSymbolicLink() || !stat.isDirectory() || await fs.realpath(target) !== target) throw new Error("unsafe_task_directory"); + return "present" as const; +} + +async function exists(target: string) { + return fs.lstat(target).then(() => true, (error: NodeJS.ErrnoException) => { + if (error.code === "ENOENT") return false; + throw error; + }); +} + +async function issueBoundToWorkspace(db: Db | Parameters[0]>[0], workspace: Workspace) { + const [bound] = await db.select({ id: issues.id }).from(issues).where(and(eq(issues.companyId, workspace.companyId), + eq(issues.id, workspace.sourceIssueId!), eq(issues.executionWorkspaceId, workspace.id))); + return Boolean(bound); +} + +async function storeTaskDirectoryRestorePoint(db: Db, storage: StorageService, workspace: Workspace, generation: number, + captured: Awaited>, signal?: AbortSignal) { + const id = randomUUID(); + const sealed = await sealRestorePoint(captured.payload, { companyId: workspace.companyId, workspaceId: workspace.id, restorePointId: id, generation }); + const objectKey = restorePointObjectKey(workspace.companyId, workspace.id, generation, id); + const ledgerId = await storeSealedRestorePoint({ db, storage, workspace: { companyId: workspace.companyId, id: workspace.id, + sourceIssueId: workspace.sourceIssueId }, generation, checkoutName: "", objectKey, sealed, signal }); + const ref: TaskDirectoryRestorePointRef = { schema: TASK_DIRECTORY_RESTORE_POINT_SCHEMA, id, objectKey, sha256: sealed.sha256, + byteSize: sealed.ciphertext.length, key: sealed.key, generation, digest: captured.digest, files: captured.files, excluded: captured.excluded }; + return { ledgerId, ref }; +} + +export async function expireIsolatedTaskDirectory(db: Db, snapshot: Workspace, options: { + dryRun: boolean; + now: Date; + notBefore: Date; + restorePoint?: TaskDirectoryRestorePointOptions; + signal?: AbortSignal; + beforeDelete?: (workspace: Workspace) => Promise; +}): Promise { + const result: TaskDirectoryRetentionResult = { candidate: false, expired: false, restorePoint: false, candidateBytes: 0, reclaimedBytes: 0, skipReason: null }; + let pending: string | null = null; + if (!await isIsolatedTaskDirectoryWorkspace(snapshot)) return { ...result, skipReason: "not_task_directory" }; + const closed = ["archived", "cleanup_failed"].includes(snapshot.status); + const existing = readTaskDirectoryRetention(snapshot); + if (existing?.removed) return { ...result, skipReason: "already_removed" }; + if (!existing && options.now.getTime() < options.notBefore.getTime()) return { ...result, skipReason: "not_due" }; + if (!existing && !options.dryRun) { + if (!options.restorePoint) return { ...result, skipReason: "restore_points_disabled" }; + if (!options.restorePoint.keyDurable) return { ...result, skipReason: "restore_point_key_not_durable" }; + } + try { + return await withIsolatedRepositorySourceLock(db, snapshot.companyId, snapshot.sourceIssueId!, () => + withDedicatedDbConnection(db, connection => connection.transaction(async tx => { + const acquired = await tx.execute<{ locked: boolean }>(sql`select pg_try_advisory_xact_lock(hashtextextended(${`execution_workspace_lifecycle:${snapshot.id}`}, 0)) as locked`); + if (!acquired[0]?.locked) throw new Error("lifecycle_busy"); + let [workspace] = await db.select().from(executionWorkspaces).where(and(eq(executionWorkspaces.id, snapshot.id), + eq(executionWorkspaces.companyId, snapshot.companyId))); + if (!workspace || workspace.updatedAt.getTime() !== snapshot.updatedAt.getTime()) throw new Error("workspace_changed"); + if (!await issueBoundToWorkspace(tx, workspace)) throw new Error("issue_not_bound"); + if (!await isGitWorkspaceExpirationEligible(tx, workspace, options.now, undefined, { closedSiblingsAllowed: true })) { + throw new Error("live_or_unresolved_consumer"); + } + const cwd = workspace.cwd!; + let state = readTaskDirectoryRetention(workspace); + const present = await directoryState(cwd) === "present"; + if (!state) { + if (!present) throw new Error("missing_task_directory"); + result.candidateBytes = await allocatedBytes(cwd, () => { options.signal?.throwIfAborted(); return true; }); + const captured = await captureTaskDirectorySnapshot(cwd, { limits: options.restorePoint?.limits, signal: options.signal }); + result.candidate = true; + if (options.dryRun) return result; + const generation = Number(workspace.metadata?.lifecycleGeneration ?? 0) + 1; + const stored = await storeTaskDirectoryRestorePoint(db, options.restorePoint!.storage, workspace, generation, captured, options.signal); + pending = stored.ledgerId; + result.restorePoint = true; + state = { schema: TASK_DIRECTORY_RETENTION_SCHEMA, generation, removed: false, + trash: shortSiblingName(cwd, ".expired-"), restorePoint: stored.ref }; + if (await exists(state.trash)) throw new Error("unknown_task_directory_trash"); + const metadata = { ...workspace.metadata, lifecycleGeneration: generation, [TASK_DIRECTORY_RETENTION_KEY]: state }; + const archive = closed ? { metadata, updatedAt: options.now } : { status: "archived", closedAt: options.now, + cleanupEligibleAt: options.now, cleanupReason: TASK_DIRECTORY_RETENTION_REASON, metadata, updatedAt: options.now }; + [workspace] = await db.transaction(async archiveTx => { + const rows = await archiveTx.update(executionWorkspaces).set(archive).where(eq(executionWorkspaces.id, workspace!.id)).returning(); + await activateGitRestorePoints(archiveTx, { ledgerIds: [stored.ledgerId], workspaceId: workspace!.id, at: options.now }); + return rows; + }); + pending = null; + if (!closed) { + await logActivity(db, { + companyId: workspace!.companyId, + actorType: "system", + actorId: "workspace_terminality_reaper", + action: "execution_workspace.task_directory_archived", + entityType: "execution_workspace", + entityId: workspace!.id, + details: { sourceIssueId: workspace!.sourceIssueId, restorePointId: stored.ref.id, cleanupReason: TASK_DIRECTORY_RETENTION_REASON }, + }); + } + } else { + result.candidate = true; + if (present) result.candidateBytes = await allocatedBytes(cwd, () => { options.signal?.throwIfAborted(); return true; }); + if (options.dryRun) return result; + } + if (!workspace) throw new Error("workspace_changed"); + await options.beforeDelete?.(workspace); + if (!await isGitWorkspaceExpirationEligible(tx, workspace, options.now, undefined, { closedSiblingsAllowed: true })) { + throw new Error("live_or_unresolved_consumer"); + } + if (await directoryState(cwd) === "present") { + const current = await inspectTaskDirectory(cwd, { limits: options.restorePoint?.limits, signal: options.signal }) + .catch((error: unknown) => { + if (error instanceof TaskDirectorySnapshotSkip) return null; + throw error; + }); + if (!current || current.digest !== state.restorePoint.digest) { + if (workspace.cleanupReason === TASK_DIRECTORY_RETENTION_REASON) { + const metadata: Record = { ...workspace.metadata, lifecycleGeneration: state.generation + 1 }; + delete metadata[TASK_DIRECTORY_RETENTION_KEY]; + await db.update(executionWorkspaces).set({ status: "active", closedAt: null, cleanupEligibleAt: null, cleanupReason: null, + metadata, updatedAt: new Date() }).where(eq(executionWorkspaces.id, workspace.id)); + } else { + const metadata: Record = { ...workspace.metadata }; + delete metadata[TASK_DIRECTORY_RETENTION_KEY]; + await db.update(executionWorkspaces).set({ metadata, updatedAt: new Date() }).where(eq(executionWorkspaces.id, workspace.id)); + } + await abandonTaskDirectoryRestorePoint(db, workspace.id, state.restorePoint.objectKey); + throw new Error("task_directory_changed"); + } + await fs.rename(cwd, state.trash); + } + if (await exists(state.trash)) { + const bytes = await allocatedBytes(state.trash, () => { options.signal?.throwIfAborted(); return true; }).catch(() => result.candidateBytes); + await removeTaskDirectoryTree(state.trash); + result.reclaimedBytes = bytes; + } + const removedAt = new Date().toISOString(); + await db.update(executionWorkspaces).set({ + metadata: sql`jsonb_set(jsonb_set(${executionWorkspaces.metadata}, ${`{${TASK_DIRECTORY_RETENTION_KEY},removed}`}::text[], 'true'::jsonb), + ${`{${TASK_DIRECTORY_RETENTION_KEY},removedAt}`}::text[], ${JSON.stringify(removedAt)}::jsonb)`, + updatedAt: new Date(), + }).where(and(eq(executionWorkspaces.id, workspace.id), + sql`${executionWorkspaces.metadata}->${TASK_DIRECTORY_RETENTION_KEY}->'restorePoint'->>'objectKey' = ${state.restorePoint.objectKey}`)); + await logActivity(db, { + companyId: workspace.companyId, + actorType: "system", + actorId: "workspace_terminality_reaper", + action: "execution_workspace.task_directory_removed", + entityType: "execution_workspace", + entityId: workspace.id, + details: { sourceIssueId: workspace.sourceIssueId, restorePointId: state.restorePoint.id, reclaimedBytes: result.reclaimedBytes, + cleanupReason: TASK_DIRECTORY_RETENTION_REASON }, + }); + result.expired = true; + return result; + })), true); + } catch (error) { + if (pending) await abandonGitRestorePoint(db, pending).catch(() => undefined); + options.signal?.throwIfAborted(); + recordSkip(result, error); + return result; + } +} + +async function abandonTaskDirectoryRestorePoint(db: Db | Parameters[0]>[0], workspaceId: string, objectKey: string) { + await db.transaction(async tx => { + await notifyGitRestorePointWork(tx, `workspace:${workspaceId}`); + await tx.update(executionWorkspaceRestorePoints).set({ status: "superseded", updatedAt: new Date() }) + .where(and(eq(executionWorkspaceRestorePoints.executionWorkspaceId, workspaceId), eq(executionWorkspaceRestorePoints.objectKey, objectKey), + inArray(executionWorkspaceRestorePoints.status, ["pending", "active"]))); + }); +} + +export async function supersedeTaskDirectoryRestorePoint(tx: Parameters[0]>[0], workspace: { id: string; metadata?: Record | null }) { + const state = readTaskDirectoryRetention(workspace); + if (state) await abandonTaskDirectoryRestorePoint(tx, workspace.id, state.restorePoint.objectKey); +} + +export async function restoreIsolatedTaskDirectory(input: { + storage: StorageService; + workspace: Pick; + signal?: AbortSignal; +}): Promise<{ restored: boolean; expired: boolean }> { + const state = readTaskDirectoryRetention(input.workspace); + if (!state) return { restored: false, expired: false }; + if (!await isIsolatedTaskDirectoryWorkspace(input.workspace)) throw new TaskDirectoryRestoreFailure("task_directory_identity_changed"); + const cwd = input.workspace.cwd!; + const parent = path.dirname(cwd); + await fs.mkdir(parent, { recursive: true, mode: 0o700 }); + if (await fs.realpath(parent) !== parent) throw new TaskDirectoryRestoreFailure("task_directory_identity_changed"); + const ref = validateRestorePointRef(state.restorePoint, input.workspace); + if (await directoryState(cwd) === "present") { + if (!state.removed) return { restored: false, expired: false }; + if ((await fs.readdir(cwd)).length === 0) await fs.rmdir(cwd); + else { + const current = await inspectTaskDirectory(cwd, { signal: input.signal }).catch(() => null); + if (current?.digest === ref.digest) return { restored: false, expired: false }; + throw new TaskDirectoryRestoreFailure("task_directory_diverged"); + } + } + if (ref.expiredAt) { + await fs.mkdir(cwd, { mode: 0o700 }); + return { restored: false, expired: true }; + } + const ciphertext = await readRestorePointObject(input.storage, input.workspace.companyId, ref.objectKey, input.signal).catch(() => { + throw new TaskDirectoryRestoreFailure("restore_point_unavailable"); + }); + if (ciphertext.length !== ref.byteSize) throw new TaskDirectoryRestoreFailure("ciphertext_size_mismatch"); + const payload = await openRestorePoint({ ciphertext, sha256: ref.sha256, key: ref.key, + identity: { companyId: input.workspace.companyId, workspaceId: input.workspace.id, restorePointId: ref.id, generation: ref.generation } }); + const staging = await materializeTaskDirectorySnapshot({ payload, target: cwd, expectedDigest: ref.digest, signal: input.signal }); + try { + await fs.rename(staging, cwd); + } catch (error) { + await removeTaskDirectoryTree(staging).catch(() => undefined); + throw error; + } + return { restored: true, expired: false }; +} + +export type TaskDirectoryFolderResult = { + companyId: string; + issueId: string; + outcome: "removed" | "preserved_and_removed" | "dry_run" | "skipped"; + reason: string | null; + candidateBytes: number; + reclaimedBytes: number; + executionWorkspaceId?: string; + retryAt?: number; + walkRetryAt?: number; + failure?: GitExpirationFailure; +}; + +type IssueTree = { exists: boolean; open: boolean; closedAt: Date | null }; + +async function issueTreeState(db: Db, companyId: string, issueId: string): Promise { + const rows = await db.execute<{ total: number; open: number; closed_at: string | Date | null }>(sql` + WITH RECURSIVE tree AS ( + SELECT id, status, completed_at, cancelled_at, updated_at FROM ${issues} + WHERE company_id = ${companyId} AND id = ${issueId} + UNION + SELECT c.id, c.status, c.completed_at, c.cancelled_at, c.updated_at FROM ${issues} c + JOIN tree p ON c.parent_id = p.id WHERE c.company_id = ${companyId} + ) + SELECT count(*)::int AS total, + count(*) FILTER (WHERE status NOT IN ('done', 'cancelled'))::int AS open, + max(CASE WHEN status = 'done' THEN coalesce(completed_at, updated_at) + WHEN status = 'cancelled' THEN coalesce(cancelled_at, updated_at) END) AS closed_at + FROM tree`); + const state = rows[0]; + if (!state || state.total === 0) return { exists: false, open: false, closedAt: null }; + return { exists: true, open: state.open > 0, closedAt: state.closed_at ? new Date(state.closed_at) : null }; +} + +async function folderRows(db: Db, folder: string) { + return db.select().from(executionWorkspaces).where(or(eq(executionWorkspaces.cwd, folder), eq(executionWorkspaces.providerRef, folder), + sql`left(${executionWorkspaces.cwd}, length(${folder}) + 1) = ${folder} || '/'`, + sql`left(${executionWorkspaces.providerRef}, length(${folder}) + 1) = ${folder} || '/'`)); +} + +async function orphanConsumer(db: Db, companyId: string, issueId: string, folder: string) { + const scope = { companyId, sourceIssueId: issueId, id: "00000000-0000-0000-0000-000000000000", cwd: folder } as Workspace; + const rows = await db.execute<{ reason: string | null }>(sql`${expirationScope(scope)} + SELECT CASE + WHEN EXISTS (SELECT 1 FROM ${projectWorkspaces} WHERE cwd = ${folder} OR left(cwd, length(${folder}) + 1) = ${folder} || '/') THEN 'project_workspace' + WHEN EXISTS (SELECT 1 FROM ${workspaceRuntimeServices} WHERE status <> 'stopped' + AND (cwd = ${folder} OR left(cwd, length(${folder}) + 1) = ${folder} || '/')) THEN 'live_runtime_service' + WHEN EXISTS (SELECT 1 FROM relevant_runs WHERE status NOT IN ('succeeded', 'failed', 'timed_out', 'cancelled', 'interrupted') + OR finished_at IS NULL OR controller_lease_expires_at > now()) THEN 'live_run' + WHEN EXISTS (SELECT 1 FROM ${nativeRunFinalizations} f WHERE f.company_id = ${companyId} + AND (f.issue_id IN (SELECT id FROM tree) OR f.run_id IN (SELECT id FROM relevant_runs)) + AND (f.lease_owner IS NOT NULL OR f.phase NOT IN ('committed', 'terminal_failure'))) THEN 'unsettled_finalization' + WHEN EXISTS (SELECT 1 FROM ${environmentLeases} l WHERE l.company_id = ${companyId} + AND (l.heartbeat_run_id IN (SELECT id FROM relevant_runs) OR l.issue_id IN (SELECT id FROM tree) + OR l.execution_workspace_id IN (SELECT w.id FROM ${executionWorkspaces} w WHERE w.cwd = ${folder} OR w.provider_ref = ${folder} + OR left(w.cwd, length(${folder}) + 1) = ${folder} || '/' OR left(w.provider_ref, length(${folder}) + 1) = ${folder} || '/')) + AND (l.status = 'pending_cleanup' OR l.cleanup_status = 'failed' OR l.metadata ? 'nativeWorkspaceExportResume' + OR (l.released_at IS NULL AND NOT coalesce(l.status = 'retained' AND l.lease_policy = 'reuse_by_environment' AND l.cleanup_status = 'success', false)))) THEN 'live_lease' + WHEN EXISTS (SELECT 1 FROM ${issueRecoveryActions} WHERE company_id = ${companyId} + AND source_issue_id IN (SELECT id FROM tree) AND status IN ('active', 'escalated')) THEN 'recovery_action' + ELSE NULL END AS reason`); + return rows[0]?.reason ?? null; +} + +async function listDirectory(target: string) { + const stat = await fs.lstat(target).catch(() => null); + if (!stat || !stat.isDirectory() || stat.isSymbolicLink()) return []; + return (await fs.readdir(target)).sort(); +} + +type FolderSweepOptions = { + dryRun: boolean; + now: Date; + orphanGraceMs: number; + terminalDelayMs: number; + restorePoint?: TaskDirectoryRestorePointOptions; + signal?: AbortSignal; + beforeDelete?: (workspace: Workspace) => Promise; +}; + +const CONSUMER_SKIPS = new Set(["live_workspace", "retention_pending", "project_workspace", "live_runtime_service", "live_run", + "unsettled_finalization", "live_lease", "recovery_action"]); + +async function inspectTaskDirectoryFolder(db: Db, companyId: string, name: string, options: FolderSweepOptions): Promise { + const nowMs = options.now.getTime(); + const root = await isolatedTaskDirectoriesRoot(); + if (!root) return null; + const companyDir = path.join(root, companyId); + const folder = path.join(companyDir, name); + const result: TaskDirectoryFolderResult = { companyId, issueId: name, outcome: "skipped", reason: null, candidateBytes: 0, reclaimedBytes: 0 }; + const retry = (at: number) => { result.retryAt = result.retryAt === undefined ? at : Math.min(result.retryAt, at); }; + try { + if (!UUID.test(name) || !UUID.test(companyId)) throw new Error("unrecognized_task_directory_name"); + const stat = await fs.lstat(folder).catch((error: NodeJS.ErrnoException) => { + if (error.code === "ENOENT") return null; + throw error; + }); + if (!stat) return null; + if (stat.isSymbolicLink() || !stat.isDirectory()) throw new Error("unsafe_task_directory"); + const rows = await folderRows(db, folder); + if (rows.some(row => !["archived", "cleanup_failed"].includes(row.status) || row.closedAt === null)) return null; + if (rows.some(row => hasPendingTaskDirectoryRetention(row))) throw new Error("retention_pending"); + const [issue] = await db.select({ id: issues.id, executionWorkspaceId: issues.executionWorkspaceId }).from(issues) + .where(and(eq(issues.companyId, companyId), eq(issues.id, name))); + const tree = issue ? await issueTreeState(db, companyId, name) : { exists: false, open: false, closedAt: null }; + if (tree.exists && (tree.open || !tree.closedAt)) throw new Error("issue_open"); + const bound = issue ? rows.find(row => row.id === issue.executionWorkspaceId) : undefined; + if (bound) { + if (bound.cwd !== folder || !await isIsolatedTaskDirectoryWorkspace(bound)) throw new Error("bound_workspace"); + result.executionWorkspaceId = bound.id; + const dueAt = tree.closedAt!.getTime() + options.terminalDelayMs; + if (dueAt > nowMs) { retry(dueAt); throw new Error("not_due"); } + const expiration = await expireIsolatedTaskDirectory(db, bound, { dryRun: options.dryRun, now: options.now, + notBefore: new Date(dueAt), restorePoint: options.restorePoint, signal: options.signal, beforeDelete: options.beforeDelete }); + result.candidateBytes = expiration.candidateBytes; + result.reclaimedBytes = expiration.reclaimedBytes; + result.reason = expiration.skipReason; + if (expiration.failure) result.failure = expiration.failure; + result.outcome = expiration.expired ? "preserved_and_removed" : options.dryRun && expiration.candidate ? "dry_run" : "skipped"; + if (isRetryableTaskDirectorySkip(expiration.skipReason)) retry(nowMs + TASK_DIRECTORY_RETRY_MS); + return result; + } + if (tree.exists && tree.closedAt!.getTime() + options.orphanGraceMs > nowMs) { + retry(tree.closedAt!.getTime() + options.orphanGraceMs); + throw new Error("grace_pending"); + } + const newest = await newestTaskDirectoryMtime(folder, options.signal); + if (newest + options.orphanGraceMs > nowMs) { + retry(newest + options.orphanGraceMs); + throw new Error("recently_modified"); + } + await withIsolatedRepositorySourceLock(db, companyId, name, async () => { + if (await directoryState(folder) !== "present") throw new Error("task_directory_changed"); + const current = await folderRows(db, folder); + if (current.some(row => !["archived", "cleanup_failed"].includes(row.status) || row.closedAt === null)) throw new Error("live_workspace"); + if (current.some(row => hasPendingTaskDirectoryRetention(row))) throw new Error("retention_pending"); + const [currentIssue] = await db.select({ executionWorkspaceId: issues.executionWorkspaceId }).from(issues) + .where(and(eq(issues.companyId, companyId), eq(issues.id, name))); + if (Boolean(currentIssue) !== Boolean(issue) || (currentIssue && currentIssue.executionWorkspaceId !== issue!.executionWorkspaceId)) { + throw new Error("task_directory_changed"); + } + const consumer = await orphanConsumer(db, companyId, name, folder); + if (consumer) throw new Error(consumer); + if (tree.exists) { + const latest = await issueTreeState(db, companyId, name); + if (latest.open || !latest.closedAt || latest.closedAt.getTime() + options.orphanGraceMs > nowMs) throw new Error("issue_open"); + } + result.candidateBytes = await allocatedBytes(folder, () => { options.signal?.throwIfAborted(); return true; }).catch(() => 0); + if (options.dryRun) { + result.outcome = "dry_run"; + return; + } + const trash = shortSiblingName(folder, ".expired-"); + await fs.rename(folder, trash); + await removeTaskDirectoryTree(trash).catch(() => { + result.walkRetryAt = nowMs + TASK_DIRECTORY_RETRY_MS; + throw new Error("task_directory_trash_pending"); + }); + result.outcome = "removed"; + result.reclaimedBytes = result.candidateBytes; + }, true); + } catch (error) { + options.signal?.throwIfAborted(); + result.reason = skipReason(error); + if (result.reason === "inspection_failed") result.failure = describeGitExpirationFailure(error); + if (isRetryableTaskDirectorySkip(result.reason) || CONSUMER_SKIPS.has(result.reason)) retry(nowMs + TASK_DIRECTORY_RETRY_MS); + } + return result; +} + +export async function inspectIsolatedTaskDirectoryFolders(db: Db, folders: Array<{ companyId: string; issueId: string }>, options: FolderSweepOptions) { + const results: TaskDirectoryFolderResult[] = []; + for (const folder of folders) { + options.signal?.throwIfAborted(); + if (!IDENTITY.test(folder.companyId) || !IDENTITY.test(folder.issueId)) continue; + const result = await inspectTaskDirectoryFolder(db, folder.companyId, folder.issueId, options); + if (result) results.push(result); + } + return results; +} + +export async function sweepIsolatedTaskDirectories(db: Db, options: FolderSweepOptions & { after?: string | null; limit?: number }): + Promise<{ results: TaskDirectoryFolderResult[]; next: string | null; retryAt: number | null }> { + const results: TaskDirectoryFolderResult[] = []; + const limit = options.limit ?? 8; + const nowMs = options.now.getTime(); + let retryAt: number | null = null; + const retry = (at: number) => { retryAt = retryAt === null ? at : Math.min(retryAt, at); }; + const root = await isolatedTaskDirectoriesRoot(); + if (!root) return { results, next: null, retryAt }; + const rootStat = await fs.lstat(root).catch(() => null); + if (!rootStat || !rootStat.isDirectory() || rootStat.isSymbolicLink()) return { results, next: null, retryAt }; + const [afterCompany, afterIssue] = options.after?.split("/") ?? []; + let inspected = 0; + let lastPosition: string | null = null; + for (const companyId of await listDirectory(root)) { + if (!IDENTITY.test(companyId)) continue; + const companyDir = path.join(root, companyId); + for (const name of await listDirectory(companyDir)) { + options.signal?.throwIfAborted(); + if (afterCompany !== undefined && (companyId < afterCompany || (companyId === afterCompany && name <= afterIssue!))) continue; + if (inspected >= limit) return { results, next: lastPosition, retryAt }; + inspected += 1; + lastPosition = `${companyId}/${name}`; + if (TRASH.test(name)) { + const folder = path.join(companyDir, name); + const stat = await fs.lstat(folder).catch(() => null); + if (!stat || options.dryRun) continue; + const touched = Math.max(stat.mtimeMs, stat.ctimeMs); + if (touched + TRASH_GRACE_MS > nowMs) { retry(touched + TRASH_GRACE_MS); continue; } + await removeTaskDirectoryTree(folder).catch(() => retry(nowMs + TASK_DIRECTORY_RETRY_MS)); + continue; + } + const result = await inspectTaskDirectoryFolder(db, companyId, name, options); + if (result) results.push(result); + } + } + return { results, next: null, retryAt }; +} + +export async function taskDirectoryFoldersForHints(db: Db, hints: { workspaceIds: string[]; issueIds: string[] }) { + const folders = new Map(); + const workspaceIds = hints.workspaceIds.filter(id => UUID.test(id)); + const issueIds = hints.issueIds.filter(id => UUID.test(id)); + if (workspaceIds.length > 0) { + const rows = await db.select({ companyId: executionWorkspaces.companyId, sourceIssueId: executionWorkspaces.sourceIssueId }) + .from(executionWorkspaces).where(and(inArray(executionWorkspaces.id, workspaceIds), + inArray(executionWorkspaces.status, ["archived", "cleanup_failed"]), eq(executionWorkspaces.strategyType, "project_primary"))); + for (const row of rows) if (row.sourceIssueId) folders.set(`${row.companyId}/${row.sourceIssueId}`, { companyId: row.companyId, issueId: row.sourceIssueId }); + } + if (issueIds.length > 0) { + const rows = await db.execute<{ id: string; company_id: string }>(sql` + WITH RECURSIVE closed_up AS ( + SELECT id, parent_id, company_id, 0 AS depth FROM ${issues} + WHERE id IN (${sql.join(issueIds.map(id => sql`${id}::uuid`), sql`, `)}) AND status IN ('done', 'cancelled') + UNION + SELECT p.id, p.parent_id, p.company_id, c.depth + 1 FROM ${issues} p + JOIN closed_up c ON p.id = c.parent_id AND p.company_id = c.company_id WHERE c.depth < 64 + ) + SELECT DISTINCT id, company_id FROM closed_up`); + for (const row of rows) folders.set(`${row.company_id}/${row.id}`, { companyId: row.company_id, issueId: row.id }); + } + const present: Array<{ companyId: string; issueId: string }> = []; + for (const folder of folders.values()) { + const target = await canonicalTaskDirectory(folder.companyId, folder.issueId); + if (target && await exists(target)) present.push(folder); + } + return present; +} + +export function taskDirectoryCandidateFilter() { + return and(inArray(executionWorkspaces.status, ["archived", "cleanup_failed"]), + sql`${executionWorkspaces.metadata}->${TASK_DIRECTORY_RETENTION_KEY}->>'removed' = 'false'`); +} diff --git a/server/src/services/isolated-task-directory-snapshot.ts b/server/src/services/isolated-task-directory-snapshot.ts new file mode 100644 index 00000000000..1eafdfb126f --- /dev/null +++ b/server/src/services/isolated-task-directory-snapshot.ts @@ -0,0 +1,265 @@ +import { createHash, randomBytes } from "node:crypto"; +import fs from "node:fs/promises"; +import path from "node:path"; +import { DEFAULT_RESTORE_POINT_LIMITS } from "./git-restore-point.js"; + +export const TASK_DIRECTORY_RETENTION_KEY = "isolatedTaskDirectoryRetention"; +export const TASK_DIRECTORY_SNAPSHOT_SCHEMA = "paperclip.task-directory-snapshot.v1"; +const PAYLOAD_MAGIC = Buffer.from("PCTD-PLAIN1\n"); +const MAX_MANIFEST_BYTES = 64 * 1024 * 1024; + +export type TaskDirectorySnapshotLimits = { maxFiles: number; maxFileBytes: number; maxTotalBytes: number }; + +export const DEFAULT_TASK_DIRECTORY_SNAPSHOT_LIMITS: TaskDirectorySnapshotLimits = { + maxFiles: DEFAULT_RESTORE_POINT_LIMITS.maxFiles, + maxFileBytes: DEFAULT_RESTORE_POINT_LIMITS.maxFileBytes, + maxTotalBytes: DEFAULT_RESTORE_POINT_LIMITS.maxTotalBytes, +}; + +export type TaskDirectoryEntry = + | { path: string; type: "directory"; mode: number } + | { path: string; type: "file"; mode: number; size: number; sha256: string } + | { path: string; type: "symlink"; target: string }; + +export type TaskDirectorySnapshotManifest = { + schema: typeof TASK_DIRECTORY_SNAPSHOT_SCHEMA; + entries: TaskDirectoryEntry[]; + excluded: string[]; +}; + +export class TaskDirectorySnapshotSkip extends Error { + constructor(readonly reason: string) { + super(reason); + this.name = "TaskDirectorySnapshotSkip"; + } +} + +export class TaskDirectoryRestoreFailure extends Error { + constructor(readonly reason: string) { + super(`The task directory could not be restored: ${reason}`); + this.name = "TaskDirectoryRestoreFailure"; + } +} + +const bySortKey = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0); + +type WalkOptions = { + limits: TaskDirectorySnapshotLimits; + signal?: AbortSignal; + readFile: (absolute: string, relative: string, size: number) => Promise; +}; + +async function walk(root: string, options: WalkOptions) { + const rootStat = await fs.lstat(root); + if (!rootStat.isDirectory() || rootStat.isSymbolicLink()) throw new TaskDirectorySnapshotSkip("unsafe_task_directory"); + const entries: TaskDirectoryEntry[] = []; + const excluded: string[] = []; + let files = 0; + let total = 0; + let newestMtimeMs = rootStat.mtimeMs; + const visit = async (relativeDir: string) => { + options.signal?.throwIfAborted(); + const absoluteDir = relativeDir ? path.join(root, relativeDir) : root; + const names = (await fs.readdir(absoluteDir)).sort(bySortKey); + const hasPackageManifest = names.includes("package.json") + && (await fs.lstat(path.join(absoluteDir, "package.json"))).isFile(); + for (const name of names) { + options.signal?.throwIfAborted(); + const relative = relativeDir ? `${relativeDir}/${name}` : name; + const absolute = path.join(absoluteDir, name); + const stat = await fs.lstat(absolute); + newestMtimeMs = Math.max(newestMtimeMs, stat.mtimeMs); + if (stat.isSymbolicLink()) { + entries.push({ path: relative, type: "symlink", target: await fs.readlink(absolute) }); + continue; + } + if (stat.isDirectory()) { + if (name === "node_modules" && hasPackageManifest) { + excluded.push(relative); + continue; + } + entries.push({ path: relative, type: "directory", mode: stat.mode & 0o777 }); + await visit(relative); + continue; + } + if (!stat.isFile()) throw new TaskDirectorySnapshotSkip("unsupported_filesystem_entry"); + files += 1; + total += stat.size; + if (files > options.limits.maxFiles) throw new TaskDirectorySnapshotSkip("task_directory_too_many_files"); + if (stat.size > options.limits.maxFileBytes) throw new TaskDirectorySnapshotSkip("task_directory_file_too_large"); + if (total > options.limits.maxTotalBytes) throw new TaskDirectorySnapshotSkip("task_directory_too_large"); + entries.push({ path: relative, type: "file", mode: stat.mode & 0o777, size: stat.size, + sha256: await options.readFile(absolute, relative, stat.size) }); + } + }; + await visit(""); + return { entries, excluded, newestMtimeMs }; +} + +export function taskDirectoryManifestDigest(manifest: Pick) { + return createHash("sha256").update(JSON.stringify([TASK_DIRECTORY_SNAPSHOT_SCHEMA, manifest.entries])).digest("hex"); +} + +async function hashFile(absolute: string, size: number) { + const handle = await fs.open(absolute, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW); + try { + const hash = createHash("sha256"); + let read = 0; + for await (const chunk of handle.createReadStream({ autoClose: false })) { + read += (chunk as Buffer).length; + hash.update(chunk as Buffer); + } + if (read !== size) throw new TaskDirectorySnapshotSkip("task_directory_changed"); + return hash.digest("hex"); + } finally { + await handle.close(); + } +} + +export async function inspectTaskDirectory(root: string, options: { limits?: TaskDirectorySnapshotLimits; signal?: AbortSignal } = {}) { + const walked = await walk(root, { limits: options.limits ?? DEFAULT_TASK_DIRECTORY_SNAPSHOT_LIMITS, signal: options.signal, + readFile: (absolute, _relative, size) => hashFile(absolute, size) }); + return { digest: taskDirectoryManifestDigest(walked), entries: walked.entries.length, excluded: walked.excluded.length, + newestMtimeMs: walked.newestMtimeMs }; +} + +export async function newestTaskDirectoryMtime(root: string, signal?: AbortSignal): Promise { + const stat = await fs.lstat(root); + let newest = stat.mtimeMs; + if (!stat.isDirectory() || stat.isSymbolicLink()) return newest; + for (const name of await fs.readdir(root)) { + signal?.throwIfAborted(); + newest = Math.max(newest, await newestTaskDirectoryMtime(path.join(root, name), signal)); + } + return newest; +} + +export async function captureTaskDirectorySnapshot(root: string, options: { limits?: TaskDirectorySnapshotLimits; signal?: AbortSignal } = {}) { + const bodies: Buffer[] = []; + const walked = await walk(root, { limits: options.limits ?? DEFAULT_TASK_DIRECTORY_SNAPSHOT_LIMITS, signal: options.signal, + readFile: async (absolute, _relative, size) => { + const handle = await fs.open(absolute, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW); + try { + const body = await handle.readFile(); + if (body.length !== size) throw new TaskDirectorySnapshotSkip("task_directory_changed"); + bodies.push(body); + return createHash("sha256").update(body).digest("hex"); + } finally { + await handle.close(); + } + } }); + const manifest: TaskDirectorySnapshotManifest = { schema: TASK_DIRECTORY_SNAPSHOT_SCHEMA, entries: walked.entries, excluded: walked.excluded }; + const encoded = Buffer.from(JSON.stringify(manifest)); + const length = Buffer.alloc(4); + length.writeUInt32BE(encoded.length); + const payload = Buffer.concat([PAYLOAD_MAGIC, length, encoded, ...bodies]); + try { decodeTaskDirectorySnapshot(payload); } + catch { throw new TaskDirectorySnapshotSkip("task_directory_not_restorable"); } + return { + payload, + digest: taskDirectoryManifestDigest(manifest), + files: walked.entries.filter(entry => entry.type === "file").length, + excluded: walked.excluded.length, + }; +} + +function validRelativePath(value: unknown): value is string { + if (typeof value !== "string" || value.length === 0 || value.length > 4096 || value.includes("\0")) return false; + if (path.sep !== "/" && value.includes(path.sep)) return false; + if (value.startsWith("/")) return false; + return value.split("/").every(part => part.length > 0 && part !== "." && part !== ".."); +} + +export function decodeTaskDirectorySnapshot(payload: Buffer): { manifest: TaskDirectorySnapshotManifest; bodies: Buffer } { + if (payload.length < PAYLOAD_MAGIC.length + 4 || !payload.subarray(0, PAYLOAD_MAGIC.length).equals(PAYLOAD_MAGIC)) { + throw new TaskDirectoryRestoreFailure("invalid_snapshot_payload"); + } + const length = payload.readUInt32BE(PAYLOAD_MAGIC.length); + const start = PAYLOAD_MAGIC.length + 4; + if (length > MAX_MANIFEST_BYTES || start + length > payload.length) throw new TaskDirectoryRestoreFailure("invalid_snapshot_payload"); + let manifest: TaskDirectorySnapshotManifest; + try { manifest = JSON.parse(payload.subarray(start, start + length).toString("utf8")); } + catch { throw new TaskDirectoryRestoreFailure("invalid_snapshot_payload"); } + if (!manifest || manifest.schema !== TASK_DIRECTORY_SNAPSHOT_SCHEMA || !Array.isArray(manifest.entries) || !Array.isArray(manifest.excluded)) { + throw new TaskDirectoryRestoreFailure("invalid_snapshot_payload"); + } + const kinds = new Map(); + let bodyBytes = 0; + for (const entry of manifest.entries) { + if (!entry || !validRelativePath(entry.path) || kinds.has(entry.path)) throw new TaskDirectoryRestoreFailure("invalid_snapshot_entry"); + const parent = entry.path.includes("/") ? entry.path.slice(0, entry.path.lastIndexOf("/")) : null; + if (parent !== null && kinds.get(parent) !== "directory") throw new TaskDirectoryRestoreFailure("invalid_snapshot_entry"); + if (entry.type === "file") { + if (!Number.isSafeInteger(entry.size) || entry.size < 0 || !/^[0-9a-f]{64}$/.test(entry.sha256) + || !Number.isInteger(entry.mode) || entry.mode < 0 || entry.mode > 0o777) throw new TaskDirectoryRestoreFailure("invalid_snapshot_entry"); + bodyBytes += entry.size; + } else if (entry.type === "directory") { + if (!Number.isInteger(entry.mode) || entry.mode < 0 || entry.mode > 0o777) throw new TaskDirectoryRestoreFailure("invalid_snapshot_entry"); + } else if (entry.type !== "symlink" || typeof entry.target !== "string" || entry.target.length === 0 || entry.target.includes("\0")) { + throw new TaskDirectoryRestoreFailure("invalid_snapshot_entry"); + } + kinds.set(entry.path, entry.type); + } + if (manifest.excluded.some(value => !validRelativePath(value))) throw new TaskDirectoryRestoreFailure("invalid_snapshot_entry"); + const bodies = payload.subarray(start + length); + if (bodies.length !== bodyBytes) throw new TaskDirectoryRestoreFailure("invalid_snapshot_payload"); + return { manifest, bodies }; +} + +export function shortSiblingName(target: string, prefix: string) { + const length = Math.max(8, path.basename(target).length - prefix.length); + return path.join(path.dirname(target), `${prefix}${randomBytes(Math.ceil(length / 2)).toString("hex").slice(0, length)}`); +} + +export async function materializeTaskDirectorySnapshot(input: { payload: Buffer; target: string; expectedDigest: string; signal?: AbortSignal }) { + const { manifest, bodies } = decodeTaskDirectorySnapshot(input.payload); + if (taskDirectoryManifestDigest(manifest) !== input.expectedDigest) throw new TaskDirectoryRestoreFailure("snapshot_digest_mismatch"); + const staging = shortSiblingName(input.target, ".restoring-"); + await fs.mkdir(staging, { mode: 0o700 }); + try { + let offset = 0; + const directories: Array<{ target: string; mode: number }> = []; + for (const entry of manifest.entries) { + input.signal?.throwIfAborted(); + const target = path.join(staging, ...entry.path.split("/")); + if (entry.type === "directory") { + await fs.mkdir(target, { mode: 0o700 }); + directories.push({ target, mode: entry.mode }); + } else if (entry.type === "symlink") { + await fs.symlink(entry.target, target); + } else { + const body = bodies.subarray(offset, offset + entry.size); + offset += entry.size; + if (createHash("sha256").update(body).digest("hex") !== entry.sha256) throw new TaskDirectoryRestoreFailure("snapshot_content_mismatch"); + const handle = await fs.open(target, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_NOFOLLOW, 0o600); + try { await handle.writeFile(body); } finally { await handle.close(); } + await fs.chmod(target, entry.mode); + } + } + for (const directory of directories.reverse()) await fs.chmod(directory.target, directory.mode); + const restored = await inspectTaskDirectory(staging, { limits: { maxFiles: Number.MAX_SAFE_INTEGER, maxFileBytes: Number.MAX_SAFE_INTEGER, + maxTotalBytes: Number.MAX_SAFE_INTEGER }, signal: input.signal }); + if (restored.digest !== input.expectedDigest) throw new TaskDirectoryRestoreFailure("restored_contents_mismatch"); + return staging; + } catch (error) { + await removeTaskDirectoryTree(staging).catch(() => undefined); + throw error; + } +} + +export async function removeTaskDirectoryTree(target: string) { + const stat = await fs.lstat(target).catch((error: NodeJS.ErrnoException) => { + if (error.code === "ENOENT") return null; + throw error; + }); + if (!stat) return; + if (stat.isSymbolicLink() || !stat.isDirectory()) throw new Error("unsafe_task_directory_trash"); + const makeWritable = async (directory: string) => { + await fs.chmod(directory, 0o700); + for (const entry of await fs.readdir(directory, { withFileTypes: true })) { + if (entry.isDirectory()) await makeWritable(path.join(directory, entry.name)); + } + }; + await makeWritable(target).catch(() => undefined); + await fs.rm(target, { recursive: true, force: true }); +} From b6591c93a075406fdc15779d795db232f501bdb0 Mon Sep 17 00:00:00 2001 From: "sentry[bot]" <39604003+sentry[bot]@users.noreply.github.com> Date: Sat, 24 Oct 2026 14:31:24 -0700 Subject: [PATCH 020/110] fix(issues): validate UUID query parameters on list and count endpoints (#17389) Reject malformed UUID filters (participantAgentId, projectId, workspaceId, executionWorkspaceId, parentId, parentIssueId, descendantOf, createdFromIssueId, labelId) on GET /api/companies/:companyId/issues and /issues/count with a 422 instead of letting Postgres fail the uuid cast with a 500. Fixes PAPERCLIP-BACKEND-4M. Co-Authored-By: Devin Foley Co-Authored-By: Claude Opus 5.5 --- .../issue-list-assignee-filter-routes.test.ts | 56 ++++++++++++ server/src/routes/issues.ts | 85 ++++++++++++++----- 2 files changed, 121 insertions(+), 20 deletions(-) diff --git a/server/src/__tests__/issue-list-assignee-filter-routes.test.ts b/server/src/__tests__/issue-list-assignee-filter-routes.test.ts index 269f5d20010..3c685dcfa3d 100644 --- a/server/src/__tests__/issue-list-assignee-filter-routes.test.ts +++ b/server/src/__tests__/issue-list-assignee-filter-routes.test.ts @@ -791,6 +791,62 @@ describeEmbeddedPostgres("issue list routes assigneeAgentId filter", () => { }); }); + it.each([ + "projectId", + "parentId", + "parentIssueId", + "workspaceId", + "executionWorkspaceId", + "descendantOf", + "labelId", + "participantAgentId", + ])("returns 422 instead of a DB error for malformed %s filters", async (param) => { + const companyId = randomUUID(); + await db.insert(companies).values({ + id: companyId, + name: "Paperclip", + issuePrefix: uniqueIssuePrefix(), + requireBoardApprovalForNewAgents: false, + }); + await seedCloudTenantMember(companyId); + + const app = createApp(companyId); + const res = await request(app) + .get(`/api/companies/${companyId}/issues`) + .query({ status: "todo", [param]: "d", limit: "20" }); + + expect(res.status, JSON.stringify(res.body)).toBe(422); + expect(res.body).toMatchObject({ error: `${param} must be a UUID` }); + }); + + it.each([ + "projectId", + "parentId", + "parentIssueId", + "workspaceId", + "executionWorkspaceId", + "descendantOf", + "labelId", + "participantAgentId", + ])("returns 422 from issues/count for malformed %s filters", async (param) => { + const companyId = randomUUID(); + await db.insert(companies).values({ + id: companyId, + name: "Paperclip", + issuePrefix: uniqueIssuePrefix(), + requireBoardApprovalForNewAgents: false, + }); + await seedCloudTenantMember(companyId); + + const app = createApp(companyId); + const res = await request(app) + .get(`/api/companies/${companyId}/issues/count`) + .query({ attention: "blocked", [param]: "d" }); + + expect(res.status, JSON.stringify(res.body)).toBe(422); + expect(res.body).toMatchObject({ error: `${param} must be a UUID` }); + }); + it("returns opt-in live descendant counts for offscreen live descendants only", async () => { const companyId = randomUUID(); const otherCompanyId = randomUUID(); diff --git a/server/src/routes/issues.ts b/server/src/routes/issues.ts index 69398e41a4c..9a29f1c9d91 100644 --- a/server/src/routes/issues.ts +++ b/server/src/routes/issues.ts @@ -3190,6 +3190,42 @@ function decrementIssueListActorClientInflight(actorClientKey: string) { else issueListActorClientInflight.set(actorClientKey, next); } +const ISSUE_LIST_UUID_QUERY_PARAMS = [ + "participantAgentId", + "projectId", + "workspaceId", + "executionWorkspaceId", + "parentId", + "parentIssueId", + "descendantOf", + "createdFromIssueId", + "labelId", +] as const; + +type IssueListUuidQueryParam = (typeof ISSUE_LIST_UUID_QUERY_PARAMS)[number]; + +function parseIssueListUuidQueryParams( + query: Record, +): + | { ok: true; values: Partial> } + | { ok: false; error: string } { + const values: Partial> = {}; + for (const name of ISSUE_LIST_UUID_QUERY_PARAMS) { + const raw = query[name]; + if (raw === undefined) continue; + if (typeof raw !== "string") { + return { ok: false, error: `${name} must be a UUID` }; + } + const trimmed = raw.trim(); + if (trimmed.length === 0) continue; + if (!isUuidLike(trimmed)) { + return { ok: false, error: `${name} must be a UUID` }; + } + values[name] = trimmed; + } + return { ok: true, values }; +} + async function coordinateIssueListGet(input: { req: Request; companyId: string; @@ -8445,6 +8481,12 @@ export function issueRoutes( }); return; } + const uuidQuery = parseIssueListUuidQueryParams(req.query); + if (!uuidQuery.ok) { + res.status(422).json({ error: uuidQuery.error }); + return; + } + const uuidFilters = uuidQuery.values; const offset = parsedOffset ?? 0; const listFilters: IssueFilters = { @@ -8452,20 +8494,18 @@ export function issueRoutes( attention: attention === "blocked" ? "blocked" : undefined, status: req.query.status as string | string[] | undefined, assigneeAgentId, - participantAgentId: req.query.participantAgentId as string | undefined, + participantAgentId: uuidFilters.participantAgentId, assigneeUserId, touchedByUserId, inboxArchivedByUserId, unreadForUserId, - projectId: req.query.projectId as string | undefined, - workspaceId: req.query.workspaceId as string | undefined, - executionWorkspaceId: req.query.executionWorkspaceId as - string | undefined, - parentId: (req.query.parentId ?? req.query.parentIssueId) as - string | undefined, - descendantOf: req.query.descendantOf as string | undefined, - createdFromIssueId: req.query.createdFromIssueId as string | undefined, - labelId: req.query.labelId as string | undefined, + projectId: uuidFilters.projectId, + workspaceId: uuidFilters.workspaceId, + executionWorkspaceId: uuidFilters.executionWorkspaceId, + parentId: uuidFilters.parentId ?? uuidFilters.parentIssueId, + descendantOf: uuidFilters.descendantOf, + createdFromIssueId: uuidFilters.createdFromIssueId, + labelId: uuidFilters.labelId, originKind: req.query.originKind as string | undefined, originKindPrefix: req.query.originKindPrefix as string | undefined, originId: req.query.originId as string | undefined, @@ -8686,22 +8726,27 @@ export function issueRoutes( return; } + const countUuidQuery = parseIssueListUuidQueryParams(req.query); + if (!countUuidQuery.ok) { + res.status(422).json({ error: countUuidQuery.error }); + return; + } + const countUuidFilters = countUuidQuery.values; + const blockedCountFilters = { readCondition: await issueReadSqlCondition(db, req.actor), attention: "blocked", status: req.query.status as string | string[] | undefined, assigneeAgentId: req.query.assigneeAgentId as string | undefined, - participantAgentId: req.query.participantAgentId as string | undefined, + participantAgentId: countUuidFilters.participantAgentId, assigneeUserId: req.query.assigneeUserId as string | undefined, - projectId: req.query.projectId as string | undefined, - workspaceId: req.query.workspaceId as string | undefined, - executionWorkspaceId: req.query.executionWorkspaceId as - string | undefined, - parentId: (req.query.parentId ?? req.query.parentIssueId) as - string | undefined, - descendantOf: req.query.descendantOf as string | undefined, - createdFromIssueId: req.query.createdFromIssueId as string | undefined, - labelId: req.query.labelId as string | undefined, + projectId: countUuidFilters.projectId, + workspaceId: countUuidFilters.workspaceId, + executionWorkspaceId: countUuidFilters.executionWorkspaceId, + parentId: countUuidFilters.parentId ?? countUuidFilters.parentIssueId, + descendantOf: countUuidFilters.descendantOf, + createdFromIssueId: countUuidFilters.createdFromIssueId, + labelId: countUuidFilters.labelId, originKind: req.query.originKind as string | undefined, originKindPrefix: req.query.originKindPrefix as string | undefined, originId: req.query.originId as string | undefined, From 470cb34c0e42cb9d0b232d0bcf5d45cc7b0a81ca Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Sat, 24 Oct 2026 15:14:48 -0700 Subject: [PATCH 021/110] Read reply repair and ownership evidence without execution payloads (#17501) Narrow native reply repair and conversation ownership reads to their consumed evidence while preserving full stored history, result receipts, locks, current authority checks, and publication authorization. Verify successful repair from equivalent unpublished states, exact final replies and decisions, no duplicate repair, preserved history, and 213 recovery/presentation tests. Build/typecheck and all CI pass. Greptile 5/5 Medium. Co-Authored-By: Paperclip --- doc/DATABASE.md | 7 + .../chat-monitor-continuation.test.ts | 11 +- .../src/services/conversation-continuation.ts | 9 +- .../native-runtime/native-run-finalizer.ts | 31 ++- .../presentation-ownership-read.test.ts | 214 ++++++++++++++++++ 5 files changed, 267 insertions(+), 5 deletions(-) create mode 100644 server/src/services/presentation-ownership-read.test.ts diff --git a/doc/DATABASE.md b/doc/DATABASE.md index 1ff88e3368d..13424c8fad6 100644 --- a/doc/DATABASE.md +++ b/doc/DATABASE.md @@ -68,6 +68,13 @@ Runner profiles retain the adapter type and complete native execution input and workspace-sync receipts. Full result evidence stays available to the existing retry and workspace checks. Stored context, profiles, and output are unchanged. +Conversation ownership checks select process identity and full recovery result +evidence without execution prompts or profiles. Committed native reply repair +selects its persisted result and identity bindings plus typed presentation flags. +It keeps its existing row locks, accepted-result digest checks, publication +authorization, and selected-answer protections. Full execution history stays in +storage. + Run-context lookups use expression indexes for both `context_snapshot.issueId` and `context_snapshot.paperclipIssue.id`. Task creation provenance has its own company-scoped expression index that follows the query's native issue ID and diff --git a/server/src/services/chat-monitor-continuation.test.ts b/server/src/services/chat-monitor-continuation.test.ts index 01b094800e4..f8e277d587b 100644 --- a/server/src/services/chat-monitor-continuation.test.ts +++ b/server/src/services/chat-monitor-continuation.test.ts @@ -1,4 +1,4 @@ -import { randomUUID } from "node:crypto"; +import { randomBytes, randomUUID } from "node:crypto"; import { and, eq } from "drizzle-orm"; import { afterAll, beforeAll, describe, expect, it } from "vitest"; import { @@ -237,6 +237,12 @@ if (!support.supported) console.warn(`Monitor publication database unavailable: it("recovers the accepted continuation explanation after interrupted finalization without another provider result", async () => { const f = await fixture(); + const executionPayload = randomBytes(128 * 1024).toString("base64"); + await db.update(heartbeatRuns).set({ + contextSnapshot: { ...f.source.contextSnapshot, largePrompt: executionPayload, + paperclipWake: { prompt: executionPayload } }, + runnerProfileJson: { instructions: executionPayload }, stdoutExcerpt: executionPayload, + }).where(eq(heartbeatRuns.id, f.source.id)); const [contract] = await db.insert(completionContracts).values({ companyId: f.company.id, issueId: f.issue.id, revision: 1, schemaVersion: "paperclip.completion-contract.v1", policyVersion: "test", risk: "standard", completionAuthority: "server_arbiter", incompleteCriteriaPolicy: "preserve_non_terminal", @@ -270,6 +276,9 @@ if (!support.supported) console.warn(`Monitor publication database unavailable: expect(coordinator).toMatchObject({ phase: "committed" }); const [settledRun] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.source.id)); expect(settledRun).toMatchObject({ status: "succeeded", resultJson: { finalizationPhase: "committed" } }); + expect(settledRun.contextSnapshot?.largePrompt).toBe(executionPayload); + expect(settledRun.runnerProfileJson?.instructions).toBe(executionPayload); + expect(settledRun.stdoutExcerpt).toBe(executionPayload); const priorComments = await db.select({ body: issueComments.body }).from(issueComments).where(eq(issueComments.createdByRunId, f.source.id)); expect(priorComments).toEqual([{ body: summary }]); expect(await repair()).toBe(false); diff --git a/server/src/services/conversation-continuation.ts b/server/src/services/conversation-continuation.ts index 36e8b7a4804..cd0c54a2dcd 100644 --- a/server/src/services/conversation-continuation.ts +++ b/server/src/services/conversation-continuation.ts @@ -111,7 +111,14 @@ export async function getConversationOwnershipBlocker(db: Db, companyId: string, and (${environmentLeases.releasedAt} is null or ${environmentLeases.status} = 'pending_cleanup' or ${environmentLeases.cleanupStatus} = 'failed'))`; - const candidates = await db.select({ run: heartbeatRuns, activeLease }).from(heartbeatRuns) + const candidates = await db.select({ run: { + id: heartbeatRuns.id, + agentId: heartbeatRuns.agentId, + processPid: heartbeatRuns.processPid, + processGroupId: heartbeatRuns.processGroupId, + processStartedAt: heartbeatRuns.processStartedAt, + resultJson: heartbeatRuns.resultJson, + }, activeLease }).from(heartbeatRuns) .where(and( eq(heartbeatRuns.companyId, companyId), eq(heartbeatRuns.runtimeMode, "legacy"), conversationRunPredicate(), diff --git a/server/src/services/native-runtime/native-run-finalizer.ts b/server/src/services/native-runtime/native-run-finalizer.ts index ff5d3267a9d..8b2ae73c349 100644 --- a/server/src/services/native-runtime/native-run-finalizer.ts +++ b/server/src/services/native-runtime/native-run-finalizer.ts @@ -596,7 +596,7 @@ function recoveredExecutionFailureMetadata() { async function projectCommittedRun(input: { db: Db; - run: typeof heartbeatRuns.$inferSelect; + run: Pick; coordinator: typeof nativeRunFinalizations.$inferSelect; }) { if (!input.coordinator.resultId) return; @@ -764,7 +764,9 @@ async function materializeCommittedReviewResponse(db: Db, runId: string) { async function acceptedResponseDigestMatches( db: Db, - run: typeof heartbeatRuns.$inferSelect, + run: Pick, accepted: typeof nativeRunResults.$inferSelect, ): Promise { const envelope = record(accepted.resultJson); @@ -842,7 +844,30 @@ export async function repairCommittedNativeChatResponse( .for("update"); if (!issue) return false; const [run] = await tx - .select() + .select({ + id: heartbeatRuns.id, + companyId: heartbeatRuns.companyId, + agentId: heartbeatRuns.agentId, + nativeIssueId: heartbeatRuns.nativeIssueId, + nativeSessionId: heartbeatRuns.nativeSessionId, + completionContractId: heartbeatRuns.completionContractId, + completionContractSha256: heartbeatRuns.completionContractSha256, + runnerInstanceId: heartbeatRuns.runnerInstanceId, + runtimeMode: heartbeatRuns.runtimeMode, + status: heartbeatRuns.status, + errorCode: heartbeatRuns.errorCode, + nativePhase: heartbeatRuns.nativePhase, + finishedAt: heartbeatRuns.finishedAt, + resultJson: heartbeatRuns.resultJson, + contextSnapshot: sql | null>`case when ${heartbeatRuns.contextSnapshot} is null then null + else jsonb_build_object( + 'skipIssueComment', ${heartbeatRuns.contextSnapshot}->'skipIssueComment', + 'source', ${heartbeatRuns.contextSnapshot}->'source', + 'externalChatContinuation', ${heartbeatRuns.contextSnapshot}->'externalChatContinuation', + 'paperclipWake', jsonb_build_object('externalInteractionContinuation', + ${heartbeatRuns.contextSnapshot} #> '{paperclipWake,externalInteractionContinuation}') + ) end`, + }) .from(heartbeatRuns) .where( and( diff --git a/server/src/services/presentation-ownership-read.test.ts b/server/src/services/presentation-ownership-read.test.ts new file mode 100644 index 00000000000..08ee36f558e --- /dev/null +++ b/server/src/services/presentation-ownership-read.test.ts @@ -0,0 +1,214 @@ +import { randomBytes, randomUUID } from "node:crypto"; +import { agents, companies, completionContracts, createDb, environmentLeases, heartbeatRunEvents, heartbeatRuns, issueComments, issues, nativeRunFinalizations, nativeRunResults, type Db } from "@paperclipai/db"; +import { eq, type SQL } from "drizzle-orm"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../__tests__/helpers/embedded-postgres.js"; +import { NativeRunCoordinatorStore } from "./native-runtime/native-run-coordinator-store.js"; +import { getConversationOwnershipBlocker } from "./conversation-continuation.js"; +import { isExternalChatPresentationContext } from "./heartbeat-run-summary.js"; +import { finalizeNativeRun, repairCommittedNativeChatResponse } from "./native-runtime/native-run-finalizer.js"; + +const support = await getEmbeddedPostgresTestSupport(); +describe.skipIf(!support.supported)("presentation and ownership PostgreSQL read projections", () => { + let database: Awaited>; + let db: ReturnType; + beforeAll(async () => { + database = await startEmbeddedPostgresTestDatabase("presentation-ownership-read-"); + db = createDb(database.connectionString); + }, 60_000); + afterAll(async () => { await db?.$client.end(); await database?.cleanup(); }); + + async function fixture(patch: Partial = {}) { + const companyId = randomUUID(), agentId = randomUUID(), issueId = randomUUID(); + await db.insert(companies).values({ id: companyId, name: "Read fixture", issuePrefix: companyId.slice(0, 8) }); + await db.insert(agents).values({ id: agentId, companyId, name: "Read agent", adapterType: "codex_local" }); + await db.insert(issues).values({ id: issueId, companyId, title: "Read task", status: "blocked", assigneeAgentId: agentId }); + const payload = randomBytes(128 * 1024).toString("base64"); + const [run] = await db.insert(heartbeatRuns).values({ companyId, agentId, nativeIssueId: issueId, + status: "failed", runtimeMode: "legacy", finishedAt: new Date("2020-01-01T00:00:00Z"), + contextSnapshot: { issueId, source: "chat:fixture", prompt: payload, + paperclipWake: { externalInteractionContinuation: true, prompt: payload } }, + runnerProfileJson: { adapterDispatch: { adapterType: "codex_local", instructions: payload }, nativeExecutionInput: { prompt: payload } }, + resultJson: { unknownFutureRecoveryReceipt: { preserved: true } }, stdoutExcerpt: payload, stderrExcerpt: payload, + ...patch, + }).returning(); + return { companyId, agentId, issueId, run }; + } + + function captureReads(fullRows = false) { + const rows: unknown[][] = []; + function recordSelects>(executor: T): T { + return new Proxy(executor, { get(target, key) { + if (key !== "select") return Reflect.get(target, key); + return (...fields: Parameters) => { + const builder = target.select(...fields), from = builder.from.bind(builder); + builder.from = ((...args: Parameters) => { + const selection = fields[0]; + const nested = selection && "run" in selection && "activeLease" in selection; + const repairSource = selection && "nativeSessionId" in selection && "completionContractId" in selection && "finishedAt" in selection; + const sourceRead = args[0] === heartbeatRuns && (nested || repairSource); + const query = fullRows && sourceRead + ? (nested ? target.select({ run: heartbeatRuns, activeLease: selection.activeLease as SQL }) : target.select()).from(heartbeatRuns) + : from(...args); + if (sourceRead) { + const execute = query.execute.bind(query); + query.execute = async (...executeArgs: Parameters) => { + const result = await execute(...executeArgs); rows.push(result); return result; + }; + } + return query; + }) as typeof builder.from; + return builder; + }; + }}); + } + const root = recordSelects(db); + const transaction: Db["transaction"] = (callback, config) => db.transaction(tx => callback(recordSelects(tx)), config); + const recorded = new Proxy(root, { get(target, key) { return key === "transaction" ? transaction : Reflect.get(target, key); } }); + return { recorded, rows }; + } + + async function compareOwnership(f: Awaited>) { + const baseline = captureReads(true), projected = captureReads(); + const expected = await getConversationOwnershipBlocker(baseline.recorded, f.companyId, f.issueId); + const actual = await getConversationOwnershipBlocker(projected.recorded, f.companyId, f.issueId); + expect(actual).toEqual(expected); + expect(projected.rows.flat()).toHaveLength(1); + expect(Buffer.byteLength(JSON.stringify(projected.rows))).toBeLessThan(4096); + expect(Buffer.byteLength(JSON.stringify(baseline.rows))).toBeGreaterThan(128 * 1024); + return actual; + } + + it("keeps current process authority without reading execution payloads", async () => { + const f = await fixture({ processPid: process.pid }); + expect(await compareOwnership(f)).toMatchObject({ runId: f.run.id, cause: "execution_owner_active" }); + expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.run.id)))[0]).toEqual(f.run); + expect(await getConversationOwnershipBlocker(db, randomUUID(), f.issueId)).toBeNull(); + await db.update(heartbeatRuns).set({ processPid: null }).where(eq(heartbeatRuns.id, f.run.id)); + expect(await getConversationOwnershipBlocker(db, f.companyId, f.issueId)).toBeNull(); + }); + + it("retains an active lease until the current database row releases it", async () => { + const f = await fixture(); + const [lease] = await db.insert(environmentLeases).values({ companyId: f.companyId, heartbeatRunId: f.run.id, + issueId: f.issueId, provider: "daytona", providerLeaseId: "fixture-lease", status: "active" }).returning(); + expect(await compareOwnership(f)).toMatchObject({ runId: f.run.id, cause: "execution_owner_active" }); + expect((await db.select().from(environmentLeases).where(eq(environmentLeases.id, lease.id)))[0]).toEqual(lease); + await db.update(environmentLeases).set({ status: "released", releasedAt: new Date("2020-01-01T00:00:00Z") }).where(eq(environmentLeases.id, lease.id)); + expect(await getConversationOwnershipBlocker(db, f.companyId, f.issueId)).toBeNull(); + }); + + it("keeps unconfirmed remote cleanup and all recovery evidence", async () => { + const f = await fixture(); + const [lease] = await db.insert(environmentLeases).values({ companyId: f.companyId, heartbeatRunId: f.run.id, + issueId: f.issueId, provider: "daytona", providerLeaseId: "retained-fixture", status: "released", + releasedAt: new Date("2020-01-01T00:00:00Z"), cleanupStatus: "success" }).returning(); + const result = { ...f.run.resultJson, workspaceRestoreFailure: "restore_unsafe_archive", + workspaceRestoreRecovery: { schema: "paperclip.workspace-restore-recovery.v1", leaseIds: [lease.id] } }; + await db.update(heartbeatRuns).set({ resultJson: result }).where(eq(heartbeatRuns.id, f.run.id)); + expect(await compareOwnership(f)).toMatchObject({ runId: f.run.id, cause: "execution_owner_active" }); + expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.run.id)))[0].resultJson).toEqual(result); + }); + + async function compareRepair(f: Awaited>) { + const baseline = captureReads(true), projected = captureReads(); + const input = { companyId: f.companyId, issueId: f.issueId, runId: f.run.id }; + expect(await repairCommittedNativeChatResponse(projected.recorded, input)) + .toBe(await repairCommittedNativeChatResponse(baseline.recorded, input)); + expect(projected.rows.flat()).toHaveLength(1); + expect(Buffer.byteLength(JSON.stringify(projected.rows))).toBeLessThan(4096); + expect(Buffer.byteLength(JSON.stringify(baseline.rows))).toBeGreaterThan(128 * 1024); + expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.run.id)))[0]).toEqual(f.run); + return projected.rows.flat()[0] as { contextSnapshot: Record | null; resultJson: unknown }; + } + + it("preserves selected answers without downloading prompts, profiles, or excerpts", async () => { + const f = await fixture({ runtimeMode: "native", status: "succeeded", resultJson: { + presentationDecision: { commentId: randomUUID() }, unknownFutureReceipt: { preserved: true } } }); + const row = await compareRepair(f); + expect(row.resultJson).toEqual(f.run.resultJson); + expect(await repairCommittedNativeChatResponse(db, { companyId: randomUUID(), issueId: f.issueId, runId: f.run.id })).toBe(false); + const [other] = await db.insert(issues).values({ companyId: f.companyId, title: "Other task" }).returning(); + expect(await repairCommittedNativeChatResponse(db, { companyId: f.companyId, issueId: other.id, runId: f.run.id })).toBe(false); + }); + + async function unpublishedAcceptedReply() { + const payload = randomBytes(128 * 1024).toString("base64"); + const f = await fixture({ runtimeMode: "native", status: "running", finishedAt: null, + contextSnapshot: { source: "internal", prompt: payload, paperclipWake: { prompt: payload } } }); + const [contract] = await db.insert(completionContracts).values({ companyId: f.companyId, issueId: f.issueId, + revision: 1, schemaVersion: "paperclip.completion-contract.v1", policyVersion: "test", risk: "standard", + completionAuthority: "server_arbiter", incompleteCriteriaPolicy: "preserve_non_terminal", + contractJson: { revision: "test", objective: "Finish the fixture task", criteria: [] }, + canonicalSha256: "read-fixture-contract", createdByActorType: "system", createdByActorId: "test" }).returning(); + const sessionId = randomUUID(), runnerId = randomUUID(); + await db.update(heartbeatRuns).set({ nativeSessionId: sessionId, runnerInstanceId: runnerId, + completionContractId: contract.id, completionContractSha256: contract.canonicalSha256 }).where(eq(heartbeatRuns.id, f.run.id)); + await db.update(issues).set({ status: "in_progress", executionRunId: f.run.id }).where(eq(issues.id, f.issueId)); + const port = new NativeRunCoordinatorStore(db, { companyId: f.companyId, issueId: f.issueId, + runId: f.run.id, agentId: f.agentId, normalizedSessionId: sessionId, completionContractId: contract.id, + completionContractSha256: contract.canonicalSha256, runnerSourceInstanceId: runnerId, + completionContractRevision: "test", completionContractCriterionIds: [] }); + const reply = "The accepted provider reply is preserved exactly."; + await db.insert(heartbeatRunEvents).values({ companyId: f.companyId, runId: f.run.id, agentId: f.agentId, + seq: 1_000_000, eventType: "item.completed", payload: { prpEvent: { turnId: "reply-turn", sourceEventId: "fixture-final-answer", + payload: { kind: "agentMessage", channel: "final", text: reply } } } }); + await port.completeRun({ result: { schema: "paperclip.run_result.v1", reportedWorkDisposition: "done", + summary: "The accepted summary differs from its final answer.", completionClaim: { contractRevision: "test", + objectiveSatisfied: true, criteria: [], remainingWork: [] }, evidence: [], verification: [], attentionRequests: [], artifacts: [] }, + terminal: { schema: "paperclip.prp.terminal.v1", runTerminalState: "succeeded", turnTerminalState: "completed", reportedWorkDisposition: "done" }, + turnId: "reply-turn" }); + await finalizeNativeRun({ db, runId: f.run.id, workspaceFinalizeStatus: "succeeded", projectRunStatus: false }); + expect((await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, f.run.id)))[0]).toMatchObject({ phase: "committed" }); + await db.update(heartbeatRuns).set({ status: "succeeded", finishedAt: new Date("2020-01-01T00:00:00Z") }).where(eq(heartbeatRuns.id, f.run.id)); + expect(await db.select().from(issueComments).where(eq(issueComments.createdByRunId, f.run.id))).toEqual([]); + const [before] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.run.id)); + expect(before.resultJson?.presentationDecision).toBeUndefined(); + return { ...f, before, reply }; + } + + it("publishes the same accepted reply and decision from equivalent full-row and projected starting states", async () => { + const outcomes: unknown[] = []; + for (const fullRows of [true, false]) { + const f = await unpublishedAcceptedReply(), captured = captureReads(fullRows); + const input = { companyId: f.companyId, issueId: f.issueId, runId: f.run.id }; + expect(await repairCommittedNativeChatResponse(captured.recorded, input)).toBe(true); + const comments = await db.select().from(issueComments).where(eq(issueComments.createdByRunId, f.run.id)); + expect(comments).toHaveLength(1); expect(comments[0].body).toBe(f.reply); + const [after] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.run.id)); + const decision = after.resultJson!.presentationDecision as Record; + expect(decision.commentId).toBe(comments[0].id); + const { commentId: _, ...stableDecision } = decision; + outcomes.push({ body: comments[0].body, decision: stableDecision }); + expect(after.resultJson).toMatchObject(f.before.resultJson!); + expect(after.contextSnapshot).toEqual(f.before.contextSnapshot); + expect(after.runnerProfileJson).toEqual(f.before.runnerProfileJson); + expect(after.stdoutExcerpt).toBe(f.before.stdoutExcerpt); + expect(after.stderrExcerpt).toBe(f.before.stderrExcerpt); + expect(await db.select().from(nativeRunResults).where(eq(nativeRunResults.runId, f.run.id))).toHaveLength(1); + expect(await repairCommittedNativeChatResponse(db, input)).toBe(false); + expect(await db.select().from(issueComments).where(eq(issueComments.createdByRunId, f.run.id))).toHaveLength(1); + expect(captured.rows.flat()).toHaveLength(1); + if (fullRows) expect(Buffer.byteLength(JSON.stringify(captured.rows))).toBeGreaterThan(128 * 1024); + else expect(Buffer.byteLength(JSON.stringify(captured.rows))).toBeLessThan(4096); + } + expect(outcomes[1]).toEqual(outcomes[0]); + }); + + it.each([null, [], "scalar", 42, { source: 42, skipIssueComment: "true", paperclipWake: [] }, + { source: "issue.comment.created", externalChatContinuation: true }, + { source: "chat:fixture", skipIssueComment: true, paperclipWake: { externalInteractionContinuation: "true" } }, + { source: "internal", paperclipWake: { externalInteractionContinuation: true } }, + ].map(context => ({ context })))("preserves typed publication flags for $context", async ({ context }) => { + const f = await fixture({ runtimeMode: "native", status: "succeeded", contextSnapshot: context as Record | null }); + const row = await compareRepair(f); + expect(isExternalChatPresentationContext(row.contextSnapshot)).toBe(isExternalChatPresentationContext(context)); + const original = context && typeof context === "object" && !Array.isArray(context) ? context : {}; + expect(row.contextSnapshot?.skipIssueComment === true).toBe((original as Record).skipIssueComment === true); + }); + + it.each([null, ["stdout", { receipt: true }], "scalar", 42].map(result => ({ result })))("preserves non-object result evidence $result", async ({ result }) => { + const f = await fixture({ runtimeMode: "native", status: "succeeded", resultJson: result as Record | null }); + expect((await compareRepair(f)).resultJson).toEqual(result); + }); +}); From a3675ddcdff1a6ff66dcb28fa7b295d0a491eed8 Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Sat, 24 Oct 2026 15:39:28 -0700 Subject: [PATCH 022/110] Add bounded database response size diagnostics (#17504) Count database response value sizes by public caller and static table for one explicit UTC window of at most 60 seconds. Keep diagnostics off by default and exclude SQL, parameters, returned values, errors, and credentials from output. Preserve lazy execution, transaction boundaries, and no-replay behavior. Verification: full build and recursive typecheck; 63 focused database and PostgreSQL tests; eight physical disconnect tests with capture enabled. Co-Authored-By: Paperclip --- doc/DATABASE.md | 25 ++ packages/db/src/client.ts | 2 + .../db/src/response-capture-postgres.test.ts | 190 ++++++++++++ packages/db/src/response-capture.test.ts | 133 +++++++++ packages/db/src/response-capture.ts | 273 ++++++++++++++++++ 5 files changed, 623 insertions(+) create mode 100644 packages/db/src/response-capture-postgres.test.ts create mode 100644 packages/db/src/response-capture.test.ts create mode 100644 packages/db/src/response-capture.ts diff --git a/doc/DATABASE.md b/doc/DATABASE.md index 13424c8fad6..bc1292bbe94 100644 --- a/doc/DATABASE.md +++ b/doc/DATABASE.md @@ -320,6 +320,31 @@ DATABASE_MAX_LIFETIME_SECONDS=1800 # recycle a pooled connection after this lo DATABASE_APPLICATION_NAME=paperclip # application_name in pg_stat_activity; default: paperclip ``` +### Bounded response diagnostics + +`PAPERCLIP_DB_RESPONSE_CAPTURE_WINDOW=/` enables one explicit UTC +window. Both timestamps use ISO format ending in `Z`. The window lasts at most +60 seconds and starts within 30 minutes. Unset, invalid, and expired windows +leave database construction unchanged. An expired window stays inactive after a +restart; remove the setting after the investigation. + +The diagnostic measures awaited Postgres.js `unsafe` responses before Drizzle +column decoding. It retains the Drizzle builder caller for normal, prepared, +transaction, and dedicated-pool execution. It issues no queries. +It logs the public server caller locations, static schema table, operation, +query/row counts, and response value sizes. It emits at most 128 aggregate +groups and a summary at the deadline. It never logs SQL, parameters, result +values, connection strings, or query errors. In-flight queries continue normally. + +Look for `paperclip.db_response_capture.entry.v1` and +`paperclip.db_response_capture.summary.v1` in the process logs. Tagged raw-driver calls, streams, unawaited raw-driver +dispatch, and protocol overhead are not measured. Relational queries use a driver-level caller fallback. +Queries still in flight at the deadline are reported separately. Sizes describe +driver values before column decoding, not billed network bytes. Complex parsed +values use JSON size estimates, counted in `estimatedValues`. Reconcile them with +provider metering and socket measurements. Serialization adds temporary CPU and memory work; +measure the final transfer rate after the window expires. + ### Push the schema ```sh diff --git a/packages/db/src/client.ts b/packages/db/src/client.ts index 5149c1c9b27..f1b8079db45 100644 --- a/packages/db/src/client.ts +++ b/packages/db/src/client.ts @@ -4,6 +4,7 @@ import { readFile, readdir } from "node:fs/promises"; import { fileURLToPath } from "node:url"; import postgres from "postgres"; import { installDatabaseWorkSignals } from "./work-signals.js"; +import { installDatabaseResponseCapture } from "./response-capture.js"; import * as schema from "./schema/index.js"; const MIGRATIONS_FOLDER = fileURLToPath(new URL("./migrations", import.meta.url)); @@ -307,6 +308,7 @@ function createDbClient(url: string, resolved: DatabaseClientOptions, owner?: ob // message cannot establish that replay is safe. Leave retries to callers // that know the complete operation is idempotent. const db = installDatabaseWorkSignals(drizzlePg(sql, { schema }), owner); + installDatabaseResponseCapture(db, schema); dedicatedDbFactories.set(db, () => createDbClient(url, { ...resolved, maxConnections: 1, applicationName: "paperclip-workspace-finalization-lock", }, db)); diff --git a/packages/db/src/response-capture-postgres.test.ts b/packages/db/src/response-capture-postgres.test.ts new file mode 100644 index 00000000000..370d738d056 --- /dev/null +++ b/packages/db/src/response-capture-postgres.test.ts @@ -0,0 +1,190 @@ +import { randomUUID } from "node:crypto"; +import { compileFunction } from "node:vm"; +import { eq, sql } from "drizzle-orm"; +import { pgTable, text } from "drizzle-orm/pg-core"; +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; +import { createDb, withDedicatedDbConnection } from "./client.js"; +import { createDatabaseResponseCapture, databaseResponseCaptureFromEnv, installDatabaseResponseCapture } from "./response-capture.js"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./test-embedded-postgres.js"; +import { encodeRunEventPayload, runEventPayload } from "./run-event-payload.js"; +import { databaseWorkPending, reconcileDatabaseWork, signalDatabaseWork, subscribeDatabaseWork } from "./work-signals.js"; + +const table = pgTable("response_capture_fixture", { id: text("id").primaryKey(), payload: text("payload").notNull() }); +const encodedTable = pgTable("response_capture_encoded_fixture", { id: text("id").primaryKey(), payload: runEventPayload("payload") }); +const support = await getEmbeddedPostgresTestSupport(); +describe.skipIf(!support.supported)("database response capture PostgreSQL behavior", () => { + let temporary: Awaited>; + const clients: Array> = []; + const captures: Array> = []; + beforeAll(async () => { + temporary = await startEmbeddedPostgresTestDatabase("response-capture-"); + const db = createDb(temporary.connectionString); + try { + await db.execute(sql`create table response_capture_fixture (id text primary key, payload text not null)`); + await db.execute(sql`create table response_capture_encoded_fixture (id text primary key, payload jsonb not null)`); + } + finally { await db.$client.end(); } + }, 90_000); + afterEach(async () => { + for (const capture of captures.splice(0)) capture.flush(); + for (const client of clients.splice(0)) await client.$client.end(); + vi.restoreAllMocks(); vi.unstubAllEnvs(); + }); + afterAll(async () => { await temporary?.cleanup(); }); + function fixture() { + const events: Array> = []; + const now = Date.now(); + const capture = createDatabaseResponseCapture({ start: now - 100, end: now + 59_000 }, event => events.push(event)); + const db = createDb(temporary.connectionString); + clients.push(db); captures.push(capture); + expect(installDatabaseResponseCapture(db, { table, encodedTable }, capture)).toBe(db); + expect(installDatabaseResponseCapture(db, { table, encodedTable }, capture)).toBe(db); + return { db, capture, events }; + } + function summary(events: Array>) { return events.find(event => event.event === "paperclip.db_response_capture.summary.v1")!; } + + it("keeps rows and builder identity through lazy select and write returning", async () => { + const f = fixture(), id = randomUUID(), payload = "sentinel-result-and-parameter-value🙂\n\""; + const insert = f.db.insert(table).values({ id, payload }); + expect(insert.returning()).toBe(insert); + expect(await insert).toEqual([{ id, payload }]); + const query = f.db.select().from(table); + expect(query.where(eq(table.id, id))).toBe(query); + expect(await query).toEqual([{ id, payload }]); + const updated = await f.db.update(table).set({ payload: "changed" }).where(eq(table.id, id)).returning(); + expect(updated).toEqual([{ id, payload: "changed" }]); + expect(await f.db.delete(table).where(eq(table.id, id)).returning()).toEqual([{ id, payload: "changed" }]); + f.capture.flush(); + expect(summary(f.events)).toMatchObject({ startedQueries: 4, completedQueries: 4 }); + expect(f.events.filter(event => event.event === "paperclip.db_response_capture.entry.v1").map(event => event.operation).sort()) + .toEqual(["delete", "insert", "select", "update"]); + expect(JSON.stringify(f.events)).not.toContain(payload); + expect(JSON.stringify(f.events)).not.toContain(id); + }); + it("counts the stored encoding before a custom column decoder changes the value", async () => { + const setup = createDb(temporary.connectionString); clients.push(setup); + const id = randomUUID(), payload = { text: "codec-payload-sentinel\u0000value".repeat(512) }; + await setup.insert(encodedTable).values({ id, payload }); + const f = fixture(); + expect(await f.db.select().from(encodedTable).where(eq(encodedTable.id, id))).toEqual([{ id, payload }]); + f.capture.flush(); + const entry = f.events.find(event => event.table === "response_capture_encoded_fixture")!; + expect(entry.responseValueBytes).toBe(Buffer.byteLength(id) + Buffer.byteLength(encodeRunEventPayload(payload))); + expect(entry.responseValueBytes).toBeGreaterThan(Buffer.byteLength(JSON.stringify({ id, payload }))); + expect(JSON.stringify(f.events)).not.toContain("codec-payload-sentinel"); + }); + it("keeps a raw driver query lazy and counts repeated awaits without replay", async () => { + const f = fixture(), id = randomUUID(); + const observer = createDb(temporary.connectionString); clients.push(observer); + const pending = f.db.$client.unsafe("insert into response_capture_fixture (id, payload) values ($1, $2) returning id", [id, "raw-lazy-sentinel"]); + expect(await observer.select().from(table).where(eq(table.id, id))).toEqual([]); + const first = await pending; + expect(await pending).toBe(first); + expect(first).toEqual([{ id }]); + expect(await observer.select().from(table).where(eq(table.id, id))).toEqual([{ id, payload: "raw-lazy-sentinel" }]); + f.capture.flush(); + expect(summary(f.events)).toMatchObject({ startedQueries: 1, completedQueries: 1 }); + expect(JSON.stringify(f.events)).not.toContain("raw-lazy-sentinel"); + expect(JSON.stringify(f.events)).not.toContain(id); + }); + it("counts prepared executions once and retains their parameter bindings", async () => { + const f = fixture(), id = randomUUID(); + await f.db.insert(table).values({ id, payload: "prepared-value" }); + const prepared = f.db.select().from(table).where(eq(table.id, sql.placeholder("id"))).prepare("response_capture_prepared"); + expect(await prepared.execute({ id })).toEqual([{ id, payload: "prepared-value" }]); + expect(await prepared.execute({ id: randomUUID() })).toEqual([]); + f.capture.flush(); + expect(summary(f.events)).toMatchObject({ startedQueries: 3, completedQueries: 3 }); + expect(JSON.stringify(f.events)).not.toContain("prepared-value"); + }); + it("retains distinct builder callers through normal, prepared, and transaction execution", async () => { + const f = fixture(), id = randomUUID(); + const setup = createDb(temporary.connectionString); clients.push(setup); + await setup.insert(table).values({ id, payload: "caller-sentinel" }); + const shape = f.db.select().from(table); + const caller = (name: string) => compileFunction( + "return db.select().from(table).where(eq(table.id, id))", ["db", "id"], + { filename: `/fixture/server/src/services/${name}.ts`, contextExtensions: [{ table, eq }] }, + ) as (db: Pick, id: string) => typeof shape; + const fromA = caller("capture-caller-a"), fromB = caller("capture-caller-b"); + const normalA = fromA(f.db, id), normalB = fromB(f.db, id); + expect(await normalA).toEqual([{ id, payload: "caller-sentinel" }]); + expect(await normalB).toEqual([{ id, payload: "caller-sentinel" }]); + const prepared = fromA(f.db, id).prepare("capture_caller_prepared"); + expect(await prepared.execute()).toEqual([{ id, payload: "caller-sentinel" }]); + await f.db.transaction(async tx => { + expect(await fromB(tx, id)).toEqual([{ id, payload: "caller-sentinel" }]); + }); + f.capture.flush(); + const entries = f.events.filter(event => event.event === "paperclip.db_response_capture.entry.v1"); + expect(entries).toHaveLength(2); + for (const name of ["a", "b"]) { + expect(entries.find(event => (event.callers as string[]).some(location => location.startsWith(`services/capture-caller-${name}.ts:`)))) + .toMatchObject({ operation: "select", table: "response_capture_fixture", calls: 2, rows: 2 }); + } + expect(summary(f.events)).toMatchObject({ startedQueries: 4, completedQueries: 4 }); + expect(JSON.stringify(f.events)).not.toContain("/fixture/"); + expect(JSON.stringify(f.events)).not.toContain("caller-sentinel"); + expect(JSON.stringify(f.events)).not.toContain(id); + }); + it("records the executed CTE rather than its unexecuted inner select", async () => { + const f = fixture(), id = randomUUID(); + await f.db.insert(table).values({ id, payload: "cte-value" }); + const cte = f.db.$with("capture_cte").as(f.db.select().from(table).where(eq(table.id, id))); + expect(await f.db.with(cte).select().from(cte)).toEqual([{ id, payload: "cte-value" }]); + f.capture.flush(); + expect(summary(f.events)).toMatchObject({ startedQueries: 2, completedQueries: 2 }); + }); + it("keeps raw execute results and rejection behavior without logging SQL or errors", async () => { + const f = fixture(); + expect(await f.db.execute(sql`select ${"sentinel-sql-parameter"}::text as value`)).toEqual([{ value: "sentinel-sql-parameter" }]); + await expect(f.db.execute(sql`select 1/0`)).rejects.toThrow(); + f.capture.flush(); + expect(summary(f.events)).toMatchObject({ startedQueries: 2, completedQueries: 2 }); + expect(f.events.find(event => event.operation === "execute")).toMatchObject({ queryErrors: 1 }); + expect(JSON.stringify(f.events)).not.toContain("sentinel-sql-parameter"); + expect(JSON.stringify(f.events)).not.toContain("select 1/0"); + }); + it("preserves nested commit, rollback, and durable work-signal boundaries", async () => { + const f = fixture(), id = randomUUID(), events: string[] = []; + const unsubscribe = subscribeDatabaseWork(f.db, "capture-topic", event => events.push(event)); + try { + expect(await f.db.transaction(async tx => { + await tx.transaction(async nested => { + await signalDatabaseWork(nested, "capture-topic"); + await nested.insert(table).values({ id, payload: "committed" }); + }); + expect(events).toEqual(["intent"]); expect(databaseWorkPending(f.db, "capture-topic")).toBe(true); + return 42; + })).toBe(42); + expect(events).toEqual(["intent", "settled"]); + expect(databaseWorkPending(f.db, "capture-topic")).toBe(false); + const rolledBack = randomUUID(); + await expect(f.db.transaction(async tx => { + await signalDatabaseWork(tx, "capture-topic"); + await tx.insert(table).values({ id: rolledBack, payload: "rolled-back" }); + throw new Error("rollback fixture"); + })).rejects.toThrow("rollback fixture"); + await reconcileDatabaseWork(f.db, "capture-topic"); + expect(databaseWorkPending(f.db, "capture-topic")).toBe(false); + expect(await f.db.select().from(table).where(eq(table.id, rolledBack))).toEqual([]); + expect(await f.db.select().from(table).where(eq(table.id, id))).toEqual([{ id, payload: "committed" }]); + } finally { unsubscribe(); } + f.capture.flush(); + expect(summary(f.events).completedQueries).toBeGreaterThan(4); + }); + it("covers automatically created dedicated pools and retains owner identity", async () => { + const logs: string[] = [], now = Date.now(); + vi.spyOn(console, "info").mockImplementation(value => logs.push(String(value))); + vi.stubEnv("PAPERCLIP_DB_RESPONSE_CAPTURE_WINDOW", `${new Date(now - 100).toISOString()}/${new Date(now + 59_000).toISOString()}`); + const db = createDb(temporary.connectionString); clients.push(db); + const capture = databaseResponseCaptureFromEnv()!; captures.push(capture); + expect(await withDedicatedDbConnection(db, async dedicated => dedicated.execute(sql`select ${"dedicated-value"}::text as value`))) + .toEqual([{ value: "dedicated-value" }]); + capture.flush(); + const events = logs.map(line => JSON.parse(line) as Record); + expect(summary(events)).toMatchObject({ startedQueries: 1, completedQueries: 1 }); + expect(logs.join("\n")).not.toContain("dedicated-value"); + expect(logs.join("\n")).not.toContain(temporary.connectionString); + }); +}); diff --git a/packages/db/src/response-capture.test.ts b/packages/db/src/response-capture.test.ts new file mode 100644 index 00000000000..65f58d10883 --- /dev/null +++ b/packages/db/src/response-capture.test.ts @@ -0,0 +1,133 @@ +import { integer, pgTable } from "drizzle-orm/pg-core"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { createDatabaseResponseCapture, installDatabaseResponseCapture, publicDatabaseCallers, responseCaptureWindow } from "./response-capture.js"; + +const epoch = Date.parse("2020-01-01T00:00:00Z"); +const metadata = { operation: "select", table: "capture_fixture", callers: ["services/fixture.ts:4:2"] }; +const table = pgTable("capture_fixture", { id: integer("id") }); +const captures: Array> = []; +afterEach(() => { for (const capture of captures.splice(0)) capture.flush(); vi.unstubAllEnvs(); }); +function fixture(emitOverride?: (event: Record) => void) { + let clock = epoch; + const events: Array> = []; + const capture = createDatabaseResponseCapture({ start: epoch, end: epoch + 60_000 }, emitOverride ?? (event => events.push(event)), () => clock); + captures.push(capture); + return { capture, events, now: (value: number) => { clock = value; } }; +} + +describe("bounded database response capture", () => { + it.each([undefined, "", "sentinel-invalid-input", "2020-01-01T00:00:00Z", "2020-01-01T00:00:00Z/2020-01-01T00:00:00Z", + "2020-01-01T00:00:00Z/2020-01-01T00:01:01Z", "2020-01-01T01:00:00Z/2020-01-01T01:01:00Z", + "2020-01-01T00:00:00Z/2020-01-01T00:01:00Z/extra", + ])("disables absent, malformed, expired, or unbounded windows: %s", value => { + expect(responseCaptureWindow(value, epoch + 60_000)).toBeUndefined(); + }); + it("accepts a fixed future window of at most one minute", () => { + expect(responseCaptureWindow("2020-01-01T00:01:00Z/2020-01-01T00:02:00Z", epoch)) + .toEqual({ start: epoch + 60_000, end: epoch + 120_000 }); + expect(() => createDatabaseResponseCapture({ start: epoch, end: epoch + 60_001 }, () => {})).toThrow("Invalid"); + }); + it("keeps only public server file locations from stacks", () => { + const stack = ["Error: sentinel-message", "at f (/private/fixture/server/src/services/example.ts:4:2)", + "at f (/private/fixture/server/src/services/example.ts:4:2)", "at f (/private/fixture/server/dist/routes/example.js:5:3)", + "at f (/private/fixture/customer-file.js:7:9)", "at f (/app/server/src/services/../../customer-file.ts:8:1)"].join("\n"); + expect(publicDatabaseCallers(stack)).toEqual(["services/example.ts:4:2", "routes/example.js:5:3"]); + }); + it("leaves methods and identity unchanged when disabled", () => { + vi.stubEnv("PAPERCLIP_DB_RESPONSE_CAPTURE_WINDOW", undefined); + const db = { select: vi.fn(), transaction: vi.fn() }, select = db.select, transaction = db.transaction; + expect(installDatabaseResponseCapture(db, { table })).toBe(db); + expect(db.select).toBe(select); expect(db.transaction).toBe(transaction); + }); + it("preserves exact values and only emits counts, sizes, and caller metadata", async () => { + const f = fixture(), rows = [{ text: "sentinel-result-value🙂\n\"", n: 4n }]; + expect(await f.capture.execute(() => Promise.resolve(rows), metadata)).toBe(rows); + f.capture.flush(); + const entry = f.events.find(event => event.event === "paperclip.db_response_capture.entry.v1")!; + expect(entry).toMatchObject({ calls: 1, rows: 1, queryErrors: 0, serializationErrors: 0, + responseValueBytes: Buffer.byteLength(JSON.stringify(rows, (_, value) => typeof value === "bigint" ? value.toString() : value)) }); + expect(JSON.stringify(f.events)).not.toContain("sentinel-result-value"); + expect(f.events.at(-1)).toMatchObject({ startedQueries: 1, completedQueries: 1, inFlightAtEnd: 0, + rowValuesLogged: false, sqlOrParametersLogged: false, wireBytesMeasured: false }); + }); + it("counts driver text values without adding JSON escaping or column names", async () => { + const f = fixture(), text = "sentinel-driver-text\n\""; + const rows = Object.assign([[text, true, 42n, null]], { columns: [ + { name: "sentinel-column-name" }, { name: "b" }, { name: "n" }, { name: "empty" } ] }); + expect(await f.capture.execute(() => Promise.resolve(rows), metadata)).toBe(rows); + f.capture.flush(); + expect(f.events[0]).toMatchObject({ responseValueBytes: Buffer.byteLength(text) + 1 + 2, estimatedValues: 0 }); + expect(JSON.stringify(f.events)).not.toContain("sentinel-driver-text"); + expect(JSON.stringify(f.events)).not.toContain("sentinel-column-name"); + }); + it("does not alter synchronous or asynchronous errors or retry them", async () => { + const f = fixture(), error = new Error("sentinel-private-error"); + const sync = vi.fn(() => { throw error; }), asyncFailure = vi.fn(() => Promise.reject(error)); + expect(() => f.capture.execute(sync, metadata)).toThrow(error); + await expect(f.capture.execute(asyncFailure, metadata)).rejects.toBe(error); + expect(sync).toHaveBeenCalledTimes(1); expect(asyncFailure).toHaveBeenCalledTimes(1); + f.capture.flush(); + expect(f.events[0]).toMatchObject({ calls: 2, queryErrors: 2, responseValueBytes: 0 }); + expect(JSON.stringify(f.events)).not.toContain("sentinel-private-error"); + }); + it("keeps unserializable results and logging failures out of the query outcome", () => { + const f = fixture(), circular: Record = {}; circular.self = circular; + expect(f.capture.execute(() => circular, metadata)).toBe(circular); + f.capture.flush(); + expect(f.events[0]).toMatchObject({ calls: 1, serializationErrors: 1 }); + const brokenLogger = fixture(() => { throw new Error("logger fixture"); }); + expect(brokenLogger.capture.execute(() => circular, metadata)).toBe(circular); + expect(() => brokenLogger.capture.flush()).not.toThrow(); + }); + it("stops accounting at the deadline and leaves in-flight work untouched", async () => { + const f = fixture(); + let resolve!: (rows: unknown[]) => void; + const pending = new Promise(done => { resolve = done; }); + const result = f.capture.execute(() => pending, metadata); + f.now(epoch + 60_000); f.capture.flush(); + expect(f.events.at(-1)).toMatchObject({ startedQueries: 1, completedQueries: 0, inFlightAtEnd: 1 }); + const rows = [{ marker: "late-result-value" }]; resolve(rows); + expect(await result).toBe(rows); + const direct = Promise.resolve(rows); + expect(f.capture.execute(() => direct, metadata)).toBe(direct); + expect(f.events).toHaveLength(1); + }); + it("retains the deadline count when a query resolves before a delayed flush", async () => { + const f = fixture(); + let resolve!: (rows: unknown[]) => void; + const pending = new Promise(done => { resolve = done; }); + const result = f.capture.execute(() => pending, metadata); + f.now(epoch + 60_001); + const rows = [{ marker: "late-before-flush-sentinel" }]; resolve(rows); + expect(await result).toBe(rows); + f.capture.flush(); + expect(f.events).toHaveLength(1); + expect(f.events[0]).toMatchObject({ startedQueries: 1, completedQueries: 0, inFlightAtEnd: 1, responseValueBytes: 0 }); + expect(JSON.stringify(f.events)).not.toContain("late-before-flush-sentinel"); + }); + it("bounds cardinality without dropping response-byte totals", () => { + const f = fixture(); + for (let i = 0; i < 200; i += 1) f.capture.execute(() => [i], { ...metadata, callers: [`services/f${i}.ts:1:1`] }); + f.capture.flush(); + const summary = f.events.at(-1)!; + expect(summary).toMatchObject({ startedQueries: 200, completedQueries: 200, groups: 128, overflowCalls: 73 }); + expect(summary.responseValueBytes).toBe(Array.from({ length: 200 }, (_, i) => Buffer.byteLength(JSON.stringify([i]))).reduce((a, b) => a + b, 0)); + }); + it("does not execute builders or prepared statements until requested", async () => { + const f = fixture(), rows = [{ id: 1 }], execute = vi.fn(async () => rows); + const query = { execute, prepare: () => ({ execute }) }; + const builder = { from: () => query }; + const db = { select: () => builder }; + expect(installDatabaseResponseCapture(db, { table }, f.capture)).toBe(db); + expect(db.select()).toBe(builder); + expect(db.select().from()).toBe(query); + expect(execute).not.toHaveBeenCalled(); + const prepared = query.prepare(); + expect(execute).not.toHaveBeenCalled(); + expect(await prepared.execute()).toBe(rows); + expect(await query.execute()).toBe(rows); + expect(execute).toHaveBeenCalledTimes(2); + f.capture.flush(); + expect(f.events.at(-1)).toMatchObject({ completedQueries: 0 }); + }); +}); diff --git a/packages/db/src/response-capture.ts b/packages/db/src/response-capture.ts new file mode 100644 index 00000000000..8f738043f4d --- /dev/null +++ b/packages/db/src/response-capture.ts @@ -0,0 +1,273 @@ +import { AsyncLocalStorage } from "node:async_hooks"; +import { randomUUID } from "node:crypto"; +import { getTableName, is, Table } from "drizzle-orm"; + +type Metadata = { operation: string; table: string; callers: string[] }; +type Entry = Metadata & { calls: number; rows: number; bytes: number; maxBytes: number; queryErrors: number; serializationErrors: number; estimatedValues: number }; +type Event = Record; +type Method = (this: unknown, ...args: unknown[]) => unknown; +export type ResponseCaptureWindow = { start: number; end: number }; + +export function responseCaptureWindow(value: string | undefined, now = Date.now()): ResponseCaptureWindow | undefined { + if (!value) return; + const parts = value.split("/"); + if (parts.length !== 2 || parts.some(part => !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?Z$/.test(part))) return; + const start = Date.parse(parts[0]!), end = Date.parse(parts[1]!); + if (!Number.isFinite(start) || !Number.isFinite(end) || end <= start || end - start > 60_000 || end <= now || start > now + 30 * 60_000) return; + return { start, end }; +} + +export function publicDatabaseCallers(stack: string | undefined): string[] { + const callers: string[] = []; + for (const line of (stack ?? "").split("\n")) { + const match = line.match(/[/\\]server[/\\](?:src|dist)[/\\]((?:services|routes|modules|middleware)[/\\][A-Za-z0-9_./\\-]+\.[cm]?[jt]s):(\d+):(\d+)/); + if (!match) continue; + const relative = match[1]!.replaceAll("\\", "/"); + if (relative.split("/").includes("..")) continue; + const caller = `${relative}:${match[2]}:${match[3]}`; + if (!callers.includes(caller)) callers.push(caller); + if (callers.length === 4) break; + } + return callers; +} + +function responseValueSize(value: unknown): { bytes: number; estimatedValues: number } { + const columns = value && typeof value === "object" ? (value as { columns?: unknown }).columns : undefined; + if (!Array.isArray(value) || !Array.isArray(columns)) { + const serialized = JSON.stringify(value, (_, item: unknown) => typeof item === "bigint" ? item.toString() : item); + return { bytes: serialized === undefined ? 0 : Buffer.byteLength(serialized), estimatedValues: 1 }; + } + let bytes = 0, estimatedValues = 0; + for (const row of value) { + const cells = Array.isArray(row) ? row : columns.map(column => row[column.name]); + for (const cell of cells) { + if (cell === null || cell === undefined) continue; + if (typeof cell === "string") bytes += Buffer.byteLength(cell); + else if (typeof cell === "boolean") bytes += 1; + else if (typeof cell === "number" || typeof cell === "bigint") bytes += Buffer.byteLength(String(cell)); + else { + estimatedValues += 1; + const serialized = JSON.stringify(cell, (_, item: unknown) => typeof item === "bigint" ? item.toString() : item); + if (serialized !== undefined) bytes += Buffer.byteLength(serialized); + } + } + } + return { bytes, estimatedValues }; +} + +export function createDatabaseResponseCapture( + window: ResponseCaptureWindow, + emit: (event: Event) => void, + now: () => number = Date.now, +) { + if (!Number.isFinite(new Date(window.start).getTime()) || !Number.isFinite(new Date(window.end).getTime()) || + window.end <= window.start || window.end - window.start > 60_000) throw new Error("Invalid database response capture window"); + const id = randomUUID(), entries = new Map(); + const roots = new WeakSet(), queries = new WeakSet(), factories = new WeakSet(); + const clients = new WeakSet(), driverQueries = new WeakSet(); + const scope = new AsyncLocalStorage(); + let closed = false, inFlight = 0, started = 0, completed = 0, overflowCalls = 0; + const send = (event: Event) => { try { emit(event); } catch {} }; + const expired = () => closed || now() >= window.end; + const active = () => !expired() && now() >= window.start; + const flush = () => { + if (closed) return; + closed = true; + clearTimeout(timer); + scope.disable(); + const ordered = [...entries.values()].sort((a, b) => b.bytes - a.bytes); + for (const entry of ordered) send({ event: "paperclip.db_response_capture.entry.v1", captureId: id, + operation: entry.operation, table: entry.table, callers: entry.callers, calls: entry.calls, rows: entry.rows, + responseValueBytes: entry.bytes, maxResponseValueBytes: entry.maxBytes, estimatedValues: entry.estimatedValues, + queryErrors: entry.queryErrors, serializationErrors: entry.serializationErrors }); + send({ event: "paperclip.db_response_capture.summary.v1", captureId: id, + windowStart: new Date(window.start).toISOString(), windowEnd: new Date(window.end).toISOString(), + closedAt: new Date(now()).toISOString(), + startedQueries: started, completedQueries: completed, inFlightAtEnd: inFlight, groups: entries.size, + overflowCalls, responseValueBytes: ordered.reduce((sum, entry) => sum + entry.bytes, 0), + rowValuesLogged: false, sqlOrParametersLogged: false, wireBytesMeasured: false, + measurementBoundary: "postgres-js results before Drizzle column decoding", + relationalQueriesMeasured: true, unsafeDriverQueriesMeasured: true, + taggedDriverQueriesMeasured: false, streamingQueriesMeasured: false }); + entries.clear(); + }; + const timer = setTimeout(flush, Math.max(0, window.end - now())); + timer.unref(); + function finish(metadata: Metadata, value: unknown, failed: boolean) { + if (!active()) return; + inFlight -= 1; + completed += 1; + try { + let key = JSON.stringify(metadata); + if (!entries.has(key) && entries.size >= 127) { + overflowCalls += 1; + metadata = { operation: "other", table: "other", callers: [] }; + key = "overflow"; + } + let entry = entries.get(key); + if (!entry) { + entry = { ...metadata, calls: 0, rows: 0, bytes: 0, maxBytes: 0, queryErrors: 0, serializationErrors: 0, estimatedValues: 0 }; + entries.set(key, entry); + } + entry.calls += 1; + if (failed) { entry.queryErrors += 1; return; } + entry.rows += Array.isArray(value) ? value.length : 0; + try { + const size = responseValueSize(value); + entry.bytes += size.bytes; + entry.maxBytes = Math.max(entry.maxBytes, size.bytes); + entry.estimatedValues += size.estimatedValues; + } catch { entry.serializationErrors += 1; } + } catch {} + } + function execute(action: () => unknown, metadata: Metadata) { + if (!active()) return action(); + inFlight += 1; started += 1; + let result: unknown; + try { result = action(); } + catch (error) { finish(metadata, undefined, true); throw error; } + let asynchronous = false; + try { asynchronous = Boolean(result && typeof (result as { then?: unknown }).then === "function"); } catch {} + if (asynchronous) { + return Promise.resolve(result).then(value => { finish(metadata, value, false); return value; }, + error => { finish(metadata, undefined, true); throw error; }); + } + finish(metadata, result, false); + return result; + } + return { window, roots, queries, factories, clients, driverQueries, scope, active, expired, execute, flush }; +} + +type Capture = ReturnType; +let environmentCapture: { key: string; capture: Capture } | undefined; +export function databaseResponseCaptureFromEnv(env: NodeJS.ProcessEnv = process.env): Capture | undefined { + const key = env.PAPERCLIP_DB_RESPONSE_CAPTURE_WINDOW; + const window = responseCaptureWindow(key); + if (!key || !window) return; + if (environmentCapture?.key === key) return environmentCapture.capture; + const capture = createDatabaseResponseCapture(window, event => console.info(JSON.stringify(event))); + environmentCapture = { key, capture }; + return capture; +} + +export function installDatabaseResponseCapture(db: T, schema: Record, capture = databaseResponseCaptureFromEnv()): T { + if (!capture || capture.expired()) return db; + const tables = new Set(Object.values(schema).filter(value => is(value, Table)).map(table => getTableName(table))); + const object = (value: unknown): value is Record => value !== null && typeof value === "object"; + function replace(target: Record, name: string, replacement: (original: Method) => Method) { + const original = target[name]; + if (typeof original !== "function") return; + try { target[name] = replacement(original as Method); } catch {} + } + function tableName(value: unknown) { + try { if (is(value, Table)) { const name = getTableName(value); if (tables.has(name)) return name; } } catch {} + return "other"; + } + function query(value: unknown, metadata: Metadata) { + if (!object(value) || capture!.queries.has(value)) return; + capture!.queries.add(value); + replace(value, "execute", original => function (this: unknown, ...args: unknown[]) { + if (capture!.expired()) return Reflect.apply(original, this, args); + return capture!.scope.run(metadata, () => Reflect.apply(original, this, args)); + }); + replace(value, "prepare", original => function (this: unknown, ...args: unknown[]) { + const prepared = Reflect.apply(original, this, args); + try { query(prepared, metadata); } catch {} + return prepared; + }); + } + function factory(value: unknown, step: string, metadata: Metadata, from = false) { + if (!object(value) || capture!.factories.has(value)) return; + capture!.factories.add(value); + replace(value, step, original => function (this: unknown, ...args: unknown[]) { + const result = Reflect.apply(original, this, args); + try { query(result, { ...metadata, table: from ? tableName(args[0]) : metadata.table }); } catch {} + return result; + }); + } + function driverQuery(value: unknown, metadata: Metadata) { + if (!object(value) || capture!.driverQueries.has(value)) return; + capture!.driverQueries.add(value); + let consumed = false; + replace(value, "then", original => function (this: unknown, ...handlers: unknown[]) { + if (consumed || !capture!.active()) { + consumed = true; + return Reflect.apply(original, this, handlers); + } + consumed = true; + const result = capture!.execute(() => Reflect.apply(original, this, []), metadata) as Promise; + return Reflect.apply(result.then, result, handlers); + }); + for (const method of ["execute", "cursor", "forEach", "readable", "writable"]) { + replace(value, method, original => function (this: unknown, ...args: unknown[]) { + consumed = true; + return Reflect.apply(original, this, args); + }); + } + } + function sqlMetadata(value: unknown): Metadata { + const scoped = capture!.scope.getStore(); + const text = typeof value === "string" ? value : ""; + let table = "other"; + for (const match of text.matchAll(/\b(?:from|update|into)\s+"([A-Za-z0-9_]+)"/gi)) { + if (tables.has(match[1]!)) { table = match[1]!; break; } + } + return scoped ? { ...scoped, table: scoped.table === "other" ? table : scoped.table } + : { operation: text.match(/^\s*(select|insert|update|delete)\b/i)?.[1]?.toLowerCase() ?? "execute", + table, callers: publicDatabaseCallers(new Error().stack) }; + } + function client(value: unknown) { + if ((!object(value) && typeof value !== "function") || capture!.clients.has(value)) return; + capture!.clients.add(value); + const target = value as Record; + replace(target, "unsafe", original => function (this: unknown, ...args: unknown[]) { + const result = Reflect.apply(original, this, args); + if (!capture!.expired()) { try { driverQuery(result, sqlMetadata(args[0])); } catch {} } + return result; + }); + for (const method of ["begin", "savepoint"]) { + replace(target, method, original => function (this: unknown, ...args: unknown[]) { + const wrapped = args.map(arg => typeof arg !== "function" ? arg : function (this: unknown, ...inner: unknown[]) { + try { client(inner[0]); } catch {} + return Reflect.apply(arg, this, inner); + }); + return Reflect.apply(original, this, wrapped); + }); + } + replace(target, "reserve", original => function (this: unknown, ...args: unknown[]) { + return Promise.resolve(Reflect.apply(original, this, args)).then(reserved => { + try { client(reserved); } catch {} + return reserved; + }); + }); + } + function root(value: unknown) { + if (!object(value) || capture!.roots.has(value)) return; + capture!.roots.add(value); + for (const method of ["select", "selectDistinct", "selectDistinctOn", "insert", "update", "delete", "execute", "with"] as const) { + replace(value, method, original => function (this: unknown, ...args: unknown[]) { + const result = Reflect.apply(original, this, args); + if (capture!.expired()) return result; + try { + if (method === "with") { root(result); return result; } + const operation = method.startsWith("select") ? "select" : method; + const metadata = { operation, table: operation === "select" || method === "execute" ? "other" : tableName(args[0]), callers: publicDatabaseCallers(new Error().stack) }; + if (operation === "select") factory(result, "from", metadata, true); + else if (method === "insert") factory(result, "values", metadata); + else if (method === "update") factory(result, "set", metadata); + else query(result, metadata); + } catch {} + return result; + }); + } + replace(value, "transaction", original => function (this: unknown, callback: unknown, ...options: unknown[]) { + if (typeof callback !== "function" || capture!.expired()) return Reflect.apply(original, this, [callback, ...options]); + return Reflect.apply(original, this, [function (this: unknown, ...args: unknown[]) { + try { root(args[0]); } catch {} + return Reflect.apply(callback, this, args); + }, ...options]); + }); + } + try { client((db as Record).$client); root(db); } catch {} + return db; +} From d0c8f0b0907afb7706ab78359e11fa226ea4a92e Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sat, 24 Oct 2026 16:16:29 -0700 Subject: [PATCH 023/110] fix: explain project access denials and add an authorized repair path (#17509) ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Low-trust agents may read only the projects in their allowed scope. > - Workspace setup correctly stops a task outside that scope. > - The task previously showed a generic failure, and agent settings did not offer an additive repair. > - This pull request explains the denial and lets authorized operators add projects while preserving other restrictions. > - The saved task then offers an explicit retry. Saving access does not start work. ## Linked Issues or Issue Description **What happened?** A project access denial appeared as an ordinary failed attempt. Operators could not add a second allowed project from agent settings. **Expected behavior** The task should explain the denied access and link to a working permission editor. The editor should preserve existing scope and restrictions, enforce operator authority, and retain drafts after a failed save. **Steps to reproduce** 1. Assign a low-trust agent to a task whose project is outside its allowed projects. 2. Let workspace setup deny project access. 3. Open the task, follow Manage project access, add the project, save, reload, and return to the task. 4. Confirm that the saved message remains and Retry task is a separate action. ## What Changed - Record a typed, non-retryable project denial before provider dispatch. Project denials do not enter automatic continuation or provider comment policy. - Project current and historical setup denials into a safe task notice. Keep unrelated failures, prior assignees, and approval/pause/budget gates separate. Recheck current project authority, including standard trust and root-issue grants. Accepted retries keep their working state. - Add board-only project-access reads and additive saves under the agent row lock. Enforce company scope, agent-management authority, pending-approval restrictions, and an audit record for new additions. - Add the production notice and searchable multi-project editor, including read-only, saving, cancellation, and failed-save states. Preserve the return-to-task query through canonical agent redirects. - Register board-only project-access routes in OpenAPI with a strict request schema. - Add production Storybook examples and API/persistence/concurrency regressions. Retain the approved design snapshot and update the behavior maps and implementation contract. ## Verification - Passed: `pnpm -r typecheck`, `pnpm build`, `pnpm build-storybook`, `pnpm check:token-gates`, `node scripts/check-maps.mjs`, and `node scripts/storybook-catalog.mjs`. - Passed: 11 permission/projection tests and 30 run-completion tests against an isolated PostgreSQL database. These cover historical failures, concurrent additions, idempotent audit, preserved restrictions, foreign projects, read-only users, agent self-grants, and no automatic wakeup. - Passed: all 27 OpenAPI route tests, including route coverage and the new board-only request/response contract. - Browser: the real app displayed a historical denial; Manage project access opened the editor; saving retained the original project and survived reload; Return to task showed the ready notice. Saving created one audit event and zero runs. Explicit Retry returned 202 and reached the separate sandbox requirement, which remained enforced. No external provider was used. - All five production Storybook interaction checks pass: blocked task, save, cancellation, failed-save recovery, and read-only settings. These use fixture callbacks; durable authorization is covered separately above. - `pnpm test:run` was attempted locally but stopped after repeated embedded PostgreSQL startup failures caused by macOS semaphore exhaustion. Full-suite CI is required before merge. The separate UI suite passed all 9,095 tests. The 41 focused server regressions also passed after rebasing onto the latest master. A further 26 recovery-classification tests pass, including a red-to-green regression for automatic continuation after a project denial. ## Risks - No schema migration. The new endpoint only adds same-company project IDs and preserves the rest of the stored policy. - The historical notice recognizes one exact setup denial message. It does not display arbitrary run errors or disclose a different source project's identity. - The retry still passes all current admission and isolation checks. The notice does not promise that other execution requirements are satisfied. - Related open work: #13309 covers inherited secret restrictions; #11234 covers the broader repository catalog. This change does not replace either policy surface. ## Model Used OpenAI Codex (GPT-6), with code execution and browser tools. The precise runtime model ID and context-window size were 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 #` 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 (focused server and full UI suites; full-suite infrastructure limit above) - [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 --- doc/SPEC-implementation.md | 9 + maps/agent-access-map/agents.md | 6 + maps/feature-map/agents.md | 6 + maps/feature-map/recovery.md | 6 + packages/shared/src/index.ts | 2 + packages/shared/src/types/agent.ts | 5 + .../shared/src/types/execution-projection.ts | 4 +- packages/shared/src/types/index.ts | 1 + packages/shared/src/validators/agent.ts | 4 + packages/shared/src/validators/index.ts | 1 + .../__tests__/agent-project-access.test.ts | 107 +++++++++++ server/src/__tests__/openapi-routes.test.ts | 16 ++ server/src/routes/agent-project-access.ts | 25 +++ server/src/routes/agents.ts | 3 + server/src/routes/openapi.ts | 23 +++ server/src/services/agent-project-access.ts | 69 +++++++ .../services/heartbeat/run-completion.test.ts | 25 ++- .../src/services/heartbeat/run-completion.ts | 27 ++- .../src/services/heartbeat/run-lifecycle.ts | 1 + server/src/services/project-access-denial.ts | 10 + .../provider-failure-classification.test.ts | 4 + server/src/services/recovery/service.ts | 1 + .../task-interruption-presentation.test.ts | 55 ++++++ .../task-interruption-presentation.ts | 52 ++++- server/src/services/task-workspace-access.ts | 8 +- ui/src/api/agents.ts | 3 + .../components/AgentProjectAccessSettings.tsx | 34 ++++ ui/src/components/AllowedProjectsEditor.tsx | 72 +++++++ ui/src/components/ExecutionBlockerNotice.tsx | 9 +- ui/src/components/ProjectAccessNotice.tsx | 38 ++++ ui/src/components/TaskProjectAccessNotice.tsx | 23 +++ ui/src/components/TrustPresetSection.tsx | 12 +- ui/src/lib/queryKeys.ts | 1 + ui/src/pages/AgentDetail.production.tsx | 9 +- ui/src/pages/AgentDetail.tsx | 9 +- ui/src/pages/Inbox.tsx | 1 + ui/src/pages/IssueDetail.tsx | 1 + .../project-access.stories.tsx | 121 ++++++++++++ .../recovery/project-access.stories.tsx | 77 ++++++++ .../ProjectAccessProposal.tsx | 180 ++++++++++++++++++ 40 files changed, 1030 insertions(+), 30 deletions(-) create mode 100644 server/src/__tests__/agent-project-access.test.ts create mode 100644 server/src/routes/agent-project-access.ts create mode 100644 server/src/services/agent-project-access.ts create mode 100644 server/src/services/project-access-denial.ts create mode 100644 server/src/services/task-interruption-presentation.test.ts create mode 100644 ui/src/components/AgentProjectAccessSettings.tsx create mode 100644 ui/src/components/AllowedProjectsEditor.tsx create mode 100644 ui/src/components/ProjectAccessNotice.tsx create mode 100644 ui/src/components/TaskProjectAccessNotice.tsx create mode 100644 ui/storybook/stories/design-proposals/project-access.stories.tsx create mode 100644 ui/storybook/stories/recovery/project-access.stories.tsx create mode 100644 ui/storybook/support/design-proposals/ProjectAccessProposal.tsx diff --git a/doc/SPEC-implementation.md b/doc/SPEC-implementation.md index 13067391ef2..1048f886509 100644 --- a/doc/SPEC-implementation.md +++ b/doc/SPEC-implementation.md @@ -891,6 +891,15 @@ grant privileged tools. Backlog assignments retain the existing human requester without starting a run. Reassignment transactionally cancels prior human requests, including service/plugin writes; cancelled runs cannot authorize later retries. See `doc/LOW-TRUST-PRESETS.md` for containment details. +Project or repository access is a separate boundary from exact-task direction. +A workspace project denial appears on the task with a link to the agent's +Permissions / Trust settings. Board operators with `agents:create` can add +same-company projects through `POST /api/agents/:id/project-access`; the operation +locks the agent, preserves existing permissions and audits added projects. +Saving does not retry work. The task offers explicit Retry after the required +project is allowed, and dispatch rechecks authorization. Existing setup failures +with the exact project-boundary denial also receive the explanation on reload. + Cross-issue writes are contained per heartbeat run. An agent-authored comment may wake the target assignee, including an explicit `resume: true` comment on a `done` or `cancelled` issue, but the wake remains agent-class and is subject to diff --git a/maps/agent-access-map/agents.md b/maps/agent-access-map/agents.md index efc593ec743..1fa58307434 100644 --- a/maps/agent-access-map/agents.md +++ b/maps/agent-access-map/agents.md @@ -104,6 +104,12 @@ Review: `baseline`. API: `present` — representative operation IDs: - `GET /api/agents/{id}/instructions-bundle/file`. +- `GET /api/agents/{id}/project-access` and `POST /api/agents/{id}/project-access` + are board-only. The POST requires `agents:create`, checks selected projects in + the same company, and adds IDs under an agent row lock. It preserves existing + containment, audits new grants and rejects pending-approval agents. Agent keys + cannot use this route to grant themselves access; a read-only board viewer + receives `canManage: false`. Saving never creates a run or wakeup. - `PUT /api/agents/{id}/instructions-bundle/file`. - `PATCH /api/agents/{id}` with an explicit `runner: "paperclip"` upgrade. - `POST /api/agents/{id}/qualify-runner` to qualify the saved effective sandbox before upgrading. diff --git a/maps/feature-map/agents.md b/maps/feature-map/agents.md index 95fed092ec1..bb3b705cd1d 100644 --- a/maps/feature-map/agents.md +++ b/maps/feature-map/agents.md @@ -41,6 +41,12 @@ existing preparation and verification lifecycle. Open `/agents/:agentId` and the configuration/instruction surfaces it exposes. +For a low-trust agent, open **Permissions / Trust → Allowed projects**. An operator +with agent-management permission can select additional projects and explicitly +save them. Existing projects and other containment restrictions remain intact. +Cancel discards the draft; a failed save retains it. Reload to verify persistence. +This does not start or retry a task. + In `/agents/all`, select roster checkboxes and choose **Edit connection & model**. A mixed selection offers one action per harness. Each field is opt-in. The editor previews each changed value and excludes agents already at the target value. diff --git a/maps/feature-map/recovery.md b/maps/feature-map/recovery.md index 4294a1876a3..6624fbc67f7 100644 --- a/maps/feature-map/recovery.md +++ b/maps/feature-map/recovery.md @@ -48,6 +48,12 @@ Open the affected task from Tasks, Inbox/Blocked, search, or a direct task link. Observe one working, backoff, failed or waiting-for-user state. Use Retry after an infrastructure failure. No process or file certification is required. +A workspace project denial names the blocked access and links to the agent's +**Permissions / Trust** settings. After an authorized person adds the required +project, return to the saved task for an explicit **Retry task** action. Saving +permissions alone does not wake the agent. Historical setup denials receive the +same notice on reload; unrelated errors and prior assignees do not. + Thinking appears immediately after Retry, before the request completes. Technical source/run details remain in deliberate diagnostics. The [task recovery contract](../../doc/task-recovery.md) describes receipt identity, diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index 99f0a885507..a45052d7fe0 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -889,6 +889,7 @@ export type { AgentDetail, ClearAgentErrorResponse, AgentPermissions, + AgentProjectAccess, AgentPublicIdentity, AgentInstructionsBundleMode, AgentInstructionsFileSummary, @@ -1882,6 +1883,7 @@ export { qualifyAgentRunnerSchema, agentPermissionsSchema, updateAgentPermissionsSchema, + addAgentProjectAccessSchema, type CreateAgent, type BuiltInAgentProvision, type BuiltInAgentReset, diff --git a/packages/shared/src/types/agent.ts b/packages/shared/src/types/agent.ts index ac1970305b7..ba4b594389b 100644 --- a/packages/shared/src/types/agent.ts +++ b/packages/shared/src/types/agent.ts @@ -25,6 +25,11 @@ export interface AgentPermissions extends Record { authorizationPolicy?: TrustAuthorizationPolicy; } +export interface AgentProjectAccess { + projectIds: string[]; + canManage: boolean; +} + export type AgentRuntimeConfig = Record & { aiConnection?: import("../ai-connection-router.js").AiRuntimeConnectionBinding; }; diff --git a/packages/shared/src/types/execution-projection.ts b/packages/shared/src/types/execution-projection.ts index 23c7d3d688d..ff28fd01dc1 100644 --- a/packages/shared/src/types/execution-projection.ts +++ b/packages/shared/src/types/execution-projection.ts @@ -104,7 +104,9 @@ export interface TaskInterruptionPresentation { state: "working" | "retry_scheduled" | "failed" | "waiting_for_user" | "resolved"; nextRetryAt: string | null; canRetry: boolean; - userAction: "approval" | "reconnect" | "assign_agent" | "choose_model" | "resume" | "budget" | null; + userAction: "approval" | "reconnect" | "assign_agent" | "choose_model" | "resume" | "budget" | "project_access" | null; + /** Only the task's own project id is exposed. Other source projects stay unnamed. */ + projectAccess?: { agentId: string; projectId: string | null; ready: boolean }; sourceRunIds: string[]; observedRunId: string | null; } diff --git a/packages/shared/src/types/index.ts b/packages/shared/src/types/index.ts index c89aa62b1e3..b10aa2c33ea 100644 --- a/packages/shared/src/types/index.ts +++ b/packages/shared/src/types/index.ts @@ -280,6 +280,7 @@ export type { AgentDetail, ClearAgentErrorResponse, AgentPermissions, + AgentProjectAccess, AgentPublicIdentity, AgentRuntimeConfig, AgentInstructionsBundleMode, diff --git a/packages/shared/src/validators/agent.ts b/packages/shared/src/validators/agent.ts index 32d65555e6d..1e9e42e2876 100644 --- a/packages/shared/src/validators/agent.ts +++ b/packages/shared/src/validators/agent.ts @@ -322,6 +322,10 @@ export const updateAgentPermissionsSchema = z.object({ export type UpdateAgentPermissions = z.infer; +export const addAgentProjectAccessSchema = z.object({ + projectIds: z.array(z.string().uuid()).min(1).max(100), +}).strict(); + export const resolveAgentInstructionCandidateSchema = z.object({ baseRevisionId: z.string().uuid().nullable(), content: z.string().max(1024 * 1024), diff --git a/packages/shared/src/validators/index.ts b/packages/shared/src/validators/index.ts index 05519dd262f..8f1ba1bf907 100644 --- a/packages/shared/src/validators/index.ts +++ b/packages/shared/src/validators/index.ts @@ -370,6 +370,7 @@ export { qualifyAgentRunnerSchema, agentPermissionsSchema, updateAgentPermissionsSchema, + addAgentProjectAccessSchema, type CreateAgent, type BuiltInAgentProvision, type BuiltInAgentReset, diff --git a/server/src/__tests__/agent-project-access.test.ts b/server/src/__tests__/agent-project-access.test.ts new file mode 100644 index 00000000000..38618a3669c --- /dev/null +++ b/server/src/__tests__/agent-project-access.test.ts @@ -0,0 +1,107 @@ +import { randomUUID } from "node:crypto"; +import express from "express"; +import request from "supertest"; +import { and, eq } from "drizzle-orm"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { agents, agentWakeupRequests, activityLog, authUsers, companies, companyMemberships, createDb, + heartbeatRuns, issues, projects, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS } from "@paperclipai/db"; +import { registerAgentProjectAccessRoutes } from "../routes/agent-project-access.js"; +import { errorHandler } from "../middleware/error-handler.js"; +import { assertTaskWorkspaceSourceProjectAccess } from "../services/task-workspace-access.js"; +import { taskInterruptionPresentation } from "../services/task-interruption-presentation.js"; +import { ProjectAccessDeniedError } from "../services/project-access-denial.js"; +import { startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; + +describe("additive project access", () => { + let database: Awaited> | undefined; + let db: ReturnType; + beforeAll(async () => { + const external = process.env.PAPERCLIP_TEST_DATABASE_URL; + if (external) db = createDb(external); + else { database = await startEmbeddedPostgresTestDatabase("agent-project-access-"); db = createDb(database.connectionString); } + }, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS); + afterAll(async () => { await db?.$client.end(); await database?.cleanup(); }); + + async function seed() { + const companyId = randomUUID(), agentId = randomUUID(), issueId = randomUUID(), runId = randomUUID(); + await db.insert(companies).values({ id: companyId, name: "Project access", issuePrefix: `A${companyId.slice(0, 6)}` }); + const selected = await db.insert(projects).values(["Existing", "Needed", "Third"].map(name => ({ companyId, name }))).returning(); + const permissions = { canCreateAgents: false, canCreateSkills: false, trustPreset: "low_trust_review", + authorizationPolicy: { reviewPreset: { id: "low_trust_review", version: 1, rawOutputDisposition: "quarantine" }, + customPolicy: { preserve: true }, trustBoundary: { mode: "low_trust_review", companyId, + projectIds: [selected[0]!.id], issueIds: [issueId], allowedToolClasses: ["git.read"], allowedSecretBindingIds: [] } } }; + await db.insert(agents).values({ id: agentId, companyId, name: "Reviewer", adapterType: "process", status: "idle", permissions }); + await db.insert(companyMemberships).values({ companyId, principalType: "agent", principalId: agentId, membershipRole: "member", status: "active" }); + const [issue] = await db.insert(issues).values({ id: issueId, companyId, title: "Saved message", status: "blocked", assigneeAgentId: agentId, projectId: selected[1]!.id }).returning(); + await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, issueId, status: "failed", errorCode: "setup_failed", + error: "Project is outside this low-trust boundary.", contextSnapshot: { issueId } }); + return { companyId, agentId, issue: issue!, runId, selected, permissions }; + } + function app(actor: express.Request["actor"]) { + const app = express(); app.use(express.json()); app.use((req, _res, next) => { req.actor = actor; next(); }); + registerAgentProjectAccessRoutes(app, db); app.use(errorHandler); return app; + } + const board = { type: "board" as const, source: "local_implicit" as const }; + + it("preserves containment, audits concurrent additions, and changes the persisted denial into an explicit retry", async () => { + const f = await seed(); + const actor = { type: "agent" as const, source: "agent_key" as const, agentId: f.agentId, companyId: f.companyId }; + await expect(assertTaskWorkspaceSourceProjectAccess(db, actor, f.companyId, f.selected[1]!.id)).rejects.toBeInstanceOf(ProjectAccessDeniedError); + expect(await taskInterruptionPresentation(db, f.issue)).toMatchObject({ userAction: "project_access", canRetry: false }); + const api = app(board); + const results = await Promise.all(f.selected.slice(1).map(project => request(api).post(`/agents/${f.agentId}/project-access`).send({ projectIds: [project.id] }))); + expect(results.map(result => result.status)).toEqual([200, 200]); + const [saved] = await db.select().from(agents).where(eq(agents.id, f.agentId)); + expect(saved!.permissions).toEqual({ ...f.permissions, authorizationPolicy: { ...f.permissions.authorizationPolicy, + trustBoundary: { ...f.permissions.authorizationPolicy.trustBoundary, projectIds: expect.arrayContaining(f.selected.map(project => project.id)) } } }); + expect((saved!.permissions as typeof f.permissions).authorizationPolicy.trustBoundary.projectIds).toHaveLength(3); + await expect(assertTaskWorkspaceSourceProjectAccess(db, actor, f.companyId, f.selected[1]!.id)).resolves.toBeUndefined(); + expect(await taskInterruptionPresentation(db, f.issue)).toMatchObject({ canRetry: true, projectAccess: { ready: true } }); + const again = await request(api).post(`/agents/${f.agentId}/project-access`).send({ projectIds: [f.selected[1]!.id] }); + expect(again.status).toBe(200); + expect(await db.select().from(activityLog).where(and(eq(activityLog.companyId, f.companyId), eq(activityLog.action, "agent.project_access_added")))).toHaveLength(2); + expect(await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.companyId, f.companyId))).toHaveLength(0); + expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.companyId, f.companyId))).toHaveLength(1); + }); + + it("rejects foreign projects, agent self-grants, unknown policy fields, and pending-approval agents", async () => { + const f = await seed(), other = await seed(), api = app(board); + expect((await request(api).post(`/agents/${f.agentId}/project-access`).send({ projectIds: [other.selected[1]!.id] })).status).toBe(404); + expect((await request(api).post(`/agents/${f.agentId}/project-access`).send({ projectIds: [f.selected[1]!.id], trustPreset: "standard" })).status).toBe(400); + expect((await request(app({ type: "agent", agentId: f.agentId, companyId: f.companyId, source: "agent_key" })) + .post(`/agents/${f.agentId}/project-access`).send({ projectIds: [f.selected[1]!.id] })).status).toBe(403); + await db.update(agents).set({ status: "pending_approval" }).where(eq(agents.id, f.agentId)); + expect((await request(api).post(`/agents/${f.agentId}/project-access`).send({ projectIds: [f.selected[1]!.id] })).status).toBe(409); + const [saved] = await db.select().from(agents).where(eq(agents.id, f.agentId)); expect(saved!.permissions).toEqual(f.permissions); + }); + + it.each(["standard", "root_issue"])("rechecks actual project authority after a %s repair and acknowledges an accepted retry", async repair => { + const f = await seed(); + const permissions = repair === "standard" ? { canCreateAgents: false, trustPreset: "standard", authorizationPolicy: {} } + : { ...f.permissions, authorizationPolicy: { ...f.permissions.authorizationPolicy, + trustBoundary: { ...f.permissions.authorizationPolicy.trustBoundary, rootIssueId: f.issue.id } } }; + await db.update(agents).set({ permissions }).where(eq(agents.id, f.agentId)); + expect(await taskInterruptionPresentation(db, f.issue)).toMatchObject({ canRetry: true, projectAccess: { ready: true } }); + await db.insert(agentWakeupRequests).values({ companyId: f.companyId, agentId: f.agentId, + source: "on_demand", status: "deferred_issue_execution", requestedByActorType: "user", payload: { issueId: f.issue.id } }); + const accepted = await taskInterruptionPresentation(db, f.issue); + expect(accepted).toMatchObject({ state: "working", canRetry: false }); + expect(accepted).not.toHaveProperty("projectAccess"); + // Current project policy remains authoritative even after agent access changes. + await db.update(projects).set({ executionWorkspacePolicy: { trustPreset: "low_trust_review", authorizationPolicy: { + trustBoundary: { mode: "low_trust_review", companyId: f.companyId, projectIds: [f.selected[0]!.id] }, + } } }).where(eq(projects.id, f.selected[1]!.id)); + if (repair === "standard") expect(await taskInterruptionPresentation(db, f.issue)) + .toMatchObject({ canRetry: false, userAction: "project_access" }); + }); + + it("shows read-only access to viewers and denies their saves and cross-company reads", async () => { + const f = await seed(), other = await seed(), userId = randomUUID(); + await db.insert(authUsers).values({ id: userId, name: "Viewer", email: `${userId}@example.test`, emailVerified: true, createdAt: new Date(), updatedAt: new Date() }); + await db.insert(companyMemberships).values({ companyId: f.companyId, principalType: "user", principalId: userId, membershipRole: "viewer", status: "active" }); + const api = app({ type: "board", source: "session", userId, companyIds: [f.companyId], memberships: [{ companyId: f.companyId, membershipRole: "viewer", status: "active" }] }); + expect((await request(api).get(`/agents/${f.agentId}/project-access`)).body).toMatchObject({ canManage: false }); + expect((await request(api).post(`/agents/${f.agentId}/project-access`).send({ projectIds: [f.selected[1]!.id] })).status).toBe(403); + expect((await request(api).get(`/agents/${other.agentId}/project-access`)).status).toBe(404); + }); +}); diff --git a/server/src/__tests__/openapi-routes.test.ts b/server/src/__tests__/openapi-routes.test.ts index d0abe4e4b4b..ff43e560394 100644 --- a/server/src/__tests__/openapi-routes.test.ts +++ b/server/src/__tests__/openapi-routes.test.ts @@ -21,6 +21,7 @@ const apiPrefixes: Record = { "activity.ts": "/api", "adapters.ts": "/api", "agents.ts": "/api", + "agent-project-access.ts": "/api", "agent-commentary.ts": "/api", "agent-avatars.ts": "/api", "agent-profile-avatar.ts": "/api", @@ -987,6 +988,21 @@ describe("openapi routes", () => { }); }); + it("documents additive project access as board-only with a strict request", () => { + const { spec } = loadSpecRoutes(); + const path = spec.paths["/api/agents/{id}/project-access"]; + for (const operation of [path.get, path.post]) { + expect(operation["x-paperclip-authorization"]).toEqual({ actor: "board" }); + expect(operation.security).toEqual([{ BoardSessionAuth: [] }, { BoardApiKeyAuth: [] }]); + expect(operation.responses["200"].content["application/json"].schema.required).toEqual(["projectIds", "canManage"]); + } + expect(path.post.requestBody.content["application/json"].schema).toMatchObject({ + additionalProperties: false, required: ["projectIds"], + properties: { projectIds: { type: "array", items: { type: "string", format: "uuid" } } }, + }); + expect(path.post.responses["409"]).toBeDefined(); + }); + it("documents the authenticated personal primary-agent contract", () => { const { spec } = loadSpecRoutes(); const path = spec.paths["/api/companies/{companyId}/primary-agent/me"]; diff --git a/server/src/routes/agent-project-access.ts b/server/src/routes/agent-project-access.ts new file mode 100644 index 00000000000..08346180aab --- /dev/null +++ b/server/src/routes/agent-project-access.ts @@ -0,0 +1,25 @@ +import type { Router } from "express"; +import { agents, type Db } from "@paperclipai/db"; +import { eq } from "drizzle-orm"; +import { addAgentProjectAccessSchema } from "@paperclipai/shared"; +import { notFound } from "../errors.js"; +import { validate } from "../middleware/validate.js"; +import { addAgentProjectAccess, readAgentProjectAccess } from "../services/agent-project-access.js"; +import { assertBoard, assertCompanyAccess, hasCompanyAccess } from "./authz.js"; + +export function registerAgentProjectAccessRoutes(router: Router, db: Db) { + router.get("/agents/:id/project-access", async (req, res) => { + assertBoard(req); + const [agent] = await db.select({ id: agents.id, companyId: agents.companyId }).from(agents).where(eq(agents.id, req.params.id as string)); + if (!agent || !hasCompanyAccess(req, agent.companyId)) throw notFound("Agent not found"); + assertCompanyAccess(req, agent.companyId); + res.json(await readAgentProjectAccess(db, req.actor, agent.companyId, agent.id)); + }); + router.post("/agents/:id/project-access", validate(addAgentProjectAccessSchema), async (req, res) => { + assertBoard(req); + const [agent] = await db.select({ id: agents.id, companyId: agents.companyId }).from(agents).where(eq(agents.id, req.params.id as string)); + if (!agent || !hasCompanyAccess(req, agent.companyId)) throw notFound("Agent not found"); + assertCompanyAccess(req, agent.companyId); + res.json(await addAgentProjectAccess(db, req.actor, agent.companyId, agent.id, req.body.projectIds)); + }); +} diff --git a/server/src/routes/agents.ts b/server/src/routes/agents.ts index 540e1f7d8cc..0aba86abb8f 100644 --- a/server/src/routes/agents.ts +++ b/server/src/routes/agents.ts @@ -98,6 +98,7 @@ import { } from "@paperclipai/adapter-utils/server-utils"; import { trackAgentCreated } from "@paperclipai/shared/telemetry"; import { validate } from "../middleware/validate.js"; +import { registerAgentProjectAccessRoutes } from "./agent-project-access.js"; import { inheritNativeRunnerAdapterConfig } from "../services/native-runtime/native-agent-runtime-inheritance.js"; import { agentInstructionRevisionService } from "../services/agent-instruction-revisions.js"; import { agentInstructionWorkingCopyService } from "../services/agent-instruction-working-copies.js"; @@ -4918,6 +4919,8 @@ export function agentRoutes( res.status(201).json({ ...redactAgentRowForResponse(agent), ...(configurationWarnings.length ? { configurationWarnings } : {}) }); }); + registerAgentProjectAccessRoutes(router, db); + router.patch("/agents/:id/permissions", validate(updateAgentPermissionsSchema), async (req, res) => { const id = req.params.id as string; const existing = await getAccessibleResource(req, res, svc.getById(id), "Agent not found"); diff --git a/server/src/routes/openapi.ts b/server/src/routes/openapi.ts index 650eb0670eb..bbb50ac7f55 100644 --- a/server/src/routes/openapi.ts +++ b/server/src/routes/openapi.ts @@ -48,6 +48,7 @@ import { updateAgentSchema, updatePrimaryAgentSchema, updateAgentPermissionsSchema, + addAgentProjectAccessSchema, updateAgentInstructionsPathSchema, updateAgentInstructionsBundleSchema, upsertAgentInstructionsFileSchema, @@ -1390,6 +1391,8 @@ const browserUseOperations = [ ] as const; const BOARD_ONLY_OPERATIONS = new Set([ + "GET /api/agents/{id}/project-access", + "POST /api/agents/{id}/project-access", "POST /api/issues/{id}/interactions/{interactionId}/dismiss", "POST /api/issues/{id}/retry", "GET /api/companies/{companyId}/prompt-injection-prevention", @@ -3790,6 +3793,26 @@ registry.registerPath({ responses: { 200: r.ok(), 400: r.badRequest, 401: r.unauthorized }, }); +const agentProjectAccessResponse = z.object({ projectIds: z.array(z.string().uuid()), canManage: z.boolean() }); +registry.registerPath({ + method: "get", + path: "/api/agents/{id}/project-access", + tags: ["agents"], + summary: "Read an agent's allowed projects and the current operator's management capability", + request: { params: z.object({ id: z.string() }) }, + responses: { 200: r.ok(agentProjectAccessResponse), 401: r.unauthorized, 403: r.forbidden, 404: r.notFound }, +}); +registry.registerPath({ + method: "post", + path: "/api/agents/{id}/project-access", + tags: ["agents"], + summary: "Add allowed projects without replacing an agent's other permissions", + description: "Requires board access and agents:create in the agent's company. Accepts 1 to 100 project IDs. Selected projects must be readable and in that company. Locks the low-trust agent, preserves existing containment, audits new additions, and rejects pending-approval agents or changed trust settings. Repeated additions are idempotent. Saving does not start or retry a task.", + request: { params: z.object({ id: z.string() }), body: jsonBody(addAgentProjectAccessSchema) }, + responses: { 200: r.ok(agentProjectAccessResponse), 400: r.badRequest, 401: r.unauthorized, + 403: r.forbidden, 404: r.notFound, 409: r.conflict }, +}); + registry.registerPath({ method: "patch", path: "/api/agents/{id}/instructions-path", diff --git a/server/src/services/agent-project-access.ts b/server/src/services/agent-project-access.ts new file mode 100644 index 00000000000..4c6ee81659a --- /dev/null +++ b/server/src/services/agent-project-access.ts @@ -0,0 +1,69 @@ +import { and, eq, inArray } from "drizzle-orm"; +import { agents, projects, type Db } from "@paperclipai/db"; +import { trustAuthorizationPolicySchema, type AgentProjectAccess } from "@paperclipai/shared"; +import { conflict, forbidden, notFound } from "../errors.js"; +import { normalizeAgentPermissions } from "../lib/agent-permissions.js"; +import { accessService } from "./access.js"; +import type { AuthorizationActor } from "./authorization.js"; +import { logActivity, publishActivity, type ActivityPublication } from "./activity-log.js"; + +export async function readAgentProjectAccess(db: Db, actor: AuthorizationActor, companyId: string, agentId: string): Promise { + const [agent] = await db.select({ permissions: agents.permissions, status: agents.status }).from(agents) + .where(and(eq(agents.companyId, companyId), eq(agents.id, agentId))); + if (!agent) throw notFound("Agent not found"); + const decision = await accessService(db).decide({ actor, action: "agents:create", resource: { type: "company", companyId } }); + const permissions = normalizeAgentPermissions(agent.permissions); + const policy = trustAuthorizationPolicySchema.safeParse(permissions.authorizationPolicy ?? {}); + const boundary = policy.success ? policy.data.trustBoundary : undefined; + return { projectIds: policy.success ? policy.data.trustBoundary?.projectIds ?? [] : [], + canManage: actor.type === "board" && decision.allowed && agent.status !== "pending_approval" + && policy.success && permissions.trustPreset === "low_trust_review" + && (!boundary || (boundary.mode === "low_trust_review" && (!boundary.companyId || boundary.companyId === companyId))) }; +} + +/** An additive operation under the agent row lock, never a stale policy replacement. */ +export async function addAgentProjectAccess(db: Db, actor: AuthorizationActor, companyId: string, agentId: string, projectIds: string[]) { + if (actor.type !== "board") throw forbidden("Board access required"); + const publications: ActivityPublication[] = []; + const result = await db.transaction(async tx => { + const [agent] = await tx.select().from(agents) + .where(and(eq(agents.companyId, companyId), eq(agents.id, agentId))).for("update"); + if (!agent) throw notFound("Agent not found"); + const transactionDb = tx as unknown as Db; + const access = accessService(transactionDb); + const decision = await access.decide({ actor, action: "agents:create", resource: { type: "company", companyId } }); + if (!decision.allowed) throw forbidden(decision.explanation); + if (agent.status === "pending_approval") throw conflict("Pending approval agent permissions cannot be changed before board approval"); + const permissions = normalizeAgentPermissions(agent.permissions); + const parsedPolicy = trustAuthorizationPolicySchema.safeParse(permissions.authorizationPolicy ?? {}); + if (!parsedPolicy.success) throw conflict("The agent’s trust settings need review before adding project access."); + const policy = parsedPolicy.data; + const boundary = policy?.trustBoundary; + if (permissions.trustPreset !== "low_trust_review" || (boundary && (boundary.mode !== "low_trust_review" + || (boundary.companyId && boundary.companyId !== companyId)))) { + throw conflict("The agent’s trust settings changed. Refresh before adding project access."); + } + const requested = [...new Set(projectIds)]; + const rows = await tx.select({ id: projects.id }).from(projects) + .where(and(eq(projects.companyId, companyId), inArray(projects.id, requested))); + if (rows.length !== requested.length) throw notFound("A selected project is unavailable"); + for (const project of rows) { + const projectDecision = await access.decide({ actor, action: "project:read", resource: { type: "project", companyId, projectId: project.id } }); + if (!projectDecision.allowed) throw forbidden("A selected project is unavailable"); + } + const previous = boundary?.projectIds ?? []; + const added = requested.filter(id => !previous.includes(id)); + const next = [...previous, ...added]; + if (added.length) { + await tx.update(agents).set({ permissions: { ...agent.permissions, authorizationPolicy: { + ...policy, trustBoundary: { ...boundary, mode: "low_trust_review", companyId, projectIds: next }, + } }, updatedAt: new Date() }).where(and(eq(agents.id, agentId), eq(agents.companyId, companyId))); + await logActivity(transactionDb, { companyId, actorType: "user", actorId: actor.userId ?? "local-board", + action: "agent.project_access_added", entityType: "agent", entityId: agentId, + details: { addedProjectIds: added, trustPreset: "low_trust_review" } }, publications); + } + return { projectIds: next, canManage: true } satisfies AgentProjectAccess; + }); + for (const publication of publications) publishActivity(publication); + return result; +} diff --git a/server/src/services/heartbeat/run-completion.test.ts b/server/src/services/heartbeat/run-completion.test.ts index 39df53e1d52..1dc15b06e9c 100644 --- a/server/src/services/heartbeat/run-completion.test.ts +++ b/server/src/services/heartbeat/run-completion.test.ts @@ -9,6 +9,7 @@ import { createAgentIdentityRedactor } from "../agent-identity-redaction.js"; import { UnresolvedWorkspaceBaseRefError } from "../workspace-runtime.js"; import { LegacyControllerLeaseLostError } from "../legacy-controller-lease.js"; import { requestedRunCancellation } from "../run-cancellation.js"; +import { ProjectAccessDeniedError } from "../project-access-denial.js"; import { createHeartbeatLifecycle, type HeartbeatLifecycleDependencies } from "./run-lifecycle.js"; import { createHeartbeatRunPreparation, ConfigurationIncompleteFailure } from "./run-preparation.js"; import { createHeartbeatRunState, getAdapterSessionCodec } from "./run-state.js"; @@ -77,15 +78,19 @@ it("constructs completion handlers without querying or starting work", () => { }); const support = await getEmbeddedPostgresTestSupport(); -describe.skipIf(!support.supported)("heartbeat run completion boundary", () => { - let database: Awaited>; +describe.skipIf(!support.supported && !process.env.PAPERCLIP_TEST_DATABASE_URL)("heartbeat run completion boundary", () => { + let database: Awaited> | undefined; let db: Db; beforeAll(async () => { // Keep the accounting transaction real without reading provider receipt files. vi.spyOn(usageReceipts, "indexPendingUsageReceipts").mockResolvedValue(new Map()); vi.spyOn(usageReceipts, "recoverPendingRunUsageReceipts").mockResolvedValue([]); - database = await startEmbeddedPostgresTestDatabase("paperclip-heartbeat-completion"); - db = createDb(database.connectionString); + const external = process.env.PAPERCLIP_TEST_DATABASE_URL; + if (external) db = createDb(external); + else { + database = await startEmbeddedPostgresTestDatabase("paperclip-heartbeat-completion"); + db = createDb(database.connectionString); + } await db.execute(sql`set client_min_messages = warning`); }, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS); afterAll(async () => { await db?.$client.end(); await database?.cleanup(); vi.restoreAllMocks(); }); @@ -334,6 +339,18 @@ describe.skipIf(!support.supported)("heartbeat run completion boundary", () => { expect(f.deps.releaseIssueExecutionAndPromote).toHaveBeenCalledWith(expect.objectContaining({ id: f.run.id }), { suppressImmediateRecovery: true }); }); + it("persists a project denial without provider work or an automatic retry", async () => { + const f = await fixture(); + const projectId = randomUUID(); + await f.completion.failRunSetup(f.setup(new ProjectAccessDeniedError(projectId))); + expect(await read(f.run.id)).toMatchObject({ status: "failed", errorCode: "project_access_denied", + resultJson: { projectAccessDenied: { projectId }, executionRecovery: { kind: "bootstrap", providerWorkStarted: false } } }); + expect(f.deps.scheduleBoundedRetryForRun).not.toHaveBeenCalled(); + expect(f.deps.enqueueWakeup).not.toHaveBeenCalled(); + expect(f.deps.scheduleInteractionContinuationInfrastructureRetryIfEligible).not.toHaveBeenCalled(); + expect(f.deps.finalizeIssueCommentPolicy).not.toHaveBeenCalled(); + }); + it("records a setup configuration gap without inventing provider work or applying comment policy", async () => { const f = await fixture(); await f.completion.failRunSetup(f.setup(new ConfigurationIncompleteFailure("missing credential", { configurationIncomplete: { reason: "missing_binding" } }))); diff --git a/server/src/services/heartbeat/run-completion.ts b/server/src/services/heartbeat/run-completion.ts index 7f2b486dfe7..95026919171 100644 --- a/server/src/services/heartbeat/run-completion.ts +++ b/server/src/services/heartbeat/run-completion.ts @@ -1,4 +1,5 @@ import { measureRunPhase } from "../execution-preparation-timing.js"; +import { PROJECT_ACCESS_DENIED, ProjectAccessDeniedError } from "../project-access-denial.js"; import { pendingCaseHandoffForRun } from "./case-handoff-lifecycle.js"; import { NON_RETRYABLE_PREFLIGHT_FAILURE_CODES, isHeartbeatRunTerminalStatus } from "./run-lifecycle.js"; import { ChatControlRecoveryUnresolvedError } from "./queue.js"; @@ -145,6 +146,7 @@ export interface FailHeartbeatRunSetupInput { } function nonRetryablePreflightFailureCode(error: unknown): string | null { + if (error instanceof ProjectAccessDeniedError) return PROJECT_ACCESS_DENIED; if (error instanceof ChatControlRecoveryUnresolvedError) return CHAT_CONTROL_RECOVERY_UNRESOLVED_CODE; if ( @@ -1344,6 +1346,8 @@ export function createHeartbeatRunCompletion(db: Db, dependencies: HeartbeatRunC // action, so it is persisted even when the agent lookup failed and the // agent-scoped stop metadata cannot be merged in. const setupFailureDetails = + (outerErr instanceof ProjectAccessDeniedError + ? { projectAccessDenied: { projectId: outerErr.projectId } } : null) ?? (workspaceGitScanFailure ? { workspaceGitScan: { code: workspaceGitScanFailure.code, @@ -1453,7 +1457,8 @@ export function createHeartbeatRunCompletion(db: Db, dependencies: HeartbeatRunC ).catch(() => undefined); if ( !isWorkspaceValidationFailedRun(livenessRun) && - !isConfigurationIncompleteFailedRun(livenessRun) + !isConfigurationIncompleteFailedRun(livenessRun) && + livenessRun.errorCode !== PROJECT_ACCESS_DENIED ) { await finalizeIssueCommentPolicy(livenessRun, failedAgent).catch( () => undefined, @@ -1462,15 +1467,17 @@ export function createHeartbeatRunCompletion(db: Db, dependencies: HeartbeatRunC // No provider work began. Retry temporary host scan failures with // the existing durable failure budget, before releasing execution. // Generic recovery must not grant a second budget on exhaustion. - await (isTransientWorkspaceGitScanCode(livenessRun.errorCode) - ? scheduleBoundedRetryForRun(livenessRun, failedAgent) - : scheduleInteractionContinuationInfrastructureRetryIfEligible(livenessRun, failedAgent) - ).catch((retryError) => { - logger.warn( - { err: retryError, runId: livenessRun.id }, - "failed to schedule interaction continuation retry after setup failure", - ); - }); + if (livenessRun.errorCode !== PROJECT_ACCESS_DENIED) { + await (isTransientWorkspaceGitScanCode(livenessRun.errorCode) + ? scheduleBoundedRetryForRun(livenessRun, failedAgent) + : scheduleInteractionContinuationInfrastructureRetryIfEligible(livenessRun, failedAgent) + ).catch((retryError) => { + logger.warn( + { err: retryError, runId: livenessRun.id }, + "failed to schedule interaction continuation retry after setup failure", + ); + }); + } } await releaseIssueExecutionAndPromote(livenessRun, { suppressImmediateRecovery: diff --git a/server/src/services/heartbeat/run-lifecycle.ts b/server/src/services/heartbeat/run-lifecycle.ts index 5f299e855fa..3bbb6f30b40 100644 --- a/server/src/services/heartbeat/run-lifecycle.ts +++ b/server/src/services/heartbeat/run-lifecycle.ts @@ -244,6 +244,7 @@ const LIVENESS_BOOKKEEPING_EVENT_TYPES = [ ]; export const NON_RETRYABLE_PREFLIGHT_FAILURE_CODES = new Set([ + "project_access_denied", "low_trust_isolation_unavailable", "low_trust_requires_isolated_workspace", "low_trust_boundary_mismatch", diff --git a/server/src/services/project-access-denial.ts b/server/src/services/project-access-denial.ts new file mode 100644 index 00000000000..f9e699d1bdc --- /dev/null +++ b/server/src/services/project-access-denial.ts @@ -0,0 +1,10 @@ +import { HttpError } from "../errors.js"; + +export const PROJECT_ACCESS_DENIED = "project_access_denied"; + +/** Carries a safe, typed setup failure without changing the authorization decision. */ +export class ProjectAccessDeniedError extends HttpError { + constructor(readonly projectId: string) { + super(403, "Project is outside this low-trust boundary."); + } +} diff --git a/server/src/services/recovery/provider-failure-classification.test.ts b/server/src/services/recovery/provider-failure-classification.test.ts index 31407ac82c3..29dded8d4d6 100644 --- a/server/src/services/recovery/provider-failure-classification.test.ts +++ b/server/src/services/recovery/provider-failure-classification.test.ts @@ -10,6 +10,10 @@ import { legacyExecutionNeedsReconciliation } from "../legacy-execution-recovery import { isConfigurationIncompleteFailedRun } from "../../modules/wake-queue/domain/values.js"; describe("classifyAdapterFailureForRecovery", () => { + it("does not automatically replay a project access denial", () => { + expect(classifyContinuationFailure({ errorCode: "project_access_denied", resultJson: null } as never)) + .toMatchObject({ kind: "non_retryable", maxAttempts: 0 }); + }); it("waits for model configuration changes instead of retrying a typed native model rejection", () => { const run = { errorCode: "native_provider_model_rejected", error: "Fixed model configuration message", resultJson: null }; expect(classifyAdapterFailureForRecovery(run)).toEqual({ kind: "configuration_incomplete" }); diff --git a/server/src/services/recovery/service.ts b/server/src/services/recovery/service.ts index e72811ec8d0..331122e10d6 100644 --- a/server/src/services/recovery/service.ts +++ b/server/src/services/recovery/service.ts @@ -516,6 +516,7 @@ const TRANSIENT_INFRA_CONTINUATION_ERROR_CODES = new Set([ ]); const NON_RETRYABLE_CONTINUATION_ERROR_CODES = new Set([ + "project_access_denied", "native_provider_model_rejected", "provider_tool_definition_invalid", "adapter_engine_unavailable", diff --git a/server/src/services/task-interruption-presentation.test.ts b/server/src/services/task-interruption-presentation.test.ts new file mode 100644 index 00000000000..9c730d1c5fc --- /dev/null +++ b/server/src/services/task-interruption-presentation.test.ts @@ -0,0 +1,55 @@ +import { describe, expect, it } from "vitest"; +import { projectTaskInterruption } from "./task-interruption-presentation.js"; + +const issue = { id: "task", companyId: "11111111-1111-4111-8111-111111111111", status: "blocked", assigneeAgentId: "agent", projectId: "22222222-2222-4222-8222-222222222222" }; +const run = { id: "run", agentId: "agent", status: "failed", scheduledRetryAt: null, + errorCode: "project_access_denied", error: null, livenessState: null, + resultJson: { projectAccessDenied: { projectId: "22222222-2222-4222-8222-222222222222" } } }; +const agent = { status: "idle", pauseReason: null }; + +describe("task project-access interruption", () => { + it("explains a project denial without offering a futile retry", () => { + expect(projectTaskInterruption(issue, { run, agent, paused: false, approval: false })).toMatchObject({ + state: "waiting_for_user", responsibility: "user", userAction: "project_access", canRetry: false, + projectAccess: { agentId: "agent", projectId: "22222222-2222-4222-8222-222222222222", ready: false }, + }); + }); + + it("projects the historical setup denial without requiring another failed run", () => { + expect(projectTaskInterruption(issue, { run: { ...run, errorCode: "setup_failed", + error: "Project is outside this low-trust boundary.", resultJson: null }, agent, paused: false, approval: false })) + .toMatchObject({ userAction: "project_access", canRetry: false }); + }); + + it("offers an explicit retry after the project is added, without changing the failed run", () => { + expect(projectTaskInterruption(issue, { run, agent, projectAccessAllowed: true, paused: false, approval: false })) + .toMatchObject({ state: "failed", canRetry: true, projectAccess: { ready: true } }); + expect(run.status).toBe("failed"); + }); + + it("shows an accepted retry as working after access is repaired", () => { + const input = { run, agent, paused: false, approval: false, wait: { id: "request", requestedAt: new Date() } }; + expect(projectTaskInterruption(issue, { ...input, projectAccessAllowed: true })) + .toMatchObject({ state: "working", canRetry: false }); + expect(projectTaskInterruption(issue, { ...input, projectAccessAllowed: true })).not.toHaveProperty("projectAccess"); + expect(projectTaskInterruption(issue, { ...input, projectAccessAllowed: false })) + .toMatchObject({ state: "waiting_for_user", userAction: "project_access", canRetry: false }); + }); + + it("does not reinterpret unrelated failures or an old assignee's denial", () => { + for (const otherRun of [{ ...run, errorCode: "setup_failed", error: "Disk full", resultJson: null }, + { ...run, agentId: "previous-agent" }]) { + expect(projectTaskInterruption(issue, { run: otherRun, agent, paused: false, approval: false })) + .not.toHaveProperty("projectAccess"); + } + }); + + it("keeps approval, pause, running and completed states authoritative", () => { + expect(projectTaskInterruption(issue, { run, agent, paused: false, approval: true })).toMatchObject({ userAction: "approval" }); + expect(projectTaskInterruption(issue, { run, agent, paused: true, approval: false })).toMatchObject({ userAction: "resume" }); + expect(projectTaskInterruption(issue, { run: { ...run, status: "running" }, agent, paused: false, approval: false })) + .toMatchObject({ state: "working" }); + expect(projectTaskInterruption({ ...issue, status: "done" }, { run, agent, paused: false, approval: false })) + .toMatchObject({ state: "resolved" }); + }); +}); diff --git a/server/src/services/task-interruption-presentation.ts b/server/src/services/task-interruption-presentation.ts index 249ff55d8e5..f8dd6664e33 100644 --- a/server/src/services/task-interruption-presentation.ts +++ b/server/src/services/task-interruption-presentation.ts @@ -4,21 +4,35 @@ import { agents, agentWakeupRequests, approvals, companies, heartbeatRuns, issue import type { TaskInterruptionPresentation } from "@paperclipai/shared"; import { isAiAuthenticationBlocked } from "./ai-auth-failure.js"; import { readSystemRecovery } from "./system-recovery-state.js"; +import { PROJECT_ACCESS_DENIED } from "./project-access-denial.js"; +import { authorizationService } from "./authorization.js"; type ProjectionIssue = Pick; type ProjectionRun = Pick; + "id" | "status" | "scheduledRetryAt" | "errorCode" | "livenessState" | "resultJson"> & + Partial>; type ProjectionState = { run?: ProjectionRun; action?: typeof issueRecoveryActions.$inferSelect; wait?: { id: string; requestedAt: Date }; agent?: Pick; + projectAccessAllowed?: boolean; project?: Pick; company?: Pick; paused: boolean; approval: boolean; }; +/** Recognize old persisted failures without displaying arbitrary run error text. */ +function deniedProjectId(issue: ProjectionIssue, run?: ProjectionRun): string | null | undefined { + const historical = run?.errorCode === "setup_failed" && run.error === "Project is outside this low-trust boundary."; + if (!run || run.status !== "failed" || run.agentId !== issue.assigneeAgentId + || (run.errorCode !== PROJECT_ACCESS_DENIED && !historical)) return undefined; + const detail = run.resultJson?.projectAccessDenied; + return detail && typeof detail === "object" && "projectId" in detail && typeof detail.projectId === "string" + ? detail.projectId : historical ? issue.projectId : null; +} + /** Presentation never grants authority. Dispatch repeats all gates under its * locks. The same projection is used in detail, lists and attention surfaces. */ export function projectTaskInterruption(issue: ProjectionIssue, input: ProjectionState, now = Date.now()): TaskInterruptionPresentation | null { @@ -36,6 +50,14 @@ export function projectTaskInterruption(issue: ProjectionIssue, input: Projectio ? "budget" : input.paused || project?.pausedAt || agent?.status === "paused" || company?.status === "paused" ? "resume" : null; if (userAction) return { ...base, responsibility: "user", state: "waiting_for_user", userAction }; if (["running", "queued"].includes(run.status)) return { ...base, state: "working" }; + const deniedProject = deniedProjectId(issue, run); + let projectAccess: TaskInterruptionPresentation["projectAccess"]; + if (deniedProject !== undefined) { + const ready = input.projectAccessAllowed === true; + projectAccess = { agentId: run.agentId!, projectId: deniedProject === issue.projectId ? deniedProject : null, ready }; + if (!ready) return { ...base, responsibility: "user", state: "waiting_for_user", + userAction: "project_access", projectAccess }; + } const retryAt = system?.nextAttemptAt ?? run.scheduledRetryAt?.getTime(); if (retryAt && retryAt > now) return { ...base, state: "retry_scheduled", nextRetryAt: new Date(retryAt).toISOString(), canRetry: true }; @@ -44,7 +66,7 @@ export function projectTaskInterruption(issue: ProjectionIssue, input: Projectio activeObservation > now - 45_000) return { ...base, state: "working" }; if (wait && wait.requestedAt.getTime() > now - 10_000 && system?.state !== "exhausted") return { ...base, state: "working" }; - return { ...base, state: "failed", canRetry: true }; + return { ...base, state: "failed", canRetry: true, ...(projectAccess ? { projectAccess } : {}) }; } /** Batch list reads rather than doing seven queries per row. Keep run logs and @@ -61,8 +83,12 @@ export async function taskInterruptionPresentations(db: Db, companyId: string, i const projectIds = selected.flatMap(issue => issue.projectId ? [issue.projectId] : []); const [runs, waits, agentRows, projectRows, pauseRows, approvalRows, companyRows] = await Promise.all([ db.selectDistinctOn([runIssue], { issueId: runIssue, id: heartbeatRuns.id, status: heartbeatRuns.status, + agentId: heartbeatRuns.agentId, + error: sql`case when ${heartbeatRuns.errorCode} = 'setup_failed' + and ${heartbeatRuns.error} = 'Project is outside this low-trust boundary.' then ${heartbeatRuns.error} else null end`, errorCode: heartbeatRuns.errorCode, livenessState: heartbeatRuns.livenessState, scheduledRetryAt: heartbeatRuns.scheduledRetryAt, - resultJson: sql>`jsonb_build_object('configurationIncomplete', ${heartbeatRuns.resultJson}->'configurationIncomplete')`, + resultJson: sql>`jsonb_build_object('configurationIncomplete', ${heartbeatRuns.resultJson}->'configurationIncomplete', + 'projectAccessDenied', ${heartbeatRuns.resultJson}->'projectAccessDenied')`, }).from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, companyId), inArray(runIssue, ids))) .orderBy(runIssue, desc(heartbeatRuns.createdAt), desc(heartbeatRuns.id)), db.selectDistinctOn([wakeIssue], { issueId: wakeIssue, id: agentWakeupRequests.id, requestedAt: agentWakeupRequests.requestedAt }) @@ -91,12 +117,32 @@ export async function taskInterruptionPresentations(db: Db, companyId: string, i )).orderBy(issueRecoveryActions.sourceIssueId, desc(issueRecoveryActions.createdAt)) : []; const byIssue = (rows: T[]) => new Map(rows.map(row => [row.issueId, row])); const runMap = byIssue(runs), waitMap = byIssue(waits); + // Recheck current authority, including standard trust, root-issue grants and + // project policy. Do not reuse the failed run's frozen policy for a new retry. + // Only denied tasks need these reads; deduplicate projects and batch per agent. + const deniedByAgent = new Map>(); + for (const issue of selected) { + const projectId = deniedProjectId(issue, runMap.get(issue.id)); + if (!projectId || !issue.assigneeAgentId || ["done", "cancelled"].includes(issue.status)) continue; + const ids = deniedByAgent.get(issue.assigneeAgentId) ?? new Set(); + ids.add(projectId); + deniedByAgent.set(issue.assigneeAgentId, ids); + } + const currentAccess = new Map(); + const authorization = authorizationService(db); + for (const [agentId, ids] of deniedByAgent) { + const projectIds = [...ids]; + const decisions = await authorization.decideReads({ type: "agent", agentId, companyId, source: "agent_key" }, + projectIds.map(projectId => ({ type: "project" as const, companyId, projectId }))); + projectIds.forEach((projectId, index) => currentAccess.set(`${agentId}:${projectId}`, decisions[index]?.allowed === true)); + } const actionMap = new Map(actions.map(action => [action.sourceIssueId, action])); const agentMap = new Map(agentRows.map(agent => [agent.id, agent])); const projectMap = new Map(projectRows.map(project => [project.id, project])); const pauses = new Set(pauseRows.map(row => row.issueId)), approvalsSet = new Set(approvalRows.map(row => row.issueId)); for (const issue of selected) result.set(issue.id, projectTaskInterruption(issue, { run: runMap.get(issue.id), action: actionMap.get(issue.id), wait: waitMap.get(issue.id), + projectAccessAllowed: currentAccess.get(`${issue.assigneeAgentId}:${deniedProjectId(issue, runMap.get(issue.id))}`), agent: agentMap.get(issue.assigneeAgentId ?? ""), project: projectMap.get(issue.projectId ?? ""), company: companyRows[0], paused: pauses.has(issue.id), approval: approvalsSet.has(issue.id), })); diff --git a/server/src/services/task-workspace-access.ts b/server/src/services/task-workspace-access.ts index b49ba9d9432..31d40f79655 100644 --- a/server/src/services/task-workspace-access.ts +++ b/server/src/services/task-workspace-access.ts @@ -8,6 +8,7 @@ import { canonicalExecutionUuid } from "./execution-identity.js"; import { assertSelectedWorkspaceTrust, runRetainsIssueIdentity, taskRepositoryRunColumns, taskRepositoryResponsibleUserMatches } from "./task-repository-acquisition.js"; import { resolveCoreTrustPreset } from "./trust-preset-resolver.js"; import { isDeepStrictEqual } from "node:util"; +import { ProjectAccessDeniedError } from "./project-access-denial.js"; import { taskWorkspaceSelectionSchema, type TaskWorkspaceSelection } from "@paperclipai/shared"; type DbTransaction = Parameters[0]>[0]; @@ -19,7 +20,12 @@ export async function assertTaskWorkspaceSourceProjectAccess( const decision = await measureRunPhase("workspace.access.authorization", () => accessService(db as Db).decide({ actor, action: "project:read", resource: { type: "project", companyId, projectId }, })); - if (!decision.allowed) throw forbidden(decision.explanation); + if (!decision.allowed) { + if (actor.type === "agent" && decision.reason === "deny_low_trust_boundary") { + throw new ProjectAccessDeniedError(projectId); + } + throw forbidden(decision.explanation); + } } export async function assertExecutionWorkspaceRecordAccess( diff --git a/ui/src/api/agents.ts b/ui/src/api/agents.ts index 5d31460ea38..9f97ce68bfe 100644 --- a/ui/src/api/agents.ts +++ b/ui/src/api/agents.ts @@ -1,4 +1,5 @@ import type { AgentPublicIdentity } from "@paperclipai/shared"; +import type { AgentProjectAccess } from "@paperclipai/shared"; import type { Agent, EnvironmentProbeResult, @@ -111,6 +112,8 @@ function agentPath(id: string, companyId?: string, suffix = "") { } export const agentsApi = { + projectAccess: (id: string) => api.get(`/agents/${id}/project-access`), + addProjectAccess: (id: string, projectIds: string[]) => api.post(`/agents/${id}/project-access`, { projectIds }), qualifyRunner: (id: string, expectedEnvironmentId: string, companyId?: string) => api.post(agentPath(id, companyId, "/qualify-runner"), { expectedEnvironmentId }), setAvatar: (companyId: string, agentId: string, imageBase64: string | null) => diff --git a/ui/src/components/AgentProjectAccessSettings.tsx b/ui/src/components/AgentProjectAccessSettings.tsx new file mode 100644 index 00000000000..2320755c85f --- /dev/null +++ b/ui/src/components/AgentProjectAccessSettings.tsx @@ -0,0 +1,34 @@ +import { useQuery, useQueryClient } from "@tanstack/react-query"; +import { isUuidLike } from "@paperclipai/shared"; +import { agentsApi } from "../api/agents"; +import { projectsApi } from "../api/projects"; +import { queryKeys } from "../lib/queryKeys"; +import { Link, useSearchParams } from "../lib/router"; +import { AllowedProjectsEditor } from "./AllowedProjectsEditor"; +import { Button } from "./ui/button"; + +export function AgentProjectAccessSettings({ agent }: { agent: { id: string; companyId: string; name: string; urlKey?: string } }) { + const client = useQueryClient(); + const [params] = useSearchParams(); + const fromTask = params.get("fromTask"); + const access = useQuery({ queryKey: queryKeys.agents.projectAccess(agent.id), queryFn: () => agentsApi.projectAccess(agent.id) }); + const projects = useQuery({ queryKey: queryKeys.projects.list(agent.companyId), queryFn: () => projectsApi.list(agent.companyId) }); + if (access.error || projects.error) return
+

Couldn’t load project access.

+
; + if (!access.data || !projects.data) return

Loading project access…

; + return
+ { + const saved = await agentsApi.addProjectAccess(agent.id, projectIds); + client.setQueryData(queryKeys.agents.projectAccess(agent.id), saved); + await Promise.all([ + client.invalidateQueries({ queryKey: queryKeys.agents.detail(agent.id) }), + ...(agent.urlKey ? [client.invalidateQueries({ queryKey: queryKeys.agents.detail(agent.urlKey) })] : []), + client.invalidateQueries({ queryKey: queryKeys.agents.list(agent.companyId) }), + client.invalidateQueries({ queryKey: ["issues"] }), + ]); + }} /> + {fromTask && isUuidLike(fromTask) && } +
; +} diff --git a/ui/src/components/AllowedProjectsEditor.tsx b/ui/src/components/AllowedProjectsEditor.tsx new file mode 100644 index 00000000000..a34ced1479d --- /dev/null +++ b/ui/src/components/AllowedProjectsEditor.tsx @@ -0,0 +1,72 @@ +import { useState } from "react"; +import { Check, FolderOpen, Loader2, Plus, X } from "lucide-react"; +import { Button } from "./ui/button"; +import { Checkbox } from "./ui/checkbox"; +import { Input } from "./ui/input"; +import { Popover, PopoverContent, PopoverTrigger } from "./ui/popover"; + +export interface AllowedProjectsEditorProps { + projects: Array<{ id: string; name: string }>; + projectIds: string[]; + canManage: boolean; + agentName: string; + onSave: (projectIds: string[]) => Promise; +} + +export function AllowedProjectsEditor({ projects, projectIds, canManage, agentName, onSave }: AllowedProjectsEditorProps) { + const [added, setAdded] = useState([]); + const [open, setOpen] = useState(false); + const [query, setQuery] = useState(""); + const [saving, setSaving] = useState(false); + const [saved, setSaved] = useState(false); + const [error, setError] = useState(null); + const pending = added.filter(id => !projectIds.includes(id)); + const visibleIds = [...new Set([...projectIds, ...pending])]; + const name = (id: string) => projects.find(project => project.id === id)?.name ?? "Unavailable project"; + const matches = projects.filter(project => project.name.toLowerCase().includes(query.toLowerCase())); + + async function save() { + if (!canManage || saving || !pending.length) return; + setSaving(true); setError(null); setSaved(false); + try { await onSave(pending); setAdded([]); setSaved(true); } + catch (failure) { setError(failure instanceof Error ? failure.message : "Couldn’t save project access."); } + finally { setSaving(false); } + } + + return
+
+

Allowed projects

+

Projects whose tasks and repositories this agent may access.

+ {canManage && + + + setQuery(event.target.value)} /> +
{matches.map(project => )}
+ {!matches.length &&

No projects found.

} + +
} +
+ {visibleIds.length ?
    + {visibleIds.map(id =>
  • + {name(id)} + {projectIds.includes(id) ? Allowed + : <>To add} +
  • )} +
:

No projects allowed yet.

} + {!canManage &&

A person with agent-management permission can add projects here.

} + {pending.length > 0 &&
+

Add access to {pending.map(name).join(", ")}

+

{agentName} will be able to access work and repositories in {pending.length === 1 ? "this project" : "these projects"}. Existing project access and low-trust restrictions stay in place.

+
} + {error &&

Couldn’t save project access. Your selection is kept. {error}

} + {saved &&

Project access saved. Return to your task to retry.

} + {canManage &&
+ + +
} +
; +} diff --git a/ui/src/components/ExecutionBlockerNotice.tsx b/ui/src/components/ExecutionBlockerNotice.tsx index 9c34d72748f..17bd169750c 100644 --- a/ui/src/components/ExecutionBlockerNotice.tsx +++ b/ui/src/components/ExecutionBlockerNotice.tsx @@ -2,9 +2,10 @@ import type { TaskInterruptionPresentation } from "@paperclipai/shared"; import { Button } from "./ui/button"; import { cn } from "../lib/utils"; import { useSecondTick } from "../hooks/useSecondTick"; +import { TaskProjectAccessNotice } from "./TaskProjectAccessNotice"; /** One ordinary interruption surface. Technical records remain in diagnostics. */ -export function ExecutionBlockerNotice({ presentation, canRetry, onRetry, optimistic, takingLonger, error, className }: { +export function ExecutionBlockerNotice({ presentation, canRetry, onRetry, optimistic, takingLonger, error, className, issueId, agentName, projectName }: { presentation: TaskInterruptionPresentation | null | undefined; canRetry: boolean; onRetry: () => void; @@ -12,8 +13,14 @@ export function ExecutionBlockerNotice({ presentation, canRetry, onRetry, optimi takingLonger?: boolean; error?: Error | null; className?: string; + issueId?: string; + agentName?: string; + projectName?: string; }) { useSecondTick(presentation?.state === "retry_scheduled"); + if (presentation?.projectAccess && !optimistic && !takingLonger) return ; if (error && !optimistic && !takingLonger) return
{error.message}{canRetry && }
; if (takingLonger) return
Taking longer than usual…{canRetry && }
; if (optimistic || !presentation || presentation.responsibility !== "system" || diff --git a/ui/src/components/ProjectAccessNotice.tsx b/ui/src/components/ProjectAccessNotice.tsx new file mode 100644 index 00000000000..07386a68de5 --- /dev/null +++ b/ui/src/components/ProjectAccessNotice.tsx @@ -0,0 +1,38 @@ +import { ShieldCheck, ShieldX, ArrowRight } from "lucide-react"; +import { Button } from "./ui/button"; +import { cn } from "../lib/utils"; + +export interface ProjectAccessNoticeProps { + agentName?: string; + projectName?: string; + ready: boolean; + canManage: boolean; + canRetry: boolean; + onManage: () => void; + onRetry: () => void; + error?: Error | null; + className?: string; +} + +export function ProjectAccessNotice({ agentName = "This agent", projectName, ready, canManage, canRetry, onManage, onRetry, error, className }: ProjectAccessNoticeProps) { + return
+
+ {ready ? : } +
+

{ready ? "Project access is ready" : `${agentName} can’t access this project`}

+

{ready + ? "The agent can now access the required project. Retry to continue with your saved message." + : `This task needs ${projectName ?? "a project"} outside the agent’s allowed projects. The agent hasn’t started. Your message is saved.`}

+ {!ready && !canManage &&

A person with agent-management permission can add this project in the agent’s Permissions / Trust settings.

} +
+
+
+ {ready ? canRetry && + : } +
+ {error &&

{error.message}

} + {!ready &&
Run details +
Stopped during
Workspace setup
Reason
Project outside allowed scope
Provider started
No
+
} +
; +} diff --git a/ui/src/components/TaskProjectAccessNotice.tsx b/ui/src/components/TaskProjectAccessNotice.tsx new file mode 100644 index 00000000000..021d955f8ec --- /dev/null +++ b/ui/src/components/TaskProjectAccessNotice.tsx @@ -0,0 +1,23 @@ +import { useQuery } from "@tanstack/react-query"; +import type { TaskInterruptionPresentation } from "@paperclipai/shared"; +import { agentsApi } from "../api/agents"; +import { useNavigate } from "../lib/router"; +import { queryKeys } from "../lib/queryKeys"; +import { ProjectAccessNotice } from "./ProjectAccessNotice"; + +export function TaskProjectAccessNotice({ access, issueId, agentName, projectName, ...props }: { + access: NonNullable; + issueId?: string; + agentName?: string; + projectName?: string; + canRetry: boolean; + onRetry: () => void; + error?: Error | null; + className?: string; +}) { + const navigate = useNavigate(); + const permission = useQuery({ queryKey: queryKeys.agents.projectAccess(access.agentId), queryFn: () => agentsApi.projectAccess(access.agentId) }); + return navigate(`/agents/${access.agentId}/permissions${issueId ? `?fromTask=${encodeURIComponent(issueId)}` : ""}`)} />; +} diff --git a/ui/src/components/TrustPresetSection.tsx b/ui/src/components/TrustPresetSection.tsx index 132ab11bff3..cae599bbdf6 100644 --- a/ui/src/components/TrustPresetSection.tsx +++ b/ui/src/components/TrustPresetSection.tsx @@ -1,4 +1,4 @@ -import { useEffect, useMemo, useState } from "react"; +import { useEffect, useMemo, useState, type ReactNode } from "react"; import type { AgentPermissions, TrustPreset } from "@paperclipai/shared"; import { Lock, ShieldAlert } from "lucide-react"; import { Button } from "@/components/ui/button"; @@ -59,6 +59,7 @@ export function TrustPresetSection({ issueCandidates = [], candidatesLoading, allowSingleIssue = true, + projectAccessEditor, }: { permissions: Partial | null | undefined; onChange: (permissions: Partial) => void; @@ -68,6 +69,7 @@ export function TrustPresetSection({ issueCandidates?: LowTrustBoundaryCandidate[]; candidatesLoading?: boolean; allowSingleIssue?: boolean; + projectAccessEditor?: ReactNode; }) { const [policyOpen, setPolicyOpen] = useState(false); const preset = getTrustPreset(permissions); @@ -148,7 +150,7 @@ export function TrustPresetSection({ : "This agent is set to low-trust review, but no project, root issue, or issue scope is set in the core policy. Add a scope before this agent can run without denial."}

- {boundaryEditable ? ( + {projectAccessEditor && (boundary?.projectIds?.length ?? 0) > 0 ? null : boundaryEditable ? (
@@ -211,7 +213,7 @@ export function TrustPresetSection({

)} -

+ {!projectAccessEditor &&

Want to set more than one containment boundary?{" "} Get Paperclip EE. -

+

} ) : null} + {lowTrust && projectAccessEditor} + {managedPermissions.authorizationPolicy?.reviewPreset ? null : (

Advanced permissions remain editable through the EE permissions extension when installed. diff --git a/ui/src/lib/queryKeys.ts b/ui/src/lib/queryKeys.ts index 85bdb7694fd..26dafb622df 100644 --- a/ui/src/lib/queryKeys.ts +++ b/ui/src/lib/queryKeys.ts @@ -222,6 +222,7 @@ export const queryKeys = { ["team-catalog", "installed", companyId] as const, }, agents: { + projectAccess: (id: string) => ["agents", "project-access", id] as const, identity: (id: string) => ["agents", "identity", id] as const, list: (companyId: string) => ["agents", companyId] as const, detail: (id: string) => ["agents", "detail", id] as const, diff --git a/ui/src/pages/AgentDetail.production.tsx b/ui/src/pages/AgentDetail.production.tsx index 1258faa6955..b89c8f42501 100644 --- a/ui/src/pages/AgentDetail.production.tsx +++ b/ui/src/pages/AgentDetail.production.tsx @@ -4,7 +4,7 @@ import { characterStateForAgent } from "@paperclipai/shared"; import { mergeRunLogChunks, readChunkSeq } from "../lib/run-log-chunks"; import { getPageVisibility, usePageVisibility } from "../lib/page-visibility"; import { useCallback, useEffect, useMemo, useState, useRef } from "react"; -import { useParams, useNavigate, Link, Navigate, useBeforeUnload, type NavigateFunction } from "@/lib/router"; +import { useParams, useNavigate, useLocation, Link, Navigate, useBeforeUnload, type NavigateFunction } from "@/lib/router"; import { useQuery, useMutation, useQueryClient, type QueryClient } from "@tanstack/react-query"; import { agentsApi, @@ -58,6 +58,7 @@ import { BuiltInBundlePanel } from "../components/BuiltInBundlePanel"; import { ConfigureBuiltInAgentModal } from "../components/ConfigureBuiltInAgentModal"; import { BudgetPolicyCard } from "../components/BudgetPolicyCard"; import { TrustPresetSection } from "../components/TrustPresetSection"; +import { AgentProjectAccessSettings } from "../components/AgentProjectAccessSettings"; import { FileTree, buildFileTree } from "../components/FileTree"; import { ScrollToBottom } from "../components/ScrollToBottom"; import { SourceResolvedFoldCallout } from "../components/SourceResolvedFoldCallout"; @@ -768,6 +769,7 @@ export function AgentDetail() { const { setBreadcrumbs } = useBreadcrumbs(); const queryClient = useQueryClient(); const navigate = useNavigate(); + const location = useLocation(); const [actionError, setActionError] = useState(null); const [dismissedLeftAgentIds, setDismissedLeftAgentIds] = useState>(() => new Set()); const { enabled: chatEnabled, githubEnabled, loaded: chatConnectorsLoaded } = useChatConnectorsEnabled(); @@ -987,10 +989,10 @@ export function AgentDetail() { ? "budget" : "dashboard"; if (routeAgentRef !== canonicalAgentRef || urlTab !== canonicalTab) { - navigate(`/agents/${canonicalAgentRef}/${canonicalTab}`, { replace: true }); + navigate(`/agents/${canonicalAgentRef}/${canonicalTab}${location.search}`, { replace: true }); return; } - }, [agent, routeAgentRef, canonicalAgentRef, urlRunId, urlTab, activeView, navigate, chatConnectorsLoaded]); + }, [agent, routeAgentRef, canonicalAgentRef, urlRunId, urlTab, activeView, navigate, chatConnectorsLoaded, location.search]); useEffect(() => { if (!agent?.companyId || agent.companyId === selectedCompanyId) return; @@ -2209,6 +2211,7 @@ function ConfigurationTab({ ) : null} {content === "configuration" ? } permissions={agent.permissions} disabled={updatePermissions.isPending} companyId={companyId} diff --git a/ui/src/pages/AgentDetail.tsx b/ui/src/pages/AgentDetail.tsx index ccc3d42335f..5a2693c0e2d 100644 --- a/ui/src/pages/AgentDetail.tsx +++ b/ui/src/pages/AgentDetail.tsx @@ -11,7 +11,7 @@ import { characterStateForAgent } from "@paperclipai/shared"; import { mergeRunLogChunks, readChunkSeq } from "../lib/run-log-chunks"; import { getPageVisibility, usePageVisibility } from "../lib/page-visibility"; import { useCallback, useEffect, useMemo, useState, useRef } from "react"; -import { useParams, useNavigate, Link, Navigate, useBeforeUnload, type NavigateFunction } from "@/lib/router"; +import { useParams, useNavigate, useLocation, Link, Navigate, useBeforeUnload, type NavigateFunction } from "@/lib/router"; import { useQuery, useMutation, useQueryClient, type QueryClient } from "@tanstack/react-query"; import { agentsApi, @@ -63,6 +63,7 @@ import { InlineBanner } from "../components/InlineBanner"; import { BuiltInBundlePanel } from "../components/BuiltInBundlePanel"; import { ConfigureBuiltInAgentModal } from "../components/ConfigureBuiltInAgentModal"; import { TrustPresetSection } from "../components/TrustPresetSection"; +import { AgentProjectAccessSettings } from "../components/AgentProjectAccessSettings"; import { FileTree, buildFileTree } from "../components/FileTree"; import { ScrollToBottom } from "../components/ScrollToBottom"; import { SourceResolvedFoldCallout } from "../components/SourceResolvedFoldCallout"; @@ -780,6 +781,7 @@ export function AgentDetail() { const { setBreadcrumbs } = useBreadcrumbs(); const queryClient = useQueryClient(); const navigate = useNavigate(); + const location = useLocation(); const [actionError, setActionError] = useState(null); const [dismissedLeftAgentIds, setDismissedLeftAgentIds] = useState>(() => new Set()); const activeView: AgentDetailView = urlRunId ? "run-detail" @@ -983,10 +985,10 @@ export function AgentDetail() { if (legacyAuditSection) return; const canonicalTab = activeView === "run-detail" ? "overview" : activeView; if (routeAgentRef !== canonicalAgentRef || urlTab !== canonicalTab) { - navigate(agentDetailHref(canonicalAgentRef, canonicalTab), { replace: true }); + navigate(`${agentDetailHref(canonicalAgentRef, canonicalTab)}${location.search}`, { replace: true }); return; } - }, [agent, routeAgentRef, canonicalAgentRef, urlRunId, urlTab, activeView, legacyAuditSection, navigate]); + }, [agent, routeAgentRef, canonicalAgentRef, urlRunId, urlTab, activeView, legacyAuditSection, navigate, location.search]); useEffect(() => { if (!agent?.companyId || agent.companyId === selectedCompanyId) return; @@ -2135,6 +2137,7 @@ export function ConfigurationTab({ {content === "permissions" ? } permissions={agent.permissions} disabled={updatePermissions.isPending} companyId={companyId} diff --git a/ui/src/pages/Inbox.tsx b/ui/src/pages/Inbox.tsx index 5913637d3f0..c64b6fc4e3f 100644 --- a/ui/src/pages/Inbox.tsx +++ b/ui/src/pages/Inbox.tsx @@ -394,6 +394,7 @@ export function FailedRunInboxRow({ : interruption?.state === "waiting_for_user" ? ({ approval: "Approval required", reconnect: "Reconnect account", assign_agent: "Assign an agent", choose_model: "Choose a supported model", resume: "Work is paused", budget: "Budget limit reached", + project_access: "Agent needs project access", }[interruption.userAction ?? "resume"]) : runFailureMessage(run); const retryAvailable = !interruption || interruption.canRetry; const showUnreadSlot = unreadState !== null; diff --git a/ui/src/pages/IssueDetail.tsx b/ui/src/pages/IssueDetail.tsx index fcb321a66f1..abac74816d5 100644 --- a/ui/src/pages/IssueDetail.tsx +++ b/ui/src/pages/IssueDetail.tsx @@ -7814,6 +7814,7 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS )} {resolvedDetailTab === "chat" && ( )} diff --git a/ui/storybook/stories/design-proposals/project-access.stories.tsx b/ui/storybook/stories/design-proposals/project-access.stories.tsx new file mode 100644 index 00000000000..8efb0bc3a7e --- /dev/null +++ b/ui/storybook/stories/design-proposals/project-access.stories.tsx @@ -0,0 +1,121 @@ +import type { Meta, StoryObj } from "@storybook/react-vite"; +import { expect, userEvent, waitFor, within } from "storybook/test"; +import { ProjectAccessProposal } from "../../support/design-proposals/ProjectAccessProposal"; + +const meta = { + id: "design-project-access", + title: "Design proposals/Patterns/Project access recovery", + component: ProjectAccessProposal, + parameters: { + layout: "fullscreen", + initialEntries: ["/PAP/issues/DEMO-42"], + docs: { description: { component: "Start at Blocked task. Manage project access opens the proposed agent settings. Add Agent Extensions, review the additive access change, save, return to the task and retry. Low-trust review stays active. Settings supports multiple allowed projects without replacing the existing one. Read-only, pending save, failed save and failed retry states remain actionable. The reply and every state transition are local fixtures; no project permissions change and no provider runs. Reset the story to restore the starting state." } }, + paperclip: { + capabilities: ["recovery/diagnosis", "recovery/source-action", "agents/instructions"], + home: "design-proposals", status: "proposed", + exception: "Requested design for a visible project denial and additive project access repair before production implementation.", + implementation: "prototype", boundary: "fixtures", + notes: "Reuses DesignPageShell, DesignSidebar, AgentAvatar, IssueStatusBadge, TaskChatBubble, TaskChatLiveRunPill and shared form primitives. Notice, access editor and navigation are a local prototype. Synthetic names and repositories only. Save retains existing projects; failed saves preserve draft but grant nothing. Retry is unavailable before a saved grant and does not run on save. Read-only viewers cannot edit. No production API, persistence, permission, provider or recovery proof. The implemented notice and editor are covered by the task-project-access stories; this retains the original design snapshot. Server regression tests and application verification cover authorization, persistence and explicit retry separately.", + }, + }, +} satisfies Meta; +export default meta; +type Story = StoryObj; + +export const BlockedTask: Story = {}; +export const AgentSettings: Story = { args: { initialView: "permissions" } }; +export const AccessSaved: Story = { args: { initialState: "access_saved" } }; +export const ReadOnly: Story = { args: { canManage: false }, play: async ({ canvasElement }) => { + const canvas = within(canvasElement); + await expect(await canvas.findByText("Reviewer can’t access this project")).toBeVisible(); + await expect(canvas.queryByRole("button", { name: "Manage project access" })).not.toBeInTheDocument(); + await userEvent.click(canvas.getByRole("button", { name: "View agent access" })); + await expect(canvas.getByText("Only people with agent configuration permission can change this access.")).toBeVisible(); + await expect(canvas.queryByRole("button", { name: "Add project" })).not.toBeInTheDocument(); +} }; +export const Light: Story = { globals: { theme: "light" } }; +export const Mobile: Story = { globals: { viewport: { value: "mobile1", isRotated: false } } }; +export const MobileSettings: Story = { args: { initialView: "permissions" }, globals: { viewport: { value: "mobile1", isRotated: false } } }; + +async function addProject(canvasElement: HTMLElement, name = "Agent Extensions") { + const canvas = within(canvasElement), screen = within(canvasElement.ownerDocument.body); + await userEvent.click(await canvas.findByRole("button", { name: "Add project" })); + await userEvent.click(await screen.findByRole("checkbox", { name })); + await userEvent.click(screen.getByRole("button", { name: "Done" })); +} + +export const RepairJourney: Story = { play: async ({ canvasElement, step }) => { + const canvas = within(canvasElement); + await step("Explain the denied project before any provider work", async () => { + await expect(await canvas.findByText("Reviewer can’t access this project")).toBeVisible(); + await expect(canvas.getByRole("alert")).toHaveTextContent("The agent hasn’t started. Your message is saved."); + await expect(canvas.queryByRole("button", { name: "Retry task" })).not.toBeInTheDocument(); + await userEvent.click(canvas.getByRole("button", { name: "Manage project access" })); + }); + await step("Add a project while preserving existing containment", async () => { + await expect(canvas.getByRole("button", { name: "Save project access" })).toBeDisabled(); + await addProject(canvasElement); + await expect(canvas.getByTestId("project-product")).toHaveTextContent("Allowed"); + await expect(canvas.getByTestId("project-extensions")).toHaveTextContent("To add"); + await expect(canvas.getByText("Low-trust review", { exact: true })).toBeVisible(); + await userEvent.click(canvas.getByRole("button", { name: "Save project access" })); + await expect(await canvas.findByText("Project access saved.")).toBeVisible(); + await expect(canvas.getByTestId("project-product")).toHaveTextContent("Allowed"); + await expect(canvas.getByTestId("project-extensions")).toHaveTextContent("Allowed"); + }); + await step("Explicitly retry the saved message after saving access", async () => { + await userEvent.click(canvas.getByRole("button", { name: "Return to task" })); + await expect(canvas.getByText("Project access is ready")).toBeVisible(); + await waitFor(() => expect(canvas.getByText("Are you there?")).toBeVisible()); + await userEvent.click(canvas.getByRole("button", { name: "Retry task" })); + await waitFor(() => expect(canvas.getByText("Yes, I’m here. What would you like me to look at?")).toBeVisible()); + await expect(canvas.queryByRole("alert")).not.toBeInTheDocument(); + }); +} }; + +export const CancelJourney: Story = { args: { initialView: "permissions" }, play: async ({ canvasElement }) => { + const canvas = within(canvasElement); + await addProject(canvasElement); + await userEvent.click(canvas.getByRole("button", { name: "Cancel" })); + await expect(canvas.getByText("Reviewer can’t access this project")).toBeVisible(); + await userEvent.click(canvas.getByRole("button", { name: "Manage project access" })); + await expect(canvas.queryByTestId("project-extensions")).not.toBeInTheDocument(); + await expect(canvas.getByTestId("project-product")).toHaveTextContent("Allowed"); +} }; + +export const SaveFailure: Story = { args: { initialView: "permissions", failSave: true }, play: async ({ canvasElement }) => { + const canvas = within(canvasElement); + await addProject(canvasElement); + await userEvent.click(canvas.getByRole("button", { name: "Save project access" })); + await expect(await canvas.findByRole("alert")).toHaveTextContent("No permissions changed. Your selection is kept."); + await expect(canvas.getByTestId("project-extensions")).toHaveTextContent("To add"); + await expect(canvas.getByTestId("project-product")).toHaveTextContent("Allowed"); +} }; +export const SaveFailureJourney: Story = { args: { initialView: "permissions", failSave: true }, play: async ({ canvasElement }) => { + const canvas = within(canvasElement); + await addProject(canvasElement); + await userEvent.click(canvas.getByRole("button", { name: "Save project access" })); + await userEvent.click(await canvas.findByRole("button", { name: "Try saving again" })); + await expect(await canvas.findByText("Project access saved.")).toBeVisible(); + await expect(canvas.getByTestId("project-extensions")).toHaveTextContent("Allowed"); +} }; +export const Saving: Story = { args: { initialView: "permissions", holdSaving: true }, play: async ({ canvasElement }) => { + const canvas = within(canvasElement); + await addProject(canvasElement); + await userEvent.click(canvas.getByRole("button", { name: "Save project access" })); + await expect(canvas.getByRole("button", { name: "Saving access…" })).toBeDisabled(); + await expect(canvas.getByRole("button", { name: "Cancel" })).toBeDisabled(); +} }; +export const RetryFailure: Story = { args: { initialState: "access_saved", failRetry: true }, play: async ({ canvasElement }) => { + const canvas = within(canvasElement); + await userEvent.click(await canvas.findByRole("button", { name: "Retry task" })); + await expect(await canvas.findByRole("alert")).toHaveTextContent("Couldn’t start the retry. Project access is saved."); +} }; +export const MultipleProjects: Story = { args: { initialView: "permissions" }, play: async ({ canvasElement }) => { + const canvas = within(canvasElement); + await addProject(canvasElement); + await addProject(canvasElement, "Website"); + await userEvent.click(canvas.getByRole("button", { name: "Save project access" })); + await expect(await canvas.findByText("Project access saved.")).toBeVisible(); + for (const id of ["product", "extensions", "website"]) await expect(canvas.getByTestId(`project-${id}`)).toHaveTextContent("Allowed"); +} }; diff --git a/ui/storybook/stories/recovery/project-access.stories.tsx b/ui/storybook/stories/recovery/project-access.stories.tsx new file mode 100644 index 00000000000..3349e6605b3 --- /dev/null +++ b/ui/storybook/stories/recovery/project-access.stories.tsx @@ -0,0 +1,77 @@ +import type { Meta, StoryObj } from "@storybook/react-vite"; +import { useState } from "react"; +import { expect, fn, userEvent, within } from "storybook/test"; +import { AllowedProjectsEditor } from "@/components/AllowedProjectsEditor"; +import { ProjectAccessNotice } from "@/components/ProjectAccessNotice"; + +const meta = { + id: "task-project-access", + title: "Projects and execution/Recovery/Task chat/Project access", + component: ProjectAccessNotice, + parameters: { paperclip: { + capabilities: ["recovery/diagnosis", "agents/instructions"], implementation: "production", boundary: "fixtures", + notes: "Production notice and additive project editor. Local save callbacks cover selection, read-only, cancellation and failed-save states. API authorization, persistence and explicit retry admission are separate server regressions and local application verification.", + } }, + decorators: [(Story) =>

], + args: { agentName: "Reviewer", projectName: "Agent Extensions", ready: false, canManage: true, canRetry: false, onManage: fn(), onRetry: fn() }, +} satisfies Meta; +export default meta; +type Story = StoryObj; + +export const BlockedTask: Story = { play: async ({ canvasElement }) => { + const canvas = within(canvasElement); + await expect(canvas.getByRole("alert")).toHaveTextContent("Your message is saved."); + await expect(canvas.queryByRole("button", { name: "Retry task" })).not.toBeInTheDocument(); + await expect(canvas.getByRole("button", { name: "Manage project access" })).toBeVisible(); +} }; +export const AccessSaved: Story = { args: { ready: true, canRetry: true } }; +export const ReadOnly: Story = { args: { canManage: false } }; +export const Light: Story = { globals: { theme: "light" } }; +export const Mobile: Story = { globals: { viewport: { value: "mobile1", isRotated: false } } }; + +const projects = [{ id: "product", name: "Product" }, { id: "extensions", name: "Agent Extensions" }, { id: "website", name: "Website" }]; +function Editor({ fail = false, canManage = true }: { fail?: boolean; canManage?: boolean }) { + const [ids, setIds] = useState(["product"]); + const [failed, setFailed] = useState(false); + return { + if (fail && !failed) { setFailed(true); throw new Error("Connection interrupted."); } + setIds(current => [...new Set([...current, ...added])]); + }} />; +} +async function selectProject(canvasElement: HTMLElement) { + const canvas = within(canvasElement), screen = within(canvasElement.ownerDocument.body); + await userEvent.click(canvas.getByRole("button", { name: "Add project" })); + await expect(await screen.findByRole("checkbox", { name: "Product" })).toBeDisabled(); + await userEvent.click(screen.getByRole("checkbox", { name: "Agent Extensions" })); + await userEvent.click(screen.getByRole("button", { name: "Done" })); +} +export const AgentSettings: Story = { render: () => }; +export const SaveAccess: Story = { ...AgentSettings, play: async ({ canvasElement }) => { + const canvas = within(canvasElement); + await selectProject(canvasElement); + await userEvent.click(canvas.getByRole("button", { name: "Save project access" })); + await expect(await canvas.findByRole("status")).toHaveTextContent("Project access saved"); + await expect(canvas.getAllByText("Allowed", { exact: true })).toHaveLength(2); + await expect(canvas.queryByRole("button", { name: "Retry task" })).not.toBeInTheDocument(); +} }; +export const CancelAddition: Story = { ...AgentSettings, play: async ({ canvasElement }) => { + const canvas = within(canvasElement); + await selectProject(canvasElement); + await userEvent.click(canvas.getByRole("button", { name: "Cancel" })); + await expect(canvas.queryByText("Agent Extensions", { exact: true })).not.toBeInTheDocument(); + await expect(canvas.getByText("Product")).toBeVisible(); +} }; +export const SaveFailure: Story = { render: () => , play: async ({ canvasElement }) => { + const canvas = within(canvasElement); + await selectProject(canvasElement); + await userEvent.click(canvas.getByRole("button", { name: "Save project access" })); + await expect(await canvas.findByRole("alert")).toHaveTextContent("Your selection is kept"); + await expect(canvas.getByText("To add")).toBeVisible(); + await userEvent.click(canvas.getByRole("button", { name: "Try saving again" })); + await expect(await canvas.findByRole("status")).toHaveTextContent("Project access saved"); +} }; +export const ReadOnlySettings: Story = { render: () => , play: async ({ canvasElement }) => { + await expect(within(canvasElement).queryByRole("button", { name: "Add project" })).not.toBeInTheDocument(); +} }; +export const MobileSettings: Story = { ...AgentSettings, globals: { viewport: { value: "mobile1", isRotated: false } } }; diff --git a/ui/storybook/support/design-proposals/ProjectAccessProposal.tsx b/ui/storybook/support/design-proposals/ProjectAccessProposal.tsx new file mode 100644 index 00000000000..a8894e19af5 --- /dev/null +++ b/ui/storybook/support/design-proposals/ProjectAccessProposal.tsx @@ -0,0 +1,180 @@ +import { useState } from "react"; +import { ArrowLeft, ArrowRight, Check, FolderOpen, Loader2, Plus, ShieldCheck, ShieldX, X } from "lucide-react"; +import { AgentAvatar } from "@/components/AgentAvatar"; +import { DesignPageShell } from "@/components/DesignPageShell"; +import { DesignSidebar } from "@/components/DesignSidebar"; +import { IssueStatusBadge } from "@/components/StatusBadge"; +import { TaskChatBubble } from "@/components/task-chat/TaskChatBubble"; +import { TaskChatLiveRunPill } from "@/components/task-chat/TaskChatLiveRunPill"; +import { Button } from "@/components/ui/button"; +import { Checkbox } from "@/components/ui/checkbox"; +import { Input } from "@/components/ui/input"; +import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"; +import { DesignProposalAccess } from "./DesignProposalAccess"; + +const projects = [ + { id: "product", name: "Product", repository: "acme/product" }, + { id: "extensions", name: "Agent Extensions", repository: "acme/agent-extensions" }, + { id: "website", name: "Website", repository: "acme/website" }, +]; +const agent = { id: "reviewer-preview", name: "Reviewer" }; +const wait = () => new Promise(resolve => setTimeout(resolve, 650)); + +export interface ProjectAccessProposalProps { + initialView?: "task" | "permissions"; + initialState?: "blocked" | "access_saved"; + canManage?: boolean; + failSave?: boolean; + failRetry?: boolean; + holdSaving?: boolean; +} + +/** Design-only state machine. It never calls a permissions or execution API. */ +function Proposal({ initialView = "task", initialState = "blocked", canManage = true, + failSave = false, failRetry = false, holdSaving = false }: ProjectAccessProposalProps) { + const [view, setView] = useState(initialView); + const [allowed, setAllowed] = useState(initialState === "access_saved" ? ["product", "extensions"] : ["product"]); + const [draft, setDraft] = useState(allowed); + const [pickerOpen, setPickerOpen] = useState(false); + const [query, setQuery] = useState(""); + const [saving, setSaving] = useState(false); + const [saveError, setSaveError] = useState(false); + const [saveAttempted, setSaveAttempted] = useState(false); + const [savedNotice, setSavedNotice] = useState(false); + const [run, setRun] = useState<"stopped" | "starting" | "replied">("stopped"); + const [retryError, setRetryError] = useState(false); + const [retryAttempted, setRetryAttempted] = useState(false); + const [shellNotice, setShellNotice] = useState(""); + const added = projects.filter(project => draft.includes(project.id) && !allowed.includes(project.id)); + const accessReady = allowed.includes("extensions"); + + function openPermissions() { + setDraft(allowed); + setSavedNotice(false); + setSaveError(false); + setView("permissions"); + } + + async function save() { + if (!canManage || saving || !added.length) return; + setSaving(true); + setSaveError(false); + if (holdSaving) return; + await wait(); + setSaving(false); + setSaveAttempted(true); + if (failSave && !saveAttempted) { setSaveError(true); return; } + setAllowed([...draft]); + setSavedNotice(true); + } + + async function retry() { + if (!accessReady || run === "starting") return; + setRun("starting"); + setRetryError(false); + await wait(); + setRetryAttempted(true); + if (failRetry && !retryAttempted) { setRun("stopped"); setRetryError(true); return; } + setRun("replied"); + } + + const task =
+
+
+ DEMO-42·Agent Extensions +
+

Quick check-in

+ +
+ Reviewer +
+ + {run === "starting" ?
+ : run === "replied" ? + :
+
+ {accessReady ? : } +
+

{accessReady ? "Project access is ready" : "Reviewer can’t access this project"}

+

{accessReady + ? "Agent Extensions is now in Reviewer’s allowed projects. Retry to continue with your saved message." + : "This task uses Agent Extensions, which isn’t in Reviewer’s allowed projects. The agent hasn’t started. Your message is saved."}

+ {!accessReady && !canManage &&

An organization admin can add this project in Reviewer’s Permissions / Trust settings.

} +
+
+
+ {accessReady ? + : canManage ? + : } +
+ {retryError &&

Couldn’t start the retry. Project access is saved. Try again.

} + {!accessReady &&
Run details +
Stopped during
Workspace setup
Reason
Project outside allowed scope
Provider started
No
+
} +
} + {run === "replied" && } +
; + + const permissions =
+ +

Reviewer

Permissions / Trust

+
+ +

Low-trust review

Runs in an isolated sandbox. Untrusted output stays quarantined.

+
+
+
+

Allowed projects

+

Projects whose tasks and repositories this agent may access.

+
+ {canManage && + + + setQuery(event.target.value)} /> +
{projects.filter(project => `${project.name} ${project.repository}`.toLowerCase().includes(query.toLowerCase())).map(project => )}
+ {!projects.some(project => `${project.name} ${project.repository}`.toLowerCase().includes(query.toLowerCase())) &&

No projects found.

} + +
} +
+
    + {projects.filter(project => draft.includes(project.id)).map(project =>
  • +

    {project.name}

    {project.repository}

    + {allowed.includes(project.id) ? Allowed + : <>To add} +
  • )} +
+ {!accessReady &&

DEMO-42 is waiting for access to Agent Extensions.

} + {!canManage &&

Only people with agent configuration permission can change this access.

} + {added.length > 0 &&
+

Add access to {added.map(project => project.name).join(" and ")}

+

Reviewer will be able to access work and repositories in {added.length === 1 ? "this project" : "these projects"}. Existing project access and low-trust restrictions stay in place.

+
} + {saveError &&

Couldn’t save project access. No permissions changed. Your selection is kept.

} + {savedNotice &&
+ Project access saved. + +
} + {canManage &&
+ + +
} +
+
; + + return
+ setShellNotice("This preview focuses on project access. Use Manage project access to try the repair.")} />} + headerActions={Design preview}> + {shellNotice &&

{shellNotice}

} + {view === "task" ? task : permissions} +
+
; +} + +export function ProjectAccessProposal(props: ProjectAccessProposalProps) { + return ; +} From 5c3dce09b5cb80911a65a03ec09d20bf8fbf78dd Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sat, 24 Oct 2026 16:44:50 -0700 Subject: [PATCH 024/110] fix(runner): preserve verified remote artifacts across controller releases (#17512) ## Thinking Path > - Paperclip manages AI agents and owns their task authority. > - Remote native agents can keep working while their controller restarts. > - The controller must authenticate the same runner and verify its provider files before recovery. > - The current path compares a retained provider pack with the new controller release. A release change can reject intact files. > - The new controller binary digest can also reject the original daemon during PRP authentication. > - This PR records the admitted release authority in private controller state and uses it for exact process reattachment. ## Linked Issues or Issue Description **What happened?** A remote Claude session started and used tools. After controller shutdown, recovery failed with `runner_remote_provider_artifact_incompatible`. The transport combined stderr into stdout, so the error omitted the verifier reason. The historical rejected manifest is unavailable. This PR reproduces controller release drift as a cause; it does not claim that the historical mismatch is proven. Reaching pack verification implies the earlier exact-process/controller-identity checks passed. That supports a preserved-state recovery path but is not a direct inspection of the deployed volume. **Expected behavior** A compatible, unchanged remote runner can reattach after a controller release changes. Full package hashes, exact process scope, protocol capabilities, and authenticated runner identity must still pass. Fresh launches use the current release. **Steps to reproduce** 1. Verify and admit a remote native session with release A. 2. Preserve its runner process and replace the controller with release B. 3. Reattach the original process. The old path compares its pack with B and fails at `manifest mismatch`. 4. With this fix, the controller reads its saved A authority and verifies all A hashes. Changed files still fail. **Paperclip version or commit** Reproduced from master `470cb34c0e42cb9d0b232d0bcf5d45cc7b0a81ca`; rebased onto `a3675ddcdf`. **Deployment mode** Native remote runner on a Daytona-backed Paperclip Computer. Local acceptance uses isolated Linux containers and actual packaged artifacts. Related work: #17361 and #17448 handle runner upgrade and qualification permissions. #17097 and #17439 add durable controller checkpoints and server adoption. That stack can skip remote artifact preparation with a saved checkpoint. This PR fixes the current file-backed path and retains full provider-pack verification; it has no checkpoint schema or empty-disk controller recovery. ## What Changed - Save the complete verified pack manifest and authenticated runner version/digest after successful session admission. - Bind the receipt to company, agent, workspace, session, runner, environment lease, remote directory, and provider descriptor. Keep it outside guest backup directories. - Reuse the saved authority for exact reattachment. Keep current release selection for fresh launches and explicit session replacement. - Fail closed for mismatched or corrupt receipts. Historical sessions without a receipt retain the current release integrity gate. - Report bounded, redacted verifier output from both transport streams. Warn on receipt write failure while returning the already admitted session to its owner. - Add scope, persistence, replacement, storage failure, and backend wiring regressions. Update recovery documentation and the feature map. ## Verification - Test-first red: the original selection chose release B instead of A after controller recreation. The new receipt regression passes. A separate red test showed the missing stdout diagnostic; it passes after the diagnostic fix. - Authority and diagnostic suites: 49 tests pass. Backend pack, process adoption, and harness persistence selection: 47 tests pass. - Actual Linux provider image: complete A manifest/artifact verification passed; controller source-revision drift failed on the old path; saved A authority passed; a modified ACPX sidecar failed its SHA-256 check. - Actual native Linux runner: authenticated a session, detached the controller, changed the controller manifest and binary, then authenticated the original PID and provider session with saved authority. There were zero duplicate spawns, zero new provider turns, no stop/suspend, and the workspace file remained. This probe used the real runner with a deterministic Codex fixture; it is separate from the real ACPX package integrity proof. - Full workspace typecheck and build passed. The full native executor suite first hit host PostgreSQL semaphore exhaustion. The complete changed files then passed 864/864 tests with separate real PostgreSQL databases in a disposable Linux container. The temporary local fixture changed only database provisioning and used normal repository migrations. Current-head CI also passed the full required test, Runner, browser, typecheck, and build lanes. - `node scripts/check-maps.mjs` and `git diff --check` passed. These structural checks do not prove live recovery. - Current head `48fca2ae33d99f7f6d2fe12f431cf76d25185c70`: 55 successful checks, two conditional skips, no pending or failed checks; fresh Greptile 5/5 with zero findings and zero unresolved review threads. Commitperclip quality review passed. - No original task was retried or changed. Existing Daytona access could not resolve the original sandbox or its image; a fresh staging Claude recovery is not claimed. ## Risks This prevents recurrence for sessions admitted with the new receipt. It does not retroactively recover the historical failed run. Saved authority exists only after this change has admitted a session. It cannot repair an ambiguous historical launch or restore a receipt on an empty replacement controller. A stale protocol or modified pack remains a hard failure. Receipt write errors warn without losing the live session handle, but later recovery still needs matching authority. The broader checkpoint stack changes the same server preparation and runner-artifact option and will require a deliberate integration. ## Model Used OpenAI GPT-6 through Codex, with reasoning, repository tools, and code execution. The runtime does not expose a more specific model ID or 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 `#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 --- doc/execution-semantics.md | 6 +- doc/native-workspace-finalization-recovery.md | 24 ++- maps/feature-map/recovery.md | 8 + .../native-session-executor.test.ts | 41 +++++- .../native-runtime/native-session-executor.ts | 137 ++++++++---------- .../remote-provider-pack-authority.test.ts | 121 ++++++++++++++++ .../remote-provider-pack-authority.ts | 107 ++++++++++++++ .../remote-provider-pack-verification.ts | 85 +++++++++++ .../remote-provider-pack.test.ts | 8 + .../native-runtime/remote-provider-pack.ts | 5 +- 10 files changed, 458 insertions(+), 84 deletions(-) create mode 100644 server/src/services/native-runtime/remote-provider-pack-authority.test.ts create mode 100644 server/src/services/native-runtime/remote-provider-pack-authority.ts create mode 100644 server/src/services/native-runtime/remote-provider-pack-verification.ts diff --git a/doc/execution-semantics.md b/doc/execution-semantics.md index 4b2df094f3a..8bc8886b075 100644 --- a/doc/execution-semantics.md +++ b/doc/execution-semantics.md @@ -1807,7 +1807,11 @@ experimental isolated-workspaces UI. Ordinary workspace updates remain gated; the runtime can bind only a validated shared workspace in the issue's company and project. Follow-ups can therefore reuse the same sandbox and provider session. A staged provider package is reused only after the complete expected -manifest and artifact hashes verify. A missing, changed, or incompatible package +manifest and artifact hashes verify. Exact live-process reattachment uses the +controller-owned pack and runner identities recorded after the original session +passed authentication. It preserves protocol and capability checks. Fresh or +replacement launches use current release authority. A missing historical receipt +retains the current release gate; guest files cannot establish old authority. A missing, changed, or incompatible package must be replaced and verified before launch. Warm attachment requires two consecutive authenticated readiness snapshots. diff --git a/doc/native-workspace-finalization-recovery.md b/doc/native-workspace-finalization-recovery.md index f6ba0ee73ea..8b9c004282c 100644 --- a/doc/native-workspace-finalization-recovery.md +++ b/doc/native-workspace-finalization-recovery.md @@ -371,6 +371,26 @@ and operator guidance remain under Recovery details. Source-only repair remains available through the board-authorized recovery resolution API and its original stop-receipt and evidence checks. +After a remote provider pack passes full integrity verification and the session +passes authenticated admission, the controller saves its manifest and runner +binary identity in `provider-pack-authority.json`. The receipt binds the company, +agent, workspace, session, runner instance, environment lease, remote working +directory, and provider descriptor. It stays in private controller state, outside +guest workspace and harness backup directories. Projectless runs use their +original environment lease as the workspace identity because each run otherwise +has a new workspace placeholder. Real workspace identities still require an exact +match. A receipt write failure warns and returns the admitted session to its +normal owner; it does not discard the live session handle. Future recovery still +fails closed without matching authority. + +Exact process reattachment uses that saved release authority. It still verifies +the full remote pack, runner protocol and capabilities, exact process identity, +and authenticated PRP handshake. A new controller release alone does not require +a live provider to change its executable files. Fresh launches and explicit +session replacement select current release artifacts. Invalid or mismatched +receipts fail closed. Older sessions without a receipt retain the strict current +release gate; a sandbox's own manifest cannot supply missing launch authority. + Remote provider-pack verification retries an interrupted read at most once. Each command retains its 30-second transport timeout. A timeout, signal, absent exit status, or transport exception does not prove artifact incompatibility. @@ -380,7 +400,9 @@ a new provider attempt, so it cannot renew this exhausted read budget. A completed nonzero verification, digest mismatch, or wrong OpenCode version remains incompatible and cannot authorize a new provider turn. Recovery retains the exact source workspace and existing ownership gates; -these read-only retries do not replay tools or alter a retained pack. +these read-only retries do not replay tools or alter a retained pack. Verification +errors include bounded, redacted output from both transport streams, including +providers that combine stderr into stdout. ### Continue after confirmed source destruction diff --git a/maps/feature-map/recovery.md b/maps/feature-map/recovery.md index 6624fbc67f7..b7de12dddc4 100644 --- a/maps/feature-map/recovery.md +++ b/maps/feature-map/recovery.md @@ -176,6 +176,14 @@ and rejected identity evidence. The Runner restart tests require positive exit evidence before replacement. This coverage does not prove recovery of a historical retained sandbox or behavior during a live provider outage. +For a release change during a remote provider session, verify that reattachment +uses the controller's admitted pack manifest and runner digest. Check useful +output from the same process without replaying a turn. Repeat with a modified +sidecar, mismatched receipt scope, replacement lease, and incompatible runner +protocol. The [authority tests](../../server/src/services/native-runtime/remote-provider-pack-authority.test.ts) +and executor wiring regressions cover selection and fail-closed scope checks. +They do not prove a historical retained sandbox was recovered. + For completion recovery, restart after a native completion proposal is appended but before its session checkpoint. Verify that the original result is finalized after provider termination, with no new provider turn or repeated external action. diff --git a/server/src/services/native-runtime/native-session-executor.test.ts b/server/src/services/native-runtime/native-session-executor.test.ts index 51e0c3af818..ad754e8e84e 100644 --- a/server/src/services/native-runtime/native-session-executor.test.ts +++ b/server/src/services/native-runtime/native-session-executor.test.ts @@ -54,9 +54,11 @@ import { type NativeExecutionInput, type PrpEvent, } from "@paperclipai/paperclip-runner"; +import { existsSync } from "node:fs"; import { createHash, generateKeyPairSync, randomUUID } from "node:crypto"; import { DatabaseSync } from "node:sqlite"; import { nativeSha256 } from "./canonical.js"; +import { resolveRemoteProviderPackAuthority } from "./remote-provider-pack-authority.js"; import { RemoteRunnerRecoveryError, readRemoteRunnerRecoveryError } from "./remote-runner-recovery-diagnostics.js"; import { agentDirectoryWorkingCopyService } from "../agent-directory-working-copies.js"; import { probeAgentDirectory } from "../agent-directory-probe.js"; @@ -1432,7 +1434,7 @@ describe("remote provider pack manifest", () => { productionLock: "pnpm-lock.yaml", opencodeCommand: "node_modules/.bin/opencode", opencodeExecutable: "node_modules/opencode-ai/bin/opencode.exe", opencodeProxy: "dist/cli/opencode-app-server-proxy.cjs", acpxSidecar: "dist/cli/acpx-runtime-sidecar.cjs", - }).map(([key, path]) => [key, { path, sha256: digest }])); + }).map(([key, path]) => [key, { path, sha256: digest }])) as Record<"nodeCommand" | "opencodeCommand", { path: string; sha256: string }>; const payload = { target: { platform: "linux", architecture }, runnerSourceRevision: "a".repeat(40), pins: { nodeMinimum: "24.11.0", codex: QUALIFIED_ACPX_PROFILES.codex.agentRuntimeVersion, @@ -1484,6 +1486,43 @@ describe("remote provider pack manifest", () => { sourcePath: state.bundledRunnerBinary, targetPath: "/workspace/.paperclip-runtime/paperclip-runner/bin/paperclip-runnerd", })] })]); expect(execute.mock.calls.some(([call]) => call.args?.[1] === "uname -s; uname -m")).toBe(false); + expect(existsSync(join(transport.stateDirectory!, "provider-pack-authority.json"))).toBe(false); + if (provider === "claude-x64") { + const identity = transport.prpIdentity!; + const artifact = { version: "0.0.0", digest: "sha256:" + createHash("sha256").update(daemon).digest("hex") }; + resolveRemoteProviderPackAuthority({ stateDirectory: transport.stateDirectory!, + binding: { companyId: remoteExecution.binding.companyId, agentId: remoteExecution.binding.agentId, + workspaceId: remoteExecution.binding.executionWorkspaceId, sessionId: remoteExecution.session.normalizedSessionId!, + runnerInstanceId: identity.runnerInstanceId, environmentLeaseId: identity.environmentLeaseId, + remoteCwd: "/workspace", providerDigest: nativeSha256(remoteExecution.provider) }, + reattach: false, current: () => manifest, runnerArtifact: () => artifact }).verified(); + await mkdir(join(transport.stateDirectory!, "control-plane"), { recursive: true }); + await writeFile(join(transport.stateDirectory!, "control-plane", "control-plane-state.json"), JSON.stringify(durableControlPlaneState(identity))); + const next = structuredClone(manifest); + next.payload.runnerSourceRevision = "b".repeat(40); + next.digest = "sha256:" + createHash("sha256").update(canonical(next.payload)).digest("hex"); + await writeFile(state.bundledPackManifestPath!, JSON.stringify(next)); + await writeFile(state.bundledRunnerBinary!, Buffer.concat([daemon, Buffer.from("new release")])); + const recoveryExecute = vi.fn(async (request: { args: string[] }) => { + const script = request.args[1]; + const stdout = script.includes("base64") ? Buffer.from(JSON.stringify({ ...identity, lifecycle: "running" })).toString("base64") + : script.includes("cat --") ? `nonce\n123\n2026-09-19T10:00:00.000Z\n${identity.runnerInstanceId}\nlinux:abcd-1234:100\n` : ""; + return { stdout, stderr: "", exitCode: 0, timedOut: false }; + }); + await createRunnerdBackend({ db: leaseDb(remoteExecution), execution: remoteExecution, + runnerInstanceId: identity.runnerInstanceId, + runnerExecutionTarget: { kind: "remote", transport: "sandbox", remoteCwd: "/workspace", + environmentId: "environment", leaseId: "lease", providerKey: "daytona", runner: { execute: recoveryExecute }, + sandboxLeaseAcquisition: { outcome: "resumed", providerLeaseId: "sandbox" } } as never, + restartRecovery: { kind: "reattach_remote_runner", runId: remoteExecution.binding.runId, + leaseOwner: "controller", controllerGeneration: 2, providerAttempt: 1, restartKind: "graceful", recoveryRequestId: null, + remote: { providerLeaseId: "sandbox", remoteCwd: "/workspace" } }, + }); + state.createBackend.mock.calls.at(-1)![1].codexTransportFactory!(); + expect(state.createTransport.mock.calls.at(-1)![0]).toMatchObject({ + providerPackAuthorityDigest: manifest.digest, runnerArtifact: artifact, adoptExistingRunner: { pid: 123 }, + }); + } } finally { state.bundledPackManifestPath = null; state.bundledRunnerBinary = null; await rm(root, { recursive: true, force: true }); diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index fe6d4732e76..cc03fcbfa56 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -1,3 +1,5 @@ +import { providerPackWorkspaceId, recordAdmittedRemoteProviderPack, resolveRemoteProviderPackAuthority } from "./remote-provider-pack-authority.js"; +import { verifyRemoteProviderPack as verifyRemoteProviderPackIdentity } from "./remote-provider-pack-verification.js"; import { writeEnvironmentCleanup } from "../environment-cleanup-notifications.js"; import { DELIVERY_QUEUES } from "../delivery-work-notifications.js"; import { writeExecutionControl } from "../execution-control-notifications.js"; @@ -47,7 +49,7 @@ import { copyBackCodexAuth } from "@paperclipai/adapter-codex-local/server"; import { nativeCompletionFeedback } from "./native-completion-feedback.js"; import { hasAcknowledgedNativeReassignmentStopIntent, hasAcknowledgedNativeStopIntent } from "../acknowledged-native-stop.js"; import { stoppedCodexTurnIsTextOnly } from "./stopped-codex-turn.js"; -import { prepareVerifiedRemoteProviderPack, useVerifiedPreinstalledRemoteProviderPack, runRemoteProviderVerification, shouldUseBundledAcpxImageAssets } from "./remote-provider-pack.js"; +import { prepareVerifiedRemoteProviderPack, useVerifiedPreinstalledRemoteProviderPack, shouldUseBundledAcpxImageAssets } from "./remote-provider-pack.js"; import { readProviderPackArchive, stageProviderPackArchive } from "./provider-pack-archive.js"; import { selectRemotePiCompanion } from "./remote-pi-companion.js"; import { readNativeLocalProcessStop, PROCESS_START_REQUESTED, withReleasedNativeRunProcess } from "../native-local-process-stop.js"; @@ -12023,7 +12025,6 @@ async function createRunnerdBackendWithinSessionClaim( })); const configuredProviderPackRoot = input.runnerRemoteProviderPackPath?.trim() || remotePiCompanion?.providerPack || bundledClaudeRoot || null; - let expectedProviderPackManifest: RemoteProviderPackManifest | null = null; const useBundledRemoteImageAssets = (requiresRemoteProviderPack && !configuredProviderPackRoot && (input.execution.provider.kind === "opencode" || remoteClaude)) || @@ -12031,24 +12032,6 @@ async function createRunnerdBackendWithinSessionClaim( requiresRemoteProviderPack, configuredProviderPackRoot, provider: input.execution.provider, }); - if (useBundledRemoteImageAssets) { - expectedProviderPackManifest = bundledClaudeManifest && (remoteClaudeTarget === "linux-x64" || remoteClaudeTarget === "linux-arm64") - ? readBundledRemoteProviderPackManifest(bundledClaudeManifest, remoteClaudeTarget) - : readBundledRemoteProviderPackManifest(); - } else if (requiresRemoteProviderPack) { - if ( - !configuredProviderPackRoot || - !existsSync(configuredProviderPackRoot) || - !lstatSync(configuredProviderPackRoot).isDirectory() - ) { - throw new Error( - "runner_remote_provider_artifact_incompatible: configure PAPERCLIP_RUNNER_REMOTE_PROVIDER_PACK_PATH with the build-owned provider pack", - ); - } - expectedProviderPackManifest = readRemoteProviderPackManifest( - configuredProviderPackRoot, - ); - } const stagedRemoteProviderPackRoot = remoteRuntimeRoot ? posix.join(remoteRuntimeRoot, "provider-pack") : null; @@ -12056,6 +12039,25 @@ async function createRunnerdBackendWithinSessionClaim( const remoteBinary = remoteRuntimeRoot ? posix.join(remoteRuntimeRoot, "bin", "paperclip-runnerd") : null; + let currentProviderPackManifest: RemoteProviderPackManifest | undefined; + const resolveCurrentProviderPackManifest = () => { + if (currentProviderPackManifest) return currentProviderPackManifest; + currentProviderPackManifest = (() => { + if (useBundledRemoteImageAssets) { + return bundledClaudeManifest && (remoteClaudeTarget === "linux-x64" || remoteClaudeTarget === "linux-arm64") + ? readBundledRemoteProviderPackManifest(bundledClaudeManifest, remoteClaudeTarget) + : readBundledRemoteProviderPackManifest(); + } + if (!configuredProviderPackRoot || !existsSync(configuredProviderPackRoot) + || !lstatSync(configuredProviderPackRoot).isDirectory()) { + throw new Error("runner_remote_provider_artifact_incompatible: configure PAPERCLIP_RUNNER_REMOTE_PROVIDER_PACK_PATH with the build-owned provider pack"); + } + return readRemoteProviderPackManifest(configuredProviderPackRoot); + })(); + return currentProviderPackManifest; + }; + const reattachProviderPack = input.restartRecovery?.kind === "reattach_remote_runner" || input.remoteWarmRecovery !== undefined; + if (requiresRemoteProviderPack && !reattachProviderPack) resolveCurrentProviderPackManifest(); // The transport hashes runnerBinary on the controller before an external // launcher starts runnerd. Keep that artifact identity in the controller's // filesystem; the remote launcher separately owns the sandbox command path. @@ -12067,6 +12069,19 @@ async function createRunnerdBackendWithinSessionClaim( : remoteTarget ? remoteClaudeRunnerBinary || input.runnerRemoteBinaryPath?.trim() || remotePiCompanion?.runnerBinary || (useBundledRemoteImageAssets ? bundledRemoteRunnerBinary() : resolvePaperclipRunnerBinary()) : resolvePaperclipRunnerBinary(); + const selectProviderPackAuthority = (reattach: boolean) => requiresRemoteProviderPack ? resolveRemoteProviderPackAuthority({ + stateDirectory: root, + binding: { companyId: input.execution.binding.companyId, agentId: input.execution.binding.agentId, + workspaceId: providerPackWorkspaceId(input.execution.binding.executionWorkspaceId, input.execution.binding.runId, effectiveEnvironmentLeaseId), sessionId: nativeSessionKey(input.execution), + runnerInstanceId: effectiveRunnerInstanceId, environmentLeaseId: effectiveEnvironmentLeaseId, + remoteCwd: remoteTarget!.remoteCwd, providerDigest: nativeSha256(input.execution.provider) }, + reattach, + runnerArtifact: () => readRunnerdArtifactBinding(controllerRunnerBinary), + current: resolveCurrentProviderPackManifest, + }) : null; + let providerPackAuthority = selectProviderPackAuthority(reattachProviderPack); + let expectedProviderPackManifest = providerPackAuthority?.manifest ?? null; + let providerPackVerified = false; const explicitRemoteCodex = input.runnerRemoteCodexPath?.trim() || null; const remoteCodexNpmSpec = input.runnerRemoteCodexNpmSpec?.trim() || null; if (explicitRemoteCodex && remoteCodexNpmSpec) { @@ -12159,62 +12174,9 @@ async function createRunnerdBackendWithinSessionClaim( const verifyRemoteProviderPack = async (packRoot: string) => { if (!remoteTarget || !remoteCommandRunner || !expectedProviderPackManifest) return; - const expected = Buffer.from( - canonicalJson(expectedProviderPackManifest), - "utf8", - ).toString("base64"); - const providerNodeCommand = posix.join( - packRoot, - expectedProviderPackManifest.payload.artifacts.nodeCommand.path, - ); - const verifyScript = [ - "const fs=require('node:fs')", - "const crypto=require('node:crypto')", - "const path=require('node:path')", - "const root=process.argv[1]", - "const expected=Buffer.from(process.argv[2],'base64').toString('utf8')", - "const actual=fs.readFileSync(path.join(root,'provider-pack.json'),'utf8').trim()", - "const canonical=(v)=>Array.isArray(v)?'['+v.map(canonical).join(',')+']':v&&typeof v==='object'?'{'+Object.keys(v).sort().map(k=>JSON.stringify(k)+':'+canonical(v[k])).join(',')+'}':JSON.stringify(v)", - "const manifest=JSON.parse(actual)", - "if(canonical(manifest)!==expected)throw new Error('manifest mismatch')", - "const hash=(p)=>'sha256:'+crypto.createHash('sha256').update(fs.readFileSync(path.join(root,p))).digest('hex')", - "const tree=(treeRoot)=>{const digest=crypto.createHash('sha256');const visit=(directory,prefix='')=>{for(const entry of fs.readdirSync(directory,{withFileTypes:true}).sort((a,b)=>a.name.localeCompare(b.name))){const relative=prefix?prefix+'/'+entry.name:entry.name;const absolute=path.join(directory,entry.name);if(entry.isDirectory()){digest.update('directory\\0'+relative+'\\n');visit(absolute,relative)}else if(entry.isFile()){digest.update('file\\0'+relative+'\\0'+'sha256:'+crypto.createHash('sha256').update(fs.readFileSync(absolute)).digest('hex')+'\\n')}else if(entry.isSymbolicLink()){digest.update('symlink\\0'+relative+'\\0'+fs.readlinkSync(absolute)+'\\n')}else throw new Error('unsupported dist entry '+relative)}};visit(treeRoot);return 'sha256:'+digest.digest('hex')}", - "for(const name of ['nodeCommand','productionLock','opencodeCommand','opencodeExecutable','opencodeProxy','acpxSidecar','grokLauncher']){const artifact=manifest.payload.artifacts[name];if(hash(artifact.path)!==artifact.sha256)throw new Error(name+' digest mismatch')}", - "if(tree(path.join(root,'dist'))!==manifest.payload.distDigest)throw new Error('dist tree digest mismatch')", - "for(const candidate of Object.values({...manifest.payload.providers,...manifest.payload.candidateProviders})){if(tree(path.join(root,candidate.path))!==candidate.sha256)throw new Error('candidate asset tree digest mismatch')}", - "const version=process.versions.node.split('.').map(Number)", - "const minimum=manifest.payload.pins.nodeMinimum.split('.').map(Number)", - "if(version[0]JSON.parse(fs.readFileSync(path.join(root,'node_modules',...pkg.split('/'),'package.json'),'utf8')).version", - "const expectedPackages={acpx:manifest.payload.pins.acpx,'@agentclientprotocol/claude-agent-acp':manifest.payload.pins.claudeAcp,'@agentclientprotocol/codex-acp':manifest.payload.pins.codexAcp,'opencode-ai':manifest.payload.pins.opencode}", - "for(const [pkg,version] of Object.entries(expectedPackages))if(packageVersion(pkg)!==version)throw new Error(pkg+' version mismatch')", - ].join(";"); - await runRemoteProviderVerification(() => remoteCommandRunner.execute({ - command: providerNodeCommand, - args: ["-e", verifyScript, packRoot, expected], - cwd: remoteTarget.remoteCwd, - bypassSession: true, - timeoutMs: 30_000, - }), "provider pack verification"); - const opencodeCommand = posix.join( - packRoot, - expectedProviderPackManifest.payload.artifacts.opencodeCommand.path, - ); - const opencodeVersion = await runRemoteProviderVerification(() => remoteCommandRunner.execute({ - command: opencodeCommand, - args: ["--version"], - cwd: remoteTarget.remoteCwd, - bypassSession: true, - timeoutMs: 30_000, - }), "OpenCode version verification"); - if ( - opencodeVersion.stdout.trim() !== REMOTE_PROVIDER_PACK_PINS.opencode - ) { - throw new Error( - "runner_remote_provider_artifact_incompatible: OpenCode version mismatch", - ); - } + await verifyRemoteProviderPackIdentity({ runner: remoteCommandRunner, + cwd: remoteTarget.remoteCwd, packRoot, manifest: expectedProviderPackManifest }); + providerPackVerified = true; }; const discoverPreinstalledProviderPack = async () => { @@ -12333,7 +12295,7 @@ async function createRunnerdBackendWithinSessionClaim( ); } const archive = await measureNativeRunnerSpan(input.trace, "provider_pack.archive.verify", () => - readProviderPackArchive(configuredProviderPackRoot, expectedProviderPackManifest.digest), + readProviderPackArchive(configuredProviderPackRoot, expectedProviderPackManifest!.digest), ); const escapedPackRoot = stagedRemoteProviderPackRoot.replaceAll( "'", @@ -13243,6 +13205,7 @@ async function createRunnerdBackendWithinSessionClaim( // makes the fresh replacement look like ambiguous lost harness state. // Keep their evidence inside the same continuity-break archive. "failover-backups", + "provider-pack-authority.json", ]) { const source = resolve(root, name); if (existsSync(source)) renameSync(source, resolve(archiveRoot, name)); @@ -13265,6 +13228,9 @@ async function createRunnerdBackendWithinSessionClaim( } } remotePrepared = false; + providerPackAuthority = selectProviderPackAuthority(false); + expectedProviderPackManifest = providerPackAuthority?.manifest ?? null; + providerPackVerified = false; }; const localRecoveryProcess = input.restartRecovery?.kind === "reattach_existing_runner" @@ -13455,6 +13421,7 @@ async function createRunnerdBackendWithinSessionClaim( : {}), stateDirectory: root, runnerBinary: controllerRunnerBinary, + ...(providerPackAuthority ? { runnerArtifact: providerPackAuthority.runnerArtifact } : {}), codexCommand: remoteCodexBinary ?? undefined, sourceCodexHome: remoteTarget ? resolveSourceCodexHome(resolveNativeProviderEnvironment(input.execution.provider, runnerEnvironment)) @@ -13660,12 +13627,22 @@ async function createRunnerdBackendWithinSessionClaim( priorAuthorityEpoch.revoke(); } sessionToolAuthorityEpochs.set(sessionScopeId, authorityEpoch); + const recordAdmittedProviderPack = async () => { + if (providerPackVerified && providerPackAuthority) { + await recordAdmittedRemoteProviderPack(providerPackAuthority, message => input.onLog?.("stderr", message)); + } + }; return { bindManagedSession: wrapManagedSession, descriptor: () => backend.descriptor(), - openSession: async (sessionInput) => wrapManagedSession(await backend.openSession(sessionInput)), + openSession: async (sessionInput) => { + const session = await backend.openSession(sessionInput); + await recordAdmittedProviderPack(); + return wrapManagedSession(session); + }, recoverSession: async (snapshot, options) => { const result = backend.recoverSession ? await backend.recoverSession(snapshot, options) : { recovered: false, reason: "driver does not support recovery" }; + if (result.session) await recordAdmittedProviderPack(); return result.session ? { ...result, session: wrapManagedSession(result.session) } : result; }, openReplacementSession: async (sessionInput) => { @@ -13675,7 +13652,9 @@ async function createRunnerdBackendWithinSessionClaim( archiveContinuityState, { parentName: "native.session.execute" }, ); - return wrapManagedSession(await backend.openSession(sessionInput)); + const session = await backend.openSession(sessionInput); + await recordAdmittedProviderPack(); + return wrapManagedSession(session); }, } satisfies NativeSessionBackend & { bindManagedSession(session: NativeSession): NativeSession }; } diff --git a/server/src/services/native-runtime/remote-provider-pack-authority.test.ts b/server/src/services/native-runtime/remote-provider-pack-authority.test.ts new file mode 100644 index 00000000000..f5f2039c4cf --- /dev/null +++ b/server/src/services/native-runtime/remote-provider-pack-authority.test.ts @@ -0,0 +1,121 @@ +import { createHash } from "node:crypto"; +import { mkdtempSync, mkdirSync, rmSync, readFileSync, writeFileSync, symlinkSync, statSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, expect, it, vi } from "vitest"; +import { providerPackWorkspaceId, recordAdmittedRemoteProviderPack, resolveRemoteProviderPackAuthority } from "./remote-provider-pack-authority.js"; +import { canonicalProviderPackJson } from "./remote-provider-pack-verification.js"; + +const directories: string[] = []; +afterEach(() => { for (const dir of directories.splice(0)) rmSync(dir, { recursive: true, force: true }); }); +const binding = { companyId: "company", agentId: "agent", workspaceId: "workspace", sessionId: "session", + runnerInstanceId: "runner", environmentLeaseId: "lease", remoteCwd: "/workspace", providerDigest: "provider" }; +const runnerArtifact = () => ({ version: "0.0.0", digest: "sha256:" + "c".repeat(64) }); +const manifest = (revision: string) => { + const payload = { runnerSourceRevision: revision.repeat(40), target: { platform: "linux", architecture: "x64" }, + pins: { opencode: "1.18.34" }, artifacts: { nodeCommand: { path: "node", sha256: "sha256:" + "1".repeat(64) }, + opencodeCommand: { path: "opencode", sha256: "sha256:" + "2".repeat(64) } } }; + return { schema: "paperclip-runner/remote-provider-pack/v1", payload, + digest: "sha256:" + createHash("sha256").update(canonicalProviderPackJson(payload)).digest("hex") }; +}; +it("reattaches with the verified launch authority after the controller release changes", () => { + const stateDirectory = mkdtempSync(join(tmpdir(), "provider-pack-authority-")); directories.push(stateDirectory); + const original = manifest("a"), next = manifest("b"); + const launched = resolveRemoteProviderPackAuthority({ stateDirectory, binding, reattach: false, runnerArtifact, current: () => original }); + launched.verified(); + const current = vi.fn(() => next); + const recovered = resolveRemoteProviderPackAuthority({ stateDirectory, binding, reattach: true, current, runnerArtifact }); + expect(recovered.manifest).toEqual(original); + expect(recovered.runnerArtifact).toEqual(runnerArtifact()); + expect(current).not.toHaveBeenCalled(); +}); + +function fixture() { + const stateDirectory = mkdtempSync(join(tmpdir(), "provider-pack-authority-")); directories.push(stateDirectory); + const current = vi.fn(() => manifest("a")); + const input = { stateDirectory, binding, reattach: false, current, runnerArtifact }; + return { input, path: join(stateDirectory, "provider-pack-authority.json") }; +} +it("uses the new release for a fresh launch without changing the old receipt until verification", () => { + const { input, path } = fixture(); + resolveRemoteProviderPackAuthority(input).verified(); + input.current.mockReturnValue(manifest("b")); + const fresh = resolveRemoteProviderPackAuthority(input); + expect(fresh.manifest).toEqual(manifest("b")); + expect(JSON.parse(readFileSync(path, "utf8")).manifest).toEqual(manifest("a")); + fresh.verified(); + expect(JSON.parse(readFileSync(path, "utf8")).manifest).toEqual(manifest("b")); + expect(statSync(path).mode & 0o777).toBe(0o600); +}); +it("keeps historical sessions without a receipt at the current release integrity gate", () => { + const { input } = fixture(); + const recovered = resolveRemoteProviderPackAuthority({ ...input, reattach: true }); + expect(recovered.manifest).toEqual(manifest("a")); + expect(input.current).toHaveBeenCalledOnce(); +}); +it.each(Object.keys(binding) as (keyof typeof binding)[])("rejects a saved authority for a different %s", field => { + const { input } = fixture(); + resolveRemoteProviderPackAuthority(input).verified(); + expect(() => resolveRemoteProviderPackAuthority({ ...input, reattach: true, + binding: { ...binding, [field]: "other" } })).toThrow("does not match this execution"); + expect(input.current).toHaveBeenCalledOnce(); +}); +it.each(["digest", "schema", "symlink", "oversized", "invalid_json"])("fails closed on %s instead of trusting remote or current bytes", kind => { + const { input, path } = fixture(); + resolveRemoteProviderPackAuthority(input).verified(); + const saved = JSON.parse(readFileSync(path, "utf8")); + if (kind === "digest") saved.manifest.payload.runnerSourceRevision = "c".repeat(40); + if (kind === "schema") saved.schema = "unknown"; + writeFileSync(path, JSON.stringify(saved)); + if (kind === "invalid_json") writeFileSync(path, "{"); + if (kind === "oversized") writeFileSync(path, " ".repeat(512 * 1024 + 1)); + if (kind === "symlink") { const copy = path + ".copy"; writeFileSync(copy, JSON.stringify(saved)); rmSync(path); symlinkSync(copy, path); } + expect(() => resolveRemoteProviderPackAuthority({ ...input, reattach: true })).toThrow("saved provider pack authority"); + expect(input.current).toHaveBeenCalledOnce(); +}); + +it("uses current authority for a replacement lease instead of restoring the prior pack", () => { + const { input, path } = fixture(); + resolveRemoteProviderPackAuthority(input).verified(); + const currentRunner = { version: "0.0.1", digest: "sha256:" + "d".repeat(64) }; + const replacement = resolveRemoteProviderPackAuthority({ ...input, binding: { ...binding, environmentLeaseId: "replacement" }, + current: () => manifest("b"), runnerArtifact: () => currentRunner }); + expect(replacement.manifest).toEqual(manifest("b")); + expect(replacement.runnerArtifact).toEqual(currentRunner); + replacement.verified(); + expect(JSON.parse(readFileSync(path, "utf8")).binding.environmentLeaseId).toBe("replacement"); +}); +it("retains the authenticated daemon identity across controller daemon replacement", () => { + const { input } = fixture(); + resolveRemoteProviderPackAuthority(input).verified(); + const changedRunner = vi.fn(() => ({ version: "new", digest: "sha256:" + "d".repeat(64) })); + const recovered = resolveRemoteProviderPackAuthority({ ...input, reattach: true, runnerArtifact: changedRunner }); + expect(recovered.runnerArtifact).toEqual(runnerArtifact()); + expect(changedRunner).not.toHaveBeenCalled(); +}); +it.each([{}, { version: "0.0.0", digest: "not-a-sha256" }])("rejects an invalid saved daemon identity: %j", runnerArtifact => { + const { input, path } = fixture(); + resolveRemoteProviderPackAuthority(input).verified(); + const saved = JSON.parse(readFileSync(path, "utf8")); + writeFileSync(path, JSON.stringify({ ...saved, runnerArtifact })); + expect(() => resolveRemoteProviderPackAuthority({ ...input, reattach: true })).toThrow("saved provider pack authority"); +}); + +it("keeps admitted session ownership with the caller if receipt storage or its warning fails", async () => { + const { input, path } = fixture(); + mkdirSync(path); + const authority = resolveRemoteProviderPackAuthority(input); + const warning = vi.fn(() => { throw new Error("log unavailable"); }); + await expect(recordAdmittedRemoteProviderPack(authority, warning)).resolves.toBe(false); + expect(warning).toHaveBeenCalledWith(expect.stringContaining("could not save remote release authority")); + expect(() => resolveRemoteProviderPackAuthority({ ...input, reattach: true })).toThrow("saved provider pack authority"); +}); +it("retains the original projectless lease across warm run placeholders but rejects a different real workspace", () => { + const { input } = fixture(); + const first = { ...binding, workspaceId: providerPackWorkspaceId("run-1", "run-1", "original-lease") }; + resolveRemoteProviderPackAuthority({ ...input, binding: first }).verified(); + const next = { ...binding, workspaceId: providerPackWorkspaceId("run-2", "run-2", "original-lease") }; + expect(resolveRemoteProviderPackAuthority({ ...input, binding: next, reattach: true }).manifest).toEqual(manifest("a")); + const changed = { ...binding, workspaceId: providerPackWorkspaceId("project-workspace", "run-2", "original-lease") }; + expect(() => resolveRemoteProviderPackAuthority({ ...input, binding: changed, reattach: true })).toThrow("does not match this execution"); +}); diff --git a/server/src/services/native-runtime/remote-provider-pack-authority.ts b/server/src/services/native-runtime/remote-provider-pack-authority.ts new file mode 100644 index 00000000000..5516ad6d959 --- /dev/null +++ b/server/src/services/native-runtime/remote-provider-pack-authority.ts @@ -0,0 +1,107 @@ +import { createHash, randomUUID } from "node:crypto"; +import { closeSync, constants, fstatSync, lstatSync, openSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { redactSensitiveText } from "../../redaction.js"; +import { canonicalProviderPackJson, type ProviderPackIdentity } from "./remote-provider-pack-verification.js"; + +export type ProviderPackBinding = { + companyId: string; + agentId: string; + workspaceId: string; + sessionId: string; + runnerInstanceId: string; + environmentLeaseId: string; + remoteCwd: string; + providerDigest: string; +}; +export type RunnerArtifactIdentity = { version: string; digest: string }; + +const schema = "paperclip.remote-provider-pack-authority.v1"; +const filename = "provider-pack-authority.json"; +const maximumBytes = 512 * 1024; + +function assertManifest(manifest: ProviderPackIdentity): void { + if (manifest?.schema !== "paperclip-runner/remote-provider-pack/v1" || !manifest.payload + || manifest.digest !== `sha256:${createHash("sha256").update(canonicalProviderPackJson(manifest.payload)).digest("hex")}`) { + throw new Error("runner_remote_provider_artifact_incompatible: saved provider pack authority is invalid"); + } +} + +export function resolveRemoteProviderPackAuthority(input: { + stateDirectory: string; + binding: ProviderPackBinding; + reattach: boolean; + current: () => T; + runnerArtifact: () => RunnerArtifactIdentity; +}): { manifest: T; runnerArtifact: RunnerArtifactIdentity; verified: () => void } { + const root = lstatSync(input.stateDirectory); + if (!root.isDirectory() || root.isSymbolicLink()) { + throw new Error("runner_remote_provider_artifact_incompatible: provider pack authority directory is unsafe"); + } + const path = join(input.stateDirectory, filename); + let manifest: T | undefined; + let runnerArtifact: RunnerArtifactIdentity | undefined; + if (input.reattach) { + let fd: number | undefined; + try { + fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW); + const stat = fstatSync(fd); + if (!stat.isFile() || stat.size > maximumBytes) throw new Error("invalid authority file"); + const saved = JSON.parse(readFileSync(fd, "utf8")); + if (saved.schema !== schema || canonicalProviderPackJson(saved.binding) !== canonicalProviderPackJson(input.binding)) { + throw new Error("authority binding mismatch"); + } + assertManifest(saved.manifest); + if (typeof saved.runnerArtifact?.version !== "string" || !saved.runnerArtifact.version + || !/^sha256:[a-f0-9]{64}$/.test(saved.runnerArtifact.digest)) throw new Error("invalid runner artifact identity"); + manifest = saved.manifest as T; + runnerArtifact = saved.runnerArtifact; + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ENOENT") { + throw new Error("runner_remote_provider_artifact_incompatible: saved provider pack authority is invalid or does not match this execution", { cause: error }); + } + } finally { + if (fd !== undefined) closeSync(fd); + } + } + manifest ??= input.current(); + assertManifest(manifest); + runnerArtifact ??= input.runnerArtifact(); + const selectedRunner = structuredClone(runnerArtifact); + const selected = structuredClone(manifest); + const receipt = JSON.stringify({ schema, binding: input.binding, manifest: selected, runnerArtifact: selectedRunner }); + if (Buffer.byteLength(receipt) > maximumBytes) throw new Error("runner_remote_provider_artifact_incompatible: provider pack authority exceeds its size limit"); + return { + manifest: selected, + runnerArtifact: selectedRunner, + verified: () => { + const temporary = `${path}.${randomUUID()}.tmp`; + try { + writeFileSync(temporary, receipt, { flag: "wx", mode: 0o600 }); + renameSync(temporary, path); + } finally { + rmSync(temporary, { force: true }); + } + }, + }; +} + +export function providerPackWorkspaceId(workspaceId: string, runId: string, environmentLeaseId: string): string { + return workspaceId === runId ? environmentLeaseId : workspaceId; +} + +export async function recordAdmittedRemoteProviderPack( + authority: { verified: () => void }, + onWarning: (message: string) => void | Promise, +): Promise { + try { + authority.verified(); + return true; + } catch (error) { + const reason = redactSensitiveText(error instanceof Error ? error.message : String(error)).slice(-1_024); + try { + await onWarning(`[paperclip-runner] could not save remote release authority; recovery still requires a verified receipt or current release artifacts: ${reason}\n`); + } catch {} + return false; + } +} diff --git a/server/src/services/native-runtime/remote-provider-pack-verification.ts b/server/src/services/native-runtime/remote-provider-pack-verification.ts new file mode 100644 index 00000000000..3f504a636e9 --- /dev/null +++ b/server/src/services/native-runtime/remote-provider-pack-verification.ts @@ -0,0 +1,85 @@ +import { posix } from "node:path"; +import type { CommandManagedRuntimeRunner } from "@paperclipai/adapter-utils/command-managed-runtime"; +import { runRemoteProviderVerification } from "./remote-provider-pack.js"; + +export function canonicalProviderPackJson(value: unknown): string { + if (Array.isArray(value)) return `[${value.map(canonicalProviderPackJson).join(",")}]`; + if (value && typeof value === "object") return `{${Object.entries(value).sort(([a], [b]) => a.localeCompare(b)) + .map(([key, entry]) => `${JSON.stringify(key)}:${canonicalProviderPackJson(entry)}`).join(",")}}`; + return JSON.stringify(value) ?? "null"; +} + +export type ProviderPackIdentity = { + schema: string; + digest: string; + payload: { + pins: { opencode: string; [key: string]: string | null }; + target: { platform: string; architecture: string }; + runnerSourceRevision: string; + artifacts: { nodeCommand: { path: string; sha256: string }; opencodeCommand: { path: string; sha256: string }; [key: string]: { path: string; sha256: string } }; + }; +}; + +export async function verifyRemoteProviderPack({ runner, cwd, packRoot, manifest }: { + runner: CommandManagedRuntimeRunner; + cwd: string; + packRoot: string; + manifest: ProviderPackIdentity; +}): Promise { + const expected = Buffer.from( + canonicalProviderPackJson(manifest), + "utf8", + ).toString("base64"); + const providerNodeCommand = posix.join( + packRoot, + manifest.payload.artifacts.nodeCommand.path, + ); + const verifyScript = [ + "const fs=require('node:fs')", + "const crypto=require('node:crypto')", + "const path=require('node:path')", + "const root=process.argv[1]", + "const expected=Buffer.from(process.argv[2],'base64').toString('utf8')", + "const actual=fs.readFileSync(path.join(root,'provider-pack.json'),'utf8').trim()", + "const canonical=(v)=>Array.isArray(v)?'['+v.map(canonical).join(',')+']':v&&typeof v==='object'?'{'+Object.keys(v).sort().map(k=>JSON.stringify(k)+':'+canonical(v[k])).join(',')+'}':JSON.stringify(v)", + "const manifest=JSON.parse(actual)", + "if(canonical(manifest)!==expected)throw new Error('manifest mismatch')", + "const hash=(p)=>'sha256:'+crypto.createHash('sha256').update(fs.readFileSync(path.join(root,p))).digest('hex')", + "const tree=(treeRoot)=>{const digest=crypto.createHash('sha256');const visit=(directory,prefix='')=>{for(const entry of fs.readdirSync(directory,{withFileTypes:true}).sort((a,b)=>a.name.localeCompare(b.name))){const relative=prefix?prefix+'/'+entry.name:entry.name;const absolute=path.join(directory,entry.name);if(entry.isDirectory()){digest.update('directory\\0'+relative+'\\n');visit(absolute,relative)}else if(entry.isFile()){digest.update('file\\0'+relative+'\\0'+'sha256:'+crypto.createHash('sha256').update(fs.readFileSync(absolute)).digest('hex')+'\\n')}else if(entry.isSymbolicLink()){digest.update('symlink\\0'+relative+'\\0'+fs.readlinkSync(absolute)+'\\n')}else throw new Error('unsupported dist entry '+relative)}};visit(treeRoot);return 'sha256:'+digest.digest('hex')}", + "for(const name of ['nodeCommand','productionLock','opencodeCommand','opencodeExecutable','opencodeProxy','acpxSidecar','grokLauncher']){const artifact=manifest.payload.artifacts[name];if(hash(artifact.path)!==artifact.sha256)throw new Error(name+' digest mismatch')}", + "if(tree(path.join(root,'dist'))!==manifest.payload.distDigest)throw new Error('dist tree digest mismatch')", + "for(const candidate of Object.values({...manifest.payload.providers,...manifest.payload.candidateProviders})){if(tree(path.join(root,candidate.path))!==candidate.sha256)throw new Error('candidate asset tree digest mismatch')}", + "const version=process.versions.node.split('.').map(Number)", + "const minimum=manifest.payload.pins.nodeMinimum.split('.').map(Number)", + "if(version[0]JSON.parse(fs.readFileSync(path.join(root,'node_modules',...pkg.split('/'),'package.json'),'utf8')).version", + "const expectedPackages={acpx:manifest.payload.pins.acpx,'@agentclientprotocol/claude-agent-acp':manifest.payload.pins.claudeAcp,'@agentclientprotocol/codex-acp':manifest.payload.pins.codexAcp,'opencode-ai':manifest.payload.pins.opencode}", + "for(const [pkg,version] of Object.entries(expectedPackages))if(packageVersion(pkg)!==version)throw new Error(pkg+' version mismatch')", + ].join(";"); + await runRemoteProviderVerification(() => runner.execute({ + command: providerNodeCommand, + args: ["-e", verifyScript, packRoot, expected], + cwd: cwd, + bypassSession: true, + timeoutMs: 30_000, + }), "provider pack verification"); + const opencodeCommand = posix.join( + packRoot, + manifest.payload.artifacts.opencodeCommand.path, + ); + const opencodeVersion = await runRemoteProviderVerification(() => runner.execute({ + command: opencodeCommand, + args: ["--version"], + cwd: cwd, + bypassSession: true, + timeoutMs: 30_000, + }), "OpenCode version verification"); + if ( + opencodeVersion.stdout.trim() !== manifest.payload.pins.opencode + ) { + throw new Error( + "runner_remote_provider_artifact_incompatible: OpenCode version mismatch", + ); + } +} diff --git a/server/src/services/native-runtime/remote-provider-pack.test.ts b/server/src/services/native-runtime/remote-provider-pack.test.ts index a4ec1f60d97..5d5991abca4 100644 --- a/server/src/services/native-runtime/remote-provider-pack.test.ts +++ b/server/src/services/native-runtime/remote-provider-pack.test.ts @@ -25,6 +25,14 @@ describe("remote provider verification", () => { await expect(runRemoteProviderVerification(execute, "pack")).rejects.toThrow("runner_remote_provider_artifact_incompatible: pack failed (exitCode=1"); expect(execute).toHaveBeenCalledOnce(); }); + it("retains a bounded redacted rejection from a combined-output transport", async () => { + const execute = vi.fn().mockResolvedValue({ ...ok, exitCode: 1, + stdout: "Error: manifest mismatch\nANTHROPIC_API_KEY=secret-fixture-value", stderr: "" }); + const failure = await runRemoteProviderVerification(execute, "pack").catch(error => error); + expect(failure.message).toContain("manifest mismatch"); + expect(failure.message).not.toContain("secret-fixture-value"); + expect(execute).toHaveBeenCalledOnce(); + }); it("recovers a transport exception and propagates cancellation", async () => { const execute = vi.fn().mockRejectedValueOnce(new Error("connection unavailable")).mockResolvedValueOnce(ok); await expect(runRemoteProviderVerification(execute, "pack")).resolves.toEqual(ok); diff --git a/server/src/services/native-runtime/remote-provider-pack.ts b/server/src/services/native-runtime/remote-provider-pack.ts index b7045ad42d7..f6621e1e1ea 100644 --- a/server/src/services/native-runtime/remote-provider-pack.ts +++ b/server/src/services/native-runtime/remote-provider-pack.ts @@ -1,3 +1,4 @@ +import { redactSensitiveText } from "../../redaction.js"; import type { NativeRunTrace } from "./native-run-trace.js"; import type { NativeExecutionInput } from "../../vendor/paperclip-runner/index.js"; @@ -37,10 +38,10 @@ export async function runRemoteProviderVerification( result = await execute(); } catch (error) { if (error instanceof Error && error.name === "AbortError") throw error; - diagnostic = error instanceof Error ? error.message : String(error); + diagnostic = redactSensitiveText(error instanceof Error ? error.message : String(error)).slice(-1_024); continue; } - diagnostic = `exitCode=${result.exitCode}; timedOut=${result.timedOut}; signal=${result.signal ?? "none"}; ${result.stderr.trim().slice(-1_024)}`; + diagnostic = `exitCode=${result.exitCode}; timedOut=${result.timedOut}; signal=${result.signal ?? "none"}; ${redactSensitiveText([result.stderr, result.stdout].filter(Boolean).join("\n")).trim().slice(-1_024)}`; if (result.timedOut || result.exitCode === null || result.signal) continue; if (result.exitCode !== 0) { throw new Error(`runner_remote_provider_artifact_incompatible: ${label} failed (${diagnostic})`); From cb47dbb2dac98bd3527c4eaaabca0b0119e2d9f2 Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Sat, 24 Oct 2026 16:49:21 -0700 Subject: [PATCH 025/110] fix: resolve git credentials with the issue's identity in background jobs (#17515) ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Git cache expiration, isolated source re-home, nested clone migration and workspace reopen fetch from the workspace's remotes to prove history is on the remote or to rebuild workspaces > - They built git credentials from the issue id alone, but the managed GitHub identity is selected from the run's responsible user and agent > - So the credential never resolved, they fell back to anonymous access, and private repositories were unreadable > - This pull request resolves credentials with the issue's responsible user and assigned agent, the same identity agent runs use > - The benefit is that workspaces with private repositories can expire, re-home, migrate and reopen like public ones ## Linked Issues or Issue Description Refs #17464, #17407, #17369. Bug report described in-PR (bug report template). **What happened?** On one instance, 18 long-closed workspaces in one project were kept on every expiration sweep with `managed_checkout_upstream_unavailable`. Their nested checkout is a private GitHub repository. Expiration called `createGitRemoteAuthProvider(db, companyId, { issueId })`. With that context, `resolveManagedGitHubCredential` returned "No managed GitHub identity is available for this run". `withAnonymousGitFallback` then tried anonymous access, which cannot read the private repository. Called with the issue's `responsibleUserId` and `agentId`, the same lookup returned a credential. **Expected behavior** Background workspace jobs authenticate as the issue's identity, as agent runs do, and can verify private repositories. **Steps to reproduce** 1. Configure a project with a private GitHub repository and a managed GitHub identity tied to the issue's responsible user. 2. Close an issue whose workspace includes that repository and let git cache expiration inspect it. 3. It is kept with `managed_checkout_upstream_unavailable`. **Paperclip version or commit:** `master` at fe85fd7ac4. **Deployment mode:** any with managed GitHub identities. **Agent adapter(s) involved:** not adapter-specific (core). ## What Changed - `createIssueGitRemoteAuthProvider(db, companyId, issueId)` in `server/src/services/git-credentials.ts`: - looks up the issue's `responsibleUserId` and `assigneeAgentId` once, lazily, scoped to the company; - builds `createGitRemoteAuthProvider` with `{ issueId, responsibleUserId, agentId }`; - falls back to the issue-only context when the issue is missing. - Callers switched from the issue-only context: - git cache expiration (`expirationGitAuth`); - isolated source re-home; - nested clone migration; - both credential sites in `reopenClosedIsolatedExecutionWorkspaceForIssue`. - Anonymous fallback for public repositories is unchanged. No code comments were added. ## Verification - `pnpm exec vitest run src/__tests__/git-credentials.test.ts src/__tests__/git-expiration-auth-fallback.test.ts` (in `server/`): 32 passed. New cases: - the helper passes the issue's responsible user and agent to the credential lookup; - it looks the issue up once across calls; - it falls back to the issue-only context when the issue is missing. - **Mutation check:** dropping the identity fields from the context fails two cases. - **Live instance:** for an affected workspace, the managed credential resolved only with the responsible user and agent; with the issue id alone, or with standing delegation, it did not. - `pnpm exec vitest run git-credentials git-expiration-auth-fallback git-workspace-expiration git-restore-point isolated-repository-rehome nested-clone-migration` (in `server/`): 296 passed. - `pnpm run typecheck` (in `server/`): pass. - Not run: server build and boot smoke. ## Risks - **Whose identity is used:** background jobs now use the issue's responsible user's managed GitHub identity, which agent runs on that issue already use. They only read: fetch, ls-remote and clone for verification and restore. - **Unchanged failure behavior:** if the identity is unavailable (for example, the user is no longer a member), the existing anonymous fallback applies, as before. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), 1M context, through Claude Code with tool use (shell, file edits, tests, read-only diagnosis on a live instance). ## 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 - [ ] I will address all Greptile and reviewer comments before requesting merge Co-authored-by: Paperclip --- server/src/__tests__/git-credentials.test.ts | 37 +++++++++++++++++++ server/src/services/execution-workspaces.ts | 8 ++-- server/src/services/git-credentials.ts | 14 +++++++ .../src/services/git-workspace-expiration.ts | 4 +- .../services/isolated-repository-rehome.ts | 4 +- server/src/services/nested-clone-migration.ts | 4 +- 6 files changed, 60 insertions(+), 11 deletions(-) diff --git a/server/src/__tests__/git-credentials.test.ts b/server/src/__tests__/git-credentials.test.ts index c286f832b42..e5aee1eb96f 100644 --- a/server/src/__tests__/git-credentials.test.ts +++ b/server/src/__tests__/git-credentials.test.ts @@ -9,6 +9,7 @@ import { GIT_CREDENTIAL_TOKEN_ENV_KEY, buildGitAuthInvocation, createGitRemoteAuthProvider, + createIssueGitRemoteAuthProvider, describeGitAuthFailure, isGitHubHttpsRemoteUrl, scrubGitCredentialText, @@ -379,3 +380,39 @@ describe("DEFAULT_GITHUB_TOKEN_SECRET_NAMES", () => { ]); }); }); + +describe("createIssueGitRemoteAuthProvider", () => { + const githubUrl = "https://github.com/paperclipai/private-repo.git"; + function issueDb(rows: unknown[]) { + const where = vi.fn(async () => rows); + return { db: { select: vi.fn(() => ({ from: () => ({ where }) })) } as unknown as Db, where }; + } + + it("resolves credentials with the issue's responsible user and assigned agent", async () => { + const { db } = issueDb([{ responsibleUserId: "user-1", assigneeAgentId: "agent-1" }]); + const inner = vi.fn(async () => ({ env: {}, configArgs: [], source: "managed_connection" })); + const create = vi.fn(() => inner) as unknown as typeof createGitRemoteAuthProvider; + const provider = createIssueGitRemoteAuthProvider(db, "company-1", "issue-1", create); + await expect(provider(githubUrl)).resolves.toMatchObject({ source: "managed_connection" }); + expect(create).toHaveBeenCalledWith(db, "company-1", { issueId: "issue-1", responsibleUserId: "user-1", agentId: "agent-1" }); + expect(inner).toHaveBeenCalledWith(githubUrl); + }); + + it("looks the issue up once across calls", async () => { + const { db } = issueDb([{ responsibleUserId: "user-1", assigneeAgentId: null }]); + const inner = vi.fn(async () => null); + const create = vi.fn(() => inner) as unknown as typeof createGitRemoteAuthProvider; + const provider = createIssueGitRemoteAuthProvider(db, "company-1", "issue-1", create); + await provider(githubUrl); await provider(githubUrl); + expect(db.select).toHaveBeenCalledTimes(1); + expect(create).toHaveBeenCalledTimes(1); + expect(inner).toHaveBeenCalledTimes(2); + }); + + it("falls back to the issue-only context when the issue is missing", async () => { + const { db } = issueDb([]); + const create = vi.fn(() => vi.fn(async () => null)) as unknown as typeof createGitRemoteAuthProvider; + await createIssueGitRemoteAuthProvider(db, "company-1", "issue-1", create)(githubUrl); + expect(create).toHaveBeenCalledWith(db, "company-1", { issueId: "issue-1", responsibleUserId: null, agentId: null }); + }); +}); diff --git a/server/src/services/execution-workspaces.ts b/server/src/services/execution-workspaces.ts index 63800f66b9e..4d83e2c8a9c 100644 --- a/server/src/services/execution-workspaces.ts +++ b/server/src/services/execution-workspaces.ts @@ -98,7 +98,7 @@ import { type PullRequestMergeDetailsResolver, } from "./github-pull-request-merge.js"; import { visibleIssueCondition } from "./issue-visibility.js"; -import { createGitRemoteAuthProvider } from "./git-credentials.js"; +import { createIssueGitRemoteAuthProvider } from "./git-credentials.js"; import { readProjectWorkspaceRuntimeConfig } from "./project-workspace-runtime-config.js"; import { workspaceGitOperationScheduler } from "./workspace-git-operation-scheduler.js"; import { isRuntimeOwnedGitBranch } from "./execution-workspace-branch-ownership.js"; @@ -4113,7 +4113,7 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic try { recipe = readGitCacheRestoration(snapshot); } catch { return { ok: false, code: "rebuild_failed", message: new GitCacheRestorationFailure().message }; } const freshStart = recipe !== null && isClosedExecutionWorkspaceStatus(snapshot.status) && gitRestorePointExpired(recipe); - const gitAuth = createGitRemoteAuthProvider(db, snapshot.companyId, { issueId: issue.id }); + const gitAuth = createIssueGitRemoteAuthProvider(db, snapshot.companyId, issue.id); const [ { ensurePersistedExecutionWorkspaceAvailable }, { workspaceOperationService }, @@ -4168,9 +4168,7 @@ export function executionWorkspaceService(db: Db, opts: ExecutionWorkspaceServic }); }; }, - resolveGitAuth: createGitRemoteAuthProvider(db, snapshot.companyId, { - issueId: issue.id, - }), + resolveGitAuth: createIssueGitRemoteAuthProvider(db, snapshot.companyId, issue.id), }); resolvedBaseCwd = managedWorkspace.cwd; } catch { diff --git a/server/src/services/git-credentials.ts b/server/src/services/git-credentials.ts index 21899e5cef1..3fce7fc2b50 100644 --- a/server/src/services/git-credentials.ts +++ b/server/src/services/git-credentials.ts @@ -1,6 +1,7 @@ import { companySecrets, heartbeatRuns, + issues, companyMemberships, connectionGrantDelegations, connectionGrants, @@ -207,6 +208,19 @@ type GitCredentialSecretsDeps = { * provider instance so one run performs at most one secret resolution (and writes at most * one audit event) no matter how many git operations it authenticates. */ +export function createIssueGitRemoteAuthProvider(db: Db, companyId: string, issueId: string, + create: typeof createGitRemoteAuthProvider = createGitRemoteAuthProvider): GitRemoteAuthProvider { + let provider: Promise | null = null; + return async (remoteUrl: string) => { + provider ??= db.select({ responsibleUserId: issues.responsibleUserId, assigneeAgentId: issues.assigneeAgentId }).from(issues) + .where(and(eq(issues.id, issueId), eq(issues.companyId, companyId))) + .then(([issue]) => create(db, companyId, { + issueId, responsibleUserId: issue?.responsibleUserId ?? null, agentId: issue?.assigneeAgentId ?? null, + })); + return (await provider)(remoteUrl); + }; +} + export function createGitRemoteAuthProvider( db: Db, companyId: string, diff --git a/server/src/services/git-workspace-expiration.ts b/server/src/services/git-workspace-expiration.ts index 12cb8e52dda..5fdd85c7f96 100644 --- a/server/src/services/git-workspace-expiration.ts +++ b/server/src/services/git-workspace-expiration.ts @@ -6,7 +6,7 @@ import { acquireGitExpirationLocks } from "./git-workspace-expiration-locks.js"; import { and, eq, inArray, ne, sql } from "drizzle-orm"; import { executionWorkspaces, issues, heartbeatRuns, nativeRunFinalizations, environmentLeases, workspaceRuntimeServices, issueRecoveryActions, projectWorkspaces, withDedicatedDbConnection, type Db } from "@paperclipai/db"; -import { createGitRemoteAuthProvider } from "./git-credentials.js"; +import { createIssueGitRemoteAuthProvider } from "./git-credentials.js"; import type { StorageService } from "../storage/types.js"; import { TASK_DIRECTORY_RETENTION_KEY } from "./isolated-task-directory-snapshot.js"; import { currentRestorePointSnapshot, RestorePointSkip, type RestorePointLimits } from "./git-restore-point.js"; @@ -37,7 +37,7 @@ export function withAnonymousGitFallback(provider: GitRemoteAuthProvider): GitRe } function expirationGitAuth(db: Db, workspace: Workspace) { - return withAnonymousGitFallback(createGitRemoteAuthProvider(db, workspace.companyId, { issueId: workspace.sourceIssueId! })); + return withAnonymousGitFallback(createIssueGitRemoteAuthProvider(db, workspace.companyId, workspace.sourceIssueId!)); } const EXPIRATION_KEY = "gitCacheExpiration"; diff --git a/server/src/services/isolated-repository-rehome.ts b/server/src/services/isolated-repository-rehome.ts index c8c02f85578..6314f5edcc7 100644 --- a/server/src/services/isolated-repository-rehome.ts +++ b/server/src/services/isolated-repository-rehome.ts @@ -23,7 +23,7 @@ import { withExecutionWorkspaceLifecycleLock } from "./execution-workspace-lifec import { loadGitRestorePoint } from "./git-restore-point-storage.js"; import { nestedWorktreeBranchPrefix, readLinkedNestedCheckout, repairMovedNestedRepositoryWorktree, withNestedRepositoryBaseLock } from "./nested-repository-worktrees.js"; import { getStorageService } from "../storage/index.js"; -import { createGitRemoteAuthProvider } from "./git-credentials.js"; +import { createIssueGitRemoteAuthProvider } from "./git-credentials.js"; import { resolvePaperclipInstanceRoot } from "../home-paths.js"; const execFile = promisify(execFileCallback); @@ -598,7 +598,7 @@ async function worktreeOfClone(worktree: string, cloneReal: string, signal?: Abo } function upstreamCheck(db: Db, companyId: string, issueId: string, clone: string, repoUrl: string, signal?: AbortSignal): MissingUpstream { - const auth = withAnonymousGitFallback(createGitRemoteAuthProvider(db, companyId, { issueId })); + const auth = withAnonymousGitFallback(createIssueGitRemoteAuthProvider(db, companyId, issueId)); return (commits, covered) => hasCommitsMissingUpstream(clone, commits, repoUrl, auth, signal, covered); } diff --git a/server/src/services/nested-clone-migration.ts b/server/src/services/nested-clone-migration.ts index eb0e3a87eda..09b4f6663a9 100644 --- a/server/src/services/nested-clone-migration.ts +++ b/server/src/services/nested-clone-migration.ts @@ -13,7 +13,7 @@ import { GIT_CACHE_RESTORATION_KEY, readGitCacheRestoration, type GitCacheRestor import { readManagedCheckoutContents, selectRestoredProjectRepositories } from "./git-workspace-contents.js"; import { applyRestorePoint, captureRestorePoint, currentRestorePointSnapshot, importRestorePoint } from "./git-restore-point.js"; import { managedProjectCheckoutName } from "./managed-project-checkout-name.js"; -import { createGitRemoteAuthProvider, type GitRemoteAuthProvider } from "./git-credentials.js"; +import { createIssueGitRemoteAuthProvider, type GitRemoteAuthProvider } from "./git-credentials.js"; import { isNestedWorktreeBranchName, isVerifiedNestedRepositoryBase, moveNestedRepositoryWorktree, nestedRepositoryBaseCandidates, nestedWorktreeBranchPrefix, readLinkedNestedCheckout, removeStaleNestedRegistrations, trackNestedWorktreeUpstream, withNestedRepositoryBaseLock } from "./nested-repository-worktrees.js"; import { assertSafeBaseConfig, assertTransferredItems, historyKey, linkedCheckoutBases, moveTransferItems, presentCommits, returnTransferItems, @@ -442,7 +442,7 @@ export async function migrateNestedRepositoryClone(db: Db, snapshot: Workspace, const base = source.base; await assertSafeBaseConfig(base, signal); await fetchBase(base, source.repoUrl, options.resolveGitAuth - ?? withAnonymousGitFallback(createGitRemoteAuthProvider(db, row!.companyId, { issueId: row!.sourceIssueId! })), signal); + ?? withAnonymousGitFallback(createIssueGitRemoteAuthProvider(db, row!.companyId, row!.sourceIssueId!)), signal); await assertSafeBaseConfig(base, signal); await assertNoBranchOnlyReflogHistory(inspected, signal); const planned = await planRefs(inspected, base, prefix, signal); From 71f06d84dc41c6e35d368147540588fd8fd8073d Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Sat, 24 Oct 2026 17:34:41 -0700 Subject: [PATCH 026/110] fix(db): keep bounded response captures attributable (#17522) Keep more caller groups in one bounded database response capture and verify public caller paths in the production bundle. All local checks and CI passed; Greptile scored the exact head 5/5 with no unresolved comments. Co-Authored-By: Paperclip --- doc/DATABASE.md | 13 +++++++++-- packages/db/src/response-capture.test.ts | 7 +++--- packages/db/src/response-capture.ts | 2 +- server/scripts/bundle-runtime.test.mjs | 29 +++++++++++++++++++++++- 4 files changed, 44 insertions(+), 7 deletions(-) diff --git a/doc/DATABASE.md b/doc/DATABASE.md index bc1292bbe94..e6211773d87 100644 --- a/doc/DATABASE.md +++ b/doc/DATABASE.md @@ -332,12 +332,21 @@ The diagnostic measures awaited Postgres.js `unsafe` responses before Drizzle column decoding. It retains the Drizzle builder caller for normal, prepared, transaction, and dedicated-pool execution. It issues no queries. It logs the public server caller locations, static schema table, operation, -query/row counts, and response value sizes. It emits at most 128 aggregate +query/row counts, and response value sizes. It emits at most 512 aggregate groups and a summary at the deadline. It never logs SQL, parameters, result values, connection strings, or query errors. In-flight queries continue normally. +For a bundled server, keep the linked source maps and enable Node's +`--enable-source-maps` option so the diagnostic can resolve public caller +locations. Restore the prior Node options after capture. Sizes still count when +caller locations are unavailable. + Look for `paperclip.db_response_capture.entry.v1` and -`paperclip.db_response_capture.summary.v1` in the process logs. Tagged raw-driver calls, streams, unawaited raw-driver +`paperclip.db_response_capture.summary.v1` in the process logs. A log provider +can store `event` as a structured field instead of message text. Filter by that +field or read the bounded window from the exact deployment. Check the summary +and group totals, including the unattributed overflow group. +Tagged raw-driver calls, streams, unawaited raw-driver dispatch, and protocol overhead are not measured. Relational queries use a driver-level caller fallback. Queries still in flight at the deadline are reported separately. Sizes describe driver values before column decoding, not billed network bytes. Complex parsed diff --git a/packages/db/src/response-capture.test.ts b/packages/db/src/response-capture.test.ts index 65f58d10883..4b87c7924a4 100644 --- a/packages/db/src/response-capture.test.ts +++ b/packages/db/src/response-capture.test.ts @@ -107,11 +107,12 @@ describe("bounded database response capture", () => { }); it("bounds cardinality without dropping response-byte totals", () => { const f = fixture(); - for (let i = 0; i < 200; i += 1) f.capture.execute(() => [i], { ...metadata, callers: [`services/f${i}.ts:1:1`] }); + for (let i = 0; i < 600; i += 1) f.capture.execute(() => [i], { ...metadata, callers: [`services/f${i}.ts:1:1`] }); f.capture.flush(); const summary = f.events.at(-1)!; - expect(summary).toMatchObject({ startedQueries: 200, completedQueries: 200, groups: 128, overflowCalls: 73 }); - expect(summary.responseValueBytes).toBe(Array.from({ length: 200 }, (_, i) => Buffer.byteLength(JSON.stringify([i]))).reduce((a, b) => a + b, 0)); + expect(summary).toMatchObject({ startedQueries: 600, completedQueries: 600, groups: 512, overflowCalls: 89 }); + expect(f.events).toHaveLength(513); + expect(summary.responseValueBytes).toBe(Array.from({ length: 600 }, (_, i) => Buffer.byteLength(JSON.stringify([i]))).reduce((a, b) => a + b, 0)); }); it("does not execute builders or prepared statements until requested", async () => { const f = fixture(), rows = [{ id: 1 }], execute = vi.fn(async () => rows); diff --git a/packages/db/src/response-capture.ts b/packages/db/src/response-capture.ts index 8f738043f4d..f8e6da8e87a 100644 --- a/packages/db/src/response-capture.ts +++ b/packages/db/src/response-capture.ts @@ -99,7 +99,7 @@ export function createDatabaseResponseCapture( completed += 1; try { let key = JSON.stringify(metadata); - if (!entries.has(key) && entries.size >= 127) { + if (!entries.has(key) && entries.size >= 511) { overflowCalls += 1; metadata = { operation: "other", table: "other", callers: [] }; key = "overflow"; diff --git a/server/scripts/bundle-runtime.test.mjs b/server/scripts/bundle-runtime.test.mjs index 14b0d46c681..6e9375f61c4 100644 --- a/server/scripts/bundle-runtime.test.mjs +++ b/server/scripts/bundle-runtime.test.mjs @@ -2,7 +2,7 @@ import { execFile } from "node:child_process"; import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; -import { pathToFileURL } from "node:url"; +import { fileURLToPath, pathToFileURL } from "node:url"; import { promisify } from "node:util"; import { afterEach, beforeEach, describe, expect, it } from "vitest"; @@ -85,6 +85,33 @@ describe("bundleRuntime", () => { expect(output.entryDir).toBe(path.join(root, "server", "dist")); }); + it("keeps database caller locations public in a source-mapped runtime bundle", async () => { + const captureModule = fileURLToPath(new URL("../../packages/db/src/response-capture.ts", import.meta.url)); + write(path.join(root, "server", "dist", "services", "response-caller.js"), [ + `import { publicDatabaseCallers } from ${JSON.stringify(captureModule)};`, + 'export function callers() { return publicDatabaseCallers(new Error("private-capture-message").stack); }', + ].join("\n")); + write(path.join(root, "server", "dist", "index.js"), [ + 'import { callers } from "./services/response-caller.js";', + 'console.log(JSON.stringify({ callers: callers() }));', + ].join("\n")); + const summary = await bundleRuntime({ entry: path.join(root, "server", "dist", "index.js"), outdir: path.join(root, "server", "dist-runtime") }); + const env = { ...process.env }; + delete env.NODE_OPTIONS; + delete env.PAPERCLIP_DB_RESPONSE_CAPTURE_WINDOW; + const options = { cwd: path.join(root, "server"), env, timeout: 30_000 }; + const plain = JSON.parse((await execFileAsync(process.execPath, [summary.outfile], options)).stdout); + const mapped = JSON.parse((await execFileAsync(process.execPath, ["--enable-source-maps", summary.outfile], options)).stdout); + expect(plain.callers).toEqual([]); + expect(mapped.callers).toEqual([expect.stringMatching(/^services\/response-caller\.js:\d+:\d+$/)]); + for (const result of [plain, mapped]) { + const output = JSON.stringify(result); + expect(output).not.toContain(root); + expect(output).not.toContain(captureModule); + expect(output).not.toContain("private-capture-message"); + } + }); + it("emits a server module that loads without starting the server", async () => { const outdir = path.join(root, "server", "dist-runtime"); const summary = await bundleRuntime({ entry: path.join(root, "server", "dist", "index.js"), outdir }); From 64a8b927c1f199c612bcd36dccb6190e6e250eb3 Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Sat, 24 Oct 2026 17:48:47 -0700 Subject: [PATCH 027/110] fix(native): narrow committed finalization and cleanup reads (#17525) Select fresh metadata for committed finalization and cleanup. Preserve full saved evidence for new finalization, cancelled workspace retention, and legacy Stop. PostgreSQL byte-budget and unchanged-row regressions pass, full CI is green, and Greptile scored the exact head 5/5. Co-Authored-By: Paperclip --- doc/DATABASE.md | 9 +++ server/src/services/heartbeat.ts | 4 ++ .../__tests__/run-control-fixtures.ts | 2 + .../src/services/heartbeat/recovery.test.ts | 2 + server/src/services/heartbeat/recovery.ts | 4 +- .../services/heartbeat/run-control.test.ts | 6 +- server/src/services/heartbeat/run-control.ts | 22 ++++--- .../src/services/heartbeat/run-state.test.ts | 57 +++++++++++++++++++ server/src/services/heartbeat/run-state.ts | 24 ++++++++ .../__tests__/helpers/committed-replay.ts | 34 +++++++++++ .../native-run-finalizer-telemetry.test.ts | 29 ++++++---- .../native-runtime/native-run-finalizer.ts | 55 ++++++++++++------ 12 files changed, 208 insertions(+), 40 deletions(-) create mode 100644 server/src/services/native-runtime/__tests__/helpers/committed-replay.ts diff --git a/doc/DATABASE.md b/doc/DATABASE.md index e6211773d87..717ec1ca0ed 100644 --- a/doc/DATABASE.md +++ b/doc/DATABASE.md @@ -68,6 +68,15 @@ Runner profiles retain the adapter type and complete native execution input and workspace-sync receipts. Full result evidence stays available to the existing retry and workspace checks. Stored context, profiles, and output are unchanged. +Committed native finalization reads run identity and ownership state before it +claims the coordinator. It loads complete saved input only when finalization +still needs to process an accepted result. Review presentation retains the full +result. Muse settlement reads its exact provider binding. Cleanup reads fresh +status and ownership metadata; cancelled native workspace retention and legacy +Stop settlement still load complete run evidence. Workspace settlement reads the +saved sync descriptor, export retry, and first-heartbeat flag. These projections +leave stored prompts, logs, results, and recovery state unchanged. + Conversation ownership checks select process identity and full recovery result evidence without execution prompts or profiles. Committed native reply repair selects its persisted result and identity bindings plus typed presentation flags. diff --git a/server/src/services/heartbeat.ts b/server/src/services/heartbeat.ts index 543d96a97f8..9a18721aaa7 100644 --- a/server/src/services/heartbeat.ts +++ b/server/src/services/heartbeat.ts @@ -811,6 +811,8 @@ export function heartbeatService( getAgent, resolveSessionBeforeForWakeup, getRun, + getRunCleanupState, + getRunWorkspaceSettlement, getRunStatus, ensureRuntimeState, getTaskSession, @@ -1014,6 +1016,7 @@ export function heartbeatService( environmentRuntime, scheduleNativeSessionResumeDispatch, getRun, + getRunWorkspaceSettlement, executeRun, activeRunExecutionPromises, cancelHeartbeatNativeRun, @@ -1386,6 +1389,7 @@ export function heartbeatService( const runControl = createHeartbeatRunControl(db, { getRun, + getRunCleanupState, options, envOrchestrator, activeRunExecutions, diff --git a/server/src/services/heartbeat/__tests__/run-control-fixtures.ts b/server/src/services/heartbeat/__tests__/run-control-fixtures.ts index 42f6bea5150..2adce9077c1 100644 --- a/server/src/services/heartbeat/__tests__/run-control-fixtures.ts +++ b/server/src/services/heartbeat/__tests__/run-control-fixtures.ts @@ -13,6 +13,7 @@ import type { HeartbeatRunControlDependencies } from "../run-control.js"; type TestCallbacks = HeartbeatRunControlDependencies & ReturnType & { getRun: Mock; getAgent: Mock; + getRunCleanupState: Mock; setRunStatusFromLive: Mock; getSchedulingSuppression: Mock; options: { closeWarmNativeSessionsForRun: Mock> }; @@ -43,6 +44,7 @@ export function callbacks(db: Db): TestCallbacks { ...state, ...lifecycle, getRun: vi.fn(state.getRun), + getRunCleanupState: vi.fn(state.getRunCleanupState), getAgent: vi.fn(state.getAgent), setRunStatusFromLive: vi.fn(lifecycle.setRunStatusFromLive), setRunStatus: vi.fn(lifecycle.setRunStatus), diff --git a/server/src/services/heartbeat/recovery.test.ts b/server/src/services/heartbeat/recovery.test.ts index 8faa8c7e865..34139757468 100644 --- a/server/src/services/heartbeat/recovery.test.ts +++ b/server/src/services/heartbeat/recovery.test.ts @@ -7,6 +7,7 @@ import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } fro import { classifyEnvironmentCapabilities, environmentRuntimeService } from "../environment-runtime.js"; import { environmentService } from "../environments.js"; import { createHeartbeatRecovery, type HeartbeatRecoveryDependencies } from "./recovery.js"; +import { createHeartbeatRunState } from "./run-state.js"; import type { HotRestartIntent } from "../hot-restart.js"; import type { NativeRestartRecoveryClaim, NativeRestartRecoveryDisposition } from "../native-runtime/index.js"; import { NATIVE_OWNERSHIP_UNVERIFIED_ERROR_CODE } from "../native-runtime/native-runner-ownership.js"; @@ -48,6 +49,7 @@ function callbacks(db: Db) { return { enterShutdown: vi.fn(), getRun: vi.fn(async () => null), + getRunWorkspaceSettlement: vi.fn(createHeartbeatRunState(db).getRunWorkspaceSettlement), getAgent: vi.fn(async () => null), appendRunEvent: vi.fn(async () => undefined), setRunStatusIfRunning: vi.fn(async () => ({ updated: false, run: null })), diff --git a/server/src/services/heartbeat/recovery.ts b/server/src/services/heartbeat/recovery.ts index 73c586bdff3..a5197485881 100644 --- a/server/src/services/heartbeat/recovery.ts +++ b/server/src/services/heartbeat/recovery.ts @@ -101,6 +101,7 @@ export interface HeartbeatRecoveryDependencies extends Pick["getRun"]>[1]) => Promise< Awaited["getRun"]>> | null >; + getRunWorkspaceSettlement: ReturnType["getRunWorkspaceSettlement"]; environmentRuntime: ReturnType; pluginWorkerManager?: WorkspaceWorkers; environmentsSvc: Pick, "getById" | "getLeaseById" | "releaseLease">; @@ -360,6 +361,7 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD environmentRuntime, scheduleNativeSessionResumeDispatch, getRun, + getRunWorkspaceSettlement, executeRun, activeRunExecutionPromises, cancelHeartbeatNativeRun, @@ -1858,7 +1860,7 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD agentId: string; succeeded: boolean; }) { - const settledRun = await getRun(input.runId); + const settledRun = await getRunWorkspaceSettlement(input.runId); const workspaceSyncReference = readNativeWorkspaceSyncReference( parseObject(settledRun?.runnerProfileJson).nativeWorkspaceSync, ); diff --git a/server/src/services/heartbeat/run-control.test.ts b/server/src/services/heartbeat/run-control.test.ts index 7f3991eaa0c..d0d08896538 100644 --- a/server/src/services/heartbeat/run-control.test.ts +++ b/server/src/services/heartbeat/run-control.test.ts @@ -98,7 +98,7 @@ describe("heartbeat run-control module boundary", () => { it("retains leases while native execution ownership is unverified", async () => { const database = guardedDatabase(); const deps = callbacks(database.db); - deps.getRun.mockResolvedValue({ runtimeMode: "native", status: "running", nativePhase: "terminal_failure", errorCode: "native_execution_ownership_unverified" } as Run); + deps.getRunCleanupState.mockResolvedValue({ runtimeMode: "native", status: "running", nativePhase: "terminal_failure", errorCode: "native_execution_ownership_unverified" } as Run); await createHeartbeatRunControl(database.db, deps).releaseEnvironmentLeasesForRun({ runId: "held", companyId: "company", agentId: "agent", status: "failed", providerResourceDisposition: "destroy" }); expect(database.access).not.toHaveBeenCalled(); expect(deps.options.closeWarmNativeSessionsForRun).not.toHaveBeenCalled(); @@ -108,7 +108,7 @@ describe("heartbeat run-control module boundary", () => { it("uses the persisted terminal outcome when choosing warm resource retention", async () => { const database = guardedDatabase(); const deps = callbacks(database.db); - deps.getRun.mockResolvedValue({ status: "failed", runtimeMode: "legacy" } as Run); + deps.getRunCleanupState.mockResolvedValue({ status: "failed", runtimeMode: "legacy" } as Run); await createHeartbeatRunControl(database.db, deps).releaseEnvironmentLeasesForRun({ runId: "failed", companyId: "company", agentId: "agent", status: "succeeded", providerResourceDisposition: "keep_running" }); expect(deps.envOrchestrator.releaseForRun).toHaveBeenCalledWith(expect.objectContaining({ heartbeatRunId: "failed", status: "failed", providerResourceDisposition: "stop_and_retain" })); expect(database.access).not.toHaveBeenCalled(); @@ -117,7 +117,7 @@ describe("heartbeat run-control module boundary", () => { it("defers destruction when a warm session remains busy", async () => { const database = guardedDatabase(); const deps = callbacks(database.db); - deps.getRun.mockResolvedValue({ status: "failed", runtimeMode: "legacy" } as Run); + deps.getRunCleanupState.mockResolvedValue({ status: "failed", runtimeMode: "legacy" } as Run); deps.options.closeWarmNativeSessionsForRun.mockResolvedValue({ closed: 0, busy: 1, failed: 0 }); await createHeartbeatRunControl(database.db, deps).releaseEnvironmentLeasesForRun({ runId: "busy", companyId: "company", agentId: "agent", status: "failed", providerResourceDisposition: "destroy" }); expect(deps.options.closeWarmNativeSessionsForRun).toHaveBeenCalledWith({ runId: "busy", reason: "terminal heartbeat run destroyed its environment lease" }); diff --git a/server/src/services/heartbeat/run-control.ts b/server/src/services/heartbeat/run-control.ts index 7f80f99321a..d7086c52508 100644 --- a/server/src/services/heartbeat/run-control.ts +++ b/server/src/services/heartbeat/run-control.ts @@ -164,7 +164,7 @@ async function withBudgetStopDelivery(db: Db, work: () => Promise): Promis /** Cancellation shares executor ownership and delegates lifecycle and admission effects. */ export interface HeartbeatRunControlDependencies extends Pick, - "getRun" | "getAgent">, + "getRun" | "getAgent" | "getRunCleanupState">, Pick, "mergeRunStopMetadataForAgent" | "setRunStatusFromLive" | "setRunStatus" | "setWakeupStatus" | "appendRunEvent">, Pick { @@ -324,6 +324,7 @@ function runCancellationFenceSql(input: { export function createHeartbeatRunControl(db: Db, dependencies: HeartbeatRunControlDependencies) { const { getRun, + getRunCleanupState, options, envOrchestrator, activeRunExecutions, @@ -359,7 +360,11 @@ export function createHeartbeatRunControl(db: Db, dependencies: HeartbeatRunCont sandboxResource: "keep_running" | "stop_and_reuse" | "destroy_after_turn"; }; }) { - const leaseOwnerRun = await getRun(input.runId); + let leaseOwnerRun = await getRunCleanupState(input.runId); + if (leaseOwnerRun && isNativeRunnerOwnershipHeld(leaseOwnerRun)) return; + const cancelledRun = leaseOwnerRun?.runtimeMode === "native" && leaseOwnerRun.status === "cancelled" + ? await getRun(input.runId) : null; + if (cancelledRun) leaseOwnerRun = cancelledRun; if (leaseOwnerRun && isNativeRunnerOwnershipHeld(leaseOwnerRun)) return; // Recovery can finish workspace copy-back outside the executor's finally. // Successful copy-back does not earn warm retention for a failed turn. @@ -368,11 +373,11 @@ export function createHeartbeatRunControl(db: Db, dependencies: HeartbeatRunCont input.providerResourceDisposition, status, ); - if (leaseOwnerRun?.runtimeMode === "native" && status === "cancelled" - && readNativeWorkspaceSyncReference(leaseOwnerRun.runnerProfileJson?.nativeWorkspaceSync)?.state === "prepared" - && !nativeRunHasNoWorkspaceAccess(leaseOwnerRun)) { + if (cancelledRun?.runtimeMode === "native" && status === "cancelled" + && readNativeWorkspaceSyncReference(cancelledRun.runnerProfileJson?.nativeWorkspaceSync)?.state === "prepared" + && !nativeRunHasNoWorkspaceAccess(cancelledRun)) { try { - const preserved = await preserveNativeFailedWorkspace(db, leaseOwnerRun, { allowPreterminal: true }); + const preserved = await preserveNativeFailedWorkspace(db, cancelledRun, { allowPreterminal: true }); if (!preserved || !hasRequiredWorkspaceRecovery(preserved.resultJson)) return; } catch { // Keep the active source eligible for the bounded retention sweep. @@ -478,13 +483,14 @@ export function createHeartbeatRunControl(db: Db, dependencies: HeartbeatRunCont async function acknowledgeRemoteStop(runId: string, companyId: string) { // The provider receipt arrives after adapter settlement. A remote ACP child // has no host PID, so only this target-aware boundary can acknowledge Stop. - const stopped = await getRun(runId); - if (stopped?.runtimeMode === "native") { + const state = await getRunCleanupState(runId); + if (state?.runtimeMode === "native") { const scopes = await stoppedRemoteCleanupScopes(db, companyId, runId); for (const remoteCleanupScope of scopes ?? []) { completeTerminatedRemoteNativeSessionCleanup({ companyId, runId, remoteCleanupScope }); } } + const stopped = state?.runtimeMode === "legacy" && state.status === "cancelled" ? await getRun(runId) : null; if (stopped?.runtimeMode === "legacy" && stopped.status === "cancelled" && parseObject(stopped.resultJson?.executionCancellation).state === "requested" && await runUsedConversationAdapter(db, stopped) && diff --git a/server/src/services/heartbeat/run-state.test.ts b/server/src/services/heartbeat/run-state.test.ts index 4a729328027..ccc91735df4 100644 --- a/server/src/services/heartbeat/run-state.test.ts +++ b/server/src/services/heartbeat/run-state.test.ts @@ -1,4 +1,5 @@ import { randomBytes, randomUUID } from "node:crypto"; +import { createDatabaseResponseCapture, installDatabaseResponseCapture } from "@paperclipai/db/response-capture"; import type { Db } from "@paperclipai/db"; import { agents, @@ -86,6 +87,9 @@ describe("heartbeat run state module", () => { expect(projectedSql(utf8.columns[0].resultJson)).toContain("pg_column_size"); await asciiState.getRun("evidence", { includeExecutionEvidence: true }); expect(projectedSql(ascii.columns[2].resultJson)).toContain("startupPreparationSettledAt"); + await asciiState.getRunWorkspaceSettlement("settlement"); + expect(projectedSql(ascii.columns[3].error)).toBe("NULL"); + expect(ascii.execute).toHaveBeenCalledTimes(1); const raw = readingDatabase("SQL_ASCII"); await extracted.createHeartbeatRunState(raw.db).getRun("raw", { unsafeFullResultJson: true }); expect(raw.execute).not.toHaveBeenCalled(); @@ -154,6 +158,59 @@ describePostgres("heartbeat run state database wiring", () => { return { companyId, agent, issue, state: extracted.createHeartbeatRunState(db) }; } + it("reads cleanup and workspace settlement without transferring saved input or changing the run", async () => { + const { companyId, agent, issue, state } = await fixture(); + const bulk = "cleanup-saved-input-sentinel🙂".repeat(40_000); + const sync = { schema: "paperclip.native-workspace-sync.v1", state: "prepared", resourceDisposition: "destroy" }; + const [run] = await db.insert(heartbeatRuns).values({ + companyId, agentId: agent.id, issueId: issue.id, runtimeMode: "native", status: "failed", + errorCode: "provider_transport_failed", error: "Retain saved files", nativePhase: "terminal_failure", + runnerProfileJson: { nativeWorkspaceSync: sync, savedInput: bulk }, + resultJson: { workspaceExportRetry: { requestId: "retry-source" }, stdout: bulk }, + contextSnapshot: { timerClaimWasFirstHeartbeat: true, savedInput: bulk }, + stdoutExcerpt: bulk, stderrExcerpt: bulk, + }).returning(); + await state.getRunWorkspaceSettlement(run.id); + const events: Array> = []; + const now = Date.now(); + const capture = createDatabaseResponseCapture({ start: now - 100, end: now + 59_000 }, event => events.push(event)); + installDatabaseResponseCapture(db, { heartbeatRuns }, capture); + expect(await state.getRunCleanupState(run.id)).toEqual({ + id: run.id, companyId, agentId: agent.id, runtimeMode: run.runtimeMode, + status: run.status, errorCode: run.errorCode, nativePhase: run.nativePhase, + }); + expect(await state.getRunWorkspaceSettlement(run.id)).toEqual({ + id: run.id, status: run.status, error: run.error, + runnerProfileJson: { nativeWorkspaceSync: sync }, + resultJson: { workspaceExportRetry: { requestId: "retry-source" } }, + contextSnapshot: { timerClaimWasFirstHeartbeat: true }, + }); + capture.flush(); + const summary = events.find(event => event.event === "paperclip.db_response_capture.summary.v1")!; + expect(summary.completedQueries).toBe(2); + expect(summary.responseValueBytes).toBeLessThan(2000); + expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, run.id)))[0]).toEqual(run); + expect(JSON.stringify(events)).not.toContain("cleanup-saved-input-sentinel"); + expect(await state.getRunCleanupState(randomUUID())).toBeNull(); + expect(await state.getRunWorkspaceSettlement(randomUUID())).toBeNull(); + }); + + it("preserves JSON types in workspace settlement decisions", async () => { + const { companyId, agent, state } = await fixture(); + for (const value of [null, false, true, "true", 0, [], { future: [1, "retained"] }]) { + const [run] = await db.insert(heartbeatRuns).values({ + companyId, agentId: agent.id, + runnerProfileJson: { nativeWorkspaceSync: value }, + resultJson: { workspaceExportRetry: value }, + contextSnapshot: { timerClaimWasFirstHeartbeat: value }, + }).returning({ id: heartbeatRuns.id }); + const actual = await state.getRunWorkspaceSettlement(run.id); + expect(actual?.runnerProfileJson?.nativeWorkspaceSync).toEqual(value); + expect(actual?.resultJson?.workspaceExportRetry).toEqual(value); + expect(actual?.contextSnapshot?.timerClaimWasFirstHeartbeat).toEqual(value); + } + }); + it("retains the consumed queue identity in issue polling summaries", async () => { const { companyId, agent, issue, state } = await fixture(); const [wake] = await db.insert(agentWakeupRequests).values({ diff --git a/server/src/services/heartbeat/run-state.ts b/server/src/services/heartbeat/run-state.ts index 30f9ef0b001..1911ad1a25c 100644 --- a/server/src/services/heartbeat/run-state.ts +++ b/server/src/services/heartbeat/run-state.ts @@ -1119,6 +1119,28 @@ export function createHeartbeatRunState(db: Db) { .then((rows) => rows[0] ?? null); } + async function getRunCleanupState(runId: string) { + return db.select({ + id: heartbeatRuns.id, companyId: heartbeatRuns.companyId, agentId: heartbeatRuns.agentId, + runtimeMode: heartbeatRuns.runtimeMode, status: heartbeatRuns.status, + errorCode: heartbeatRuns.errorCode, nativePhase: heartbeatRuns.nativePhase, + }).from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)).then(rows => rows[0] ?? null); + } + + async function getRunWorkspaceSettlement(runId: string) { + const safeForLegacyEncoding = await hasUnsafeTextProjectionDatabase(); + return db.select({ + id: heartbeatRuns.id, status: heartbeatRuns.status, + error: safeForLegacyEncoding ? heartbeatRunSqlAsciiSafeColumns.error : heartbeatRuns.error, + runnerProfileJson: sql | null>`case when ${heartbeatRuns.runnerProfileJson} is null then null + else jsonb_build_object('nativeWorkspaceSync', ${heartbeatRuns.runnerProfileJson}->'nativeWorkspaceSync') end`, + resultJson: sql | null>`case when ${heartbeatRuns.resultJson} is null then null + else jsonb_build_object('workspaceExportRetry', ${heartbeatRuns.resultJson}->'workspaceExportRetry') end`, + contextSnapshot: sql | null>`case when ${heartbeatRuns.contextSnapshot} is null then null + else jsonb_build_object('timerClaimWasFirstHeartbeat', ${heartbeatRuns.contextSnapshot}->'timerClaimWasFirstHeartbeat') end`, + }).from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)).then(rows => rows[0] ?? null); + } + async function getRunStatus(runId: string) { return db .select({ @@ -1688,6 +1710,8 @@ export function createHeartbeatRunState(db: Db) { getAgent, resolveSessionBeforeForWakeup, getRun, + getRunCleanupState, + getRunWorkspaceSettlement, ensureRuntimeState, getTaskSession, getLatestAgentConfigRevision, diff --git a/server/src/services/native-runtime/__tests__/helpers/committed-replay.ts b/server/src/services/native-runtime/__tests__/helpers/committed-replay.ts new file mode 100644 index 00000000000..7caef7cf216 --- /dev/null +++ b/server/src/services/native-runtime/__tests__/helpers/committed-replay.ts @@ -0,0 +1,34 @@ +import { heartbeatRuns, type Db } from "@paperclipai/db"; +import { createDatabaseResponseCapture, installDatabaseResponseCapture } from "@paperclipai/db/response-capture"; +import { eq } from "drizzle-orm"; +import { expect } from "vitest"; + +export async function verifyCommittedReplayPayloadReads( + db: Db, + binding: { runId: string; companyId: string; agentId: string }, + replay: () => Promise, +) { + const { runId, companyId, agentId } = binding; + const bulk = "saved-native-input-sentinel🙂".repeat(40_000); + const [original] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)); + await db.update(heartbeatRuns).set({ + contextSnapshot: { ...original.contextSnapshot, savedInput: bulk }, + runnerProfileJson: { savedInput: bulk, nativeExecutionInput: { + schema: "paperclip.native-execution-input.v8", savedInput: bulk, + provider: { kind: "muse", binding: { companyId, agentId, bindingId: runId } }, + } }, stdoutExcerpt: bulk, stderrExcerpt: bulk, + }).where(eq(heartbeatRuns.id, runId)); + const [before] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)); + const events: Array> = []; + const now = Date.now(); + const capture = createDatabaseResponseCapture({ start: now - 100, end: now + 59_000 }, event => events.push(event)); + installDatabaseResponseCapture(db, { heartbeatRuns }, capture); + try { await replay(); } + finally { capture.flush(); } + const summary = events.find(event => event.event === "paperclip.db_response_capture.summary.v1")!; + expect(summary.completedQueries).toBeGreaterThan(0); + expect(summary.responseValueBytes).toBeLessThan(100_000); + const [after] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)); + expect(after).toEqual(before); + expect(JSON.stringify(events)).not.toContain("saved-native-input-sentinel"); +} diff --git a/server/src/services/native-runtime/native-run-finalizer-telemetry.test.ts b/server/src/services/native-runtime/native-run-finalizer-telemetry.test.ts index 0a8b6ce4ed1..2c2e534081b 100644 --- a/server/src/services/native-runtime/native-run-finalizer-telemetry.test.ts +++ b/server/src/services/native-runtime/native-run-finalizer-telemetry.test.ts @@ -1,5 +1,6 @@ import { enableRunFailureReporting } from "../../__tests__/helpers/run-failure-reporting.js"; import { randomUUID } from "node:crypto"; +import { verifyCommittedReplayPayloadReads } from "./__tests__/helpers/committed-replay.js"; import { eq } from "drizzle-orm"; import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; import { @@ -34,6 +35,12 @@ const mockTelemetryClient = vi.hoisted(() => ({ })); vi.mock("../../telemetry.ts", () => ({ getTelemetryClient: () => mockTelemetryClient })); +const reconcileMuseAssignments = vi.hoisted(() => vi.fn(async () => undefined)); +vi.mock("../muse-runner-broker.js", async importOriginal => ({ + ...await importOriginal(), + museRunnerBroker: () => ({ reconcileTerminalAssignments: reconcileMuseAssignments }), +})); + const mockCaptureRunFailure = vi.hoisted(() => vi.fn()); vi.mock("../../sentry.ts", async () => { const actual = await vi.importActual("../../sentry.ts"); @@ -261,18 +268,18 @@ describeEmbeddedPostgres("native run finalizer / status decision committer — a projectRunStatus: true, }); - const callsBefore = mockTelemetryClient.track.mock.calls.length; - // The coordinator is already "committed", so this second call takes the - // projectCommittedRun short-circuit. A succeeded row is eligible so stale - // cleanup errors can be projected separately; an unchanged terminal state - // must still never emit a second agent.task_run event. - await finalizeNativeRun({ - db, - runId: fixture.runId, - workspaceFinalizeStatus: "succeeded", - projectRunStatus: true, + await verifyCommittedReplayPayloadReads(db, { runId: fixture.runId, companyId, agentId }, async () => { + const callsBefore = mockTelemetryClient.track.mock.calls.length; + reconcileMuseAssignments.mockClear(); + await finalizeNativeRun({ + db, + runId: fixture.runId, + workspaceFinalizeStatus: "succeeded", + projectRunStatus: true, + }); + expect(agentTaskRunCalls(callsBefore)).toHaveLength(0); + expect(reconcileMuseAssignments).toHaveBeenCalledExactlyOnceWith(companyId, agentId, fixture.runId); }); - expect(agentTaskRunCalls(callsBefore)).toHaveLength(0); }); it("repairs a stale succeeded-run error once without duplicate telemetry or destroying retained owner evidence", async () => { diff --git a/server/src/services/native-runtime/native-run-finalizer.ts b/server/src/services/native-runtime/native-run-finalizer.ts index 8b2ae73c349..7d60d73e0d7 100644 --- a/server/src/services/native-runtime/native-run-finalizer.ts +++ b/server/src/services/native-runtime/native-run-finalizer.ts @@ -568,7 +568,7 @@ export async function recordNativeFinalizationFailure(input: { }); } -async function resolveCommittedFinalizationRecovery(db: Db, run: typeof heartbeatRuns.$inferSelect, issueId: string) { +async function resolveCommittedFinalizationRecovery(db: Db, run: Pick, issueId: string) { const actions = await db.select().from(issueRecoveryActions).where(and( eq(issueRecoveryActions.companyId, run.companyId), eq(issueRecoveryActions.sourceIssueId, issueId), eq(issueRecoveryActions.kind, "active_run_watchdog"), inArray(issueRecoveryActions.status, ["active", "escalated"]), @@ -704,7 +704,8 @@ async function projectCommittedRun(input: { async function materializeCommittedReviewResponse(db: Db, runId: string) { try { const [run] = await db - .select() + .select({ id: heartbeatRuns.id, companyId: heartbeatRuns.companyId, agentId: heartbeatRuns.agentId, + nativeIssueId: heartbeatRuns.nativeIssueId, resultJson: heartbeatRuns.resultJson }) .from(heartbeatRuns) .where(eq(heartbeatRuns.id, runId)) .limit(1); @@ -1146,13 +1147,15 @@ export async function finalizeNativeRun(input: { preserveProviderAttempt?: boolean; failpoint?: NativeStatusCommitFailpoint; }) { - const run = await input.db - .select() + const admittedRun = await input.db + .select({ id: heartbeatRuns.id, companyId: heartbeatRuns.companyId, agentId: heartbeatRuns.agentId, + runtimeMode: heartbeatRuns.runtimeMode, status: heartbeatRuns.status, errorCode: heartbeatRuns.errorCode, + nativePhase: heartbeatRuns.nativePhase, finishedAt: heartbeatRuns.finishedAt }) .from(heartbeatRuns) .where(eq(heartbeatRuns.id, input.runId)) .limit(1) .then((rows) => rows[0] ?? null); - if (!run || run.runtimeMode !== "native") + if (!admittedRun || admittedRun.runtimeMode !== "native") throw new Error("native_finalization_run_missing"); const claim = await claimCoordinator({ db: input.db, @@ -1161,12 +1164,12 @@ export async function finalizeNativeRun(input: { }); const coordinator = claim.coordinator; if (!claim.leaseOwner && coordinator.phase === "committed") { - if (isNativeRunnerOwnershipHeld(run)) return coordinator; + if (isNativeRunnerOwnershipHeld(admittedRun)) return coordinator; const presentationAlreadyMaterialized = coordinator.decisionId ? await hasMaterializedNativeReviewResponse(input.db, { - companyId: run.companyId, + companyId: admittedRun.companyId, issueId: coordinator.issueId, - runId: run.id, + runId: admittedRun.id, decisionId: coordinator.decisionId, }) : false; @@ -1178,9 +1181,9 @@ export async function finalizeNativeRun(input: { ) { await input.db.transaction((tx) => restoreNativeChatReviewPresentationInTransaction(tx as unknown as Db, { - companyId: run.companyId, + companyId: admittedRun.companyId, issueId: coordinator.issueId, - runId: run.id, + runId: admittedRun.id, decisionId: coordinator.decisionId!, resultId: coordinator.resultId!, assessmentId: coordinator.assessmentId!, @@ -1188,27 +1191,45 @@ export async function finalizeNativeRun(input: { ); } if (input.projectRunStatus) - await projectCommittedRun({ db: input.db, run, coordinator }); + await projectCommittedRun({ db: input.db, run: admittedRun, coordinator }); if (input.projectRunStatus && !presentationAlreadyMaterialized) await materializeCommittedReviewResponse(input.db, input.runId); if (input.projectRunStatus) await repairCommittedNativeChatResponse(input.db, { - companyId: run.companyId, + companyId: admittedRun.companyId, issueId: coordinator.issueId, - runId: run.id, + runId: admittedRun.id, }); if (input.projectRunStatus) { - await settleExternalConversation(input.db, run.companyId, coordinator.issueId).catch((err) => { - logger.warn({ err, runId: run.id }, "Slack conversation settlement deferred to reconciliation"); + await settleExternalConversation(input.db, admittedRun.companyId, coordinator.issueId).catch((err) => { + logger.warn({ err, runId: admittedRun.id }, "Slack conversation settlement deferred to reconciliation"); }); } - await resolveCommittedFinalizationRecovery(input.db, run, coordinator.issueId); + await resolveCommittedFinalizationRecovery(input.db, admittedRun, coordinator.issueId); if (input.projectRunStatus) { - const [projectedRun] = await input.db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, run.id)); + const [projectedRun] = await input.db.select({ + id: heartbeatRuns.id, companyId: heartbeatRuns.companyId, agentId: heartbeatRuns.agentId, + runtimeMode: heartbeatRuns.runtimeMode, status: heartbeatRuns.status, + runnerProfileJson: sql | null>`case when ${heartbeatRuns.runnerProfileJson} is null then null + else jsonb_build_object('nativeExecutionInput', jsonb_build_object( + 'schema', ${heartbeatRuns.runnerProfileJson} #> '{nativeExecutionInput,schema}', + 'provider', jsonb_build_object( + 'kind', ${heartbeatRuns.runnerProfileJson} #> '{nativeExecutionInput,provider,kind}', + 'binding', jsonb_build_object( + 'companyId', ${heartbeatRuns.runnerProfileJson} #> '{nativeExecutionInput,provider,binding,companyId}', + 'agentId', ${heartbeatRuns.runnerProfileJson} #> '{nativeExecutionInput,provider,binding,agentId}', + 'bindingId', ${heartbeatRuns.runnerProfileJson} #> '{nativeExecutionInput,provider,binding,bindingId}' + ) + ) + )) end`, + }).from(heartbeatRuns).where(eq(heartbeatRuns.id, admittedRun.id)); if (projectedRun) await reconcileMuseNativeTerminalRun(input.db, projectedRun); } return coordinator; } + const run = await input.db.select().from(heartbeatRuns) + .where(eq(heartbeatRuns.id, input.runId)).limit(1).then(rows => rows[0] ?? null); + if (!run || run.runtimeMode !== "native") throw new Error("native_finalization_run_missing"); const [resultRow, contractRow] = await Promise.all([ input.db .select() From e82d86bfebe34db8757036316b8997162aaa5b10 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sat, 24 Oct 2026 19:01:15 -0700 Subject: [PATCH 028/110] fix(server): gate periodic heartbeat recovery to one chain in flight (#11699) Bind periodic recovery admission to lifecycle tracking. Keep one physical pass active through cleanup, report skipped ticks and long-held ownership, and preserve direct scheduled delivery. Full build, typecheck, 32 focused tests, complete CI, and exact-head Greptile5/5 pass. Co-Authored-By: Senior Engineer Fable Co-Authored-By: Dotta Co-Authored-By: Devin Foley Co-Authored-By: Claude Fable 5 Co-Authored-By: Paperclip --- doc/native-workspace-finalization-recovery.md | 10 ++ server/src/index.ts | 13 +- server/src/lib/single-flight.test.ts | 163 ++++++++++++++++++ server/src/lib/single-flight.ts | 51 ++++++ 4 files changed, 236 insertions(+), 1 deletion(-) create mode 100644 server/src/lib/single-flight.test.ts create mode 100644 server/src/lib/single-flight.ts diff --git a/doc/native-workspace-finalization-recovery.md b/doc/native-workspace-finalization-recovery.md index 8b9c004282c..428c32b3fe4 100644 --- a/doc/native-workspace-finalization-recovery.md +++ b/doc/native-workspace-finalization-recovery.md @@ -1,5 +1,15 @@ # Native workspace finalization ownership and recovery +Periodic heartbeat recovery runs one pass at a time in each server process. +A tick that arrives during a slow pass reports its age and starts no duplicate. +A later tick can start a fresh pass after the current work settles. Shutdown +and idle sleep still track the actual recovery promise through cleanup. Direct +run operations and scheduled work delivery keep their existing paths. A pass +that remains active for three scheduler intervals produces an error log with its +age. A waiting timeout does not admit another pass: the actual work must settle +before ownership is released. A stuck operation requires investigation and +recovery at the operation or provider boundary. + A native provider can fail before it submits a result while its workspace still contains unpublished edits. A prepared workspace reference is not an export receipt. Terminal provider failure pins the exact bound sandbox and records a diff --git a/server/src/index.ts b/server/src/index.ts index 584e9e67697..e83d603e2aa 100644 --- a/server/src/index.ts +++ b/server/src/index.ts @@ -38,6 +38,7 @@ import { chatCompletionDeliveryService } from "./services/chat-completion-delive // instrumentationReady before opening DB connections or constructing the // HTTP server, so trace coverage does not depend on incidental timing. import { instrumentationReady, shutdownInstrumentation } from "./instrumentation.js"; +import { createTrackedSingleFlight } from "./lib/single-flight.js"; import { sentryReady, shutdownSentry, captureException } from "./sentry.js"; import { setSentryRunLinkResolver } from "./sentry-links.js"; import { createSentryRunLinkResolver } from "./services/sentry-run-links.js"; @@ -1209,6 +1210,16 @@ async function startServerWithDatabaseTeardown( }); heartbeatSchedulerInFlight.add(tracked); }; + const runPeriodicRecovery = createTrackedSingleFlight({ + trackWork: trackHeartbeatSchedulerWork, + onSkipped: (inFlightForMs) => { + if (inFlightForMs >= 3 * config.heartbeatSchedulerIntervalMs) { + logger.error({ inFlightForMs }, "periodic heartbeat recovery remains in flight; duplicate pass suppressed"); + } else { + logger.warn({ inFlightForMs }, "skipped periodic heartbeat recovery tick; previous chain still in flight"); + } + }, + }); const waitForHeartbeatSchedulerIdle = async () => { while (heartbeatSchedulerInFlight.size > 0) { await Promise.allSettled([...heartbeatSchedulerInFlight]); @@ -1887,7 +1898,7 @@ async function startServerWithDatabaseTeardown( if (!(await heartbeat.resolveSchedulingSuppression()).suppressed) { // Periodically reap orphaned runs (5-min staleness threshold) and make sure // persisted queued work is still being driven forward. - trackHeartbeatSchedulerWork(heartbeat + runPeriodicRecovery(() => heartbeat .reapOrphanedRuns({ staleThresholdMs: 5 * 60 * 1000 }) .then(() => heartbeat.promoteDueScheduledRetries()) .then(async (promotion) => { diff --git a/server/src/lib/single-flight.test.ts b/server/src/lib/single-flight.test.ts new file mode 100644 index 00000000000..06dabc92485 --- /dev/null +++ b/server/src/lib/single-flight.test.ts @@ -0,0 +1,163 @@ +import { describe, expect, it, vi } from "vitest"; +import { createSingleFlight, createTrackedSingleFlight } from "./single-flight.js"; +import { beginIdleTrackedWork, idleWorkSnapshot } from "../services/task-admission.js"; + +function deferred() { + let resolve!: () => void; + let reject!: (err: unknown) => void; + const promise = new Promise((res, rej) => { + resolve = res; + reject = rej; + }); + return { promise, resolve, reject }; +} + +describe("createSingleFlight", () => { + it("runs work when idle and reports busy until it settles", async () => { + const gate = createSingleFlight(); + const gap = deferred(); + + const first = gate.run(() => gap.promise); + expect(first.started).toBe(true); + expect(gate.busy).toBe(true); + + gap.resolve(); + await (first as { settled: Promise }).settled; + expect(gate.busy).toBe(false); + }); + + it("skips a tick while the previous invocation is still in flight", async () => { + const clock = { nowMs: 1_000 }; + const gate = createSingleFlight(() => clock.nowMs); + const gap = deferred(); + const work = vi.fn(() => gap.promise); + + const first = gate.run(work); + clock.nowMs = 31_000; + const second = gate.run(work); + + expect(second).toEqual({ started: false, inFlightForMs: 30_000 }); + expect(work).toHaveBeenCalledTimes(1); + + gap.resolve(); + await (first as { settled: Promise }).settled; + }); + + it("admits new work after the previous invocation resolves", async () => { + const gate = createSingleFlight(); + const gap = deferred(); + + const first = gate.run(() => gap.promise); + gap.resolve(); + await (first as { settled: Promise }).settled; + + const second = gate.run(async () => {}); + expect(second.started).toBe(true); + await (second as { settled: Promise }).settled; + }); + + it("releases the gate when work rejects and never rejects the settled promise", async () => { + const gate = createSingleFlight(); + const gap = deferred(); + + const first = gate.run(() => gap.promise); + gap.reject(new Error("chain failed")); + await expect((first as { settled: Promise }).settled).resolves.toBeUndefined(); + expect(gate.busy).toBe(false); + + const second = gate.run(async () => {}); + expect(second.started).toBe(true); + await (second as { settled: Promise }).settled; + }); + + it("propagates a synchronous throw and leaves the gate free", async () => { + const gate = createSingleFlight(); + + expect(() => + gate.run(() => { + throw new Error("sync failure"); + }), + ).toThrow("sync failure"); + expect(gate.busy).toBe(false); + + const second = gate.run(async () => {}); + expect(second.started).toBe(true); + await (second as { settled: Promise }).settled; + }); + + it("keeps the owned pass active after a caller stops waiting", async () => { + const gate = createSingleFlight(), work = deferred(), observer = deferred(); + const first = gate.run(() => work.promise); + if (!first.started) throw new Error("initial pass was not admitted"); + const stopped = Promise.race([first.settled, observer.promise]); + observer.reject(new Error("observer stopped")); + await expect(stopped).rejects.toThrow("observer stopped"); + const duplicate = vi.fn(async () => undefined); + expect(gate.run(duplicate).started).toBe(false); + expect(duplicate).not.toHaveBeenCalled(); + expect(gate.busy).toBe(true); + work.resolve(); + await first.settled; + expect(gate.busy).toBe(false); + }); + + it("keeps cleanup joined after the main operation completes", async () => { + const gate = createSingleFlight(), operation = deferred(), cleanup = deferred(); + const first = gate.run(() => operation.promise.finally(() => cleanup.promise)); + if (!first.started) throw new Error("initial pass was not admitted"); + operation.resolve(); + await Promise.resolve(); + expect(gate.busy).toBe(true); + const duplicate = vi.fn(async () => undefined); + expect(gate.run(duplicate).started).toBe(false); + expect(duplicate).not.toHaveBeenCalled(); + cleanup.resolve(); + await first.settled; + expect(gate.busy).toBe(false); + const next = gate.run(duplicate); + expect(next.started).toBe(true); + if (next.started) await next.settled; + expect(duplicate).toHaveBeenCalledTimes(1); + }); + + it("tracks one periodic pass through scheduler shutdown and idle sleep", async () => { + vi.useFakeTimers(); + const before = idleWorkSnapshot().active; + const operation = deferred(), cleanup = deferred(); + const tracked: Promise[] = []; + const trackWork = vi.fn((work: Promise) => { + const finish = beginIdleTrackedWork(); + tracked.push(work.finally(finish)); + }); + const onSkipped = vi.fn(); + const tick = createTrackedSingleFlight({ trackWork, onSkipped }); + const heartbeat = vi.fn(() => operation.promise.finally(() => cleanup.promise)); + const timer = setInterval(() => tick(heartbeat), 30_000); + try { + await vi.advanceTimersByTimeAsync(60_000); + expect(heartbeat).toHaveBeenCalledOnce(); + expect(trackWork).toHaveBeenCalledOnce(); + expect(onSkipped).toHaveBeenCalledExactlyOnceWith(30_000); + clearInterval(timer); + let shutdownComplete = false; + const shutdown = Promise.all(tracked).then(() => { shutdownComplete = true; }); + await Promise.resolve(); + expect(shutdownComplete).toBe(false); + expect(idleWorkSnapshot().active).toBe(before + 1); + operation.resolve(); + await Promise.resolve(); + expect(shutdownComplete).toBe(false); + expect(idleWorkSnapshot().active).toBe(before + 1); + cleanup.resolve(); + await shutdown; + expect(shutdownComplete).toBe(true); + expect(idleWorkSnapshot().active).toBe(before); + } finally { + clearInterval(timer); + operation.resolve(); + cleanup.resolve(); + await Promise.all(tracked); + vi.useRealTimers(); + } + }); +}); diff --git a/server/src/lib/single-flight.ts b/server/src/lib/single-flight.ts new file mode 100644 index 00000000000..68dc1b035f4 --- /dev/null +++ b/server/src/lib/single-flight.ts @@ -0,0 +1,51 @@ +export interface SingleFlightSkip { + started: false; + inFlightForMs: number; +} + +export interface SingleFlightStart { + started: true; + settled: Promise; +} + +export type SingleFlightResult = SingleFlightSkip | SingleFlightStart; + +export function createSingleFlight(now: () => number = Date.now) { + let inFlight: Promise | null = null; + let startedAtMs = 0; + + return { + get busy(): boolean { + return inFlight !== null; + }, + run(work: () => Promise): SingleFlightResult { + if (inFlight) { + return { started: false, inFlightForMs: now() - startedAtMs }; + } + startedAtMs = now(); + const settled = Promise.resolve(work()) + .then( + () => undefined, + () => undefined, + ) + .finally(() => { + inFlight = null; + }); + inFlight = settled; + return { started: true, settled }; + }, + }; +} + +export function createTrackedSingleFlight(options: { + trackWork: (work: Promise) => void; + onSkipped: (inFlightForMs: number) => void; + now?: () => number; +}) { + const gate = createSingleFlight(options.now); + return (work: () => Promise) => { + const tick = gate.run(work); + if (tick.started) options.trackWork(tick.settled); + else options.onSkipped(tick.inFlightForMs); + }; +} From 39e5c8c1c32ee38d7b40d068560e63b2e93320be Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Sat, 24 Oct 2026 19:01:19 -0700 Subject: [PATCH 029/110] perf(server): narrow committed chat authorization reads (#17530) Select current chat authorization fields for committed responses under the existing scoped share lock. Preserve complete evidence for actual retries, source revocation, JSON types, and saved run data. Full build, typecheck, 113 focused tests, complete CI, and exact-head Greptile5/5 pass. Co-Authored-By: Paperclip --- doc/native-workspace-finalization-recovery.md | 6 + .../authorization-run-read.test.ts | 116 ++++++++++++++++++ .../chat-channels/authorization-run-read.ts | 46 +++++++ .../chat-channels/failed-run-retry.ts | 20 +-- 4 files changed, 174 insertions(+), 14 deletions(-) create mode 100644 server/src/services/chat-channels/authorization-run-read.test.ts create mode 100644 server/src/services/chat-channels/authorization-run-read.ts diff --git a/doc/native-workspace-finalization-recovery.md b/doc/native-workspace-finalization-recovery.md index 428c32b3fe4..c888ce1a34f 100644 --- a/doc/native-workspace-finalization-recovery.md +++ b/doc/native-workspace-finalization-recovery.md @@ -475,3 +475,9 @@ For a cancelled native run, the file-recovery form also offers an optional confirmation that no external actions were performed. Leave it unchecked unless the run history verifies that fact. The default records files without certifying action outcomes. Changing the selected source clears the evidence and confirmations. + +Committed chat response authorization reads current run identity, completion +binding, and chat source fields under the existing nonblocking share lock. +It excludes saved execution input, runner profiles, and log excerpts. Actual +retry admission still reads the complete run and its recovery evidence. These +reads preserve stored run data, source revocation checks, and JSON value types. diff --git a/server/src/services/chat-channels/authorization-run-read.test.ts b/server/src/services/chat-channels/authorization-run-read.test.ts new file mode 100644 index 00000000000..3d56b695222 --- /dev/null +++ b/server/src/services/chat-channels/authorization-run-read.test.ts @@ -0,0 +1,116 @@ +import { randomBytes, randomUUID } from "node:crypto"; +import { agents, companies, createDb, heartbeatRuns } from "@paperclipai/db"; +import { createDatabaseResponseCapture, installDatabaseResponseCapture } from "@paperclipai/db/response-capture"; +import { eq } from "drizzle-orm"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embedded-postgres.js"; +import { readChatAuthorizationRun } from "./authorization-run-read.js"; + +const support = await getEmbeddedPostgresTestSupport(); + +describe.skipIf(!support.supported)("chat authorization run reads", () => { + let database: Awaited>; + let db: ReturnType; + let companyId: string; + let agentId: string; + + beforeAll(async () => { + database = await startEmbeddedPostgresTestDatabase("chat-authorization-read-"); + db = createDb(database.connectionString); + const [company] = await db.insert(companies).values({ name: "Chat authorization fixture", issuePrefix: "CAR" }).returning(); + const [agent] = await db.insert(agents).values({ companyId: company.id, name: "Chat agent", adapterType: "process" }).returning(); + companyId = company.id; + agentId = agent.id; + }, 60_000); + + afterAll(async () => { + await db?.$client.end(); + await database?.cleanup(); + }); + + async function seed(contextSnapshot: unknown = {}) { + const [run] = await db.insert(heartbeatRuns).values({ + companyId, agentId, contextSnapshot: contextSnapshot as Record | null, + }).returning(); + return { companyId, agentId, failedRunId: run.id }; + } + + it("reads committed authority below the byte budget and keeps complete retry evidence", async () => { + const bulk = randomBytes(128 * 1024).toString("base64"); + const context = { + source: "chat:slack", issueId: randomUUID(), interactionId: null, taskKey: "CAR-1", + wakeCommentIds: [randomUUID()], wakeCommentId: null, + chatFailedRunRetry: { version: 1, actionId: randomUUID(), failedRunId: randomUUID() }, + retryOfRunId: randomUUID(), + }; + const scope = await seed({ ...context, savedInput: bulk }); + await db.update(heartbeatRuns).set({ runnerProfileJson: { savedInput: bulk }, stdoutExcerpt: bulk, stderrExcerpt: bulk }) + .where(eq(heartbeatRuns.id, scope.failedRunId)); + const [before] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, scope.failedRunId)); + const events: Array> = []; + const now = Date.now(); + const capture = createDatabaseResponseCapture({ start: now - 100, end: now + 59_000 }, event => events.push(event)); + installDatabaseResponseCapture(db, { heartbeatRuns }, capture); + try { + const selected = await db.transaction(tx => readChatAuthorizationRun(tx, scope, true)); + expect(selected.kind).toBe("committed"); + expect(selected.run?.contextSnapshot).toEqual(context); + expect(selected.run).not.toHaveProperty("runnerProfileJson"); + expect(selected.run).not.toHaveProperty("stdoutExcerpt"); + } finally { capture.flush(); } + const summary = events.find(event => event.event === "paperclip.db_response_capture.summary.v1")!; + expect(summary.completedQueries).toBeGreaterThan(0); + expect(summary.responseValueBytes).toBeLessThan(4096); + const retry = await db.transaction(tx => readChatAuthorizationRun(tx, scope, false)); + expect(retry.kind).toBe("retry"); + expect(retry.run).toEqual(before); + const [after] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, scope.failedRunId)); + expect(after).toEqual(before); + expect(JSON.stringify(events)).not.toContain(bulk.slice(0, 64)); + }); + + it.each([{}, { wakeCommentId: null }, { wakeCommentId: false, wakeCommentIds: "invalid", interactionId: [] }])( + "preserves key presence and JSON types in %j", async context => { + const scope = await seed(context); + expect((await readChatAuthorizationRun(db, scope, true)).run?.contextSnapshot).toEqual(context); + }, + ); + + it.each([null, [], "invalid", 42])("handles non-object context %j", async context => { + const scope = await seed(context); + expect((await readChatAuthorizationRun(db, scope, true)).run?.contextSnapshot).toEqual(context === null ? null : {}); + expect((await readChatAuthorizationRun(db, scope, false)).run?.contextSnapshot).toEqual(context); + }); + + it("reads current authority and fails closed for another company or agent", async () => { + const scope = await seed({ source: "chat:slack", taskKey: "CAR-1" }); + expect((await readChatAuthorizationRun(db, scope, true)).run?.contextSnapshot).toEqual({ source: "chat:slack", taskKey: "CAR-1" }); + await db.update(heartbeatRuns).set({ contextSnapshot: { source: "chat:discord", taskKey: "CAR-2" } }) + .where(eq(heartbeatRuns.id, scope.failedRunId)); + expect((await readChatAuthorizationRun(db, scope, true)).run?.contextSnapshot).toEqual({ source: "chat:discord", taskKey: "CAR-2" }); + for (const committed of [true, false]) { + expect((await readChatAuthorizationRun(db, { ...scope, companyId: randomUUID() }, committed)).run).toBeUndefined(); + expect((await readChatAuthorizationRun(db, { ...scope, agentId: randomUUID() }, committed)).run).toBeUndefined(); + expect((await readChatAuthorizationRun(db, { ...scope, failedRunId: randomUUID() }, committed)).run).toBeUndefined(); + } + }); + + it("preserves nonblocking authorization row locks", async () => { + const scope = await seed(); + let acquired!: () => void, release!: () => void; + const ready = new Promise(resolve => { acquired = resolve; }); + const released = new Promise(resolve => { release = resolve; }); + const holder = db.transaction(async tx => { + await tx.update(heartbeatRuns).set({ status: "running" }).where(eq(heartbeatRuns.id, scope.failedRunId)); + acquired(); + await released; + }); + try { + await ready; + for (const committed of [true, false]) { + await expect(db.transaction(tx => readChatAuthorizationRun(tx, scope, committed))).rejects.toMatchObject({ cause: { code: "55P03" } }); + } + } finally { release(); await holder; } + expect((await readChatAuthorizationRun(db, scope, true)).run?.status).toBe("running"); + }); +}); diff --git a/server/src/services/chat-channels/authorization-run-read.ts b/server/src/services/chat-channels/authorization-run-read.ts new file mode 100644 index 00000000000..3390ba103b7 --- /dev/null +++ b/server/src/services/chat-channels/authorization-run-read.ts @@ -0,0 +1,46 @@ +import { heartbeatRuns, type Db } from "@paperclipai/db"; +import { and, eq, sql } from "drizzle-orm"; + +type Database = Db | Parameters[0]>[0]; +type Scope = { companyId: string; agentId: string; failedRunId: string }; + +const contextKeys = [ + "source", "issueId", "interactionId", "taskKey", "wakeCommentIds", + "wakeCommentId", "chatFailedRunRetry", "retryOfRunId", +] as const; + +const committedContext = sql | null>` + case when ${heartbeatRuns.contextSnapshot} is null then null else ( + select coalesce(jsonb_object_agg(field.key, field.value), '{}'::jsonb) + from jsonb_each(case when jsonb_typeof(${heartbeatRuns.contextSnapshot}) = 'object' + then ${heartbeatRuns.contextSnapshot} else '{}'::jsonb end) as field(key, value) + where field.key in (${sql.join(contextKeys.map(key => sql`${key}`), sql`, `)}) + ) end +`; + +export async function readChatAuthorizationRun(db: Database, scope: Scope, committed: boolean) { + const where = and( + eq(heartbeatRuns.id, scope.failedRunId), + eq(heartbeatRuns.companyId, scope.companyId), + eq(heartbeatRuns.agentId, scope.agentId), + ); + if (!committed) { + const [run] = await db.select().from(heartbeatRuns).where(where).for("share", { noWait: true }); + return { kind: "retry" as const, run }; + } + const [run] = await db.select({ + id: heartbeatRuns.id, + companyId: heartbeatRuns.companyId, + agentId: heartbeatRuns.agentId, + wakeupRequestId: heartbeatRuns.wakeupRequestId, + status: heartbeatRuns.status, + finishedAt: heartbeatRuns.finishedAt, + runtimeMode: heartbeatRuns.runtimeMode, + errorCode: heartbeatRuns.errorCode, + nativeIssueId: heartbeatRuns.nativeIssueId, + completionContractId: heartbeatRuns.completionContractId, + retryOfRunId: heartbeatRuns.retryOfRunId, + contextSnapshot: committedContext, + }).from(heartbeatRuns).where(where).for("share", { noWait: true }); + return { kind: "committed" as const, run }; +} diff --git a/server/src/services/chat-channels/failed-run-retry.ts b/server/src/services/chat-channels/failed-run-retry.ts index 2b5d2c9b026..6310d448a66 100644 --- a/server/src/services/chat-channels/failed-run-retry.ts +++ b/server/src/services/chat-channels/failed-run-retry.ts @@ -2,6 +2,7 @@ import { continuingTeamsFilePublication, type ContinuingTeamsFileTransfer } from import { readTaskChatRetryIntent, taskChatRetryCanAwaitRecovery, taskChatRetryExecutionStopped } from "./task-retry-authority.js"; import { notifyChatActionWork, notifyChatPublicationWork } from "../chat-work-notifications.js"; import { FAILED_RUN_RETRY_STALE_MS, dueChatAction } from "../chat-action-work.js"; +import { readChatAuthorizationRun } from "./authorization-run-read.js"; import { createHash, @@ -688,17 +689,8 @@ export function createChatFailedRunRetry(db: Db, options: ChatFailedRunRetryOpti ), ) .for("share", { noWait: true }); - const [failedRun] = await tx - .select() - .from(heartbeatRuns) - .where( - and( - eq(heartbeatRuns.id, input.failedRunId), - eq(heartbeatRuns.companyId, input.companyId), - eq(heartbeatRuns.agentId, input.agentId), - ), - ) - .for("share", { noWait: true }); + const evidence = await readChatAuthorizationRun(tx, input, Boolean(input.committedResponse)); + const failedRun = evidence.run; if ( !issue || issue.assigneeAgentId !== input.agentId || @@ -719,7 +711,7 @@ export function createChatFailedRunRetry(db: Db, options: ChatFailedRunRetryOpti "process_exit", "timeout", ].includes(failedRun.errorCode ?? "") || - (await isPreProviderReviewedChatFailure(tx, failedRun)) + (evidence.kind === "retry" && await isPreProviderReviewedChatFailure(tx, evidence.run)) )) || (!input.publication && ["backlog", "done", "cancelled"].includes(issue.status)) @@ -729,8 +721,8 @@ export function createChatFailedRunRetry(db: Db, options: ChatFailedRunRetryOpti companyId: input.companyId, issueId: issue.id, agentId: input.agentId, sourceRunId: failedRun.id, intentId: input.taskRetryIntentId, })) throw failedChatRetryDenied(); - if (failedRun.runtimeMode === "native" && !input.committedResponse && !input.taskRetryIntentId) - await failedNativeRetryCoordinator(tx, failedRun, issue.id); + if (failedRun.runtimeMode === "native" && evidence.kind === "retry" && !input.taskRetryIntentId) + await failedNativeRetryCoordinator(tx, evidence.run, issue.id); const context = failedRun.contextSnapshot ?? {}; const provider = CHAT_PROVIDERS.find( (value) => context.source === `chat:${value}`, From ef0a8db50252c23ca4a1326a27bbb9441c3bc52c Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Sat, 24 Oct 2026 19:01:23 -0700 Subject: [PATCH 030/110] perf(native): narrow reconciliation candidate payloads (#17531) Select the complete workspace-sync record and native status wake identifier for reconciliation candidates. Preserve candidate policy, JSON types, full later evidence, and stored data. The committed replay regression includes the real reconciliation scan. Full build, typecheck, 114 focused tests, complete CI, and exact-head Greptile5/5 pass. Co-Authored-By: Paperclip --- doc/native-workspace-finalization-recovery.md | 5 +++++ .../native-runtime/native-finalization-reconciler.ts | 11 +++++------ .../native-run-finalizer-telemetry.test.ts | 5 +++++ 3 files changed, 15 insertions(+), 6 deletions(-) diff --git a/doc/native-workspace-finalization-recovery.md b/doc/native-workspace-finalization-recovery.md index c888ce1a34f..3d16ff3aada 100644 --- a/doc/native-workspace-finalization-recovery.md +++ b/doc/native-workspace-finalization-recovery.md @@ -19,6 +19,11 @@ cleanup run. This includes descriptor reads that fail inside runtime selection. preparation failure; another owner or a stale claim prevents cleanup. Settling that claim and recording file retention share a transaction. +The reconciliation candidate scan selects the complete workspace-sync record and +the native status wake identifier from each saved run. It keeps their JSON types +and reads full evidence later where finalization or recovery needs it. Saved +execution input, runner profiles, and logs stay in the stored run. + The recovery card names the original run and requires evidence that its exact allocation stopped and its files were recovered. Recording that evidence does not retry the old turn, certify unknown external actions, change the current task diff --git a/server/src/services/native-runtime/native-finalization-reconciler.ts b/server/src/services/native-runtime/native-finalization-reconciler.ts index ec391457b07..283aac76b2d 100644 --- a/server/src/services/native-runtime/native-finalization-reconciler.ts +++ b/server/src/services/native-runtime/native-finalization-reconciler.ts @@ -742,8 +742,8 @@ async function reconcileNativeFinalizationsPass( resultId: nativeRunFinalizations.resultId, assessmentId: nativeRunFinalizations.assessmentId, decisionId: nativeRunFinalizations.decisionId, - runnerProfileJson: heartbeatRuns.runnerProfileJson, - contextSnapshot: heartbeatRuns.contextSnapshot, + nativeWorkspaceSync: sql`${heartbeatRuns.runnerProfileJson}->'nativeWorkspaceSync'`, + nativeStatusWakeIntentId: sql`${heartbeatRuns.contextSnapshot}->'nativeStatusWakeIntentId'`, }) .from(heartbeatRuns) .innerJoin(nativeRunFinalizations, eq(nativeRunFinalizations.runId, heartbeatRuns.id)) @@ -955,8 +955,7 @@ async function reconcileNativeFinalizationsPass( if (reviewBarrier && reviewBarrier.status !== "succeeded") continue; const childCompletionRecipient = { companyId: row.companyId, issueId: row.issueId, agentId: row.agentId, runId: row.runId, - sourceIntentId: typeof record(row.contextSnapshot).nativeStatusWakeIntentId === "string" - ? record(row.contextSnapshot).nativeStatusWakeIntentId as string : null, + sourceIntentId: typeof row.nativeStatusWakeIntentId === "string" ? row.nativeStatusWakeIntentId : null, }; const hasPendingChildCompletion = await hasPendingNativeChildCompletion(db, childCompletionRecipient); const reassessmentRow = await recordNativeWorkAssessment({ @@ -1095,7 +1094,7 @@ async function reconcileNativeFinalizationsPass( projectRunStatus: true, preserveProviderAttempt: Boolean( readNativeWorkspaceSyncReference( - record(row.runnerProfileJson).nativeWorkspaceSync, + row.nativeWorkspaceSync, ), ), }); @@ -1153,7 +1152,7 @@ async function reconcileNativeFinalizationsPass( projectRunStatus: true, preserveProviderAttempt: Boolean( readNativeWorkspaceSyncReference( - record(row.runnerProfileJson).nativeWorkspaceSync, + row.nativeWorkspaceSync, ), ), }); diff --git a/server/src/services/native-runtime/native-run-finalizer-telemetry.test.ts b/server/src/services/native-runtime/native-run-finalizer-telemetry.test.ts index 2c2e534081b..5d1ed177987 100644 --- a/server/src/services/native-runtime/native-run-finalizer-telemetry.test.ts +++ b/server/src/services/native-runtime/native-run-finalizer-telemetry.test.ts @@ -279,6 +279,11 @@ describeEmbeddedPostgres("native run finalizer / status decision committer — a }); expect(agentTaskRunCalls(callsBefore)).toHaveLength(0); expect(reconcileMuseAssignments).toHaveBeenCalledExactlyOnceWith(companyId, agentId, fixture.runId); + await db.insert(workspaceOperations).values({ companyId, issueId: fixture.issueId, + heartbeatRunId: fixture.runId, phase: "workspace_finalize", status: "succeeded" }); + const reconciled = await reconcileNativeFinalizations(db, [fixture.runId]); + expect(reconciled).toContainEqual(expect.objectContaining({ runId: fixture.runId, phase: "committed" })); + expect(agentTaskRunCalls(callsBefore)).toHaveLength(0); }); }); From ac15d883f7baeda25753aa7631c83a8d30d3d1e5 Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Sat, 24 Oct 2026 19:26:27 -0700 Subject: [PATCH 031/110] fix: preserve remote-tracking history when expiring nested worktrees (#17535) ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Nested project repositories are now worktrees of one shared clone per project repository, and existing standalone clones are converted in place > - Conversion keeps the clone's remote-tracking refs as task-owned branches (`paperclip//remotes/...`) so commits only they hold survive > - Expiration then required every task-owned branch, including those, to be on the remote > - Remote-tracking refs for branches deleted or force-pushed upstream never are, so converted checkouts were kept forever > - This pull request treats those refs the way the standalone-clone path already does: commits missing upstream go into the restore point instead of blocking > - The benefit is that converted workspaces can expire and free disk without losing any history ## Linked Issues or Issue Description Refs #17407, #17382, #17289. Bug report described in-PR (bug report template). **What happened?** On one instance, 17 closed workspaces in a two-repository project were kept on every expiration sweep with `unpushed_managed_checkout_branches`. Each nested checkout is a converted worktree whose task-owned refs include `paperclip//remotes/origin/` for upstream branches since deleted or force-pushed (dependabot, squashed feature branches). Their commits are on no remote, so `provenNestedWorktreeHistory` refused. The task's own branch was fully pushed. **Expected behavior** As in the standalone-clone path (#17289), remote-tracking commits missing upstream are preserved in the restore point, and only genuinely local branches block expiration. **Steps to reproduce** 1. Fetch an upstream branch into a standalone nested clone, then delete that branch upstream. 2. Convert the clone into a worktree (nested clone migration). 3. Close the issue and let expiration inspect it: kept with `unpushed_managed_checkout_branches`. **Paperclip version or commit:** `master` at cb47dbb2da. **Deployment mode:** any. **Agent adapter(s) involved:** not adapter-specific (core). ## What Changed - `provenNestedWorktreeHistory` in `server/src/services/git-workspace-restoration.ts`: - splits task-owned refs into those under `remotes/` and the rest; - still requires the rest (and their reflogs) to be on the remote; - returns commits under `remotes/` that are missing upstream, and their reflogs, as `preserve`, which the restore point bundles. This matches the standalone-clone path. - `restorePointHistoryDigest` in `server/src/services/git-restore-point.ts`: for a linked worktree, it fingerprints the task's own refs and their reflogs instead of the shared clone's `refs/remotes`. Other tasks change those whenever they fetch, and they never covered the task-owned remote refs. It loads `nested-repository-worktrees` lazily to avoid an import cycle. No code comments were added. ## Verification - `pnpm exec vitest run nested-clone-migration` (in `server/`). New cases: - A converted checkout whose only extra history is a remote-tracking commit deleted upstream expires with a restore point. After its refs are removed and the shared clone is garbage-collected, reopening restores the commit. - The digest ignores the shared clone's remote refs and changes when the task's own refs move. - **Mutation checks**, each failing its test: - reverting the prover split; - dropping the preserve list; - reverting the digest change. - The existing case where a converted checkout with a genuinely unpushed branch is kept still passes. - `pnpm exec vitest run git-restore-point nested-repository-worktrees nested-clone-migration git-workspace-expiration git-reproducible-managed-checkouts isolated-task-directory isolated-repository-rehome git-credentials execution-workspace` (in `server/`): 591 passed. - `pnpm run typecheck` (in `server/`): pass. - Not run: server build and boot smoke. ## Risks - **Misclassified branches:** a local branch literally named `remotes/...` in a standalone clone becomes `remotes/...` after conversion and is now preserved in the restore point instead of blocking expiration. Its commits are still saved, not lost. - **Leftover refs:** after expiry, the task's other owned refs stay in the shared clone, as they did before this change, so their commits stay in two places. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), 1M context, through Claude Code with tool use (shell, file edits, tests, read-only diagnosis on a live instance). ## 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 - [ ] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip --- .../__tests__/nested-clone-migration.test.ts | 37 ++++++++++++++++++- server/src/services/git-restore-point.ts | 18 +++++++-- .../src/services/git-workspace-restoration.ts | 15 +++++--- .../services/nested-repository-worktrees.ts | 1 + 4 files changed, 62 insertions(+), 9 deletions(-) diff --git a/server/src/__tests__/nested-clone-migration.test.ts b/server/src/__tests__/nested-clone-migration.test.ts index e77222c4b9e..b417a4ce897 100644 --- a/server/src/__tests__/nested-clone-migration.test.ts +++ b/server/src/__tests__/nested-clone-migration.test.ts @@ -14,7 +14,7 @@ import { realizeExecutionWorkspace } from "../services/workspace-runtime.js"; import { executionWorkspaceService } from "../services/execution-workspaces.js"; import { prepareProjectRepositoryWorkspaces } from "../services/heartbeat/workspaces.js"; import { expireReconstructableGitWorkspace } from "../services/git-workspace-expiration.js"; -import { currentRestorePointSnapshot } from "../services/git-restore-point.js"; +import { currentRestorePointSnapshot, restorePointHistoryDigest } from "../services/git-restore-point.js"; import { nestedRepositoryBaseCandidates, nestedWorktreeBranchPrefix, readLinkedNestedCheckout, withNestedRepositoryBaseLock } from "../services/nested-repository-worktrees.js"; import { listNestedCloneMigrationNames, migrateNestedRepositoryClone, nextNestedCloneMigrationBatch, type NestedCloneMigrationOptions } from "../services/nested-clone-migration.js"; import { getStorageService } from "../storage/index.js"; @@ -225,6 +225,41 @@ describeEmbeddedPostgres("nested repository clone migration", () => { expect(git(f.checkout, "cat-file", "-t", feature)).toBe("commit"); }); + it("expires a converted checkout whose only extra history is remote-tracking and restores that history", async () => { + const f = await fixture({ issueStatus: "done" }); + git(f.nested.author, "checkout", "-q", "-b", "squashed-away"); + await fs.writeFile(path.join(f.nested.author, "feature.txt"), "feature\n"); + git(f.nested.author, "add", "."); git(f.nested.author, "commit", "-qm", "Feature"); + const feature = git(f.nested.author, "rev-parse", "HEAD"); + git(f.nested.author, "push", "-q", f.nested.remote, "squashed-away"); + git(f.checkout, "fetch", "-q", "origin"); + git(f.nested.remote, "branch", "-D", "squashed-away"); + git(f.nested.remote, "reflog", "expire", "--expire=now", "--all"); + git(f.nested.remote, "gc", "-q", "--prune=now"); + expect(await f.migrate()).toMatchObject({ outcome: "migrated" }); + + expect(await f.expire()).toMatchObject({ expired: true, restorePoint: true, skipReason: null }); + for (const line of ownedRefs(f.base, f.prefix).split("\n").filter(Boolean)) git(f.base, "update-ref", "-d", line.split(" ")[0]!); + git(f.base, "reflog", "expire", "--expire=now", "--all"); + git(f.base, "gc", "-q", "--prune=now"); + expect(() => git(f.base, "cat-file", "-e", `${feature}^{commit}`)).toThrow(); + expect(await f.reopen()).toMatchObject({ ok: true, reopened: true }); + expect(git(f.checkout, "cat-file", "-t", feature)).toBe("commit"); + }); + + it("fingerprints a converted checkout's own history rather than the shared clone's remote refs", async () => { + const f = await fixture(); + expect(await f.migrate()).toMatchObject({ outcome: "migrated" }); + const head = git(f.checkout, "rev-parse", "HEAD"); + const before = await restorePointHistoryDigest(f.checkout); + git(f.base, "update-ref", "refs/remotes/origin/another-task", head); + expect(await restorePointHistoryDigest(f.checkout)).toBe(before); + git(f.base, "update-ref", `refs/heads/${f.prefix}remotes/origin/extra`, head); + expect(await restorePointHistoryDigest(f.checkout)).not.toBe(before); + for (let index = 0; index < 64; index++) git(f.base, "update-ref", `refs/heads/${f.prefix}remotes/origin/bulk-${index}`, head); + await expect(restorePointHistoryDigest(f.checkout)).rejects.toThrow("managed_checkout_local_tip_budget"); + }); + it("finishes an interrupted conversion after the workspace is archived and forgets one whose workspace is gone", async () => { const f = await fixture(); const { unpushed } = await nestedWork(f.checkout); diff --git a/server/src/services/git-restore-point.ts b/server/src/services/git-restore-point.ts index 698b1395ade..3af9997b693 100644 --- a/server/src/services/git-restore-point.ts +++ b/server/src/services/git-restore-point.ts @@ -595,9 +595,21 @@ export async function restorePointHistoryDigest(input: string, signal?: AbortSig const cwd = await fs.realpath(input); const reflog = await gitText(cwd, ["reflog", "show", "--format=%H", "HEAD"], { signal }).catch(() => ""); const original = await gitText(cwd, ["rev-parse", "--verify", "-q", "ORIG_HEAD^{commit}"], { signal }).catch(() => ""); - const remotes = await gitText(cwd, ["for-each-ref", "--format=%(objectname) %(refname)", "refs/remotes"], { signal }).catch(() => ""); - const remoteReflogs = (await gitText(cwd, ["reflog", "show", "--all", "--format=%H %gD"], { signal }).catch(() => "")) - .split("\n").filter((line) => / refs\/remotes\//.test(line)); + const linked = (await fs.lstat(path.join(cwd, ".git")).catch(() => null))?.isFile() ?? false; + const nested = linked ? await import("./nested-repository-worktrees.js") : null; + const scope = nested ? `refs/heads/${await nested.nestedWorktreeBranchPrefix(cwd)}` : "refs/remotes"; + const remotes = await gitText(cwd, ["for-each-ref", ...nested ? [`--count=${nested.OWNED_NESTED_REF_LIMIT + 1}`] : [], + "--format=%(objectname) %(refname)", scope], { signal }).catch(() => ""); + const remoteReflogs: string[] = []; + if (nested) { + if (remotes.split("\n").filter(Boolean).length > nested.OWNED_NESTED_REF_LIMIT) throw new Error("managed_checkout_local_tip_budget"); + for (const ref of remotes.split("\n").map((line) => line.split(" ")[1]).filter(Boolean)) { + remoteReflogs.push(...(await gitText(cwd, ["reflog", "show", "--format=%H", ref!], { signal }).catch(() => "")).split("\n").filter((line) => SHA.test(line)).map((sha) => `${sha} ${ref}`)); + } + } else { + remoteReflogs.push(...(await gitText(cwd, ["reflog", "show", "--all", "--format=%H %gD"], { signal }).catch(() => "")) + .split("\n").filter((line) => / refs\/remotes\//.test(line))); + } return createHash("sha256").update(JSON.stringify([reflog.split("\n").filter((line) => SHA.test(line)), SHA.test(original) ? original : null, remotes.split("\n").filter(Boolean), remoteReflogs])).digest("hex"); } diff --git a/server/src/services/git-workspace-restoration.ts b/server/src/services/git-workspace-restoration.ts index f71c1851e7c..5aacb475a80 100644 --- a/server/src/services/git-workspace-restoration.ts +++ b/server/src/services/git-workspace-restoration.ts @@ -18,7 +18,7 @@ import { ensureGitRestorePointCommit, validateGitRestorePointRef, type GitRestor import { getStorageService } from "../storage/index.js"; import type { StorageService } from "../storage/types.js"; import { PROJECT_REPOSITORIES_DIR } from "@paperclipai/adapter-utils/git-workspace-sync"; -import { forgetExpiredNestedRepositoryWorktree, nestedRepositoryBaseCandidates, readLinkedNestedCheckout, recordedNestedRepositoryBase, type LinkedNestedCheckout } from "./nested-repository-worktrees.js"; +import { OWNED_NESTED_REF_LIMIT, forgetExpiredNestedRepositoryWorktree, nestedRepositoryBaseCandidates, readLinkedNestedCheckout, recordedNestedRepositoryBase, type LinkedNestedCheckout } from "./nested-repository-worktrees.js"; const execFile = promisify(execFileCallback); const shaPattern = /^[a-f0-9]{40}$/; @@ -249,7 +249,6 @@ async function assertCommitMessageSaved(cwd: string, gitDir: string, signal?: Ab if (!saved.includes(message.trim())) throw new Error("uncommitted_git_message"); } -const OWNED_NESTED_REF_LIMIT = 64; async function ownedNestedRefs(linked: LinkedNestedCheckout, signal?: AbortSignal) { const refs = (await gitCacheCommand(linked.checkout, ["for-each-ref", `--count=${OWNED_NESTED_REF_LIMIT + 1}`, @@ -380,9 +379,13 @@ async function provenNestedWorktreeHistory(linked: LinkedNestedCheckout, repoUrl const covered = new Set([head, ...shas(await gitCacheCommand(checkout, ["reflog", "show", "--format=%H", "HEAD"], signal).catch(() => "")), ...shas(await gitCacheCommand(checkout, ["rev-parse", "--verify", "-q", "ORIG_HEAD^{commit}"], signal).catch(() => ""))]); - const owned = await ownedNestedRefs(linked, signal); + const allOwned = await ownedNestedRefs(linked, signal); + const remotePrefix = `refs/heads/${linked.branchPrefix}remotes/`; + const owned = allOwned.filter(([, ref]) => !ref.startsWith(remotePrefix)); + const remoteTracked = [...new Set([...allOwned.filter(([, ref]) => ref.startsWith(remotePrefix)).map(([sha]) => sha), + ...await ownedNestedReflogs(linked, allOwned.filter(([, ref]) => ref.startsWith(remotePrefix)), signal)])]; const recorded = new Set([...owned.map(([sha]) => sha), ...await ownedNestedReflogs(linked, owned, signal)]); - if (recorded.size + covered.size > MANAGED_CHECKOUT_LOCAL_TIP_LIMIT) throw new Error("managed_checkout_local_tip_budget"); + if (recorded.size + covered.size + remoteTracked.length > MANAGED_CHECKOUT_LOCAL_TIP_LIMIT) throw new Error("managed_checkout_local_tip_budget"); const current = (await gitCacheCommand(checkout, ["symbolic-ref", "--quiet", "HEAD"], signal).catch(() => "")).trim(); const otherTips = owned.filter(([, ref]) => ref !== current).map(([sha]) => sha); if (otherTips.length && await hasCommitsMissingUpstream(checkout, otherTips, repoUrl, resolveGitAuth, signal, [head])) { @@ -393,7 +396,9 @@ async function provenNestedWorktreeHistory(linked: LinkedNestedCheckout, repoUrl throw new Error("unpushed_managed_checkout_branches"); } const headOnRemote = !await hasCommitsMissingUpstream(checkout, [head], repoUrl, resolveGitAuth, signal); - return { headOnRemote, preserve: [] }; + const preserve = remoteTracked.length + ? await tipsMissingUpstream(checkout, remoteTracked, repoUrl, resolveGitAuth, signal, [...covered, ...recorded]) : []; + return { headOnRemote, preserve }; } async function tipsMissingUpstream(checkout: string, tips: string[], repoUrl: string, diff --git a/server/src/services/nested-repository-worktrees.ts b/server/src/services/nested-repository-worktrees.ts index 8a2969ec2f3..ad907159cc3 100644 --- a/server/src/services/nested-repository-worktrees.ts +++ b/server/src/services/nested-repository-worktrees.ts @@ -15,6 +15,7 @@ import { sanitizeRuntimeServiceBaseEnv } from "./runtime-service-env.js"; const execFile = promisify(execFileCallback); const NESTED_WORKTREE_GIT_TIMEOUT_MS = 10 * 60 * 1000; const NESTED_WORKTREE_BRANCH = /^paperclip\/[a-f0-9]{12}\/./; +export const OWNED_NESTED_REF_LIMIT = 64; export const DETACHED_REPOSITORIES_DIR = path.join(".paperclip-runtime", "detached-repositories"); export type LinkedNestedCheckout = { checkout: string; base: string; gitDir: string; admin: string; branchPrefix: string }; From e0855fe92ad02250d3a289543e6900a050ccf411 Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Sat, 24 Oct 2026 19:32:51 -0700 Subject: [PATCH 032/110] perf(wake-queue): narrow native release reads (#17539) Native wake-queue release reads omit saved profiles and excerpts. Legacy release reads keep their complete inputs. Ownership, cleanup, and file retention checks remain unchanged. Verified with 275 wake-queue tests, the full build, and typecheck. All CI checks pass. Greptile scored the exact head 5/5 with Medium impact and no unresolved comments. Co-Authored-By: Paperclip --- doc/native-workspace-finalization-recovery.md | 6 ++ .../wake-queue/adapters/postgres.test.ts | 9 ++- .../modules/wake-queue/adapters/postgres.ts | 27 +++---- .../adapters/release-run-read.test.ts | 74 +++++++++++++++++++ .../wake-queue/adapters/release-run-read.ts | 22 ++++++ 5 files changed, 117 insertions(+), 21 deletions(-) create mode 100644 server/src/modules/wake-queue/adapters/release-run-read.test.ts create mode 100644 server/src/modules/wake-queue/adapters/release-run-read.ts diff --git a/doc/native-workspace-finalization-recovery.md b/doc/native-workspace-finalization-recovery.md index 3d16ff3aada..51d174bb3e7 100644 --- a/doc/native-workspace-finalization-recovery.md +++ b/doc/native-workspace-finalization-recovery.md @@ -24,6 +24,12 @@ the native status wake identifier from each saved run. It keeps their JSON types and reads full evidence later where finalization or recovery needs it. Saved execution input, runner profiles, and logs stay in the stored run. +Wake-queue release reads keep complete context and result receipts. Native runs +omit runner profiles and log excerpts from this read; cleanup and execution +read their own current evidence. Legacy runs retain the full release row so +workspace-restore and pre-dispatch proofs keep their existing inputs. The +selection is one scoped database query for either runtime. + The recovery card names the original run and requires evidence that its exact allocation stopped and its files were recovered. Recording that evidence does not retry the old turn, certify unknown external actions, change the current task diff --git a/server/src/modules/wake-queue/adapters/postgres.test.ts b/server/src/modules/wake-queue/adapters/postgres.test.ts index 16479253a2f..6a8c360e22d 100644 --- a/server/src/modules/wake-queue/adapters/postgres.test.ts +++ b/server/src/modules/wake-queue/adapters/postgres.test.ts @@ -206,7 +206,7 @@ describeEmbeddedPostgres("wake-queue postgres adapter", () => { return { recorded, rows }; } - it("keeps in-flight work and every recovery receipt while omitting output from release reads", async () => { + it.each(["legacy", "native"])("keeps %s in-flight work and every recovery receipt while omitting output from release reads", async runtimeMode => { const companyId = await seedCompany(); const agentId = await seedAgent({ companyId }); const issueId = await seedIssue({ companyId, assigneeAgentId: agentId }); @@ -218,7 +218,9 @@ describeEmbeddedPostgres("wake-queue postgres adapter", () => { nativeCancellation: { schema: "paperclip.native-cancellation.v1", runId, companyId, issueId }, executionCancellation: { state: "acknowledged" }, executionRecovery: { kind: "interrupted", providerStopped: true }, configurationIncomplete: { reason: "workspace_unavailable" }, unknownFutureReceipt: { retained: true } }; - await db.update(heartbeatRuns).set({ resultJson: { ...evidence, stdout: payload.repeat(3), stderr: payload } }).where(eq(heartbeatRuns.id, runId)); + await db.update(heartbeatRuns).set({ runtimeMode, + ...(runtimeMode === "native" ? { runnerProfileJson: { savedInput: payload }, stdoutExcerpt: payload, stderrExcerpt: payload } : {}), + resultJson: { ...evidence, stdout: payload.repeat(3), stderr: payload } }).where(eq(heartbeatRuns.id, runId)); await db.update(issues).set({ executionRunId: runId, checkoutRunId: runId }).where(eq(issues.id, issueId)); const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)); const [issue] = await db.select().from(issues).where(eq(issues.id, issueId)); @@ -230,7 +232,8 @@ describeEmbeddedPostgres("wake-queue postgres adapter", () => { ); expect(result.outcome.kind).toBe("released"); expect(rows).toHaveLength(1); - expect(rows[0]).toEqual([{ ...run, resultJson: evidence }]); + expect(rows[0]).toEqual([{ ...run, resultJson: evidence, + ...(runtimeMode === "native" ? { runnerProfileJson: null, stdoutExcerpt: null, stderrExcerpt: null } : {}) }]); expect(Buffer.byteLength(JSON.stringify(rows))).toBeLessThan(8 * 1024); expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)))[0]).toEqual(run); expect((await db.select().from(issues).where(eq(issues.id, issueId)))[0]).toEqual(issue); diff --git a/server/src/modules/wake-queue/adapters/postgres.ts b/server/src/modules/wake-queue/adapters/postgres.ts index 6db54a82725..cd2f1aa7a48 100644 --- a/server/src/modules/wake-queue/adapters/postgres.ts +++ b/server/src/modules/wake-queue/adapters/postgres.ts @@ -5,7 +5,8 @@ import { isCompletedOnboardingHandoffWake } from "../../../services/chat-complet import { instanceSettingsService } from "../../../services/instance-settings.js"; import { currentConversationCommentCondition } from "../../../services/agent-conversations.js"; import { getExecutionBlocker, hasPendingRunCleanup } from "../../../services/execution-blocker.js"; -import { and, asc, eq, getTableColumns, inArray, isNull, notInArray, or, sql } from "drizzle-orm"; +import { and, asc, eq, inArray, isNull, notInArray, or, sql } from "drizzle-orm"; +import { readReleaseRun, type ReleaseRun } from "./release-run-read.js"; import type { Db } from "@paperclipai/db"; import { extractIssueReferenceIdentifiers, isUuidLike } from "@paperclipai/shared"; import { @@ -74,14 +75,6 @@ const EXECUTION_PATH_HEARTBEAT_RUN_STATUSES = ["queued", "running", "scheduled_r type HeartbeatRunRow = typeof heartbeatRuns.$inferSelect; type IssueRow = typeof issues.$inferSelect; -const releaseRunFields = { - ...getTableColumns(heartbeatRuns), - resultJson: sql | null>`case - when jsonb_typeof(${heartbeatRuns.resultJson}) = 'object' - then ${heartbeatRuns.resultJson} - 'stdout' - 'stderr' - else ${heartbeatRuns.resultJson} end`, -}; - function normalizeAgentNameKey(value: string | null | undefined): string | null { if (typeof value !== "string") return null; const normalized = value.trim().toLowerCase(); @@ -94,7 +87,7 @@ function toRequestedByActorType(value: string | null): "user" | "agent" | "syste return value === "user" || value === "agent" || value === "system" ? value : null; } -function toRunSnapshot(row: HeartbeatRunRow): RunSnapshot { +function toRunSnapshot(row: ReleaseRun): RunSnapshot { const configurationIncompletePayload = parseObject(parseObject(row.resultJson).configurationIncomplete); return { id: row.id, @@ -206,7 +199,7 @@ function buildHost(_tx: Db, deps: WakeQueuePostgresAdapterDeps): WakeQueueHost { }; } -function buildTransaction(tx: Db, deps: WakeQueuePostgresAdapterDeps, db: Db, run: HeartbeatRunRow): WakeQueueTransaction { +function buildTransaction(tx: Db, deps: WakeQueuePostgresAdapterDeps, db: Db, run: ReleaseRun): WakeQueueTransaction { const treeControlSvc = issueTreeControlService(tx); const issuesSvc = issueService(tx); const interruptQueueId = run.runtimeMode !== "native" && run.status === "cancelled" @@ -750,7 +743,7 @@ function buildTransaction(tx: Db, deps: WakeQueuePostgresAdapterDeps, db: Db, ru }; } -async function recordNativeTerminalRecoveryIfNeeded(tx: Db, run: HeartbeatRunRow, issue: IssueRow, now: Date): Promise { +async function recordNativeTerminalRecoveryIfNeeded(tx: Db, run: ReleaseRun, issue: IssueRow, now: Date): Promise { const applies = run.runtimeMode === "native" && ["failed", "timed_out", "interrupted", "cancelled"].includes(run.status) && @@ -1058,11 +1051,8 @@ export function createPostgresWakeQueueAdapter(db: Db, deps: WakeQueuePostgresAd async withIssueExecutionLock(input, fn): Promise { return db.transaction(async (rawTx) => { const tx = rawTx as unknown as Db; - const run = await tx - .select(releaseRunFields) - .from(heartbeatRuns) - .where(and(eq(heartbeatRuns.id, input.runId), eq(heartbeatRuns.companyId, input.companyId))) - .then((rows) => rows[0] ?? null); + const evidence = await readReleaseRun(tx, input); + const run = evidence.run; if (!run) { throw new Error(`wake-queue: run ${input.runId} was not found while releasing issue execution`); } @@ -1164,7 +1154,8 @@ export function createPostgresWakeQueueAdapter(db: Db, deps: WakeQueuePostgresAd issueStatus: issueRow?.status ?? "", hasAssigneeUser: Boolean(issueRow?.assigneeUserId), assigneeAgentMatchesRunAgent: issueRow?.assigneeAgentId === run.agentId, - legacyExecutionNeedsReconciliation: await legacyExecutionNeedsReconciliationWithEvidence(tx as unknown as Db, run), + legacyExecutionNeedsReconciliation: evidence.kind === "complete" && + await legacyExecutionNeedsReconciliationWithEvidence(tx as unknown as Db, evidence.run), // An operator stop never promotes old queued work by itself. The // next explicit wake adopts those messages atomically when it // queues a run. diff --git a/server/src/modules/wake-queue/adapters/release-run-read.test.ts b/server/src/modules/wake-queue/adapters/release-run-read.test.ts new file mode 100644 index 00000000000..e4129e6c692 --- /dev/null +++ b/server/src/modules/wake-queue/adapters/release-run-read.test.ts @@ -0,0 +1,74 @@ +import { randomBytes, randomUUID } from "node:crypto"; +import { agents, companies, createDb, heartbeatRuns } from "@paperclipai/db"; +import { createDatabaseResponseCapture, installDatabaseResponseCapture } from "@paperclipai/db/response-capture"; +import { eq } from "drizzle-orm"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../../__tests__/helpers/embedded-postgres.js"; +import { readReleaseRun } from "./release-run-read.js"; + +const support = await getEmbeddedPostgresTestSupport(); + +describe.skipIf(!support.supported)("wake release run reads", () => { + let database: Awaited>; + let db: ReturnType; + let companyId: string; + let agentId: string; + + beforeAll(async () => { + database = await startEmbeddedPostgresTestDatabase("wake-release-read-"); + db = createDb(database.connectionString); + const [company] = await db.insert(companies).values({ name: "Wake release fixture", issuePrefix: "WRR" }).returning(); + const [agent] = await db.insert(agents).values({ companyId: company.id, name: "Release agent", adapterType: "process" }).returning(); + companyId = company.id; + agentId = agent.id; + }, 60_000); + + afterAll(async () => { + await db?.$client.end(); + await database?.cleanup(); + }); + + it("omits native bulk at the driver boundary and preserves the complete legacy fallback", async () => { + const bulk = randomBytes(128 * 1024).toString("base64"); + const context = { issueId: randomUUID(), opaqueFutureContext: { savedInput: "keep this input" }, explicitUserContinuation: true }; + const evidence = { nativeCancellation: { schema: "paperclip.native-cancellation.v1", acknowledged: true }, unknownFutureReceipt: [true, null, 42] }; + const [before] = await db.insert(heartbeatRuns).values({ + companyId, agentId, runtimeMode: "native", status: "running", contextSnapshot: context, + runnerProfileJson: { nativeExecutionInput: { savedInput: bulk } }, stdoutExcerpt: bulk, stderrExcerpt: bulk, + resultJson: { ...evidence, stdout: bulk, stderr: bulk }, + }).returning(); + const scope = { companyId, runId: before.id }; + const events: Array> = []; + const now = Date.now(); + const capture = createDatabaseResponseCapture({ start: now - 100, end: now + 59_000 }, event => events.push(event)); + installDatabaseResponseCapture(db, { heartbeatRuns }, capture); + try { + const native = await db.transaction(tx => readReleaseRun(tx as unknown as typeof db, scope)); + expect(native.kind).toBe("native"); + expect(native.run?.contextSnapshot).toEqual(context); + expect(native.run?.resultJson).toEqual(evidence); + expect(native.run).not.toHaveProperty("runnerProfileJson"); + expect(native.run).not.toHaveProperty("stdoutExcerpt"); + expect(native.run).not.toHaveProperty("stderrExcerpt"); + } finally { capture.flush(); } + const summary = events.find(event => event.event === "paperclip.db_response_capture.summary.v1")!; + expect(summary.completedQueries).toBe(1); + expect(summary.responseValueBytes).toBeLessThan(8192); + expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, before.id)))[0]).toEqual(before); + expect(JSON.stringify(events)).not.toContain(bulk.slice(0, 64)); + await db.update(heartbeatRuns).set({ runtimeMode: "legacy" }).where(eq(heartbeatRuns.id, before.id)); + const legacy = await readReleaseRun(db, scope); + expect(legacy.kind).toBe("complete"); + expect(legacy.run).toEqual({ ...before, runtimeMode: "legacy", resultJson: evidence }); + expect((await readReleaseRun(db, { ...scope, companyId: randomUUID() })).run).toBeUndefined(); + expect((await readReleaseRun(db, { companyId, runId: randomUUID() })).run).toBeUndefined(); + }); + + it.each([null, ["stdout", { stderr: "evidence" }], "scalar", 42].map(result => ({ result })))( + "preserves non-object native result evidence $result", async ({ result }) => { + const [run] = await db.insert(heartbeatRuns).values({ companyId, agentId, runtimeMode: "native", + resultJson: result as Record | null }).returning(); + expect((await readReleaseRun(db, { companyId, runId: run.id })).run?.resultJson).toEqual(result); + }, + ); +}); diff --git a/server/src/modules/wake-queue/adapters/release-run-read.ts b/server/src/modules/wake-queue/adapters/release-run-read.ts new file mode 100644 index 00000000000..cc8bcf80388 --- /dev/null +++ b/server/src/modules/wake-queue/adapters/release-run-read.ts @@ -0,0 +1,22 @@ +import { heartbeatRuns, type Db } from "@paperclipai/db"; +import { and, eq, getTableColumns, sql } from "drizzle-orm"; + +type Run = typeof heartbeatRuns.$inferSelect; +export type ReleaseRun = Omit; + +export async function readReleaseRun(db: Db, scope: { companyId: string; runId: string }) { + const [selected] = await db.select({ + ...getTableColumns(heartbeatRuns), + runnerProfileJson: sql`case when ${heartbeatRuns.runtimeMode} = 'native' + then null else ${heartbeatRuns.runnerProfileJson} end`, + stdoutExcerpt: sql`case when ${heartbeatRuns.runtimeMode} = 'native' + then null else ${heartbeatRuns.stdoutExcerpt} end`, + stderrExcerpt: sql`case when ${heartbeatRuns.runtimeMode} = 'native' + then null else ${heartbeatRuns.stderrExcerpt} end`, + resultJson: sql`case when jsonb_typeof(${heartbeatRuns.resultJson}) = 'object' + then ${heartbeatRuns.resultJson} - 'stdout' - 'stderr' else ${heartbeatRuns.resultJson} end`, + }).from(heartbeatRuns).where(and(eq(heartbeatRuns.id, scope.runId), eq(heartbeatRuns.companyId, scope.companyId))); + if (!selected || selected.runtimeMode !== "native") return { kind: "complete" as const, run: selected }; + const { runnerProfileJson: _profile, stdoutExcerpt: _stdout, stderrExcerpt: _stderr, ...run } = selected; + return { kind: "native" as const, run }; +} From a12329b8a96208918a03a9f11be93a7319b21cb9 Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Sat, 24 Oct 2026 19:34:31 -0700 Subject: [PATCH 033/110] fix(db): complete bounded response attribution (#17537) Raise bounded database-response attribution to 2048 groups and add numbered 128-entry log pages. Preserve the overflow bucket and exact completed-call and byte totals. Document complete page retrieval and validation. Verified with 30 focused tests, the full build, and typecheck. All CI checks pass. Exact-head Greptile is 5/5 at Medium impact with no unresolved comments. Co-Authored-By: Paperclip --- doc/DATABASE.md | 21 +++++++++++++++++- packages/db/src/response-capture.test.ts | 27 ++++++++++++++++++++---- packages/db/src/response-capture.ts | 7 ++++-- 3 files changed, 48 insertions(+), 7 deletions(-) diff --git a/doc/DATABASE.md b/doc/DATABASE.md index 717ec1ca0ed..17fbb47f400 100644 --- a/doc/DATABASE.md +++ b/doc/DATABASE.md @@ -341,7 +341,7 @@ The diagnostic measures awaited Postgres.js `unsafe` responses before Drizzle column decoding. It retains the Drizzle builder caller for normal, prepared, transaction, and dedicated-pool execution. It issues no queries. It logs the public server caller locations, static schema table, operation, -query/row counts, and response value sizes. It emits at most 512 aggregate +query/row counts, and response value sizes. It emits at most 2,048 aggregate groups and a summary at the deadline. It never logs SQL, parameters, result values, connection strings, or query errors. In-flight queries continue normally. @@ -355,6 +355,25 @@ Look for `paperclip.db_response_capture.entry.v1` and can store `event` as a structured field instead of message text. Filter by that field or read the bounded window from the exact deployment. Check the summary and group totals, including the unattributed overflow group. + +Fetch a complete capture as follows: + +1. Read the summary events from the exact deployment and window. Keep each + distinct `captureId` separately. +2. Each entry has a unique `groupIndex` within that capture and a `groupPage`. + The summary gives `groupPageSize` (128) and `groupPages`. Fetch every page + from zero through `groupPages - 1`, filtering on the entry event, `captureId`, + and `groupPage`. Request at least `groupPageSize` matching records per page. + A structured query can use + `@event:paperclip.db_response_capture.entry.v1 AND @captureId: AND @groupPage:0`. +3. If the provider's record limit is smaller than a page, fetch each + `groupIndex` separately with the same capture ID. Each index matches one + entry. Do not split by timestamp: entries can share a timestamp. +4. Deduplicate by `(captureId, groupIndex)`. Require every index from zero + through `groups - 1`, with no gaps. Entry count must equal `groups`, summed + `calls` must equal `completedQueries`, and summed `responseValueBytes` must + equal the summary total. A missing page is an incomplete measurement. + Tagged raw-driver calls, streams, unawaited raw-driver dispatch, and protocol overhead are not measured. Relational queries use a driver-level caller fallback. Queries still in flight at the deadline are reported separately. Sizes describe diff --git a/packages/db/src/response-capture.test.ts b/packages/db/src/response-capture.test.ts index 4b87c7924a4..9fc1c80f5b1 100644 --- a/packages/db/src/response-capture.test.ts +++ b/packages/db/src/response-capture.test.ts @@ -107,12 +107,31 @@ describe("bounded database response capture", () => { }); it("bounds cardinality without dropping response-byte totals", () => { const f = fixture(); - for (let i = 0; i < 600; i += 1) f.capture.execute(() => [i], { ...metadata, callers: [`services/f${i}.ts:1:1`] }); + for (let i = 0; i < 2200; i += 1) f.capture.execute(() => [i], { ...metadata, callers: [`services/f${i}.ts:1:1`] }); f.capture.flush(); const summary = f.events.at(-1)!; - expect(summary).toMatchObject({ startedQueries: 600, completedQueries: 600, groups: 512, overflowCalls: 89 }); - expect(f.events).toHaveLength(513); - expect(summary.responseValueBytes).toBe(Array.from({ length: 600 }, (_, i) => Buffer.byteLength(JSON.stringify([i]))).reduce((a, b) => a + b, 0)); + expect(summary).toMatchObject({ startedQueries: 2200, completedQueries: 2200, groups: 2048, overflowCalls: 153, + groupPageSize: 128, groupPages: 16 }); + expect(f.events).toHaveLength(2049); + const entries = f.events.slice(0, -1); + expect(entries.map(entry => entry.groupIndex)).toEqual(Array.from({ length: 2048 }, (_, index) => index)); + for (let page = 0; page < 16; page += 1) { + expect(entries.filter(entry => entry.groupPage === page)).toHaveLength(128); + } + expect(entries.reduce((sum, entry) => sum + Number(entry.calls), 0)).toBe(2200); + expect(summary.responseValueBytes).toBe(Array.from({ length: 2200 }, (_, i) => Buffer.byteLength(JSON.stringify([i]))).reduce((a, b) => a + b, 0)); + }); + it.each([0, 129])("numbers every page including an empty or partial final page (%s)", count => { + const f = fixture(); + for (let index = 0; index < count; index += 1) { + f.capture.execute(() => [index], { ...metadata, callers: [`services/page${index}.ts:1:1`] }); + } + f.capture.flush(); + const entries = f.events.slice(0, -1), summary = f.events.at(-1)!; + expect(summary).toMatchObject({ groups: count, groupPageSize: 128, groupPages: Math.ceil(count / 128) }); + expect(entries.map(entry => entry.groupIndex)).toEqual(Array.from({ length: count }, (_, index) => index)); + expect(entries.filter(entry => entry.groupPage === 0)).toHaveLength(Math.min(count, 128)); + expect(entries.filter(entry => entry.groupPage === 1)).toHaveLength(Math.max(0, count - 128)); }); it("does not execute builders or prepared statements until requested", async () => { const f = fixture(), rows = [{ id: 1 }], execute = vi.fn(async () => rows); diff --git a/packages/db/src/response-capture.ts b/packages/db/src/response-capture.ts index f8e6da8e87a..675d57eeb82 100644 --- a/packages/db/src/response-capture.ts +++ b/packages/db/src/response-capture.ts @@ -7,6 +7,7 @@ type Entry = Metadata & { calls: number; rows: number; bytes: number; maxBytes: type Event = Record; type Method = (this: unknown, ...args: unknown[]) => unknown; export type ResponseCaptureWindow = { start: number; end: number }; +const GROUP_PAGE_SIZE = 128; export function responseCaptureWindow(value: string | undefined, now = Date.now()): ResponseCaptureWindow | undefined { if (!value) return; @@ -76,7 +77,8 @@ export function createDatabaseResponseCapture( clearTimeout(timer); scope.disable(); const ordered = [...entries.values()].sort((a, b) => b.bytes - a.bytes); - for (const entry of ordered) send({ event: "paperclip.db_response_capture.entry.v1", captureId: id, + for (const [groupIndex, entry] of ordered.entries()) send({ event: "paperclip.db_response_capture.entry.v1", captureId: id, + groupIndex, groupPage: Math.floor(groupIndex / GROUP_PAGE_SIZE), operation: entry.operation, table: entry.table, callers: entry.callers, calls: entry.calls, rows: entry.rows, responseValueBytes: entry.bytes, maxResponseValueBytes: entry.maxBytes, estimatedValues: entry.estimatedValues, queryErrors: entry.queryErrors, serializationErrors: entry.serializationErrors }); @@ -84,6 +86,7 @@ export function createDatabaseResponseCapture( windowStart: new Date(window.start).toISOString(), windowEnd: new Date(window.end).toISOString(), closedAt: new Date(now()).toISOString(), startedQueries: started, completedQueries: completed, inFlightAtEnd: inFlight, groups: entries.size, + groupPageSize: GROUP_PAGE_SIZE, groupPages: Math.ceil(ordered.length / GROUP_PAGE_SIZE), overflowCalls, responseValueBytes: ordered.reduce((sum, entry) => sum + entry.bytes, 0), rowValuesLogged: false, sqlOrParametersLogged: false, wireBytesMeasured: false, measurementBoundary: "postgres-js results before Drizzle column decoding", @@ -99,7 +102,7 @@ export function createDatabaseResponseCapture( completed += 1; try { let key = JSON.stringify(metadata); - if (!entries.has(key) && entries.size >= 511) { + if (!entries.has(key) && entries.size >= 2047) { overflowCalls += 1; metadata = { operation: "other", table: "other", callers: [] }; key = "overflow"; From 80c1261417a578393b5420ca8d6ec95d7efaf8e0 Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Sat, 24 Oct 2026 19:50:19 -0700 Subject: [PATCH 034/110] perf(recovery): decline native legacy checks before bulk reads (#17540) Decline native legacy-continuation checks before loading saved execution input. Preserve exact nonblank task bindings, skip reasons, complete legacy recovery inputs, company scope, and retry accounting. Verified with 105 recovery tests, the full build, and typecheck; the binding review fix passed 73 affected tests and server typecheck. CI is green and exact-head Greptile is 5/5 at Medium impact with no unresolved comments. Co-Authored-By: Paperclip --- doc/native-workspace-finalization-recovery.md | 7 ++ .../recovery/legacy-disposition-read.test.ts | 88 +++++++++++++++++++ .../recovery/legacy-disposition-read.ts | 24 +++++ server/src/services/recovery/service.ts | 11 ++- 4 files changed, 126 insertions(+), 4 deletions(-) create mode 100644 server/src/services/recovery/legacy-disposition-read.test.ts create mode 100644 server/src/services/recovery/legacy-disposition-read.ts diff --git a/doc/native-workspace-finalization-recovery.md b/doc/native-workspace-finalization-recovery.md index 51d174bb3e7..0875b177449 100644 --- a/doc/native-workspace-finalization-recovery.md +++ b/doc/native-workspace-finalization-recovery.md @@ -492,3 +492,10 @@ binding, and chat source fields under the existing nonblocking share lock. It excludes saved execution input, runner profiles, and log excerpts. Actual retry admission still reads the complete run and its recovery evidence. These reads preserve stored run data, source revocation checks, and JSON value types. + +Legacy continuation recovery rejects native runs before it loads their saved +execution input. The persisted disposition check reads only the task binding +for a native run. It keeps the same task-binding and native-finalization skip +reasons, including the original nonblank binding values. Native input and history +stay stored. Real legacy recovery still reads +its complete context, profile, excerpts, and required failure evidence. diff --git a/server/src/services/recovery/legacy-disposition-read.test.ts b/server/src/services/recovery/legacy-disposition-read.test.ts new file mode 100644 index 00000000000..749a7991879 --- /dev/null +++ b/server/src/services/recovery/legacy-disposition-read.test.ts @@ -0,0 +1,88 @@ +import { randomBytes, randomUUID } from "node:crypto"; +import { agents, companies, createDb, heartbeatRuns } from "@paperclipai/db"; +import { createDatabaseResponseCapture, installDatabaseResponseCapture } from "@paperclipai/db/response-capture"; +import { eq } from "drizzle-orm"; +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embedded-postgres.js"; +import { readLegacyDispositionSource } from "./legacy-disposition-read.js"; +import { recoveryService } from "./service.js"; + +const support = await getEmbeddedPostgresTestSupport(); + +describe.skipIf(!support.supported)("legacy disposition source reads", () => { + let database: Awaited>; + let db: ReturnType; + let companyId: string; + let agentId: string; + + beforeAll(async () => { + database = await startEmbeddedPostgresTestDatabase("legacy-disposition-read-"); + db = createDb(database.connectionString); + const [company] = await db.insert(companies).values({ name: "Legacy disposition fixture", issuePrefix: "LDF" }).returning(); + const [agent] = await db.insert(agents).values({ companyId: company.id, name: "Disposition agent", adapterType: "process" }).returning(); + companyId = company.id; + agentId = agent.id; + }, 60_000); + + afterAll(async () => { + await db?.$client.end(); + await database?.cleanup(); + }); + + it("declines native input below the byte budget and keeps complete legacy evidence", async () => { + const issueId = randomUUID(), bulk = randomBytes(128 * 1024).toString("base64"); + const context = { issueId, savedInput: bulk, executionRetryAccounting: { version: 1, failureRetries: 2, maxTurnContinuations: 1 } }; + const [before] = await db.insert(heartbeatRuns).values({ companyId, agentId, runtimeMode: "native", status: "succeeded", + contextSnapshot: context, runnerProfileJson: { savedInput: bulk }, stdoutExcerpt: bulk, stderrExcerpt: bulk, + errorCode: "adapter_failed", resultJson: { executionRecovery: { providerWorkStarted: true }, stdout: bulk } }).returning(); + const events: Array> = []; + const now = Date.now(); + const capture = createDatabaseResponseCapture({ start: now - 100, end: now + 59_000 }, event => events.push(event)); + installDatabaseResponseCapture(db, { heartbeatRuns }, capture); + try { + expect(await readLegacyDispositionSource(db, { companyId, issueId, runId: before.id })) + .toEqual({ kind: "skip", decision: { kind: "skip", reason: "native_finalization" } }); + } finally { capture.flush(); } + expect(events.at(-1)).toMatchObject({ completedQueries: 1, groups: 1 }); + expect(Number(events.at(-1)?.responseValueBytes)).toBeLessThan(1024); + expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, before.id)))[0]).toEqual(before); + expect(JSON.stringify(events)).not.toContain(bulk.slice(0, 64)); + await db.update(heartbeatRuns).set({ runtimeMode: "legacy" }).where(eq(heartbeatRuns.id, before.id)); + const legacy = await readLegacyDispositionSource(db, { companyId, issueId, runId: before.id }); + expect(legacy.kind).toBe("full"); + if (legacy.kind !== "full") throw new Error("expected complete legacy input"); + expect(legacy.run).toEqual({ ...before, runtimeMode: "legacy" }); + expect((await readLegacyDispositionSource(db, { companyId: randomUUID(), issueId, runId: before.id }))) + .toMatchObject({ kind: "full", run: undefined }); + }); + + it.each([ + { context: { issueId: " target " }, issueId: "target", reason: "invalid_issue_binding" }, + { context: { issueId: " ", taskId: "target" }, issueId: "target", reason: "native_finalization" }, + { context: { taskId: " target " }, issueId: "target", reason: "invalid_issue_binding" }, + { context: { issueId: 42, taskId: "target" }, issueId: "target", reason: "native_finalization" }, + { context: { issueId: "other", taskId: "target" }, issueId: "target", reason: "invalid_issue_binding" }, + { context: { issueId: null, taskId: false }, issueId: "target", reason: "invalid_issue_binding" }, + { context: null, issueId: "target", reason: "invalid_issue_binding" }, + ])("keeps native binding decisions for $context", async ({ context, issueId, reason }) => { + const [run] = await db.insert(heartbeatRuns).values({ companyId, agentId, runtimeMode: "native", contextSnapshot: context }).returning(); + expect(await readLegacyDispositionSource(db, { companyId, issueId, runId: run.id })) + .toEqual({ kind: "skip", decision: { kind: "skip", reason } }); + }); + + it("skips native continuation in SQL without loading or rewriting its saved input", async () => { + const bulk = randomBytes(128 * 1024).toString("base64"); + const [before] = await db.insert(heartbeatRuns).values({ companyId, agentId, runtimeMode: "native", status: "succeeded", + contextSnapshot: { issueId: randomUUID(), savedInput: bulk }, runnerProfileJson: { savedInput: bulk } }).returning(); + const enqueueWakeup = vi.fn(async () => { throw new Error("native work must not enter legacy recovery"); }); + const service = recoveryService(db, { enqueueWakeup }); + const events: Array> = [], now = Date.now(); + const capture = createDatabaseResponseCapture({ start: now - 100, end: now + 59_000 }, event => events.push(event)); + installDatabaseResponseCapture(db, { heartbeatRuns }, capture); + try { expect(await service.reconcileLegacyContinuation(before.id)).toBe("skipped"); } + finally { capture.flush(); } + expect(events.at(-1)).toMatchObject({ completedQueries: 1, responseValueBytes: 0 }); + expect(enqueueWakeup).not.toHaveBeenCalled(); + expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, before.id)))[0]).toEqual(before); + }); +}); diff --git a/server/src/services/recovery/legacy-disposition-read.ts b/server/src/services/recovery/legacy-disposition-read.ts new file mode 100644 index 00000000000..08f9204f491 --- /dev/null +++ b/server/src/services/recovery/legacy-disposition-read.ts @@ -0,0 +1,24 @@ +import { heartbeatRuns, type Db } from "@paperclipai/db"; +import { and, eq, getTableColumns, sql } from "drizzle-orm"; +import { recoveryRunResultColumn } from "./run-result-read.js"; + +export async function readLegacyDispositionSource( + db: Db, + scope: { companyId: string; issueId: string; runId: string }, +) { + const where = and(eq(heartbeatRuns.id, scope.runId), eq(heartbeatRuns.companyId, scope.companyId)); + const [native] = await db.select({ + issueId: sql`${heartbeatRuns.contextSnapshot}->'issueId'`, + taskId: sql`${heartbeatRuns.contextSnapshot}->'taskId'`, + }).from(heartbeatRuns).where(and(where, eq(heartbeatRuns.runtimeMode, "native"))).limit(1); + if (native) { + const bound = [native.issueId, native.taskId] + .map(value => typeof value === "string" && value.trim().length > 0 ? value : null).find(Boolean) ?? null; + return { kind: "skip" as const, decision: { + kind: "skip" as const, reason: bound === scope.issueId ? "native_finalization" : "invalid_issue_binding", + } }; + } + const [run] = await db.select({ ...getTableColumns(heartbeatRuns), resultJson: recoveryRunResultColumn }) + .from(heartbeatRuns).where(where).limit(1); + return { kind: "full" as const, run }; +} diff --git a/server/src/services/recovery/service.ts b/server/src/services/recovery/service.ts index 331122e10d6..5701571e864 100644 --- a/server/src/services/recovery/service.ts +++ b/server/src/services/recovery/service.ts @@ -1,5 +1,6 @@ import { recoveryRunContextColumn, recoveryRunVersionColumn } from "./run-context-read.js"; import { recoveryRunResultColumn } from "./run-result-read.js"; +import { readLegacyDispositionSource } from "./legacy-disposition-read.js"; import { isAgentAwaitingSetup } from "../../modules/agent-lifecycle/index.js"; import { onboardingFirstTaskAwaitingUserSql } from "./onboarding-first-task-wait.js"; import { isAiAuthenticationBlocked } from "../ai-auth-failure.js"; @@ -3793,9 +3794,9 @@ export function recoveryService( episode: LegacyDispositionEpisode, dispatchRunId?: string, ) { - const [run] = await db.select(recoveryRunFields).from(heartbeatRuns).where(and( - eq(heartbeatRuns.id, runId), eq(heartbeatRuns.companyId, issue.companyId), - )).limit(1); + const source = await readLegacyDispositionSource(db, { companyId: issue.companyId, issueId: issue.id, runId }); + if (source.kind === "skip") return source.decision; + const run = source.run; if (!run) return { kind: "skip" as const, reason: "missing_run" }; const context = parseObject(run.contextSnapshot); if ((readNonEmptyString(context.issueId) ?? readNonEmptyString(context.taskId)) !== issue.id) { @@ -3854,7 +3855,9 @@ export function recoveryService( } async function reconcileLegacyContinuation(runId: string) { - const [run] = await db.select(recoveryRunFields).from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)).limit(1); + const [run] = await db.select(recoveryRunFields).from(heartbeatRuns).where(and( + eq(heartbeatRuns.id, runId), not(eq(heartbeatRuns.runtimeMode, "native")), eq(heartbeatRuns.status, "succeeded"), + )).limit(1); if (!run || run.runtimeMode === "native" || run.status !== "succeeded") return "skipped" as const; const context = parseObject(run.contextSnapshot); const issueId = readNonEmptyString(context.issueId) ?? readNonEmptyString(context.taskId); From 2f637fe8c49b5ad0276c3d23e9003859d311ffb5 Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Sat, 24 Oct 2026 20:05:45 -0700 Subject: [PATCH 035/110] perf(tools): scope connection readiness assignment reads (#17541) Connection readiness reads current permitted connection identities without unrelated catalog rows or complete profile-rule payloads. Reuse profile precedence and selector logic, preserve full public/runtime summaries, and keep installed connections, identity checks, and gateway authorization current. Verified with 106 focused tests, the full build, and typecheck. The direct catalog inventory regression fails at 102 rows when the scope filter is removed and passes at two rows with the filter. One unrelated CI timing assertion differed by 1 ms; the exact local test and the single failed shard rerun passed on unchanged source. CI is green and exact-head Greptile is 5/5 at Medium impact with no unresolved comments. Co-Authored-By: Paperclip --- doc/DATABASE.md | 7 + .../tool-effective-assignments.test.ts | 49 +++++- server/src/services/connection-intents.ts | 4 +- .../tool-access/profiles/projection.ts | 10 +- .../tool-access/profiles/resolution.ts | 161 +++++++++++------- 5 files changed, 167 insertions(+), 64 deletions(-) diff --git a/doc/DATABASE.md b/doc/DATABASE.md index 17fbb47f400..aacf4f9f23d 100644 --- a/doc/DATABASE.md +++ b/doc/DATABASE.md @@ -471,6 +471,13 @@ bindings, selectors, exclusions, and installed connections on every call. The public effective-profile response continues to include complete tool schemas and annotations. +Connection readiness checks use a scoped assignment reader. It applies the same +current profile precedence, selectors, and exclusions to the candidate connection +IDs. The reader selects rule match fields and catalog identities. It does not +load rule conditions, catalog schemas, profile summaries, or the company-agent +list. Installed connections and later identity and gateway checks remain fresh. +Full effective-profile and effective-tool responses keep their complete shape. + ## Execution identity row locks Identity initialization, credential acquisition, and steering reconciliation lock diff --git a/server/src/__tests__/tool-effective-assignments.test.ts b/server/src/__tests__/tool-effective-assignments.test.ts index 2f69d9e62d0..13de5533fbf 100644 --- a/server/src/__tests__/tool-effective-assignments.test.ts +++ b/server/src/__tests__/tool-effective-assignments.test.ts @@ -1,10 +1,11 @@ -import { randomUUID } from "node:crypto"; +import { randomBytes, randomUUID } from "node:crypto"; import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest"; import { eq, sql } from "drizzle-orm"; import { agents, companies, createDb, toolApplications, toolCatalogEntries, toolConnections, toolProfileBindings, toolProfileEntries, toolProfiles, type Db, } from "@paperclipai/db"; +import { createDatabaseResponseCapture, installDatabaseResponseCapture } from "@paperclipai/db/response-capture"; import { toolAccessService } from "../services/tool-access.js"; import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; @@ -49,6 +50,11 @@ describeDatabase("effective tool assignments", () => { expect(assignments).toEqual({ ...full, allowedTools: full.allowedTools.map( ({ id, applicationId, connectionId, toolName }) => ({ id, applicationId, connectionId, toolName }), ) }); + const connections = await service.getConnectionAssignmentsForAgent(f.company.id, f.agent.id, [f.connection.id]); + expect(connections).toEqual({ + installedConnections: full.installedConnections, + allowedConnectionIds: [...new Set(full.allowedTools.filter(tool => tool.connectionId === f.connection.id).map(tool => tool.connectionId))], + }); return { service, full, assignments }; } @@ -130,4 +136,45 @@ describeDatabase("effective tool assignments", () => { expect(observed[1].bytes).toBeLessThan(observed[0].bytes / 100); expect(full.allowedTools[0].inputSchema).toEqual(f.read.inputSchema); }); + it("scopes catalog reads, omits rule payloads, and keeps current full definitions", async () => { + const f = await fixture(); + const bulk = randomBytes(128 * 1024).toString("base64"); + const [rule] = await db.insert(toolProfileEntries).values({ companyId: f.company.id, profileId: f.profile.id, + selectorType: "application", effect: "include", applicationId: f.application.id, conditions: { savedRuleMetadata: bulk } }).returning(); + const [unrelated] = await db.insert(toolConnections).values({ companyId: f.company.id, applicationId: f.application.id, + name: "Other connection", uid: randomUUID(), transport: "mcp_remote", status: "active", enabled: true }).returning(); + await db.insert(toolCatalogEntries).values(Array.from({ length: 100 }, (_, index) => ({ companyId: f.company.id, + applicationId: f.application.id, connectionId: unrelated.id, name: `other_${index}`, toolName: `other_${index}`, versionHash: `v${index}` }))); + const service = toolAccessService(db); + const before = await service.getEffectiveToolAssignmentsForAgent(f.company.id, f.agent.id); + expect(before.allowedTools).toHaveLength(102); + const events: Array> = [], now = Date.now(); + const capture = createDatabaseResponseCapture({ start: now - 100, end: now + 59_000 }, event => events.push(event)); + installDatabaseResponseCapture(db, { toolCatalogEntries, toolProfileEntries }, capture); + let scoped: Awaited>; + try { scoped = await service.getConnectionAssignmentsForAgent(f.company.id, f.agent.id, [f.connection.id]); } + finally { capture.flush(); } + expect(Number(events.at(-1)?.completedQueries)).toBeGreaterThan(0); + expect(Number(events.at(-1)?.responseValueBytes)).toBeLessThan(16 * 1024); + const catalogQueries = events.filter(event => event.event === "paperclip.db_response_capture.entry.v1" + && event.table === "tool_catalog_entries" && event.operation === "select"); + expect(catalogQueries).toHaveLength(1); + expect(catalogQueries[0]).toMatchObject({ calls: 1, rows: 2 }); + expect(scoped!).toEqual({ allowedConnectionIds: [f.connection.id], installedConnections: before.installedConnections }); + expect(JSON.stringify(events)).not.toContain(bulk.slice(0, 64)); + expect((await db.select().from(toolProfileEntries).where(eq(toolProfileEntries.id, rule.id)))[0]).toEqual(rule); + expect(await service.getEffectiveToolAssignmentsForAgent(f.company.id, f.agent.id)).toEqual(before); + expect((await service.getConnectionAssignmentsForAgent(f.company.id, f.agent.id, [])).allowedConnectionIds).toEqual([]); + await db.delete(toolProfileBindings).where(eq(toolProfileBindings.profileId, f.profile.id)); + expect((await service.getConnectionAssignmentsForAgent(f.company.id, f.agent.id, [f.connection.id])).allowedConnectionIds).toEqual([]); + }); + + it("keeps other companies' catalog rows out of scoped assignments", async () => { + const f = await fixture(); + const other = await fixture(); + await db.update(toolProfiles).set({ defaultAction: "allow" }).where(eq(toolProfiles.id, f.profile.id)); + expect((await toolAccessService(db).getConnectionAssignmentsForAgent(f.company.id, f.agent.id, [other.connection.id])).allowedConnectionIds).toEqual([]); + await expect(toolAccessService(db).getConnectionAssignmentsForAgent(f.company.id, other.agent.id, [f.connection.id])).rejects.toThrow("same company"); + }); + }); diff --git a/server/src/services/connection-intents.ts b/server/src/services/connection-intents.ts index a6d07331c0c..77dabac142b 100644 --- a/server/src/services/connection-intents.ts +++ b/server/src/services/connection-intents.ts @@ -291,9 +291,9 @@ export function connectionIntentService(db: Db) { && connection.status !== "archived" && connection.connectionPurpose !== "ai" ); if (matching.length === 0) return null; - const effective = await access.getEffectiveToolAssignmentsForAgent(input.companyId, input.agentId); + const effective = await access.getConnectionAssignmentsForAgent(input.companyId, input.agentId, matching.map(connection => connection.id)); const installedIds = new Set(effective.installedConnections.map((connection) => connection.id)); - const permittedIds = new Set(effective.allowedTools.map((tool) => tool.connectionId)); + const permittedIds = new Set(effective.allowedConnectionIds); const usable = (connection: ToolConnection | undefined) => connection && installedIds.has(connection.id) && permittedIds.has(connection.id) && connection.status === "active" && connection.enabled diff --git a/server/src/services/tool-access/profiles/projection.ts b/server/src/services/tool-access/profiles/projection.ts index 50b77ae3a79..53b92ef182f 100644 --- a/server/src/services/tool-access/profiles/projection.ts +++ b/server/src/services/tool-access/profiles/projection.ts @@ -80,9 +80,15 @@ export type ProfileApplication = Pick; +export type ProfileEntryMatch = Pick; + +export type ProfileCatalogMatch = Pick; + export function profileEntryMatchesCatalog( - entry: typeof toolProfileEntries.$inferSelect, - catalogEntry: ProfileCatalogEntry, + entry: ProfileEntryMatch, + catalogEntry: ProfileCatalogMatch, ): boolean { if (entry.selectorType === "application") return entry.applicationId === catalogEntry.applicationId; diff --git a/server/src/services/tool-access/profiles/resolution.ts b/server/src/services/tool-access/profiles/resolution.ts index 80aa6870681..3cc4d36df4b 100644 --- a/server/src/services/tool-access/profiles/resolution.ts +++ b/server/src/services/tool-access/profiles/resolution.ts @@ -3,20 +3,67 @@ import type { Db } from "@paperclipai/db"; import { agents, toolCatalogEntries, toolProfileBindings, toolProfileEntries, toolProfiles } from "@paperclipai/db"; import type { ToolCatalogEntry, ToolConnection, ToolProfileEffectiveSummary, ToolProfileWithDetails } from "@paperclipai/shared"; import { effectiveToolProfileBindings, profileIdsInBindingOrder } from "../../tool-profile-binding-precedence.js"; -import { buildProfileDetails, profileCatalogColumns, profileEntryMatchesCatalog, toProfileBinding, toProfileEntry, type ProfileCatalogEntry } from "./projection.js"; +import { buildProfileDetails, profileCatalogColumns, profileEntryMatchesCatalog, toProfileBinding, toProfileEntry, type ProfileCatalogEntry, type ProfileEntryMatch, type ProfileCatalogMatch } from "./projection.js"; type ProfileAssignmentDependencies = { assertOptionalAgent(companyId: string, agentId: string | null | undefined, label: string): Promise; resolveInstalledConnectionsForAgent(companyId: string, agentId: string): Promise; toCatalogEntry(row: typeof toolCatalogEntries.$inferSelect): ToolCatalogEntry; }; +function resolveCatalogAccess( + profiles: Array>, + entries: Array, + catalog: ProfileCatalogMatch[], +) { + const allowedCatalogIds = new Set(); + const allowedToolNames = new Set(); + const entriesByProfile = new Map(); + for (const entry of entries) { + const group = entriesByProfile.get(entry.profileId) ?? []; + group.push(entry); + entriesByProfile.set(entry.profileId, group); + } + for (const profile of profiles) { + const profileEntries = entriesByProfile.get(profile.id) ?? []; + const includes = profileEntries.filter( + (entry) => entry.effect === "include", + ); + const excludes = profileEntries.filter( + (entry) => entry.effect === "exclude", + ); + for (const catalogEntry of catalog) { + if ( + excludes.some((entry) => + profileEntryMatchesCatalog(entry, catalogEntry), + ) + ) + continue; + if ( + profile.defaultAction === "allow" || + includes.some((entry) => + profileEntryMatchesCatalog(entry, catalogEntry), + ) + ) { + allowedCatalogIds.add(catalogEntry.id); + allowedToolNames.add(catalogEntry.toolName); + } + } + for (const entry of includes.filter( + (item) => item.selectorType === "tool_name" && item.toolName, + )) { + const matchingExclude = excludes.some( + (item) => + item.selectorType === "tool_name" && + item.toolName === entry.toolName, + ); + if (!matchingExclude) allowedToolNames.add(entry.toolName!); + } + } + return { allowedCatalogIds, allowedToolNames }; +} + export function createToolProfileResolver(db: Db, { assertOptionalAgent, resolveInstalledConnectionsForAgent, toCatalogEntry }: ProfileAssignmentDependencies) { - async function resolveEffectiveProfiles( - companyId: string, - agentId: string, - loadCatalog: () => PromiseLike, - toAllowedTool: (entry: TEntry) => TAllowedTool, - ): Promise & { allowedTools: TAllowedTool[] }> { + async function readEffectiveProfileState(companyId: string, agentId: string) { await assertOptionalAgent( companyId, agentId, @@ -36,21 +83,8 @@ export function createToolProfileResolver(db: Db, { assertOptionalAgent, resolve binding.targetId === companyId) || (binding.targetType === "agent" && binding.targetId === agentId), ); - if (matchingBindings.length === 0) { - return { - agentId, - profiles: [], - entries: [], - bindings: [], - allowedTools: [], - allowedToolNames: [], - installedConnections: await resolveInstalledConnectionsForAgent( - companyId, - agentId, - ), - }; - } const candidateProfileIds = profileIdsInBindingOrder(matchingBindings); + if (candidateProfileIds.length === 0) return { bindings: [], activeProfiles: [] }; const candidateProfiles = await db .select() .from(toolProfiles) @@ -73,6 +107,16 @@ export function createToolProfileResolver(db: Db, { assertOptionalAgent, resolve .filter((profile): profile is typeof toolProfiles.$inferSelect => Boolean(profile && profile.status === "active"), ); + return { bindings, activeProfiles }; + } + + async function resolveEffectiveProfiles( + companyId: string, + agentId: string, + loadCatalog: () => PromiseLike, + toAllowedTool: (entry: TEntry) => TAllowedTool, + ): Promise & { allowedTools: TAllowedTool[] }> { + const { bindings, activeProfiles } = await readEffectiveProfileState(companyId, agentId); if (activeProfiles.length === 0) { return { agentId, @@ -114,44 +158,7 @@ export function createToolProfileResolver(db: Db, { assertOptionalAgent, resolve list.push(entry); entriesByProfile.set(entry.profileId, list); } - const allowedCatalogIds = new Set(); - const allowedToolNames = new Set(); - for (const profile of activeProfiles) { - const profileEntries = entriesByProfile.get(profile.id) ?? []; - const includes = profileEntries.filter( - (entry) => entry.effect === "include", - ); - const excludes = profileEntries.filter( - (entry) => entry.effect === "exclude", - ); - for (const catalogEntry of catalog) { - if ( - excludes.some((entry) => - profileEntryMatchesCatalog(entry, catalogEntry), - ) - ) - continue; - if ( - profile.defaultAction === "allow" || - includes.some((entry) => - profileEntryMatchesCatalog(entry, catalogEntry), - ) - ) { - allowedCatalogIds.add(catalogEntry.id); - allowedToolNames.add(catalogEntry.toolName); - } - } - for (const entry of includes.filter( - (item) => item.selectorType === "tool_name" && item.toolName, - )) { - const matchingExclude = excludes.some( - (item) => - item.selectorType === "tool_name" && - item.toolName === entry.toolName, - ); - if (!matchingExclude) allowedToolNames.add(entry.toolName!); - } - } + const { allowedCatalogIds, allowedToolNames } = resolveCatalogAccess(activeProfiles, entries, catalog); const agentIds = companyAgents.map((agent) => agent.id); const details: ToolProfileWithDetails[] = activeProfiles.map((profile) => buildProfileDetails({ @@ -182,7 +189,43 @@ export function createToolProfileResolver(db: Db, { assertOptionalAgent, resolve ), }; } + async function getConnectionAssignmentsForAgent(companyId: string, agentId: string, connectionIds: string[]) { + const { activeProfiles } = await readEffectiveProfileState(companyId, agentId); + if (activeProfiles.length === 0 || connectionIds.length === 0) { + return { allowedConnectionIds: [], installedConnections: await resolveInstalledConnectionsForAgent(companyId, agentId) }; + } + const [entries, catalog] = await Promise.all([ + db.select({ + profileId: toolProfileEntries.profileId, + effect: toolProfileEntries.effect, + selectorType: toolProfileEntries.selectorType, + applicationId: toolProfileEntries.applicationId, + connectionId: toolProfileEntries.connectionId, + catalogEntryId: toolProfileEntries.catalogEntryId, + toolName: toolProfileEntries.toolName, + riskLevel: toolProfileEntries.riskLevel, + }).from(toolProfileEntries).where(and( + eq(toolProfileEntries.companyId, companyId), inArray(toolProfileEntries.profileId, activeProfiles.map(profile => profile.id)), + )), + db.select({ + id: toolCatalogEntries.id, + applicationId: toolCatalogEntries.applicationId, + connectionId: toolCatalogEntries.connectionId, + toolName: toolCatalogEntries.toolName, + riskLevel: toolCatalogEntries.riskLevel, + }).from(toolCatalogEntries).where(and( + eq(toolCatalogEntries.companyId, companyId), eq(toolCatalogEntries.status, "active"), inArray(toolCatalogEntries.connectionId, connectionIds), + )), + ]); + const { allowedCatalogIds } = resolveCatalogAccess(activeProfiles, entries, catalog); + return { + allowedConnectionIds: [...new Set(catalog.filter(entry => allowedCatalogIds.has(entry.id)).map(entry => entry.connectionId))], + installedConnections: await resolveInstalledConnectionsForAgent(companyId, agentId), + }; + } + return { + getConnectionAssignmentsForAgent, getEffectiveProfilesForAgent: (companyId: string, agentId: string) => resolveEffectiveProfiles( companyId, From c8a6b4561bb679df1f507b819f9dc0f67e368473 Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Sat, 24 Oct 2026 20:18:23 -0700 Subject: [PATCH 036/110] perf(heartbeat): narrow native Stop evidence rechecks (#17544) Read current native Stop identity, acknowledgement, and process evidence without saved execution inputs, profiles, excerpts, or unrelated result data. Preserve the complete nested acknowledgement and every existing lease, remote-termination, process, ownership, and admission check. The physical-stop helper body is unchanged. Verified with 101 tests across the affected suites, the full build, and typecheck. The review fix passed 62 focused tests. Large valid saved inputs stay below 2 KB at the raw driver boundary; large malformed string and array results stay below 1 KB and remain stored. CI is green and exact-head Greptile is 5/5 at Medium impact with no unresolved comments. Co-Authored-By: Paperclip --- doc/native-workspace-finalization-recovery.md | 6 ++ .../src/services/acknowledged-native-stop.ts | 3 +- .../native-stop-evidence-read.test.ts | 93 +++++++++++++++++++ .../heartbeat/native-stop-evidence-read.ts | 20 ++++ server/src/services/heartbeat/run-control.ts | 3 +- 5 files changed, 123 insertions(+), 2 deletions(-) create mode 100644 server/src/services/heartbeat/native-stop-evidence-read.test.ts create mode 100644 server/src/services/heartbeat/native-stop-evidence-read.ts diff --git a/doc/native-workspace-finalization-recovery.md b/doc/native-workspace-finalization-recovery.md index 0875b177449..01e7a7031c4 100644 --- a/doc/native-workspace-finalization-recovery.md +++ b/doc/native-workspace-finalization-recovery.md @@ -499,3 +499,9 @@ for a native run. It keeps the same task-binding and native-finalization skip reasons, including the original nonblank binding values. Native input and history stay stored. Real legacy recovery still reads its complete context, profile, excerpts, and required failure evidence. + +The native Stop continuation recheck reads current run identity, the full Stop +acknowledgement receipt, and process identity. It does not load saved execution +input, runner profiles, excerpts, or unrelated result fields. Lease cleanup, +remote termination receipts, local process checks, task ownership, and admission +checks keep their existing behavior. Stored runs retain all of their data. diff --git a/server/src/services/acknowledged-native-stop.ts b/server/src/services/acknowledged-native-stop.ts index bb6b7fa74c3..9d07f7b61a7 100644 --- a/server/src/services/acknowledged-native-stop.ts +++ b/server/src/services/acknowledged-native-stop.ts @@ -37,7 +37,8 @@ export function isAcknowledgedNativeStop(run: Parameters) { if (!isAcknowledgedNativeStop(run)) return false; const leases = await db.select().from(environmentLeases).where(and( eq(environmentLeases.companyId, run.companyId), eq(environmentLeases.heartbeatRunId, run.id), diff --git a/server/src/services/heartbeat/native-stop-evidence-read.test.ts b/server/src/services/heartbeat/native-stop-evidence-read.test.ts new file mode 100644 index 00000000000..d53a5d4c417 --- /dev/null +++ b/server/src/services/heartbeat/native-stop-evidence-read.test.ts @@ -0,0 +1,93 @@ +import { randomBytes, randomUUID } from "node:crypto"; +import { heartbeatRuns, issues, type Db } from "@paperclipai/db"; +import { createDatabaseResponseCapture, installDatabaseResponseCapture } from "@paperclipai/db/response-capture"; +import { eq, sql } from "drizzle-orm"; +import { describe, expect, it, vi } from "vitest"; +import { isAcknowledgedNativeStop } from "../acknowledged-native-stop.js"; +import { callbacks, runControlPostgresSupport, setupRunControlDatabase } from "./__tests__/run-control-fixtures.js"; +import { readNativeStopExecutionEvidence } from "./native-stop-evidence-read.js"; +import { createHeartbeatRunControl } from "./run-control.js"; + +vi.mock("../local-service-supervisor.js", async importOriginal => ({ + ...await importOriginal(), + terminateLocalService: vi.fn(async () => undefined), +})); + +describe.skipIf(!runControlPostgresSupport.supported)("native Stop evidence reads", () => { + let db: Db; + const { fixture } = setupRunControlDatabase("native-stop-evidence-", value => { db = value; }); + + it("reads current receipts below the byte budget without changing saved data", async () => { + const { company, agent } = await fixture(); + const [issue] = await db.insert(issues).values({ companyId: company.id, title: "Stop evidence fixture" }).returning(); + const id = randomUUID(), bulk = randomBytes(128 * 1024).toString("base64"); + const receipt = { schema: "paperclip.native-cancellation.v1", runId: id, companyId: company.id, issueId: issue.id, + scope: "run", reasonCode: "cancellation_run_only", dispatchState: "acknowledged", dispatched: true, + intentAuditId: randomUUID(), acknowledgementAuditId: randomUUID(), futureProof: { version: 2 } }; + const result = { nativeCancellation: receipt, cancelledByActorType: "user", cancelledByUserId: randomUUID(), + stdout: bulk, stderr: bulk, futureExecutionEvidence: { savedInput: bulk } }; + const [before] = await db.insert(heartbeatRuns).values({ id, companyId: company.id, agentId: agent.id, + nativeIssueId: issue.id, runtimeMode: "native", status: "cancelled", processPid: 123, processGroupId: 456, + contextSnapshot: { savedInput: bulk }, runnerProfileJson: { savedInput: bulk }, stdoutExcerpt: bulk, + stderrExcerpt: bulk, resultJson: result }).returning(); + const events: Array> = [], now = Date.now(); + const capture = createDatabaseResponseCapture({ start: now - 100, end: now + 59_000 }, event => events.push(event)); + installDatabaseResponseCapture(db, { heartbeatRuns }, capture); + let evidence: Awaited>; + try { evidence = await readNativeStopExecutionEvidence(db, company.id, id); } + finally { capture.flush(); } + expect(evidence!).toEqual({ id, companyId: company.id, nativeIssueId: issue.id, status: "cancelled", processPid: 123, + processGroupId: 456, resultJson: { nativeCancellation: receipt, cancelledByActorType: "user", cancelledByUserId: result.cancelledByUserId } }); + expect(isAcknowledgedNativeStop(evidence!)).toBe(true); + expect(events.at(-1)).toMatchObject({ completedQueries: 1, groups: 1 }); + expect(Number(events.at(-1)?.responseValueBytes)).toBeLessThan(2048); + expect(JSON.stringify(events)).not.toContain(bulk.slice(0, 64)); + expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, id)))[0]).toEqual(before); + await db.update(heartbeatRuns).set({ resultJson: { ...result, nativeCancellation: { ...receipt, dispatchState: "pending" } } }) + .where(eq(heartbeatRuns.id, id)); + expect(isAcknowledgedNativeStop((await readNativeStopExecutionEvidence(db, company.id, id))!)).toBe(false); + expect(await readNativeStopExecutionEvidence(db, randomUUID(), id)).toBeNull(); + expect(await readNativeStopExecutionEvidence(db, company.id, randomUUID())).toBeNull(); + }); + + it.each([null, [], false, 42, "not a receipt", { nativeCancellation: null }, { nativeCancellation: { dispatched: "true" } }])( + "keeps malformed receipts fail-closed: %j", async result => { + const { company, agent } = await fixture(); + const [run] = await db.insert(heartbeatRuns).values({ companyId: company.id, agentId: agent.id, + runtimeMode: "native", status: "cancelled" }).returning(); + await db.execute(sql`update ${heartbeatRuns} set result_json = ${JSON.stringify(result)}::jsonb where id = ${run.id}`); + expect(isAcknowledgedNativeStop((await readNativeStopExecutionEvidence(db, company.id, run.id))!)).toBe(false); + }, + ); + + it.each(["string", "array"])("does not transfer a large malformed %s result", async kind => { + const { company, agent } = await fixture(); + const bulk = randomBytes(128 * 1024).toString("base64"); + const saved = kind === "array" ? [bulk] : bulk; + const [run] = await db.insert(heartbeatRuns).values({ companyId: company.id, agentId: agent.id, + runtimeMode: "native", status: "cancelled" }).returning(); + await db.execute(sql`update ${heartbeatRuns} set result_json = ${JSON.stringify(saved)}::jsonb where id = ${run.id}`); + const events: Array> = [], now = Date.now(); + const capture = createDatabaseResponseCapture({ start: now - 100, end: now + 59_000 }, event => events.push(event)); + installDatabaseResponseCapture(db, { heartbeatRuns }, capture); + try { + const evidence = await readNativeStopExecutionEvidence(db, company.id, run.id); + expect(evidence?.resultJson).toBeNull(); + expect(isAcknowledgedNativeStop(evidence!)).toBe(false); + } finally { capture.flush(); } + expect(events.at(-1)).toMatchObject({ completedQueries: 1, groups: 1 }); + expect(Number(events.at(-1)?.responseValueBytes)).toBeLessThan(1024); + expect((await db.select({ result: heartbeatRuns.resultJson }).from(heartbeatRuns).where(eq(heartbeatRuns.id, run.id)))[0].result).toEqual(saved); + }); + + it("uses the scoped receipt reader for the native continuation recheck", async () => { + const { company, agent } = await fixture(); + const [issue] = await db.insert(issues).values({ companyId: company.id, title: "Native continuation fixture" }).returning(); + const [run] = await db.insert(heartbeatRuns).values({ companyId: company.id, agentId: agent.id, + nativeIssueId: issue.id, runtimeMode: "native", status: "succeeded" }).returning(); + const deps = callbacks(db); + const control = createHeartbeatRunControl(db, deps); + await control.resumeRemoteStopComments(run); + expect(deps.getRun).not.toHaveBeenCalled(); + }); +}); diff --git a/server/src/services/heartbeat/native-stop-evidence-read.ts b/server/src/services/heartbeat/native-stop-evidence-read.ts new file mode 100644 index 00000000000..6ee776bf03f --- /dev/null +++ b/server/src/services/heartbeat/native-stop-evidence-read.ts @@ -0,0 +1,20 @@ +import { heartbeatRuns, type Db } from "@paperclipai/db"; +import { and, eq, sql } from "drizzle-orm"; + +export async function readNativeStopExecutionEvidence(db: Db, companyId: string, runId: string) { + const [run] = await db.select({ + id: heartbeatRuns.id, + companyId: heartbeatRuns.companyId, + nativeIssueId: heartbeatRuns.nativeIssueId, + status: heartbeatRuns.status, + processPid: heartbeatRuns.processPid, + processGroupId: heartbeatRuns.processGroupId, + resultJson: sql`case + when jsonb_typeof(${heartbeatRuns.resultJson}) = 'object' then ( + select coalesce(jsonb_object_agg(key, value), '{}'::jsonb) + from jsonb_each(${heartbeatRuns.resultJson}) + where key = any(array['nativeCancellation', 'cancelledByActorType', 'cancelledByUserId']) + ) else null end`, + }).from(heartbeatRuns).where(and(eq(heartbeatRuns.id, runId), eq(heartbeatRuns.companyId, companyId))).limit(1); + return run ?? null; +} diff --git a/server/src/services/heartbeat/run-control.ts b/server/src/services/heartbeat/run-control.ts index d7086c52508..b4ba5f0ddea 100644 --- a/server/src/services/heartbeat/run-control.ts +++ b/server/src/services/heartbeat/run-control.ts @@ -1,4 +1,5 @@ import { notifyEnvironmentCleanup } from "../environment-cleanup-notifications.js"; +import { readNativeStopExecutionEvidence } from "./native-stop-evidence-read.js"; import { readTaskRetryIntent, reconcileTaskChatRetryReceipts } from "../task-retry.js"; import { PROCESS_IDENTITY_RECORDED, PROCESS_START_REQUESTED, readNativeLocalProcessStop, recordedLocalExecutionStopped } from "../native-local-process-stop.js"; import { isHeartbeatRunTerminalStatus } from "./run-lifecycle.js"; @@ -522,7 +523,7 @@ export function createHeartbeatRunControl(db: Db, dependencies: HeartbeatRunCont !(await recordedLocalExecutionStopped(db, run))) return; const issueId = run.nativeIssueId ?? (typeof run.contextSnapshot?.issueId === "string" ? run.contextSnapshot.issueId : null); if (!issueId) return; - const currentRun = run.runtimeMode === "native" ? await getRun(run.id, { includeExecutionEvidence: true }) : null; + const currentRun = run.runtimeMode === "native" ? await readNativeStopExecutionEvidence(db, run.companyId, run.id) : null; const [coordinator] = currentRun ? await db.select({ phase: nativeRunFinalizations.phase, leaseOwner: nativeRunFinalizations.leaseOwner }).from(nativeRunFinalizations).where(and( eq(nativeRunFinalizations.companyId, run.companyId), eq(nativeRunFinalizations.runId, run.id), From 8a85d9d647b9081cf6b71c0635383edf542eed2e Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Sat, 24 Oct 2026 21:04:36 -0700 Subject: [PATCH 037/110] perf(heartbeat): coalesce repeated native stranded releases (#17547) Skip repeated successful native release checks for the same unchanged source within one recovery pass. Preserve every saved request, failure retry, cursor update, source change, legacy path, and current admission gate. Verified with 201 focused tests, 32 full-control queue cases, build and typecheck. Exact-head CI is green, Greptile is 5/5 with Low impact, and no review threads remain unresolved. Co-Authored-By: Paperclip --- doc/native-workspace-finalization-recovery.md | 8 ++ server/src/services/heartbeat/queue.test.ts | 130 ++++++++++++++++-- server/src/services/heartbeat/queue.ts | 8 +- 3 files changed, 137 insertions(+), 9 deletions(-) diff --git a/doc/native-workspace-finalization-recovery.md b/doc/native-workspace-finalization-recovery.md index 01e7a7031c4..c8353239234 100644 --- a/doc/native-workspace-finalization-recovery.md +++ b/doc/native-workspace-finalization-recovery.md @@ -505,3 +505,11 @@ acknowledgement receipt, and process identity. It does not load saved execution input, runner profiles, excerpts, or unrelated result fields. Lease cleanup, remote termination receipts, local process checks, task ownership, and admission checks keep their existing behavior. Stored runs retain all of their data. + +One periodic stranded-message pass coalesces successful native release checks +for the same company, task, source run, and current source row version. The release +path already drains that +task's queue through current admission checks. Each saved request still advances +its recovery cursor. Rejected attempts, changed source runs, and updated source evidence remain eligible, +and the next pass checks current state again. Legacy per-request handling stays +unchanged. Pending work is awaited before a source is marked checked. diff --git a/server/src/services/heartbeat/queue.test.ts b/server/src/services/heartbeat/queue.test.ts index 5a31b5ee131..ef889747669 100644 --- a/server/src/services/heartbeat/queue.test.ts +++ b/server/src/services/heartbeat/queue.test.ts @@ -1,12 +1,14 @@ import { claimNativeSessionResumptions } from "../native-runtime/native-finalization-reconciler.js"; import type { Db } from "@paperclipai/db"; import { agents, agentWakeupRequests, caseHandoffs, cases, companies, createDb, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, heartbeatRuns, issueComments, issues, nativeRunFinalizations } from "@paperclipai/db"; -import { eq, sql } from "drizzle-orm"; +import { eq, inArray, sql } from "drizzle-orm"; import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embedded-postgres.js"; import { createPostgresWakeQueueAdapter } from "../../modules/wake-queue/adapters/postgres.js"; import { createReleaseIssueExecution } from "../../modules/wake-queue/application/use-cases.js"; import { createHeartbeatQueue, type HeartbeatQueueDependencies } from "./queue.js"; +import { createHeartbeatRunControl } from "./run-control.js"; +import { callbacks as runControlCallbacks } from "./__tests__/run-control-fixtures.js"; import { createHeartbeatQueueTestDependencies as callbacks } from "../../__tests__/helpers/heartbeat-queue.js"; @@ -113,6 +115,116 @@ describe.skipIf(!support.supported)("heartbeat queue database wiring", () => { return { ...seeded, recipient, pending }; } + async function addStrandedMessages(seeded: Awaited>) { + const messages = [seeded.pending]; + for (let index = 0; index < 2; index++) { + const [comment] = await db.insert(issueComments).values({ companyId: seeded.company.id, issueId: seeded.issue.id, + body: `Additional saved feedback ${index}`, authorAgentId: seeded.agent.id }).returning(); + const [wake] = await db.insert(agentWakeupRequests).values({ companyId: seeded.company.id, agentId: seeded.recipient.id, + source: "automation", reason: "issue_execution_deferred", status: "deferred_issue_execution", + payload: { issueId: seeded.issue.id, _paperclipWakeContext: { issueId: seeded.issue.id, + wakeReason: "issue_comment_mentioned", wakeCommentIds: [comment.id] } } }).returning(); + messages.push(wake); + } + await db.update(agentWakeupRequests).set({ updatedAt: new Date(0) }).where(inArray(agentWakeupRequests.id, messages.map(row => row.id))); + return messages; + } + + async function expectSavedMessages(messages: Awaited>) { + const rows = await db.select().from(agentWakeupRequests).where(inArray(agentWakeupRequests.id, messages.map(row => row.id))); + expect(rows).toHaveLength(messages.length); + for (const before of messages) { + const row = rows.find(row => row.id === before.id)!; + expect(row).toMatchObject({ payload: before.payload, status: "deferred_issue_execution", runId: null, + finishedAt: null, error: null }); + expect(row.updatedAt.getTime()).toBeGreaterThan(0); + } + } + + it.each(["legacy", "native"])("keeps saved %s messages while avoiding repeated native source release", async runtimeMode => { + const seeded = await strandedMention(runtimeMode); + const messages = await addStrandedMessages(seeded); + const deps = callbacks(db), queue = createHeartbeatQueue(db, deps); + await queue.resumeQueuedRuns(); + expect(deps.releaseIssueExecutionAndPromote).toHaveBeenCalledTimes(runtimeMode === "native" ? 1 : 3); + await expectSavedMessages(messages); + await queue.resumeQueuedRuns(); + expect(deps.releaseIssueExecutionAndPromote).toHaveBeenCalledTimes(runtimeMode === "native" ? 2 : 6); + expect(deps.executeRun).not.toHaveBeenCalled(); + }); + + it("retries a rejected native release on the next saved message", async () => { + const seeded = await strandedMention("native"), messages = await addStrandedMessages(seeded); + const deps = callbacks(db); + deps.releaseIssueExecutionAndPromote.mockRejectedValueOnce(new Error("Fixture release remains pending")); + await createHeartbeatQueue(db, deps).resumeQueuedRuns(); + expect(deps.releaseIssueExecutionAndPromote).toHaveBeenCalledTimes(2); + await expectSavedMessages(messages); + expect(deps.executeRun).not.toHaveBeenCalled(); + }); + + it("joins the native release before it suppresses another message's duplicate check", async () => { + const seeded = await strandedMention("native"), messages = await addStrandedMessages(seeded); + const deps = callbacks(db); + let finish!: () => void; + deps.releaseIssueExecutionAndPromote.mockImplementationOnce(() => new Promise(resolve => { finish = resolve; })); + let settled = false; + const pending = createHeartbeatQueue(db, deps).resumeQueuedRuns().then(() => { settled = true; }); + try { + await vi.waitFor(() => expect(deps.releaseIssueExecutionAndPromote).toHaveBeenCalledTimes(1)); + expect(settled).toBe(false); + } finally { finish?.(); } + await pending; + expect(deps.releaseIssueExecutionAndPromote).toHaveBeenCalledTimes(1); + await expectSavedMessages(messages); + }); + + it("rechecks a different native source that completes during the pass", async () => { + const seeded = await strandedMention("native"), messages = await addStrandedMessages(seeded); + await db.update(heartbeatRuns).set({ createdAt: new Date(0) }).where(eq(heartbeatRuns.id, seeded.run.id)); + const deps = callbacks(db); + let nextId: string | undefined; + deps.releaseIssueExecutionAndPromote.mockImplementationOnce(async () => { + const [next] = await db.insert(heartbeatRuns).values({ companyId: seeded.company.id, agentId: seeded.agent.id, + runtimeMode: "native", nativeIssueId: seeded.issue.id, status: "succeeded", finishedAt: new Date(), + contextSnapshot: { issueId: seeded.issue.id } }).returning(); + nextId = next.id; + }); + await createHeartbeatQueue(db, deps).resumeQueuedRuns(); + expect(deps.releaseIssueExecutionAndPromote.mock.calls.map(([run]) => run.id)).toEqual([seeded.run.id, nextId]); + await expectSavedMessages(messages); + }); + + it("rechecks changed native evidence on the same source run", async () => { + const seeded = await strandedMention("native"), messages = await addStrandedMessages(seeded); + const deps = callbacks(db); + deps.releaseIssueExecutionAndPromote.mockImplementationOnce(async () => { + await db.update(heartbeatRuns).set({ resultJson: { observedReceipt: "new evidence" } }).where(eq(heartbeatRuns.id, seeded.run.id)); + }); + await createHeartbeatQueue(db, deps).resumeQueuedRuns(); + expect(deps.releaseIssueExecutionAndPromote).toHaveBeenCalledTimes(2); + expect(deps.releaseIssueExecutionAndPromote.mock.calls.map(([run]) => run.id)).toEqual([seeded.run.id, seeded.run.id]); + await expectSavedMessages(messages); + }); + + it("checks each unrelated native task in the same pass", async () => { + const seeded = await strandedMention("native"), firstMessages = await addStrandedMessages(seeded); + const [issue] = await db.insert(issues).values({ companyId: seeded.company.id, title: "Another saved task", status: "todo", assigneeAgentId: seeded.agent.id }).returning(); + const [run] = await db.insert(heartbeatRuns).values({ companyId: seeded.company.id, agentId: seeded.agent.id, + runtimeMode: "native", nativeIssueId: issue.id, status: "succeeded", finishedAt: new Date(), contextSnapshot: { issueId: issue.id } }).returning(); + const [comment] = await db.insert(issueComments).values({ companyId: seeded.company.id, issueId: issue.id, + body: "Other task feedback", authorAgentId: seeded.agent.id }).returning(); + const [pending] = await db.insert(agentWakeupRequests).values({ companyId: seeded.company.id, agentId: seeded.recipient.id, + source: "automation", reason: "issue_execution_deferred", status: "deferred_issue_execution", + payload: { issueId: issue.id, _paperclipWakeContext: { issueId: issue.id, wakeReason: "issue_comment_mentioned", wakeCommentIds: [comment.id] } } }).returning(); + const secondMessages = await addStrandedMessages({ ...seeded, issue, run, pending }); + const deps = callbacks(db); + await createHeartbeatQueue(db, deps).resumeQueuedRuns(); + expect(deps.releaseIssueExecutionAndPromote).toHaveBeenCalledTimes(2); + expect(new Set(deps.releaseIssueExecutionAndPromote.mock.calls.map(([row]) => row.id))).toEqual(new Set([seeded.run.id, run.id])); + await expectSavedMessages([...firstMessages, ...secondMessages]); + }); + it("rechecks a handoff's assignment version under the issue claim lock", async () => { const { company, agent, issue, wake, run } = await fixture("queued"); const [record] = await db.insert(cases).values({ companyId: company.id, caseNumber: 1, identifier: "QM-CASE-1", @@ -137,7 +249,9 @@ describe.skipIf(!support.supported)("heartbeat queue database wiring", () => { }); it.each(["legacy", "native"])("periodic recovery preserves a paused recipient through the real %s release adapter", async runtimeMode => { - const { company, issue, recipient, pending } = await strandedMention(runtimeMode); + const seeded = await strandedMention(runtimeMode); + const { company, issue, recipient } = seeded; + const messages = await addStrandedMessages(seeded); await db.update(agents).set({ status: "paused" }).where(eq(agents.id, recipient.id)); await db.update(issues).set({ status: "blocked" }).where(eq(issues.id, issue.id)); const deps = callbacks(db); @@ -146,16 +260,16 @@ describe.skipIf(!support.supported)("heartbeat queue database wiring", () => { getRoutineEnv: async () => ({ routineId: null, env: null, responsibleUserId: null }), resolveSessionBeforeForWakeup: async () => null, }), recovery: { escalateStrandedAssignedIssue: async () => undefined, escalateStrandedRecoveryIssueInPlace: async () => undefined } }); - deps.releaseIssueExecutionAndPromote.mockImplementation(async (run, options) => { - await release({ companyId: run.companyId, runId: run.id, now: new Date(), ...options }); - }); + const controlDeps = runControlCallbacks(db); + vi.mocked(controlDeps.wakeQueue.releaseIssueExecution).mockImplementation(release); + const control = createHeartbeatRunControl(db, controlDeps); + deps.releaseIssueExecutionAndPromote.mockImplementation(control.releaseIssueExecutionAndPromote); for (let pass = 0; pass < 2; pass++) { await createHeartbeatQueue(db, deps).resumeQueuedRuns(); - expect((await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, pending.id)))[0]) - .toMatchObject({ status: "deferred_issue_execution", runId: null, finishedAt: null, error: null, payload: pending.payload }); + await expectSavedMessages(messages); expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.companyId, company.id))).toHaveLength(1); } - expect(deps.releaseIssueExecutionAndPromote).toHaveBeenCalledTimes(2); + expect(deps.releaseIssueExecutionAndPromote).toHaveBeenCalledTimes(runtimeMode === "native" ? 2 : 6); expect(deps.executeRun).not.toHaveBeenCalled(); }); diff --git a/server/src/services/heartbeat/queue.ts b/server/src/services/heartbeat/queue.ts index 515bd683fb3..35ff18e6e88 100644 --- a/server/src/services/heartbeat/queue.ts +++ b/server/src/services/heartbeat/queue.ts @@ -1834,6 +1834,7 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende AND live_issue_run.status IN ('queued', 'running', 'scheduled_retry'))`, cutoff ? gte(agentWakeupRequests.requestedAt, cutoff) : undefined)) .orderBy(asc(agentWakeupRequests.updatedAt)).limit(50); + const releasedNativeSources = new Set(); for (const { wake } of strandedQueues) { if (!queuedCommentIdsFromWakePayload(wake.payload).length && !await readQueuedInteractionResponse(db, wake.companyId, String(wake.payload?.issueId), wake.payload)) continue; @@ -1845,6 +1846,7 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende startedAt: heartbeatRuns.startedAt, runtimeMode: heartbeatRuns.runtimeMode, errorCode: heartbeatRuns.errorCode, + sourceVersion: sql`${heartbeatRuns}.xmin::text`, }).from(heartbeatRuns).where(and( eq(heartbeatRuns.companyId, wake.companyId), sql`${heartbeatRuns.contextSnapshot}->>'issueId' = ${String(wake.payload?.issueId)}`, @@ -1855,6 +1857,8 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende )); if (!latest || !latest.finishedAt || !isHeartbeatRunTerminalStatus(latest.status)) continue; if (latest.runtimeMode !== "legacy" && latest.runtimeMode !== "native") continue; + const releaseSource = `${latest.companyId}:${String(wake.payload?.issueId)}:${latest.id}:${latest.sourceVersion}`; + if (latest.runtimeMode === "native" && releasedNativeSources.has(releaseSource)) continue; if (latest.runtimeMode === "legacy") { const cancelledAdmission = latest.status === "cancelled" && !latest.startedAt && latest.errorCode === "execution_reconciliation_required"; @@ -1864,7 +1868,9 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende }); } } - await releaseIssueExecutionAndPromote(latest, { suppressImmediateRecovery: true, resumeStrandedQueue: true }).catch(err => { + await releaseIssueExecutionAndPromote(latest, { suppressImmediateRecovery: true, resumeStrandedQueue: true }).then(() => { + if (latest.runtimeMode === "native") releasedNativeSources.add(releaseSource); + }).catch(err => { logger.warn({ err, queueId: wake.id }, "failed to promote stranded comments"); }); } From 2a9d527c68ab1d2e61b8408eed9a194603bddfca Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sat, 24 Oct 2026 21:05:45 -0700 Subject: [PATCH 038/110] fix: preserve native startup during controller restart (#17511) ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - The native runtime keeps a durable runner alive across controller restarts. > - A restart can begin while a provider session is still opening. > - The old controller fenced read-only run admission before it could publish that prepared session. > - Admission failure then closed the runner that shutdown needed to detach. > - This pull request lets only the existing startup finish admission within the bounded shutdown wait. > - The controller detaches that exact session before it can submit a turn. New work and state changes stay fenced. ## Linked Issues or Issue Description **What happened?** A controller restart during native provider startup could close the prepared runner with `native control-plane run admission failed`. Recovery then found no running process and placed the task in a reconciliation hold. The same admission path follows both fresh startup and replacement after a failed provider resume. **Expected behavior** Shutdown must detach the existing prepared session so the next controller can recover it through the normal identity checks. Shutdown must not admit a new executor, submit a turn, or override an explicit Stop. **Steps to reproduce** 1. Delay a native backend while it opens its provider session. 2. Request controller restart detachment for that run. 3. Let backend startup finish before the 30-second deadline. 4. Observe that read-only admission fails and shutdown reports the run as inactive instead of detached. **Additional context** Related work: #17073 handles remote process-monitor classification; #17459 handles macOS process fingerprints; #17097 covers broader hot upgrade recovery. This change fixes the startup admission fence. It does not relax process identity or provider launch-profile checks. ## What Changed - Separate the read-only admission guard from the guard on control-plane state changes. - Let shutdown await only the startup already registered for the run. Close its admission window when the wait ends. - Reject a new execution after its run is fenced for shutdown. - Detach the prepared session and exit before runtime-question attachment or provider turn submission. - If Stop is pending before or after publication, retain its exact cancellation acknowledgment and cleanup owner across authority reads and runtime-question attachment. - Share one 30-second admission/Stop-settlement deadline across the restart sweep. Report an unsettled run as pending while healthy runs continue hot-restart adoption. - Cover the real runtime and admission path, deadline expiry, new-start rejection, persisted binding checks, and write fences. - Document the bounded startup handoff in the restart ownership contract. ## Verification - Red: the new actual-runtime/admission regression failed on the previous code. Shutdown reported the run as inactive and did not detach it. - Red: review regressions reproduced detach before a post-publication Stop acknowledgment and an actual hot-restart preparation error when startup Stop cleanup timed out. - Green on `e10d0cb238`: 18 startup/restart tests passed, including Stop during authority reads and runtime-question attachment, the real recovery preparation and shutdown coordinator with a stalled Stop plus healthy peer, and the shared sweep deadline. The earlier 36-case Stop/restart selection also passed before this follow-up. - Both complete changed test files previously passed on head `8e9c2610fe`: 857 tests. They used real PostgreSQL 18 with a fresh database per fixture. An earlier local harness attempt reused one database and hit duplicate fixture keys; that harness was corrected before this complete pass. - Real PostgreSQL: 7 admission and revocation tests passed. These cover wrong runner identity, persisted binding mismatch, checkpoint/result rejection, and in-flight write revocation. The local test harness used a fresh Docker PostgreSQL 18 instance because macOS embedded Postgres exhausted the host semaphore limit. Only database provisioning was replaced; assertions and production port code were unchanged. - Transport safety acceptance: the current source transport controlled a real Linux ARM runner and a deterministic Codex test provider in a disposable Debian container. After startup, detach and generic cleanup preserved the process. A new controller authenticated the same PID and provider session. The provider log had exactly one session start and no turn start. Duplicate launch was forbidden, the retained workspace was unchanged, and no stop or suspend command was issued. - The Linux acceptance check tests the shared native transport safety contract. It is not a live Claude response, a hosted Daytona run, or recovery of the original task. Those remain unverified. No original task, sandbox, credentials, or permissions were changed. - `pnpm -r typecheck` and `pnpm build` passed before the review follow-up. Server typecheck passed on current head `e10d0cb238`; current-head CI also passed the full typecheck and build gates. - The full local `pnpm test:run` command was attempted, then stopped after repeated embedded PostgreSQL bootstrap setup failures. That broad local run is incomplete. The current-head four-file Docker PostgreSQL run passed 879 tests, with one existing warm-copy `claim-uncertain` case timing out and recovery failing to import because the temporary provisioning mock omitted a support export. The harness is corrected and affected cases are being rechecked. The timeout is unexplained; it is not being labeled an infrastructure failure. No assertions are skipped by the database provisioning replacement. - All 55 clean-host CI checks passed on current head `e10d0cb238` (2 conditional skips), including all general test shards and native runner verification. Greptile reviewed that exact head at 5/5 with no findings. The previous Paperclip review findings are addressed in [the review response](https://github.com/paperclipai/paperclip/pull/17511#issuecomment-6391520242); its new advisory review remains queued. ## Risks - Admission must stay read-only. All writes retain the original synchronous controller fence, and both admission checks still validate the exact persisted binding. - Startup that exceeds the 30-second shutdown wait still fails closed. It cannot claim a successful detach or start a turn. - No schema migration or provider configuration change is included. ## Model Used OpenAI Codex, based on GPT-6, with reasoning, repository tools, code execution, and test execution. The exact runtime 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 (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 --- doc/execution-semantics.md | 12 + .../native-session-executor.test.ts | 322 +++++++++++++++++- .../native-runtime/native-session-executor.ts | 79 ++++- .../paperclip-control-plane-port.test.ts | 32 ++ .../paperclip-control-plane-port.ts | 8 +- 5 files changed, 435 insertions(+), 18 deletions(-) diff --git a/doc/execution-semantics.md b/doc/execution-semantics.md index 8bc8886b075..b4d63b5687f 100644 --- a/doc/execution-semantics.md +++ b/doc/execution-semantics.md @@ -1683,6 +1683,18 @@ controller must recover it through the authenticated ownership checks. This preserves active work and queued messages without treating a server restart as user cancellation. +During controller shutdown, already registered provider startups share one +30-second sweep deadline to finish read-only run admission and publish their exact +sessions for detachment. Its company, run, session, runner and completion-contract binding +must still match persisted authority. The draining controller cannot checkpoint, +publish events, submit a turn or settle the run. A new startup after the shutdown +fence, or admission after the window expires, remains rejected. A Stop pending +before or after session publication keeps cancellation and cleanup with the +current owner. Shutdown waits for that owner only until the same sweep deadline; +it does not detach the session or submit a prompt while Stop is pending. An +unsettled owner remains explicitly pending for reconciliation. Its timeout does +not abort detachment of healthy sessions or trigger a global graceful drain. + Recovery restores a structured result proposal from the durable run events when its append survived but the active turn's session checkpoint did not. Advancing the replay cursor must preserve that proposal for the exact run, session, source, diff --git a/server/src/services/native-runtime/native-session-executor.test.ts b/server/src/services/native-runtime/native-session-executor.test.ts index ad754e8e84e..bfb1f4f309f 100644 --- a/server/src/services/native-runtime/native-session-executor.test.ts +++ b/server/src/services/native-runtime/native-session-executor.test.ts @@ -33,6 +33,7 @@ import { dirname, join } from "node:path"; import { heartbeatRuns, heartbeatRunEvents, + issueThreadInteractions, issues, nativeRunFinalizations, nativeRunResults, @@ -49,6 +50,7 @@ import { validatePrpStructuredRunResult, validatePrpEvent, parseNativeExecutionInput, + executeNativeSession, type NativeExecutionInputV1, type NativeExecutionInputV3, type NativeExecutionInput, @@ -343,6 +345,7 @@ import { executePaperclipNativeSession, detachNativeSessionsForRestart, NativeControllerDetachedForRestartError, + NativeCancellationPendingRecoveryError, getNativeSessionSteeringState, NativeSessionSteeringError, assertRemoteRunnerBuildMetadata, @@ -5695,6 +5698,10 @@ function leaseDb( agentId: boundExecution.binding.agentId, companyId: boundExecution.binding.companyId, nativeIssueId: boundExecution.binding.issueId, + nativeSessionId: boundExecution.session.normalizedSessionId ?? `session-${boundExecution.binding.runId}`, + runnerInstanceId: "runner", + completionContractId: boundExecution.completionContract.id, + completionContractSha256: boundExecution.completionContract.sha256, resultJson: runResultJson, runnerProfileJson, runtimeMode: "native", @@ -5892,6 +5899,306 @@ describe("native startup cancellation fence", () => { }); describe("native startup restart detachment", () => { + it("uses one admission deadline for the whole restart sweep", async () => { + const inputs = ["first", "second"].map(label => { + const input = structuredClone(execution); + input.binding.runId = `restart-shared-deadline-${label}`; + input.binding.agentId = `restart-shared-deadline-agent-${label}`; + return input; + }); + const releases: Array<() => void> = []; + const ready: Array> = []; + state.execute.mockReset(); + for (const _input of inputs) { + let started!: () => void; + ready.push(new Promise(resolve => { started = resolve; })); + const opening = new Promise(resolve => { releases.push(resolve); }); + state.execute.mockImplementationOnce(async () => { + started(); await opening; + throw new Error("startup fixture released"); + }); + } + const outcomes = inputs.map(input => executePaperclipNativeSession({ + db: leaseDb(input), execution: input, runnerInstanceId: "runner", + }).catch(error => error)); + await Promise.all(ready); + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "Date"] }); + const finished = vi.fn(); + const runIds = inputs.map(input => input.binding.runId); + const shutdown = detachNativeSessionsForRestart(runIds).then(finished); + try { + await vi.advanceTimersByTimeAsync(30_000); + expect(finished).toHaveBeenCalledWith({ detachedRunIds: [], inactiveRunIds: [], + unsupportedRunIds: [], pendingRunIds: runIds }); + } finally { + vi.useRealTimers(); releases.forEach(release => release()); + await Promise.all(outcomes); await shutdown; + } + }); + + it.each(["authority", "questions"])("keeps a post-publication Stop owner through %s attachment and restart", async (seam) => { + const restarting = structuredClone(execution); + restarting.binding.runId = `restart-stop-after-publication-${seam}`; + let published!: () => void, releaseRead!: () => void, acknowledgeStop!: () => void; + let cleaning!: () => void, releaseCleanup!: () => void; + const publication = new Promise(resolve => { published = resolve; }); + const read = new Promise(resolve => { releaseRead = resolve; }); + const receipt = new Promise(resolve => { acknowledgeStop = resolve; }); + const cleanupStarted = new Promise(resolve => { cleaning = resolve; }); + const cleanup = new Promise(resolve => { releaseCleanup = resolve; }); + const detach = vi.fn(async () => undefined); + const cancel = vi.fn(() => ({ cleanup: receipt })); + const submit = vi.fn(); + const db = leaseDb(restarting); + const select = db.select.bind(db); + db.select = ((fields?: Record) => { + if (seam === "authority" && fields && Object.keys(fields).length === 2 && "status" in fields && "resultJson" in fields) { + return { from: () => ({ where: () => ({ limit: () => { + published(); + return read.then(() => [{ status: "running", resultJson: {} }]); + } }) }) }; + } + if (seam === "questions" && !fields) { + const query = select(); + return { from: (table: unknown) => table === issueThreadInteractions + ? { where: () => ({ orderBy: () => { published(); return read.then(() => []); } }) } + : query.from(table as never) }; + } + return select(fields as never); + }) as typeof db.select; + state.execute.mockReset().mockImplementationOnce(async options => { + try { + await options.onSession({ detachControllerForRestart: detach, cancel, resolveRuntimeRequest: vi.fn() }); + submit(); + } finally { + cleaning(); + await cleanup; + await options.onSession(null); + } + }); + const outcome = executePaperclipNativeSession({ db, execution: restarting, runnerInstanceId: "runner" }).catch(error => error); + await publication; + const stopping = cancelNativeSession(restarting.binding.runId, "operator Stop after publication"); + const completed = vi.fn(); + const shutdown = detachNativeSessionsForRestart([restarting.binding.runId]).then(completed); + try { + releaseRead(); + await new Promise(resolve => setImmediate(resolve)); + expect(cancel).toHaveBeenCalledOnce(); + expect(detach).not.toHaveBeenCalled(); + expect(completed).not.toHaveBeenCalled(); + // Admission must not unwind into generic close while Stop awaits its ACK. + const cleanupObserved = vi.fn(); + void cleanupStarted.then(cleanupObserved); + await new Promise(resolve => setImmediate(resolve)); + expect(cleanupObserved).not.toHaveBeenCalled(); + acknowledgeStop(); + expect(await stopping).toBe(true); + await cleanupStarted; + expect(completed).not.toHaveBeenCalled(); + releaseCleanup(); + await outcome; + await shutdown; + expect(completed).toHaveBeenCalledWith(expect.objectContaining({ + detachedRunIds: [], inactiveRunIds: [restarting.binding.runId], pendingRunIds: [], + })); + expect(detach).not.toHaveBeenCalled(); + expect(submit).not.toHaveBeenCalled(); + } finally { + releaseRead(); acknowledgeStop(); releaseCleanup(); + await stopping; await outcome; await shutdown; + } + }); + + it.each(["startup", "active"])("keeps healthy hot-restart adoption when another %s Stop cleanup exceeds the sweep deadline", async (mode) => { + const { coordinateHeartbeatSchedulerShutdown } = await import("../../shutdown.js"); + const { createHeartbeatRecovery } = await import("../heartbeat/recovery.js"); + const { writeHotRestartIntent, readHotRestartIntent } = await import("../hot-restart.js"); + const home = await mkdtemp(join(tmpdir(), "native-restart-stop-sweep-")); + const previousHome = process.env.PAPERCLIP_HOME; + process.env.PAPERCLIP_HOME = home; + await writeHotRestartIntent({ previousServerPid: process.pid, previousServerIdentity: "test-controller" }); + const stoppingExecution = structuredClone(execution); + stoppingExecution.binding.runId = `restart-${mode}-stop-timeout`; + stoppingExecution.session.normalizedSessionId = "d371f9bb-6c46-44c6-9e3a-026fa9be0153"; + const healthyExecution = structuredClone(execution); + healthyExecution.binding.runId = `restart-healthy-with-${mode}-stopping-peer`; + healthyExecution.session.normalizedSessionId = "a8fa0cb8-9cf1-46b0-96f0-78518b15847e"; + healthyExecution.binding.agentId = "healthy-restart-agent"; + let stoppedReady!: () => void, healthyReady!: () => void; + let releaseStopped!: () => void, releaseHealthy!: () => void, opening!: () => void, open!: () => void; + const openingStarted = new Promise(resolve => { opening = resolve; }); + const openingGate = new Promise(resolve => { open = resolve; }); + const stopPublished = new Promise(resolve => { stoppedReady = resolve; }); + const healthyPublished = new Promise(resolve => { healthyReady = resolve; }); + const stoppedLifetime = new Promise(resolve => { releaseStopped = resolve; }); + const healthyLifetime = new Promise(resolve => { releaseHealthy = resolve; }); + const stoppedDetach = vi.fn(async () => undefined); + const healthyDetach = vi.fn(async () => undefined); + state.execute.mockReset() + .mockImplementationOnce(async options => { + opening(); await openingGate; + try { + await options.onSession({ detachControllerForRestart: stoppedDetach, cancel: () => ({ cleanup: Promise.resolve() }) }); + } finally { + stoppedReady(); await stoppedLifetime; + await options.onSession(null); + } + throw new Error("stopped owner settled"); + }) + .mockImplementationOnce(async options => { + await options.onSession({ detachControllerForRestart: healthyDetach }); + healthyReady(); await healthyLifetime; + await options.onSession(null); + throw new Error("healthy controller detached"); + }); + const stoppedOutcome = executePaperclipNativeSession({ db: leaseDb(stoppingExecution), execution: stoppingExecution, runnerInstanceId: "runner" }).catch(error => error); + await openingStarted; + const stopping = mode === "startup" ? cancelNativeSession(stoppingExecution.binding.runId, "Stop while opening") : null; + open(); + await stopPublished; + await stopping; + const healthyOutcome = executePaperclipNativeSession({ db: leaseDb(healthyExecution), execution: healthyExecution, runnerInstanceId: "runner" }).catch(error => error); + await healthyPublished; + if (mode === "active") await cancelNativeSession(stoppingExecution.binding.runId, "operator Stop after active admission"); + const snapshotRows = [stoppingExecution, healthyExecution].map(item => ({ + adapterType: "paperclip_runner", adapterConfig: {}, + run: { id: item.binding.runId, companyId: item.binding.companyId, agentId: item.binding.agentId, + runtimeMode: "native", nativeSessionId: item.session.normalizedSessionId, status: "running", contextSnapshot: {} }, + })); + const snapshotDb = { select: () => ({ from: () => ({ innerJoin: () => ({ where: async () => snapshotRows }) }) }) } as unknown as Db; + const { logger } = await import("../../middleware/logger.js"); + const logged = vi.spyOn(logger, "info").mockImplementation(() => undefined); + const recovery = createHeartbeatRecovery(snapshotDb, { + enterShutdown: vi.fn(), appendRunEvent: vi.fn(async () => undefined), + } as unknown as import("../heartbeat/recovery.js").HeartbeatRecoveryDependencies); + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "Date"] }); + const shutdown = coordinateHeartbeatSchedulerShutdown({ signal: "SIGTERM", + waitForHeartbeatSchedulerIdle: async () => undefined, + prepareHotRestartShutdown: recovery.prepareHotRestartShutdown, + }); + try { + // Wait for the real snapshot I/O before advancing its bounded sweep. + await vi.waitFor(() => expect(vi.getTimerCount()).toBeGreaterThan(0)); + await vi.advanceTimersByTimeAsync(30_000); + expect(await shutdown).toMatchObject({ hotRestart: { mode: "hot_restart", skipDrain: true }, preparationError: null }); + expect(logged).toHaveBeenCalledWith(expect.objectContaining({ detachedNativeSessions: { + detachedRunIds: [healthyExecution.binding.runId], inactiveRunIds: [], unsupportedRunIds: [], + pendingRunIds: [stoppingExecution.binding.runId], + } }), expect.any(String)); + expect((await readHotRestartIntent())?.shutdownSnapshot?.activeRuns.map(run => run.runId)) + .toEqual([stoppingExecution.binding.runId, healthyExecution.binding.runId]); + expect(stoppedDetach).not.toHaveBeenCalled(); + expect(healthyDetach).toHaveBeenCalledOnce(); + } finally { + vi.useRealTimers(); releaseStopped(); releaseHealthy(); + await stoppedOutcome; await healthyOutcome; await shutdown; + logged.mockRestore(); + if (previousHome === undefined) delete process.env.PAPERCLIP_HOME; + else process.env.PAPERCLIP_HOME = previousHome; + await rm(home, { recursive: true, force: true }); + } + }); + + it.each(["detach", "expired", "stop"])("bounds read-only startup admission during drain: %s", async (mode) => { + const expired = mode === "expired"; + const stopped = mode === "stop"; + const restarting = structuredClone(execution); + restarting.binding.runId = `restart-real-admission-${mode}`; + restarting.session.normalizedSessionId = "restart-real-admission-session"; + const identity = { ...restarting.binding, sessionId: restarting.session.normalizedSessionId }; + let release!: () => void, started!: () => void; + const opening = new Promise(resolve => { release = resolve; }); + const pending = new Promise(resolve => { started = resolve; }); + const detach = vi.fn(async () => undefined); + const close = vi.fn(async () => undefined); + const startTurn = vi.fn(); + let acknowledgeStop!: () => void; + const stopReceipt = new Promise(resolve => { acknowledgeStop = resolve; }); + const cancel = vi.fn(() => ({ cleanup: stopReceipt })); + const backend = { + descriptor: async () => ({ kind: "mock" as const, name: "startup-drain", version: "1", + capabilities: { resume: true, typedEvents: true, steering: false, interruption: true, structuredResult: true }, + runtimeContextCapabilities: { instructions: "native", skills: "native", mcp: "native" } }), + openSession: vi.fn(async () => { + started(); await opening; + return { identity: () => identity, detachControllerForRestart: detach, close, startTurn, cancel, + snapshot: async () => ({ sessionId: identity.sessionId, identity, backendKind: "mock" as const }), + }; + }), + }; + let runtimeError: unknown; + state.execute.mockReset().mockImplementationOnce(async options => { + try { return await executeNativeSession({ ...options, onSessionAdmission: undefined }); } catch (error) { runtimeError = error; throw error; } + }); + const outcome = executePaperclipNativeSession({ db: leaseDb(restarting), execution: restarting, + runnerInstanceId: "runner", backend: backend as never }).catch(error => error); + await Promise.race([pending, outcome.then(error => { throw runtimeError ?? error; })]); + const stopping = stopped ? cancelNativeSession(restarting.binding.runId, "operator Stop during startup") : null; + if (expired) vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); + const shutdown = detachNativeSessionsForRestart([restarting.binding.runId]).catch(error => error); + try { + if (expired) { + await vi.advanceTimersByTimeAsync(30_000); + expect(await shutdown).toMatchObject({ pendingRunIds: [restarting.binding.runId], detachedRunIds: [] }); + vi.useRealTimers(); + } else { + await new Promise(resolve => setImmediate(resolve)); + } + release(); + if (stopped) { + await vi.waitFor(() => expect(cancel).toHaveBeenCalledOnce()); + expect(detach).not.toHaveBeenCalled(); + acknowledgeStop(); + expect(await stopping).toBe(true); + } + expect(await outcome).toBeInstanceOf(NativeControllerDetachedForRestartError); + if (stopped) { + expect(await shutdown).toMatchObject({ detachedRunIds: [], inactiveRunIds: [restarting.binding.runId] }); + expect(detach).not.toHaveBeenCalled(); + } else if (expired) { + expect(detach).not.toHaveBeenCalled(); + expect(close).toHaveBeenCalledWith({ reason: "native control-plane run admission failed" }); + } else { + expect(await shutdown).toMatchObject({ detachedRunIds: [restarting.binding.runId], inactiveRunIds: [] }); + expect(detach).toHaveBeenCalledOnce(); + expect(close).not.toHaveBeenCalledWith({ reason: "native control-plane run admission failed" }); + } + expect(backend.openSession).toHaveBeenCalledOnce(); + expect(startTurn).not.toHaveBeenCalled(); + } finally { vi.useRealTimers(); release(); acknowledgeStop(); await stopping; await outcome; await shutdown; } + }); + it("bounds a pending startup Stop without detaching its cleanup owner", async () => { + const restarting = structuredClone(execution); + restarting.binding.runId = "restart-startup-stop-cleanup-timeout"; + let open!: () => void, started!: () => void, releaseCleanup!: () => void, cleaning!: () => void; + const opening = new Promise(resolve => { open = resolve; }); + const pending = new Promise(resolve => { started = resolve; }); + const cleanup = new Promise(resolve => { releaseCleanup = resolve; }); + const cleanupStarted = new Promise(resolve => { cleaning = resolve; }); + const detach = vi.fn(async () => undefined); + const cancel = vi.fn(() => ({ cleanup: Promise.resolve() })); + state.execute.mockReset().mockImplementationOnce(async options => { + started(); await opening; + try { await options.onSession({ detachControllerForRestart: detach, cancel }); } + finally { cleaning(); await cleanup; } + }); + const outcome = executePaperclipNativeSession({ db: leaseDb(restarting), execution: restarting, runnerInstanceId: "runner" }).catch(error => error); + await pending; + const stopping = cancelNativeSession(restarting.binding.runId, "operator Stop before restart"); + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); + const shutdown = detachNativeSessionsForRestart([restarting.binding.runId]).catch(error => error); + try { + open(); + await cleanupStarted; + expect(await stopping).toBe(true); + await vi.advanceTimersByTimeAsync(30_000); + expect(await shutdown).toMatchObject({ pendingRunIds: [restarting.binding.runId], detachedRunIds: [] }); + expect(detach).not.toHaveBeenCalled(); + expect(cancel).toHaveBeenCalledOnce(); + } finally { vi.useRealTimers(); open(); releaseCleanup(); await stopping; await outcome; await shutdown; } + }); + it("waits for a checkpointed governed settlement before relinquishing its controller", async () => { const restarting = structuredClone(execution); restarting.binding.runId = "restart-governed-settlement"; @@ -6033,7 +6340,7 @@ describe("native startup restart detachment", () => { const detached = detachNativeSessionsForRestart([restarting.binding.runId]).catch(error => error); if (exceedDeadline) { await vi.advanceTimersByTimeAsync(30_000); - expect(await detached).toMatchObject({ message: "native_restart_startup_not_ready" }); + expect(await detached).toMatchObject({ pendingRunIds: [restarting.binding.runId], detachedRunIds: [] }); vi.useRealTimers(); } else { release(); @@ -6049,18 +6356,13 @@ describe("native startup restart detachment", () => { } }); - it("remembers shutdown while the session is still opening and detaches its late publication", async () => { + it("rejects an entirely new startup after the run has been fenced for shutdown", async () => { const restarting = structuredClone(execution); - restarting.binding.runId = "restart-during-session-open"; - const detach = vi.fn(async () => undefined); + restarting.binding.runId = "restart-new-startup-after-drain"; await expect(detachNativeSessionsForRestart([restarting.binding.runId])).resolves.toMatchObject({ inactiveRunIds: [restarting.binding.runId] }); - state.execute.mockReset().mockImplementationOnce(async (options) => { - await options.onSession({ detachControllerForRestart: detach }); - expect(detach).toHaveBeenCalledOnce(); - await options.onSession(null); - throw new Error("detachment closed the old event stream"); - }); + state.execute.mockReset(); await expect(executePaperclipNativeSession({ db: leaseDb(restarting), execution: restarting, runnerInstanceId: "runner" })).rejects.toBeInstanceOf(NativeControllerDetachedForRestartError); + expect(state.execute).not.toHaveBeenCalled(); }); }); diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index cc03fcbfa56..ccf020f577b 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -227,6 +227,7 @@ import { type ActiveNativeSession = { session: NativeSession; cancelRequested: boolean; + cancellationSettled?: Promise; restartDetach?: Promise; }; @@ -264,6 +265,7 @@ type NativeSessionStartup = { promise: Promise; resolve: (session: ActiveNativeSession | null) => void; stopRequested?: boolean; + restartAdmissionPending?: boolean; cancellationSettled?: Promise; governedWait?: boolean; settled: Promise; @@ -272,13 +274,14 @@ type NativeSessionStartup = { const nativeSessionStartups = new Map(); function detachActiveNativeSessionForRestart(active: ActiveNativeSession) { - active.restartDetach ??= Promise.resolve().then(() => active.session.detachControllerForRestart!()); + active.restartDetach ??= active.session.detachControllerForRestart!(); return active.restartDetach; } async function waitForNativeSessionStartup( runId: string, timeoutError: () => Error = () => new Error("native_restart_startup_not_ready"), + timeoutMs = 30_000, ) { const startup = nativeSessionStartups.get(runId); if (!startup) return null; @@ -287,7 +290,7 @@ async function waitForNativeSessionStartup( return await Promise.race([ startup.promise, new Promise((_resolve, reject) => { - timer = setTimeout(() => reject(timeoutError()), 30_000); + timer = setTimeout(() => reject(timeoutError()), timeoutMs); }), ]); } finally { @@ -301,10 +304,13 @@ export async function detachNativeSessionsForRestart( detachedRunIds: string[]; inactiveRunIds: string[]; unsupportedRunIds: string[]; + pendingRunIds: string[]; }> { const detachedRunIds: string[] = []; const inactiveRunIds: string[] = []; const unsupportedRunIds: string[] = []; + const pendingRunIds: string[] = []; + const restartDeadline = Date.now() + 30_000; const settlementDeadline = Date.now() + 20_000; for (const runId of new Set(runIds)) { // A governed stop already revoked new work and is collecting terminal @@ -320,11 +326,48 @@ export async function detachNativeSessionsForRestart( } finally { clearTimeout(timer); } } nativeRunsDetachingForRestart.add(runId); - const active = activeNativeSessions.get(runId) ?? await waitForNativeSessionStartup(runId); + let active = activeNativeSessions.get(runId); + if (!active) { + // Only a startup registered before this fence may complete read-only + // admission. It must publish its exact session for detachment; writes and + // new turns remain revoked, including after the bounded wait expires. + const startup = nativeSessionStartups.get(runId); + if (startup && Date.now() >= restartDeadline) { + pendingRunIds.push(runId); + continue; + } + if (startup) startup.restartAdmissionPending = true; + try { + active = await waitForNativeSessionStartup(runId, undefined, Math.max(0, restartDeadline - Date.now())) ?? undefined; + } catch (error) { + if (!(error instanceof Error) || error.message !== "native_restart_startup_not_ready") throw error; + pendingRunIds.push(runId); + continue; + } finally { + if (startup) startup.restartAdmissionPending = false; + } + } if (!active) { inactiveRunIds.push(runId); continue; } + const stopping = nativeSessionStartups.get(runId); + if (stopping?.stopRequested || active.cancelRequested) { + // Stop owns cancellation and final cleanup, including after publication. + // A deadline leaves this run pending; it must not abort healthy adoption + // or claim that the transport/cleanup owner has settled. + let timer: ReturnType | undefined; + try { + const settled = stopping && await Promise.race([ + stopping.settled.then(() => true), + new Promise(resolve => { + timer = setTimeout(() => resolve(false), Math.max(0, restartDeadline - Date.now())); + }), + ]); + (settled ? inactiveRunIds : pendingRunIds).push(runId); + } finally { clearTimeout(timer); } + continue; + } if (active.session.detachControllerForRestart === undefined) { unsupportedRunIds.push(runId); continue; @@ -332,7 +375,7 @@ export async function detachNativeSessionsForRestart( await detachActiveNativeSessionForRestart(active); detachedRunIds.push(runId); } - return { detachedRunIds, inactiveRunIds, unsupportedRunIds }; + return { detachedRunIds, inactiveRunIds, unsupportedRunIds, pendingRunIds }; } const MAX_REMOTE_CHECKPOINT_ARCHIVE_BYTES = 64 * 1024 * 1024; const MAX_REMOTE_CHECKPOINT_EXPANDED_BYTES = 64 * 1024 * 1024; @@ -7230,6 +7273,7 @@ export async function cancelNativeSession( // Do not acknowledge a no-op Stop and let that owner submit a turn afterwards. const startup = runStop && !activeNativeSessions.has(runId) ? nativeSessionStartups.get(runId) : undefined; let settleStartupCancellation: (() => void) | undefined; + let settleActiveCancellation: (() => void) | undefined; if (startup) { startup.stopRequested = true; startup.cancellationSettled = new Promise(resolve => { settleStartupCancellation = resolve; }); @@ -7242,6 +7286,7 @@ export async function cancelNativeSession( dispatched = true; if (!active.cancelRequested) { active.cancelRequested = true; + active.cancellationSettled = new Promise(resolve => { settleActiveCancellation = resolve; }); try { if (active.session.cancel) { const cancellationAbort = new AbortController(); @@ -7451,6 +7496,7 @@ export async function cancelNativeSession( return { dispatched, decision, decisionId, auditId }; } finally { settleStartupCancellation?.(); + settleActiveCancellation?.(); } } @@ -7674,6 +7720,9 @@ export async function executePaperclipNativeSession(input: { } } const runId = input.execution.binding.runId; + if (nativeRunsDetachingForRestart.has(runId)) { + throw new NativeControllerDetachedForRestartError(); + } if (nativeSessionStartups.has(runId)) { throw new Error("native_session_supervisor_busy"); } @@ -8362,6 +8411,12 @@ async function executePaperclipNativeSessionWithinScope( throw new NativeControllerDetachedForRestartError(); } }; + const startupForAdmission = nativeSessionStartups.get(input.execution.binding.runId); + const assertRunAdmissionActive = () => { + if (startupForAdmission?.restartAdmissionPending + && nativeSessionStartups.get(input.execution.binding.runId) === startupForAdmission) return; + assertControllerActive(); + }; const controlPlane = new PaperclipControlPlanePort( input.db, { @@ -8378,6 +8433,7 @@ async function executePaperclipNativeSessionWithinScope( { privateKeyPem: input.runnerEnvironment?.PAPERCLIP_AGENT_PRIVATE_KEY, assertControllerActive, + assertRunAdmissionActive, onCommittedEvent: async (event) => { const textKind = !firstTokenRecorded ? observeDeliverableText(event) : null; if (textKind) { @@ -9220,6 +9276,13 @@ async function executePaperclipNativeSessionWithinScope( eq(heartbeatRuns.agentId, input.execution.binding.agentId), )).limit(1); const cancellation = record(currentRun?.resultJson?.nativeCancellation); + if (active.cancelRequested) { + // A Stop can acquire the published handle while the authority + // read above is in flight. Keep its ACK/cleanup owner before + // unwinding admission; neither detach nor generic close wins. + await active.cancellationSettled; + throw new NativeCancellationPendingRecoveryError(); + } if (!currentRun || currentRun.status !== "running" || currentRun.resultJson?.startupCancellation || (cancellation.scope === "run" && @@ -9229,11 +9292,15 @@ async function executePaperclipNativeSessionWithinScope( // callback fails; no provider turn may follow publication. throw new NativeCancellationPendingRecoveryError(); } - if (session.resolveRuntimeRequest) await liveQuestions.attach(); if (nativeRunsDetachingForRestart.has(input.execution.binding.runId)) { if (session.detachControllerForRestart) await detachActiveNativeSessionForRestart(active); + throw new NativeControllerDetachedForRestartError(); + } + if (session.resolveRuntimeRequest) await liveQuestions.attach(); + if (active.cancelRequested) { + await active.cancellationSettled; + throw new NativeCancellationPendingRecoveryError(); } - if (active.cancelRequested) throw new NativeCancellationPendingRecoveryError(); } else { liveQuestions.close(); activeNativeSessions.delete(input.execution.binding.runId); 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 5321a764f8b..f8b9eb1d022 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 @@ -300,6 +300,38 @@ describe("PaperclipControlPlanePort conformance", () => { } }); + it("permits only read-only admission while an existing startup drains", async () => { + const identity = { ...CONTROL_PLANE_CONFORMANCE_OPEN.identity, runId: randomUUID(), sessionId: randomUUID() }; + const runnerId = randomUUID(); + await db.insert(heartbeatRuns).values({ + id: identity.runId, companyId: identity.companyId, agentId: identity.agentId, + status: "running", runtimeMode: "native", nativeIssueId: identity.issueId, + nativeSessionId: identity.sessionId, runnerInstanceId: runnerId, + completionContractId: contractId, completionContractSha256: contractSha, + }); + let awaitingStartup = true; + const port = new PaperclipControlPlanePort(db, { + ...identity, completionContractId: contractId, completionContractSha256: contractSha, + sourceInstanceId: runnerId, controlPlaneSourceInstanceId: `draining-${identity.runId}`, + }, { + assertControllerActive: () => { throw new Error("controller_detached"); }, + assertRunAdmissionActive: () => { if (!awaitingStartup) throw new Error("controller_detached"); }, + }); + const open = { identity, backendKind: "mock" as const, sourceInstanceId: runnerId }; + await expect(port.openRun({ ...open, sourceInstanceId: randomUUID() })).rejects.toThrow("native_open_run_binding_mismatch"); + await db.update(heartbeatRuns).set({ runnerInstanceId: randomUUID() }).where(eq(heartbeatRuns.id, identity.runId)); + await expect(port.openRun(open)).rejects.toThrow("native_open_run_not_authorized"); + await db.update(heartbeatRuns).set({ runnerInstanceId: runnerId }).where(eq(heartbeatRuns.id, identity.runId)); + await expect(port.openRun(open)).resolves.toBeUndefined(); + await expect(port.checkpointSession({ backendKind: "mock", sessionId: identity.sessionId, identity })).rejects.toThrow("controller_detached"); + await expect(port.completeRun({ result: CONTROL_PLANE_CONFORMANCE_RESULT, terminal: CONTROL_PLANE_CONFORMANCE_TERMINAL })).rejects.toThrow("controller_detached"); + awaitingStartup = false; + await expect(port.openRun(open)).rejects.toThrow("controller_detached"); + const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, identity.runId)); + expect(run.runnerProfileJson?.sessionCheckpoint).toBeUndefined(); + expect(await db.select().from(nativeRunResults).where(eq(nativeRunResults.runId, identity.runId))).toEqual([]); + }); + it.each([ ["checkpoint", "detach"], ["result", "detach"], ["event", "detach"], ["checkpoint", "abort"], ["result", "abort"], ["event", "abort"], diff --git a/server/src/services/native-runtime/paperclip-control-plane-port.ts b/server/src/services/native-runtime/paperclip-control-plane-port.ts index acb02e19b63..d6c6413d060 100644 --- a/server/src/services/native-runtime/paperclip-control-plane-port.ts +++ b/server/src/services/native-runtime/paperclip-control-plane-port.ts @@ -83,6 +83,7 @@ export class PaperclipControlPlanePort implements ControlPlanePort { readonly #binding: PaperclipControlPlaneBinding; #sessionId: string | null = null; readonly #assertControllerActive?: () => void; + readonly #assertRunAdmissionActive?: () => void; readonly #onCommittedEvent?: (event: PrpEvent) => Promise; readonly #onDuplicateEvent?: (event: PrpEvent) => Promise; @@ -94,12 +95,15 @@ export class PaperclipControlPlanePort implements ControlPlanePort { privateKeyPem?: string; /** Synchronous revocation fence for a controller handing off on restart. */ assertControllerActive?: () => void; + /** Read-only admission may finish an existing startup solely for restart detachment. */ + assertRunAdmissionActive?: () => void; onCommittedEvent?: (event: PrpEvent) => Promise; onDuplicateEvent?: (event: PrpEvent) => Promise; } = {}, ) { this.#db = db; this.#assertControllerActive = options.assertControllerActive; + this.#assertRunAdmissionActive = options.assertRunAdmissionActive ?? options.assertControllerActive; this.#identityRedactor = createAgentIdentityRedactor(options.privateKeyPem); this.#binding = structuredClone(binding); this.#onCommittedEvent = options.onCommittedEvent; @@ -123,7 +127,7 @@ export class PaperclipControlPlanePort implements ControlPlanePort { } async openRun(input: OpenControlPlaneRunInput): Promise { - this.#assertControllerActive?.(); + this.#assertRunAdmissionActive?.(); const identity = input.identity; if ( identity.companyId !== this.#binding.companyId @@ -146,7 +150,7 @@ export class PaperclipControlPlanePort implements ControlPlanePort { if (!run || !this.#matchesPersistedBinding(run)) { throw new Error("native_open_run_not_authorized"); } - this.#assertControllerActive?.(); + this.#assertRunAdmissionActive?.(); this.#sessionId = identity.sessionId; } From 970127a0220d3145efe2111b0643aaa883cb162f Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sat, 24 Oct 2026 21:32:42 -0700 Subject: [PATCH 039/110] test: retain onboarding Connect failure evidence (#17529) ## Thinking Path > - Paperclip manages agents and their work through normal company controls. > - Product E2E journeys check these controls through the browser and public API. > - Cloud onboarding uses one Connect action to validate the environment and hire the first agent. > - A failed Connect action previously left only a general journey error in the report. > - This pull request retains a closed diagnostic receipt for that action. > - The report can show the observed failure boundary without retaining private response text. ## Linked Issues or Issue Description **What existing behavior does this improve?** Cloud onboarding Product E2E failure evidence and report detail. **Current behavior** A validation or hire failure can reach the journey as a general operation failure. The report does not retain which Connect response failed. **Proposed behavior** Observe only the same-origin, same-company validation and hire POST requests made during one Connect action. Retain a closed receipt with the checkpoint, response state, bounded HTTP status, and allowlisted adapter, outcome, check code, level, and server code. The Get started control and saved-agent readback remain required. **Reason and benefit** The next failure can be attributed to the exact observed browser/API boundary. This change does not claim the cause of a historical failure. **Breaking changes** The new receipt is optional. Historical results remain valid. Explicit validation and hire rejections now stop the journey with a precise closed error code. This changes only E2E source; it does not change product behavior or qualification gates. ## What Changed - Add a bounded Connect observer with exact request matching and listener cleanup. - Retain known server codes from `details.code` or `code` without response messages, hints, headers, request bodies, provider text, or credentials. - Validate the receipt as a closed schema and render its allowlisted fields in existing report detail. - Include the new helper in the journey definition hash. - Add route, privacy, malformed-body, deadline, late-response, delayed-failure, success, and historical compatibility tests. Document the evidence boundary. ## Verification - Focused Product E2E tests passed: 3 files, 58 tests on the review-fix head. - E2E typecheck, workspace typecheck, and full build passed on the preceding implementation head. The review fix changes only report labels, checkpoint timing, and the matching tests. - The local full `pnpm test:run` command stopped progressing at the general-server start header. Its owned session was interrupted. This is not recorded as a pass. - All 58 remote checks completed on the final review-fix head: 55 passed, one neutral, and two expected skips. Both Greptile and Paperclip reviews are 5/5 with no unresolved review threads. - No live campaign was run with this patch. The observed historical failure is preserved. ## Risks - Unknown or missing responses remain explicit diagnostic states. They do not establish a product root cause. - Response body reads stop after five seconds or the action deadline and accept at most 64 KiB of JSON. Checks are capped at 32 retained entries. - New server or check codes appear as `unrecognized` until the closed allowlist is updated. - The production launch classifier, native gateway qualification, and Get started requirement are unchanged. ## Model Used OpenAI Codex (GPT-6 family), with code execution and tool use. The host does not expose the exact model ID or context window to this run; these values are unavailable. ## 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/README.md | 5 + tests/runner-e2e/SECURITY.md | 7 + tests/runner-e2e/case-outcome.ts | 24 +++ .../product-journeys/cloud-onboarding.test.ts | 3 + .../product-journeys/cloud-onboarding.ts | 6 +- .../product-journeys/contracts.test.ts | 54 ++++++ tests/runner-e2e/product-journeys/launch.ts | 2 +- .../onboarding-connect.test.ts | 182 ++++++++++++++++++ .../product-journeys/onboarding-connect.ts | 131 +++++++++++++ tests/runner-e2e/product-journeys/types.ts | 1 + tests/runner-e2e/result-validation.ts | 2 + 11 files changed, 414 insertions(+), 3 deletions(-) create mode 100644 tests/runner-e2e/product-journeys/onboarding-connect.test.ts create mode 100644 tests/runner-e2e/product-journeys/onboarding-connect.ts diff --git a/tests/runner-e2e/README.md b/tests/runner-e2e/README.md index 47853d3ba74..129f75c4e31 100644 --- a/tests/runner-e2e/README.md +++ b/tests/runner-e2e/README.md @@ -237,6 +237,11 @@ The explicit [deployment-targeted Product journeys](PRODUCT-JOURNEYS.md) reuse browser actions across managed self-hosted and Cloud targets. They include a model-free task-properties story, fresh Cloud onboarding, credential-free previews, private evidence, and prerequisite reuse; `--all` is unchanged. +Cloud onboarding may retain a versioned `onboardingConnect` receipt for the +Connect action: its last checkpoint, validation/hire response state and HTTP +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. ## Live provider connection journeys diff --git a/tests/runner-e2e/SECURITY.md b/tests/runner-e2e/SECURITY.md index 26a326b9cca..afbcf8dd494 100644 --- a/tests/runner-e2e/SECURITY.md +++ b/tests/runner-e2e/SECURITY.md @@ -14,6 +14,13 @@ their expected four-field result, exact base64 download bytes, checksums, size, and attachment/run IDs. Extra fields and arbitrary agent output are rejected. It contains no credentials, browser state, request headers, or provider text. +The optional `onboardingConnect` diagnostic is also a closed, versioned receipt. +It retains only a known checkpoint, response states, HTTP statuses, known adapter +names, and allowlisted outcome/check/server codes (at most 32 checks per response). +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. + ## 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 03316c81995..489f16f8384 100644 --- a/tests/runner-e2e/case-outcome.ts +++ b/tests/runner-e2e/case-outcome.ts @@ -1,5 +1,6 @@ import type { RunnerE2EResult } from "./types.js"; import { isBlockedConnectionResult } from "./connection-evidence.js"; +import { validateOnboardingConnectEvidence } from "./product-journeys/onboarding-connect.js"; const html = (value: unknown) => String(value ?? "").replace( /[&<>"']/g, @@ -8,6 +9,28 @@ const html = (value: unknown) => c ]!, ); + +function renderOnboardingConnect(result: RunnerE2EResult): string { + const receipt = result.productJourney?.onboardingConnect; + if (receipt === undefined) return ""; + try { + validateOnboardingConnectEvidence(receipt); + } catch { + return "

Onboarding Connect diagnostics unavailable: invalid receipt.

"; + } + return `
Onboarding Connect diagnostics +

Last checkpoint: ${html(receipt.checkpoint)}

+ ${([["validation", "Native validation"], ["hire", "Agent hire"]] as const).map(([key, label]) => { + const response = receipt[key]; + return `

${label}

${[ + ["Response state", response.state], ["HTTP status", response.httpStatus], + ["Test endpoint adapter", response.requestedAdapter], ["Returned adapter", response.adapter], + ["Validation outcome", response.outcome], ["Server code", response.serverCode], + ].map(([name, value]) => `
${name}
${html(value ?? "Unavailable")}
`).join("")}
+ ${response.checks.length ? `

Validation checks:

    ${response.checks.map(check => `
  • ${html(check.code)} · ${html(check.level)}
  • `).join("")}
` : ""} + ${response.truncatedChecks ? "

Only the first 32 validation checks were retained.

" : ""}`; + }).join("")}
`; +} /** An interrupted first-task journey is not evidence of failed downstream behavior. */ export function isIncompleteFirstTaskResult( result: RunnerE2EResult, @@ -69,6 +92,7 @@ export function renderCaseOutcome( ${result.productJourney.deployment?.effectiveFeatures ? `

Effective features:

${Object.entries(result.productJourney.deployment.effectiveFeatures).map(([key, value]) => `
${html(key)}
${html(value)}
`).join("")}
` : ""}` : ""} ${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)} ${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/product-journeys/cloud-onboarding.test.ts b/tests/runner-e2e/product-journeys/cloud-onboarding.test.ts index 94589ca5069..0878ade8065 100644 --- a/tests/runner-e2e/product-journeys/cloud-onboarding.test.ts +++ b/tests/runner-e2e/product-journeys/cloud-onboarding.test.ts @@ -86,6 +86,8 @@ function fixture(entry: Entry, options: { intentFailure?: boolean; qualification }, }); const page = { + on() { return this; }, + off() { return this; }, getByLabel(label: string) { return locator(() => controls().filter(control => control.name === label && control.role === "textbox")); }, getByRole(role: string, { name: label }: { name: string | RegExp }) { return locator(() => controls().filter(control => control.role === role && match(control.name, label))); @@ -93,6 +95,7 @@ function fixture(entry: Entry, options: { intentFailure?: boolean; qualification locator(selector: string) { expect(selector).toBe("summary"); return locator(() => controls().filter(control => control.role === "summary")); }, }; const context = { page, company: { id: "company" }, identity: { kind: "cloud" }, startingState: "recipe", api: { + origin: "https://tenant.example.test", async get(route: string) { if (route.endsWith("/ai-connections")) return { connections: saved ? [connection] : [] }; if (route.endsWith("/agents")) return hired ? [{ id: "agent", name, adapterType: "paperclip_runner", adapterConfig: { provider: "codex", model: gateway.model } }] : []; diff --git a/tests/runner-e2e/product-journeys/cloud-onboarding.ts b/tests/runner-e2e/product-journeys/cloud-onboarding.ts index 3173676c3ad..6f9a75634a7 100644 --- a/tests/runner-e2e/product-journeys/cloud-onboarding.ts +++ b/tests/runner-e2e/product-journeys/cloud-onboarding.ts @@ -1,5 +1,6 @@ import { expect } from "@playwright/test"; import { createConnectionProof } from "../connection-evidence.js"; +import { onboardingConnect } from "./onboarding-connect.js"; import { onboardingFirstTask } from "./onboarding-first-task.js"; import { JourneyError, type JourneyContext, type JourneyEvidence, type TargetSession } from "./types.js"; @@ -69,11 +70,12 @@ export async function cloudOnboarding(input: CloudOnboardingInput): Promise { evidence.onboardingConnect = value; } }); const agents = await api.get(`/api/companies/${company.id}/agents`); const agent = agents.find(a => a.name === name); if (!agent || agents.length !== 1 || agent.adapterType !== "paperclip_runner" || agent.adapterConfig?.provider !== "codex" || agent.adapterConfig?.model !== input.gateway.model) throw new JourneyError("failed", "onboarding_agent_configuration_mismatch"); + connect.checkpoint = "agent-verification"; await input.own({ kind: "agent", name, id: agent.id }); evidence.checks.push({ id: "ui-connection-and-native-agent", passed: true }); await input.own({ kind: "issue", name: "Paperclip onboarding" }); diff --git a/tests/runner-e2e/product-journeys/contracts.test.ts b/tests/runner-e2e/product-journeys/contracts.test.ts index 754d6c7bab9..b02057281a3 100644 --- a/tests/runner-e2e/product-journeys/contracts.test.ts +++ b/tests/runner-e2e/product-journeys/contracts.test.ts @@ -13,6 +13,7 @@ import type { RunnerE2EResult } from "../types.js"; import type { JourneyContext, JourneyEvidence, TargetSession } from "./types.js"; import { createConnectionProof } from "../connection-evidence.js"; import { retainOnboardingArtifact } from "./artifact-evidence.js"; +import type { OnboardingConnectEvidence } from "./onboarding-connect.js"; vi.mock("@playwright/test", () => ({ expect: Object.assign( (locator: { textContent(): Promise }) => ({ async toContainText(value: string) { expect(await locator.textContent()).toContain(value); } }), @@ -29,7 +30,60 @@ function result(): RunnerE2EResult { return { schema: "paperclip.runner-e2e.result/v2", suiteId: "product-journeys", suiteDefinitionHash: "test", executionId: "product-journeys.local-qa.local.task-properties", profileId: "local-qa", environmentId: "local", caseId: "task-properties", provider: null, model: null, runtimeMode: "none", status: "passed", cleanup: "passed", attempt: 1, startedAt: "2026-01-01T00:00:00Z", finishedAt: "2026-01-01T00:00:01Z", durationMs: 1000, productJourney: { outcome: "passed", startingState: "recipe", phases: [{phase: "journey", outcome: "passed"}], checks: [{id:"assignment-persisted", passed:true},{id:"no-agent-work",passed:true}], privacy: "private", resourceDisposition: "released", deployment: { kind: "self-hosted", targetId: "local-qa", origin: "http://127.0.0.1:3100", commit: "a".repeat(40), cloudRelease: null, runtimeImage: null, configurationHash: "test" } } }; } +function connectReceipt(): OnboardingConnectEvidence { + return { + version: 1, checkpoint: "hire", + validation: { state: "json", httpStatus: 200, requestedAdapter: "paperclip_runner", adapter: "paperclip_runner", outcome: "fail", serverCode: null, checks: [{ code: "adapter_auth_missing", level: "error" }], truncatedChecks: false }, + hire: { state: "json", httpStatus: 422, requestedAdapter: null, adapter: null, outcome: null, serverCode: "agent_runner_unavailable", checks: [], truncatedChecks: false }, + }; +} describe("deployment journey contracts", () => { + it("accepts historical results without Connect diagnostics and optional closed receipts", () => { + const retained = result(); + retained.caseId = "cloud-onboarding"; + retained.status = "failed"; + expect(() => validateRetainedRunnerResult(retained)).not.toThrow(); + expect(renderCaseOutcome(retained, true, [])).not.toContain("Onboarding Connect diagnostics"); + retained.productJourney!.onboardingConnect = connectReceipt(); + expect(() => validateRetainedRunnerResult(JSON.parse(JSON.stringify(retained)))).not.toThrow(); + retained.productJourney!.onboardingConnect.validation = { state: "pending", httpStatus: 200, requestedAdapter: "codex_local", adapter: null, outcome: null, serverCode: null, checks: [], truncatedChecks: false }; + expect(() => validateRetainedRunnerResult(retained)).not.toThrow(); + }); + it.each([ + ["request headers", () => ({ ...connectReceipt(), requestHeaders: { authorization: "must-not-retain" } })], + ["response bodies", () => ({ ...connectReceipt(), validation: { ...connectReceipt().validation, body: "must-not-retain" } })], + ["check messages", () => ({ ...connectReceipt(), validation: { ...connectReceipt().validation, checks: [{ code: "adapter_auth_missing", level: "error", message: "must-not-retain" }] } })], + ["unknown server codes", () => ({ ...connectReceipt(), hire: { ...connectReceipt().hire, serverCode: "raw-provider-error" } })], + ["unknown check codes", () => ({ ...connectReceipt(), validation: { ...connectReceipt().validation, checks: [{ code: "raw-provider-error", level: "error" }] } })], + ["unknown adapters", () => ({ ...connectReceipt(), validation: { ...connectReceipt().validation, adapter: "raw-provider-name" } })], + ["unknown requested adapters", () => ({ ...connectReceipt(), validation: { ...connectReceipt().validation, requestedAdapter: "raw-provider-name" } })], + ["unknown outcomes", () => ({ ...connectReceipt(), validation: { ...connectReceipt().validation, outcome: "raw-provider-message" } })], + ["unknown response states", () => ({ ...connectReceipt(), validation: { ...connectReceipt().validation, state: "raw-provider-message" } })], + ["unknown check levels", () => ({ ...connectReceipt(), validation: { ...connectReceipt().validation, checks: [{ code: "adapter_auth_missing", level: "fatal" }] } })], + ["oversized check arrays", () => ({ ...connectReceipt(), validation: { ...connectReceipt().validation, checks: Array.from({ length: 33 }, () => ({ code: "adapter_auth_missing", level: "error" })) } })], + ["invalid HTTP statuses", () => ({ ...connectReceipt(), validation: { ...connectReceipt().validation, httpStatus: 600 } })], + ["non-boolean truncation", () => ({ ...connectReceipt(), validation: { ...connectReceipt().validation, truncatedChecks: "true" } })], + ["missing response fields", () => ({ ...connectReceipt(), hire: { state: "missing" } })], + ["unsupported receipt versions", () => ({ ...connectReceipt(), version: 2 })], + ["unknown checkpoints", () => ({ ...connectReceipt(), checkpoint: "raw-browser-text" })], + ] as const)("rejects Connect receipts containing %s", (_label, makeReceipt) => { + const retained = result(); + retained.productJourney!.onboardingConnect = makeReceipt() as OnboardingConnectEvidence; + expect(() => validateRetainedRunnerResult(retained)).toThrow("result.productJourney.onboardingConnect"); + }); + it("renders only validated Connect fields and marks missing or truncated evidence", () => { + const retained = result(); + retained.productJourney!.onboardingConnect = connectReceipt(); + const output = renderCaseOutcome(retained, true, []); + for (const text of ["Onboarding Connect diagnostics", "Last checkpoint", "Native validation", "Agent hire", "HTTP status", "Test endpoint adapter", "Returned adapter", "200", "422", "paperclip_runner", "adapter_auth_missing", "agent_runner_unavailable", "error", "Unavailable"]) expect(output).toContain(text); + retained.productJourney!.onboardingConnect.validation.truncatedChecks = true; + expect(renderCaseOutcome(retained, true, [])).toContain("Only the first 32 validation checks were retained"); + Object.assign(retained.productJourney!.onboardingConnect.validation, { body: "" }); + const invalid = renderCaseOutcome(retained, false, []); + expect(invalid).toContain("Onboarding Connect diagnostics unavailable: invalid receipt"); + expect(invalid).not.toContain("must-not-render"); + expect(invalid).not.toContain("adapter_auth_missing"); + }); it("validates optional historical artifact evidence without trusting extra fields or a different run", () => { const retained = result(); retained.caseId = "cloud-onboarding"; diff --git a/tests/runner-e2e/product-journeys/launch.ts b/tests/runner-e2e/product-journeys/launch.ts index 2d0233bd2e9..410bb7725bf 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-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", "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-connect.test.ts b/tests/runner-e2e/product-journeys/onboarding-connect.test.ts new file mode 100644 index 00000000000..be9535cf0c7 --- /dev/null +++ b/tests/runner-e2e/product-journeys/onboarding-connect.test.ts @@ -0,0 +1,182 @@ +import { EventEmitter } from "node:events"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { onboardingConnect, validateOnboardingConnectEvidence, type OnboardingConnectEvidence } from "./onboarding-connect.js"; + +const origin = "https://tenant.example.test", companyId = "company-1"; +const validation = `/api/companies/${companyId}/adapters/paperclip_runner/test-environment`; +const hire = `/api/companies/${companyId}/agent-hires`; +const secret = "PRIVATE_SENTINEL_do_not_retain"; +function fixture(options: { ready?: boolean; durationMs?: number; click?: () => Promise | void; wait?: () => Promise } = {}) { + const events = new EventEmitter(); + let retained!: OnboardingConnectEvidence; + const page = Object.assign(events, { getByRole(_role: string, { name }: { name: string }) { + return { click: vi.fn(async () => { expect(name).toBe("Connect"); await options.click?.(); }), + waitFor: vi.fn(({ timeout }: { timeout: number }) => { + expect(name).toBe("Get started"); + if (options.wait) return options.wait(); + return options.ready ? Promise.resolve() : new Promise((_resolve, reject) => { + setTimeout(() => reject(Object.assign(new Error(secret), { name: "TimeoutError" })), timeout); + }); + }) }; + } }); + const request = (path = validation, method = "POST", requestOrigin = origin) => ({ url: () => requestOrigin + path, method: () => method }); + const respond = (body: unknown, status = 200, path = validation, method = "POST", requestOrigin = origin) => { + const req = request(path, method, requestOrigin); + const response = { request: () => req, status: () => status, body: () => Promise.resolve(Buffer.isBuffer(body) ? body : Buffer.from(JSON.stringify(body))) }; + events.emit("request", req); events.emit("response", response); + return response; + }; + const run = () => onboardingConnect({ page: page as any, origin, companyId, deadlineAt: Date.now() + (options.durationMs ?? 100), retain: value => { retained = value; } }); + return { page, events, request, respond, run, receipt: () => retained }; +} +afterEach(() => { vi.useRealTimers(); }); + +describe("one onboarding Connect diagnostic boundary", () => { + it("does not press Connect after the action deadline already expired", async () => { + const click = vi.fn(); + const f = fixture({ durationMs: 0, click }); + await expect(f.run()).rejects.toMatchObject({ code: "onboarding_connect_timeout" }); + expect(click).not.toHaveBeenCalled(); + expect(f.receipt().checkpoint).toBe("connect"); + expect(f.events.eventNames()).toEqual([]); + }); + + it("rejects a delayed failure body even after Get started becomes visible", async () => { + let resolveBody!: (bytes: Buffer) => void; + const body = new Promise(resolve => { resolveBody = resolve; }); + let reviewSeen!: () => void; + const review = new Promise(resolve => { reviewSeen = resolve; }); + const f = fixture({ wait: async () => { reviewSeen(); }, click: () => { + const req = f.request(); f.events.emit("request", req); + f.events.emit("response", { request: () => req, status: () => 200, body: () => body }); + } }); + const result = expect(f.run()).rejects.toMatchObject({ code: "onboarding_native_validation_failed" }); + await review; + for (let i = 0; i < 10 && f.events.listenerCount("response"); i++) await Promise.resolve(); + expect(f.events.listenerCount("response")).toBe(0); + resolveBody(Buffer.from(JSON.stringify({ status: "fail", checks: [] }))); + await result; + expect(f.receipt().validation.outcome).toBe("fail"); + expect(f.receipt().checkpoint).toBe("validation"); + expect(f.events.eventNames()).toEqual([]); + }); + + it.each(["details", "top-level"])("retains a known %s server rejection without its free text", async location => { + const f = fixture({ click: () => { f.respond({ error: secret, ...(location === "details" ? { details: { code: "agent_runner_config_incompatible", fields: [secret] } } : { code: "agent_runner_unavailable" }) }, 422); } }); + await expect(f.run()).rejects.toMatchObject({ code: "onboarding_native_validation_failed" }); + expect(f.receipt()).toMatchObject({ checkpoint: "validation", validation: { state: "json", httpStatus: 422, serverCode: location === "details" ? "agent_runner_config_incompatible" : "agent_runner_unavailable" }, hire: { state: "missing" } }); + expect(JSON.stringify(f.receipt())).not.toContain(secret); + validateOnboardingConnectEvidence(f.receipt()); + expect(f.events.listenerCount("response")).toBe(0); + }); + + it.each([{ status: "fail", checks: [] }, { status: "pass", checks: [{ code: "adapter_auth_missing", level: "error" }] }])("fails on a 200 validation rejection: %j", async body => { + const f = fixture({ click: () => { f.respond(body); } }); + await expect(f.run()).rejects.toMatchObject({ code: "onboarding_native_validation_failed" }); + expect(f.receipt().validation.httpStatus).toBe(200); + }); + + it("retains the hire boundary rejection and does not wait for Get started", async () => { + const f = fixture({ click: () => { f.respond({ details: { code: "agent_runner_platform_probe_failed" }, error: secret }, 503, hire); } }); + await expect(f.run()).rejects.toMatchObject({ code: "onboarding_agent_hire_failed" }); + expect(f.receipt()).toMatchObject({ checkpoint: "hire", hire: { httpStatus: 503, serverCode: "agent_runner_platform_probe_failed" } }); + }); + + it("projects only enums from malicious nested fields, including unknown codes and bounded checks", async () => { + const f = fixture({ ready: true, click: () => { f.respond({ adapterType: secret, status: secret, code: { credential: secret }, details: { code: secret }, + message: secret, hint: secret, headers: { authorization: secret }, checks: Array.from({ length: 40 }, () => ({ code: secret, level: secret, message: secret, nested: { apiKey: secret } })) }); } }); + const result = await f.run(); + expect(result.validation).toMatchObject({ adapter: "unrecognized", outcome: "unrecognized", serverCode: "unrecognized", truncatedChecks: true }); + expect(result.validation.checks).toHaveLength(32); + expect(result.validation.checks[0]).toEqual({ code: "unrecognized", level: "unrecognized" }); + expect(JSON.stringify(result)).not.toContain(secret); + validateOnboardingConnectEvidence(result); + expect(() => validateOnboardingConnectEvidence({ ...result, validation: { ...result.validation, requestedAdapter: ["codex_local"] } })).toThrow(); + }); + + it("ignores wrong origin, company, method, query, and responses without an in-action request", async () => { + vi.useFakeTimers(); + const f = fixture({ click: () => { + f.respond({}, 500, validation, "POST", "https://foreign.example.test"); + f.respond({}, 500, validation.replace(companyId, "company-2")); + f.respond({}, 500, validation, "GET"); + f.respond({}, 500, validation + "?private=" + secret); + f.events.emit("response", { request: () => f.request(), status: () => 500 }); + } }); + const result = expect(f.run()).rejects.toMatchObject({ code: "onboarding_get_started_timeout" }); + await vi.advanceTimersByTimeAsync(101); await result; + expect(f.receipt()).toMatchObject({ checkpoint: "connect", validation: { state: "missing" }, hire: { state: "missing" } }); + expect(f.events.eventNames()).toEqual([]); + }); + + it.each([Buffer.from("{not-json"), Buffer.alloc(65_537, "x")])("keeps malformed or oversized bodies unknown and still requires Get started", async bytes => { + vi.useFakeTimers(); + const f = fixture({ click: () => { f.respond(bytes); } }); + const result = expect(f.run()).rejects.toMatchObject({ code: "onboarding_get_started_timeout" }); + await vi.advanceTimersByTimeAsync(101); await result; + expect(f.receipt().validation.state).toBe(bytes.byteLength > 65_536 ? "oversized" : "unreadable"); + expect(f.receipt().checkpoint).toBe("validation"); + }); + + it("records missing responses and ignores late responses after timeout", async () => { + vi.useFakeTimers(); + const f = fixture({ click: () => { f.events.emit("request", f.request()); } }); + const result = expect(f.run()).rejects.toMatchObject({ code: "onboarding_get_started_timeout" }); + await vi.advanceTimersByTimeAsync(101); await result; + const sealed = JSON.stringify(f.receipt()); + f.respond({ status: "pass", adapterType: "paperclip_runner", checks: [] }); + expect(JSON.stringify(f.receipt())).toBe(sealed); + expect(f.receipt().validation.state).toBe("missing"); + }); + + it("bounds stalled JSON reads and cannot mutate retained evidence after return or reject unhandled", async () => { + vi.useFakeTimers(); + let rejectBody!: (reason: Error) => void; + const body = new Promise((_resolve, reject) => { rejectBody = reject; }); + const f = fixture({ ready: true, durationMs: 10_000, click: () => { + const req = f.request(); f.events.emit("request", req); + f.events.emit("response", { request: () => req, status: () => 200, body: () => body }); + } }); + const result = f.run(); + await vi.advanceTimersByTimeAsync(5001); + expect((await result).validation.state).toBe("unreadable"); + const sealed = JSON.stringify(f.receipt()); + rejectBody(new Error(secret)); await Promise.resolve(); + expect(JSON.stringify(f.receipt())).toBe(sealed); + expect(f.events.eventNames()).toEqual([]); + }); + + it("preserves the Get started timeout when a previously received body arrives later", async () => { + vi.useFakeTimers(); + let resolveBody!: (bytes: Buffer) => void; + const body = new Promise(resolve => { resolveBody = resolve; }); + const f = fixture(); + const result = expect(f.run()).rejects.toMatchObject({ code: "onboarding_get_started_timeout" }); + await vi.advanceTimersByTimeAsync(10); + const req = f.request(); f.events.emit("request", req); + f.events.emit("response", { request: () => req, status: () => 200, body: () => body }); + await vi.advanceTimersByTimeAsync(90); + resolveBody(Buffer.from(JSON.stringify({ status: "fail" }))); + await vi.advanceTimersByTimeAsync(1); await result; + expect(f.receipt().checkpoint).toBe("validation"); + expect(f.events.eventNames()).toEqual([]); + }); + + it("keeps a browser error at its own boundary without retaining the browser text", async () => { + const f = fixture({ click: () => { throw new Error(secret); } }); + await expect(f.run()).rejects.toMatchObject({ code: "onboarding_connect_failed" }); + expect(f.receipt().checkpoint).toBe("connect"); + expect(JSON.stringify(f.receipt())).not.toContain(secret); + expect(f.events.eventNames()).toEqual([]); + }); + + it("observes both successful responses and requires the visible review step", async () => { + const f = fixture({ ready: true, click: () => { + f.respond({ adapterType: "paperclip_runner", status: "pass", checks: [{ code: "codex_hello_probe_passed", level: "info", message: secret }] }, 200, validation.replace("paperclip_runner", "codex_local")); + f.respond({ agent: { id: secret }, approval: null }, 201, hire); + } }); + expect(await f.run()).toMatchObject({ checkpoint: "review", validation: { requestedAdapter: "codex_local", adapter: "paperclip_runner", outcome: "pass", checks: [{ code: "codex_hello_probe_passed", level: "info" }] }, hire: { state: "json", httpStatus: 201 } }); + expect(JSON.stringify(f.receipt())).not.toContain(secret); + expect(f.events.eventNames()).toEqual([]); + }); +}); diff --git a/tests/runner-e2e/product-journeys/onboarding-connect.ts b/tests/runner-e2e/product-journeys/onboarding-connect.ts new file mode 100644 index 00000000000..4aa6e43becf --- /dev/null +++ b/tests/runner-e2e/product-journeys/onboarding-connect.ts @@ -0,0 +1,131 @@ +import type { Page, Response, Request } from "@playwright/test"; +import { JourneyError } from "./types.js"; + +export const onboardingServerCodes = ["agent_runner_config_incompatible", "agent_runner_unavailable", "agent_runner_platform_probe_failed", "managed_sandbox_unavailable", "environment_company_mismatch"] as const; +export const onboardingCheckCodes = ["adapter_auth_missing", "codex_hello_probe_failed", "codex_hello_probe_passed", "codex_hello_probe_timeout", "codex_hello_probe_auth_required", "environment_lease_acquire_failed", "environment_workspace_realize_failed", "environment_target_failed", "environment_target_unsupported", "environment_not_found", "environment_target_unavailable", "managed_sandbox_unavailable", "environment_env_binding_missing", "environment_env_resolution_failed", "ai_connection_api_key_rejected", "ai_connection_verification_failed", "sandbox_test_identity"] as const; +const checkpoints = ["connect", "validation", "hire", "review", "agent-verification"] as const; +const states = ["missing", "pending", "json", "unreadable", "oversized"] as const; +const requestedAdapters = ["codex_local", "paperclip_runner"] as const; +const adapters = ["codex_local", "paperclip_runner", "unrecognized"] as const; +const outcomes = ["pass", "warn", "fail", "unrecognized"] as const; +const levels = ["info", "warn", "error", "unrecognized"] as const; +type Known = T[number] | "unrecognized"; +export interface OnboardingResponseEvidence { + state: typeof states[number]; httpStatus: number | null; + requestedAdapter: "codex_local" | "paperclip_runner" | null; + adapter: typeof adapters[number] | null; outcome: typeof outcomes[number] | null; + serverCode: Known | null; + checks: Array<{ code: Known; level: typeof levels[number] }>; + truncatedChecks: boolean; +} +export interface OnboardingConnectEvidence { + version: 1; checkpoint: typeof checkpoints[number]; validation: OnboardingResponseEvidence; hire: OnboardingResponseEvidence; +} +const blank = (): OnboardingResponseEvidence => ({ state: "missing", httpStatus: null, requestedAdapter: null, adapter: null, outcome: null, serverCode: null, checks: [], truncatedChecks: false }); +const record = (v: unknown): v is Record => Boolean(v && typeof v === "object" && !Array.isArray(v)); +const member = (values: T, v: unknown): v is T[number] => typeof v === "string" && values.includes(v); +const closed = (v: unknown, keys: string[]) => record(v) && Object.keys(v).length === keys.length && keys.every(key => Object.hasOwn(v, key)); +export function validateOnboardingConnectEvidence(value: unknown): void { + if (!closed(value, ["version", "checkpoint", "validation", "hire"]) || !record(value) || value.version !== 1 || !member(checkpoints, value.checkpoint)) throw new Error("invalid_onboarding_connect_evidence"); + for (const response of [value.validation, value.hire]) { + if (!closed(response, ["state", "httpStatus", "requestedAdapter", "adapter", "outcome", "serverCode", "checks", "truncatedChecks"]) || !record(response) || + !member(states, response.state) || !(response.httpStatus === null || Number.isSafeInteger(response.httpStatus) && Number(response.httpStatus) >= 100 && Number(response.httpStatus) <= 599) || + !(response.requestedAdapter === null || member(requestedAdapters, response.requestedAdapter)) || + !(response.adapter === null || member(adapters, response.adapter)) || !(response.outcome === null || member(outcomes, response.outcome)) || + !(response.serverCode === null || response.serverCode === "unrecognized" || member(onboardingServerCodes, response.serverCode)) || + typeof response.truncatedChecks !== "boolean" || !Array.isArray(response.checks) || response.checks.length > 32 || + response.checks.some(check => !closed(check, ["code", "level"]) || !record(check) || !(check.code === "unrecognized" || member(onboardingCheckCodes, check.code)) || !member(levels, check.level))) throw new Error("invalid_onboarding_connect_evidence"); + } +} + +/** Observe only responses to this Connect action; never retain bodies, text, headers or browser errors. */ +export async function onboardingConnect(input: { page: Page; origin: string; companyId: string; deadlineAt: number; retain(value: OnboardingConnectEvidence): void }): Promise { + const { page } = input, receipt: OnboardingConnectEvidence = { version: 1, checkpoint: "connect", validation: blank(), hire: blank() }; + input.retain(receipt); + let active = true, failure: JourneyError | undefined; + let signalFailure!: (error: JourneyError) => void; + const failed = new Promise(resolve => { signalFailure = resolve; }); + const requests = new Set(), pending = new Set>(); + const deadlineAt = Math.min(input.deadlineAt, Date.now() + 180_000); + const remaining = () => Math.max(1, deadlineAt - Date.now()); + const advance = (checkpoint: OnboardingConnectEvidence["checkpoint"]) => { + if (checkpoints.indexOf(checkpoint) > checkpoints.indexOf(receipt.checkpoint)) receipt.checkpoint = checkpoint; + }; + const reject = (code: string) => { failure ??= new JourneyError("failed", code); signalFailure(failure); }; + const route = (request: Request): { kind: "validation" | "hire"; adapter: "codex_local" | "paperclip_runner" | null } | null => { + try { + const url = new URL(request.url()); + if (request.method() !== "POST" || url.origin !== input.origin || url.search || url.hash) return null; + const prefix = `/api/companies/${encodeURIComponent(input.companyId)}`; + if (url.pathname === `${prefix}/agent-hires`) return { kind: "hire", adapter: null }; + for (const adapter of ["codex_local", "paperclip_runner"] as const) if (url.pathname === `${prefix}/adapters/${adapter}/test-environment`) return { kind: "validation", adapter }; + } catch { /* An unrelated or malformed URL is not this action's evidence. */ } + return null; + }; + const onRequest = (request: Request) => { if (active && route(request)) requests.add(request); }; + const onResponse = (response: Response) => { + const request = response.request(), matched = route(request); + if (!active || !matched || !requests.delete(request)) return; + const observed = receipt[matched.kind]; + // One Connect action can report each boundary once. Later traffic cannot replace its failure. + if (observed.state !== "missing") return; + advance(matched.kind); observed.state = "pending"; + const status = response.status(); + observed.httpStatus = Number.isSafeInteger(status) && status >= 100 && status <= 599 ? status : null; + observed.requestedAdapter = matched.adapter; + if (response.status() >= 400) reject(matched.kind === "validation" ? "onboarding_native_validation_failed" : "onboarding_agent_hire_failed"); + const classify = async () => { + let timer: ReturnType | undefined; + try { + const bytes = await Promise.race([response.body(), new Promise(resolve => { timer = setTimeout(() => resolve(null), Math.min(5000, remaining())); })]); + if (!active) return; + if (!bytes) { observed.state = "unreadable"; return; } + if (bytes.byteLength > 65_536) { observed.state = "oversized"; return; } + let body: unknown; try { body = JSON.parse(bytes.toString("utf8")); } catch { observed.state = "unreadable"; return; } + if (!record(body)) { observed.state = "unreadable"; return; } + observed.state = "json"; + const detailCode = record(body.details) ? body.details.code : undefined; + const code = member(onboardingServerCodes, detailCode) ? detailCode : member(onboardingServerCodes, body.code) ? body.code : detailCode ?? body.code; + if (code !== undefined) observed.serverCode = member(onboardingServerCodes, code) ? code : "unrecognized"; + if (matched.kind === "validation") { + observed.adapter = member(adapters, body.adapterType) ? body.adapterType : "unrecognized"; + observed.outcome = member(outcomes, body.status) ? body.status : "unrecognized"; + if (Array.isArray(body.checks)) { + observed.truncatedChecks = body.checks.length > 32; + observed.checks = body.checks.slice(0, 32).map(check => ({ code: record(check) && member(onboardingCheckCodes, check.code) ? check.code : "unrecognized", level: record(check) && member(levels, check.level) ? check.level : "unrecognized" })); + if (body.status === "fail" || body.checks.some(check => record(check) && check.code === "adapter_auth_missing")) reject("onboarding_native_validation_failed"); + } else if (body.status === "fail") reject("onboarding_native_validation_failed"); + } + } catch { if (active) observed.state = "unreadable"; } + finally { clearTimeout(timer); } + }; + const work = classify(); pending.add(work); void work.then(() => pending.delete(work), () => pending.delete(work)); + }; + page.on("request", onRequest); page.on("response", onResponse); + try { + if (Date.now() >= deadlineAt) throw new JourneyError("failed", "onboarding_connect_timeout"); + const clicked = page.getByRole("button", { name: "Connect", exact: true }).click({ timeout: remaining() }) + .then(() => null, error => new JourneyError("failed", error?.name === "TimeoutError" ? "onboarding_connect_timeout" : "onboarding_connect_failed")); + const clickResult = await Promise.race([failed, clicked]); + if (clickResult) throw clickResult; + if (failure) throw failure; + const result = await Promise.race([failed, page.getByRole("button", { name: "Get started", exact: true }).waitFor({ timeout: remaining() }) + .then(() => null, error => new JourneyError("failed", error?.name === "TimeoutError" ? "onboarding_get_started_timeout" : "onboarding_get_started_failed"))]); + const boundaryFailure = failure; + // Seal the observed boundary before awaiting body reads. A response arriving + // after Get started or its timeout cannot change this action's outcome. + page.off("request", onRequest); page.off("response", onResponse); + if (pending.size) await Promise.all([...pending]); + if (boundaryFailure) throw boundaryFailure; + if (result) throw result; + if (failure) throw failure; + if (Date.now() >= deadlineAt) throw new JourneyError("failed", "onboarding_get_started_timeout"); + advance("review"); + return receipt; + } finally { + // Settle only already observed responses within their bounded read; detach before later traffic. + page.off("request", onRequest); page.off("response", onResponse); + if (pending.size) await Promise.all([...pending]); + active = false; requests.clear(); + } +} diff --git a/tests/runner-e2e/product-journeys/types.ts b/tests/runner-e2e/product-journeys/types.ts index 65941f30d86..da0b054a606 100644 --- a/tests/runner-e2e/product-journeys/types.ts +++ b/tests/runner-e2e/product-journeys/types.ts @@ -28,6 +28,7 @@ export interface JourneyEvidence { attemptId?: string; operations?: JourneyOperations; artifact?: OnboardingArtifactEvidence; + onboardingConnect?: import("./onboarding-connect.js").OnboardingConnectEvidence; } 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 883d928c510..56f38ed0bec 100644 --- a/tests/runner-e2e/result-validation.ts +++ b/tests/runner-e2e/result-validation.ts @@ -4,6 +4,7 @@ import { githubJourneyCheckpoints, gradeGitHubReviewJourney } from "./github-rev import { STARTUP_REUSE_LAYERS, STARTUP_REUSE_REASONS } from "../../packages/adapter-utils/src/startup-reuse.js"; 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"; type Rule = (value: unknown, at: string) => void; @@ -344,6 +345,7 @@ const fields = { productJourney: optional(shape({ targetId: optional(string), campaignId: optional(string), attemptId: optional(string), + onboardingConnect: optional((value, at) => { try { validateOnboardingConnectEvidence(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) })), From a0e5166e974a7f6ffabe2a43f816a83449fdef57 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sat, 24 Oct 2026 21:39:21 -0700 Subject: [PATCH 040/110] Fix GitHub journey registration diagnostics and native retry cleanup (#17513) ## Thinking Path > - Paperclip manages work performed by AI agents. > - The Product E2E harness verifies a GitHub review-bot journey. > - GitHub can return a registration page without the expected creation control. > - The journey could then wait for the full login allowance without useful evidence. > - A failed native run can also retain a retry after its terminal status is visible. > - This change records a safe registration boundary and uses the normal Stop route for owned retries. > - Operators can diagnose the setup failure and confirm cleanup without changing the behavioral oracle. ## Linked Issues or Issue Description Refs: #17457. **What happened?** The GitHub review journey waited at App registration with no useful handoff evidence. Its cleanup also skipped failed native runs that still owned a durable retry. **Expected behavior** The journey should report a bounded registration failure or reauthentication boundary. Cleanup should Stop an owned native retry and require its audited acknowledgement. **Steps to reproduce** 1. Run the configured GitHub review journey. 2. Return a GitHub registration page without the expected creation button, or fail a native review run while its coordinator can retry. 3. Inspect the result and cleanup evidence. **Paperclip version or commit** Source built from current master. This extends the driver merged in #17457. ## What Changed - Bound the registration render wait to 30 seconds. Keep the separate attended confirmation allowance. - Retain GitHub origin, path, and control-presence flags. Retain headings, button labels, and alerts only on known registration error pages without authentication fields. - Exclude query parameters, entered values, page bodies, grant payloads, and authentication content from that diagnostic. - Add an optional private authentication hook for ordinary GitHub access reconfirmation. Detect passkey-first sudo at the manifest URL without retaining its authentication content. - Stop owned failed native retries through the existing run-only cancellation route. Verify company, agent, task, and audit acknowledgement. - Use native Stop correlation only for native runs. Queued legacy or unresolved runs use the ordinary cancel request. Stop scheduled retries and wait for them to leave the live state set. - Keep pending accounting debt intact. Add regression coverage and journey documentation. ## Verification - Focused journey and report suite: 58 tests passed. - Runner E2E TypeScript check passed. - `git diff --check` passed. Credential-value scan passed. - Live fixture reproduced the missing creation control at the manifest handoff. The new diagnostic retained its path and control-presence flags. No model work started. Draft cleanup passed. - All 58 current-head checks are terminal and green. Greptile scored the exact head 5/5, with no unresolved review threads. ## Risks GitHub pages that take more than 30 seconds to render the creation control now fail early. Native cleanup fails closed if the server does not provide the expected Stop acknowledgement. The live setup-to-Done behavioral journey is still unqualified. These changes do not repair a missing provider usage receipt or weaken its accounting gate. ## Model Used OpenAI Codex, based on GPT-6. Exact runtime model identifier and context-window size are not exposed in this session. Used for code execution, browser tooling, and regression analysis. ## 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 Co-authored-by: Paperclip --- tests/runner-e2e/GITHUB-REVIEW-JOURNEY.md | 9 ++ tests/runner-e2e/github-review-browser.ts | 48 +++++++++ tests/runner-e2e/github-review-flow.ts | 8 +- .../runner-e2e/github-review-journey.test.ts | 101 +++++++++++++++++- tests/runner-e2e/github-review-launch.ts | 19 ++-- tests/runner-e2e/github-review-ownership.ts | 31 ++++++ 6 files changed, 203 insertions(+), 13 deletions(-) diff --git a/tests/runner-e2e/GITHUB-REVIEW-JOURNEY.md b/tests/runner-e2e/GITHUB-REVIEW-JOURNEY.md index ceeb56a95e0..12cddb6c387 100644 --- a/tests/runner-e2e/GITHUB-REVIEW-JOURNEY.md +++ b/tests/runner-e2e/GITHUB-REVIEW-JOURNEY.md @@ -89,6 +89,15 @@ connections, and completed task evidence. An unconfirmed cleanup fails the attempt; retain the resource receipt for recovery. Read the receipt before any manual cleanup. Never delete by a guessed name or broad account search. +Registration render waits are bounded separately from attended confirmation. +The driver retains only the GitHub origin/path and control-presence flags when +the creation control is missing. On a known registration error page without auth +fields, it also retains headings, button labels, and alerts. It excludes query +parameters and authentication content. Reauthentication is a setup boundary, +not evidence that an App exists. +Cleanup also stops failed native runs that still own a retry, and requires the +normal run-only Stop acknowledgement. It never clears pending accounting debt. + The configured deadline and observed run limit bound the attempt. They are not a hard provider-dollar cap or proof that no request outlives cancellation. Use the existing budgeted Cloud operations adapter before automated paid campaigns; diff --git a/tests/runner-e2e/github-review-browser.ts b/tests/runner-e2e/github-review-browser.ts index dffb516bcdd..b064d0ad384 100644 --- a/tests/runner-e2e/github-review-browser.ts +++ b/tests/runner-e2e/github-review-browser.ts @@ -10,6 +10,54 @@ export async function enterGitHubJourneyCompany(page: Page, origin: string, comp await page.waitForURL(url => url.origin === origin && url.pathname === pathname); } +export interface GitHubRegistrationBoundary { + origin: string; pathname: string; passwordRequired: boolean; oneTimeCodeRequired: boolean; + reauthenticationRequired: boolean; createControlVisible: boolean; + controls?: { headings: string[]; buttons: string[]; alerts: string[] }; +} + +/** Keep only navigation and control-presence evidence. Authentication fields, + * page content, query parameters, and grant payloads must stay out of reports. */ +export async function waitForGitHubRegistrationControl(page: Page, owner: string, timeoutMs: number, + record: (boundary: GitHubRegistrationBoundary) => Promise = async () => {}, reauthenticate?: () => Promise) { + const control = page.getByRole("button", { name: new RegExp(`^Create GitHub App(?: for ${owner})?$`) }); + const observe = async (includeErrorControls = false) => { + const url = new URL(page.url()); + if (url.origin !== "https://github.com") throw new ConnectionFailure("github_registration_origin_mismatch"); + const boundary: GitHubRegistrationBoundary = { origin: url.origin, pathname: url.pathname, + passwordRequired: await page.locator('input[type="password"]:visible').count() > 0, + oneTimeCodeRequired: await page.locator('input[autocomplete="one-time-code"]:visible').count() > 0, + reauthenticationRequired: await page.getByRole("heading", { name: /^Confirm access$/i }).isVisible() + || await page.getByRole("button", { name: /^Use (?:your password|passkey)$/i }).isVisible(), + createControlVisible: await control.isVisible() }; + boundary.reauthenticationRequired ||= boundary.passwordRequired || boundary.oneTimeCodeRequired + || /\/(?:login|sessions)(?:\/|$)/.test(boundary.pathname); + if (includeErrorControls && !boundary.reauthenticationRequired + && ["/settings/apps/new", "/settings/apps/manifest"].includes(url.pathname)) { + boundary.controls = { headings: await page.getByRole("heading").allTextContents(), + buttons: await page.getByRole("button").allTextContents(), alerts: await page.getByRole("alert").allTextContents() }; + } + await record(boundary); + return boundary; + }; + await observe(); + let authenticationAttempted = false; + for (;;) { + try { await control.waitFor({ timeout: Math.min(timeoutMs, 30_000) }); break; } + catch (error) { + if (page.isClosed()) throw error; + const boundary = await observe(true); + if (boundary.reauthenticationRequired) { + if (reauthenticate && !authenticationAttempted) { authenticationAttempted = true; await reauthenticate(); continue; } + throw new ConnectionBlock("awaiting_user", "github_registration_reauthentication_required"); + } + throw new ConnectionFailure("github_registration_create_control_missing"); + } + } + await observe(); + return control; +} + /** Capture measured pages only, excluding authentication and unrelated GitHub data. */ export function isGitHubJourneyEvidencePage(value: string, targetOrigin: string, repository: string, appSlug?: string) { const url = new URL(value); diff --git a/tests/runner-e2e/github-review-flow.ts b/tests/runner-e2e/github-review-flow.ts index c580ed767fa..5547adf21a2 100644 --- a/tests/runner-e2e/github-review-flow.ts +++ b/tests/runner-e2e/github-review-flow.ts @@ -3,7 +3,7 @@ import type { GitHubTaskReview } from "../../packages/shared/src/types/chat-gith import type { GitHubRepositoryPage } from "../../packages/shared/src/types/chat-channels.js"; import { ConnectionBlock, ConnectionFailure } from "./connection-config.js"; import { ConnectionApi } from "./connection-target.js"; -import { awaitJourneyCondition, createGitHubJourneyPullRequest, enterGitHubJourneyCompany, observeGitHubHead, selectGitHubJourneyRepository } from "./github-review-browser.js"; +import { awaitJourneyCondition, createGitHubJourneyPullRequest, enterGitHubJourneyCompany, observeGitHubHead, selectGitHubJourneyRepository, waitForGitHubRegistrationControl, type GitHubRegistrationBoundary } from "./github-review-browser.js"; import { githubCartFixture, hasOnlyOpenedAutomaticReview, matchesGitHubJourneyEnvironment, retainGitHubReview, verifyGitHubReview, verifyGitHubReviewRun, type GitHubReviewJourneyEvidence } from "./github-review-evidence.js"; import type { GitHubReviewJourneyConfig } from "./github-review-config.js"; import { captureOwnedGitHubApp, readOwnedGitHubReviewRuns, type GitHubJourneyResources } from "./github-review-ownership.js"; @@ -15,6 +15,8 @@ export async function runGitHubReviewFlow(input: { checkpoint(id: keyof GitHubReviewJourneyEvidence["checkpoints"], page: Page): Promise; phase(id: string): Promise; persistResources(): Promise; + recordRegistrationBoundary?(boundary: GitHubRegistrationBoundary): Promise; + authenticateRegistration?(page: Page): Promise; }) { const { page, github, api, config, resources, evidence } = input; const capabilities = await api.get('/api/instance/settings/experimental'); @@ -69,8 +71,8 @@ export async function runGitHubReviewFlow(input: { // Manifest flow navigates the same tab. External App grants remain attended. evidence.assisted = true; await awaitJourneyCondition(async () => new URL(page.url()).hostname === "github.com", 30_000, "github_manifest_handoff_missing", input.signal); - const createApp = page.getByRole("button", { name: new RegExp(`^Create GitHub App(?: for ${config.github.appOwner})?$`) }); - await createApp.waitFor({ timeout: config.browser.loginTimeoutMs }); + const createApp = await waitForGitHubRegistrationControl(page, config.github.appOwner, config.browser.loginTimeoutMs, + input.recordRegistrationBoundary, input.authenticateRegistration ? () => input.authenticateRegistration!(page) : undefined); await page.bringToFront(); await input.checkpoint("app_creation_consent", page); console.log(`[github-review-journey] Authorize creation of only ${resources.appName} in the dedicated QA browser. Install it only on ${config.github.repository}.`); diff --git a/tests/runner-e2e/github-review-journey.test.ts b/tests/runner-e2e/github-review-journey.test.ts index 8489b4596b0..09ce3e869dd 100644 --- a/tests/runner-e2e/github-review-journey.test.ts +++ b/tests/runner-e2e/github-review-journey.test.ts @@ -8,9 +8,9 @@ import type { GitHubTaskReview } from "../../packages/shared/src/types/chat-gith import { verifyConnectionTarget } from "./connection-target.js"; import { parseConnectionConfig } from "./connection-config.js"; import type { APIRequestContext } from "@playwright/test"; -import { captureOwnedGitHubApp, readOwnedGitHubReviewRuns, type GitHubJourneyResources } from "./github-review-ownership.js"; +import { captureOwnedGitHubApp, readOwnedGitHubReviewRuns, stopOwnedGitHubReviewRun, type GitHubJourneyResources } from "./github-review-ownership.js"; import type { ChatEndpoint } from "../../packages/shared/src/types/chat-channels.js"; -import { enterGitHubJourneyCompany, isGitHubJourneyEvidencePage } from "./github-review-browser.js"; +import { enterGitHubJourneyCompany, isGitHubJourneyEvidencePage, waitForGitHubRegistrationControl } from "./github-review-browser.js"; import { attendGitHubJourneyAction } from "./github-review-attendance.js"; import { PassThrough } from "node:stream"; import type { Locator, Page } from "@playwright/test"; @@ -19,7 +19,104 @@ import { runGitHubReviewCampaign } from "./github-review-launch.js"; import type { ConnectionApi } from "./connection-target.js"; import { runGitHubReviewFlow } from "./github-review-flow.js"; +describe("GitHub registration handoff", () => { + const page = (pathname: string, password: boolean, available: boolean) => ({ + url: () => `https://github.com${pathname}?return_to=private-grant&token=never-retain`, isClosed: () => false, + locator: (selector: string) => ({ count: async () => selector.includes('password') && password ? 1 : 0 }), + getByRole: (_role?: string, options?: { name?: string | RegExp }) => ({ isVisible: async () => String(options?.name).includes('Create GitHub App') && available, allTextContents: async () => ['Registration error'], + waitFor: vi.fn(async () => { if (!available) throw new Error("control_missing"); }) }), + }); + it("classifies a reauthentication boundary and retains no query or auth content", async () => { + const record = vi.fn(); + await expect(waitForGitHubRegistrationControl(page('/sessions/sudo', true, false) as unknown as Page, 'fixture', 600000, record)) + .rejects.toThrow('github_registration_reauthentication_required'); + expect(record.mock.calls.at(-1)?.[0]).toEqual({ origin: 'https://github.com', pathname: '/sessions/sudo', passwordRequired: true, oneTimeCodeRequired: false, reauthenticationRequired: true, createControlVisible: false }); + expect(JSON.stringify(record.mock.calls)).not.toMatch(/private-grant|never-retain/); + }); + it("fails a missing creation control on an ordinary registration page", async () => { + const record = vi.fn(); + await expect(waitForGitHubRegistrationControl(page('/settings/apps/manifest', false, false) as unknown as Page, 'fixture', 600000, record)) + .rejects.toThrow('github_registration_create_control_missing'); + expect(record.mock.calls.at(-1)?.[0].controls.alerts).toEqual(['Registration error']); + }); + it("admits the ordinary creation control with a bounded render wait", async () => { + const target = page('/settings/apps/new', false, true); + const control = target.getByRole('button', { name: /^Create GitHub App/ }); + const get = target.getByRole; + target.getByRole = (role, options) => String(options?.name).includes('Create GitHub App') ? control : get(role, options); + await expect(waitForGitHubRegistrationControl(target as unknown as Page, 'fixture', 600000)).resolves.toBe(control); + expect(control.waitFor).toHaveBeenCalledWith({ timeout: 30000 }); + }); + it("keeps passkey-first sudo at the manifest path out of authentication content diagnostics", async () => { + const target = page('/settings/apps/manifest', false, false), get = target.getByRole; + target.getByRole = (role, options) => String(options?.name).includes('Confirm access') + ? { ...get(role, options), isVisible: async () => true } : get(role, options); + const record = vi.fn(); + await expect(waitForGitHubRegistrationControl(target as unknown as Page, 'fixture', 600000, record)) + .rejects.toThrow('github_registration_reauthentication_required'); + expect(record.mock.calls.at(-1)?.[0].reauthenticationRequired).toBe(true); + expect(record.mock.calls.at(-1)?.[0].controls).toBeUndefined(); + }); + it("uses a supplied ordinary reauthentication adapter once before retrying creation readiness", async () => { + const target = page('/settings/apps/manifest', true, false), get = target.getByRole; + let authenticated = false; + const control = { ...get(), isVisible: async () => authenticated, + waitFor: vi.fn(async () => { if (!authenticated) throw new Error('sudo_required'); }) }; + target.getByRole = (role, options) => String(options?.name).includes('Create GitHub App') ? control : get(role, options); + const authenticate = vi.fn(async () => { authenticated = true; }); + await expect(waitForGitHubRegistrationControl(target as unknown as Page, 'fixture', 600000, async () => {}, authenticate)).resolves.toBe(control); + expect(authenticate).toHaveBeenCalledOnce(); + }); +}); + describe("reused target ownership", () => { + it("stops a scheduled legacy retry and waits until its cancellation finishes", async () => { + const scope = { companyId: 'company', agentId: 'agent', issueId: 'issue' }; + const scheduled = { ...scope, id: 'run', status: 'scheduled_retry', runtimeMode: 'legacy' }; + const get = vi.fn().mockResolvedValueOnce(scheduled).mockResolvedValueOnce(scheduled) + .mockResolvedValue({ ...scheduled, status: 'cancelled' }); + const post = vi.fn().mockResolvedValue({}); + await stopOwnedGitHubReviewRun({ get, post } as unknown as ConnectionApi, 'run', scope, new AbortController().signal); + expect(post).toHaveBeenCalledExactlyOnceWith('/api/heartbeat-runs/run/cancel', {}); + expect(get).toHaveBeenCalledTimes(3); + }); + it.each(['legacy', undefined])("stops a queued %s run without a native-only cancellation request", async runtimeMode => { + const scope = { companyId: 'company', agentId: 'agent', issueId: 'issue' }; + const queued = { ...scope, id: 'run', status: 'queued', runtimeMode }; + const get = vi.fn().mockResolvedValueOnce(queued).mockResolvedValue({ ...queued, status: 'cancelled' }); + const post = vi.fn(async (_route: string, body: Record) => { + if (body.cancellationRequestId) throw new Error('Correlated Stop requires a native run'); + return {}; + }); + await stopOwnedGitHubReviewRun({ get, post } as unknown as ConnectionApi, 'run', scope, new AbortController().signal); + expect(post).toHaveBeenCalledExactlyOnceWith('/api/heartbeat-runs/run/cancel', {}); + expect(get).toHaveBeenCalledTimes(2); + }); + it.each([true, false])("stops a failed native retry and verifies its audited acknowledgement (dispatched=%s)", async dispatched => { + const scope = { companyId: 'company', agentId: 'agent', issueId: 'issue' }; + const failed = { ...scope, id: 'run', status: 'failed', runtimeMode: 'native', nativePhase: 'retryable_failure' }; + const get = vi.fn().mockResolvedValueOnce(failed).mockResolvedValue({ ...failed, status: 'cancelled', costAccountingPending: true, + resultJson: { nativeCancellation: { schema: 'paperclip.native-cancellation.v1', runId: 'run', companyId: 'company', issueId: 'issue', scope: 'run', reasonCode: 'cancellation_run_only', dispatched, dispatchState: 'acknowledged', intentAuditId: 'intent', acknowledgementAuditId: 'ack' } } }); + const post = vi.fn().mockResolvedValue({}); + await stopOwnedGitHubReviewRun({ get, post } as unknown as ConnectionApi, 'run', scope, new AbortController().signal); + expect(post).toHaveBeenCalledExactlyOnceWith('/api/heartbeat-runs/run/cancel', { cancellationRequestId: expect.any(String) }); + expect(get).toHaveBeenCalledTimes(2); + }); + it("refuses to stop a related run belonging to a different task", async () => { + const post = vi.fn(); + const api = { get: async () => ({ id: 'run', companyId: 'company', agentId: 'agent', issueId: 'other', status: 'running' }), post }; + await expect(stopOwnedGitHubReviewRun(api as unknown as ConnectionApi, 'run', { companyId: 'company', agentId: 'agent', issueId: 'issue' }, new AbortController().signal)) + .rejects.toThrow('cleanup_run_owner_mismatch'); + expect(post).not.toHaveBeenCalled(); + }); + it("does not accept cancelled status as native Stop acknowledgement", async () => { + const scope = { companyId: 'company', agentId: 'agent', issueId: 'issue' }; + const get = vi.fn().mockResolvedValueOnce({ ...scope, id: 'run', status: 'running', runtimeMode: 'native' }) + .mockResolvedValue({ ...scope, id: 'run', status: 'cancelled', runtimeMode: 'native' }); + await expect(stopOwnedGitHubReviewRun({ get, post: async () => ({}) } as unknown as ConnectionApi, 'run', scope, new AbortController().signal, 1)) + .rejects.toThrow('owned_run_cancellation_unconfirmed'); + expect(get.mock.calls.length).toBeGreaterThan(1); + }); it("admits an inherited environment before setup and still leaves actual-run verification mandatory", async () => { const setup = parseGitHubReviewJourneyConfig(config()); const company = { id: setup.target.companyId, issuePrefix: "QA" }; diff --git a/tests/runner-e2e/github-review-launch.ts b/tests/runner-e2e/github-review-launch.ts index a78365f6add..83f4667d90c 100644 --- a/tests/runner-e2e/github-review-launch.ts +++ b/tests/runner-e2e/github-review-launch.ts @@ -12,7 +12,7 @@ import { createPrivateJourneyRepository, ensureGitHubJourneyLogin, closeOwnedGit import { loadGitHubReviewJourneyConfig } from "./github-review-config.js"; import { gradeGitHubReviewJourney, type GitHubReviewJourneyEvidence } from "./github-review-evidence.js"; import { runGitHubReviewFlow } from "./github-review-flow.js"; -import { captureOwnedGitHubApp, readOwnedGitHubReviewRuns, type GitHubJourneyResources } from "./github-review-ownership.js"; +import { captureOwnedGitHubApp, readOwnedGitHubReviewRuns, stopOwnedGitHubReviewRun, type GitHubJourneyResources } from "./github-review-ownership.js"; import { JourneyDependencyError, resolveJourneyCredential } from "./journey-dependencies.js"; import { sanitizeJson, assertSecretFree } from "./redaction.js"; import { writeGitHubReviewReport } from "./github-review-report.js"; @@ -101,7 +101,14 @@ export async function runGitHubReviewCampaign(input: { executions: readonly Matr const identity = await verifyConnectionTarget(config.target.baseURL, common, browser.context.request); evidence.targetCommit = identity.commit; evidence.checkpoints.target = true; await runGitHubReviewFlow({ page, github, githubUsername: config.github.account, api, config, resources, evidence, signal, - phase: checkpoint, persistResources: () => save("owned-resources.json", resources), checkpoint: async (id, tab) => { + phase: checkpoint, persistResources: () => save("owned-resources.json", resources), + ...(typeof authentication?.authenticateGitHubJourneyRegistration === "function" ? { + authenticateRegistration: (tab: Page) => authentication.authenticateGitHubJourneyRegistration({ page: tab, + configFile: config!.authentication!.configFile, expectedAccount: config!.github.account, signal, + deadlineAt: Date.now() + Math.min(config!.browser.loginTimeoutMs, 120_000), + registerSecret: (value: string) => secrets.push(value), checkpoint: (id: string) => checkpoint(id) }), + } : {}), + recordRegistrationBoundary: boundary => save("github-registration-boundary.json", boundary), checkpoint: async (id, tab) => { evidence.checkpoints[id] = true; // Authentication pages and forms are deliberately never captured. const consentUrl = new URL(tab.url()); @@ -180,12 +187,8 @@ export async function runGitHubReviewCampaign(input: { executions: readonly Matr await save("owned-resources.json", resources); await api.post(`/api/chat-endpoints/${resources.endpointId}/setup`, { action: "remove" }); for (const runId of resources.runIds) { - const run = await api.get(`/api/heartbeat-runs/${runId}`); - if (run.companyId !== config!.target.companyId || run.agentId !== config!.agent.id) throw new ConnectionFailure("cleanup_run_owner_mismatch"); - if (["queued", "running"].includes(run.status)) { - await api.post(`/api/heartbeat-runs/${runId}/cancel`); - await awaitJourneyCondition(async () => !["queued", "running"].includes((await api!.get(`/api/heartbeat-runs/${runId}`)).status), 30_000, "owned_run_cancellation_unconfirmed", cleanupSignal, "failed"); - } + if (!resources.issueId) throw new ConnectionFailure("cleanup_run_issue_missing"); + await stopOwnedGitHubReviewRun(api, runId, { companyId: config!.target.companyId, agentId: config!.agent.id, issueId: resources.issueId }, cleanupSignal); } if (resources.issueId && result.status !== "passed") { const issue = await api.get(`/api/issues/${resources.issueId}`); diff --git a/tests/runner-e2e/github-review-ownership.ts b/tests/runner-e2e/github-review-ownership.ts index f1d15ee4855..867ff16e84c 100644 --- a/tests/runner-e2e/github-review-ownership.ts +++ b/tests/runner-e2e/github-review-ownership.ts @@ -2,6 +2,10 @@ import type { ChatEndpoint } from "../../packages/shared/src/types/chat-channels import { ConnectionFailure } from "./connection-config.js"; import type { GitHubReviewJourneyConfig } from "./github-review-config.js"; import type { ConnectionApi } from "./connection-target.js"; +import { randomUUID } from "node:crypto"; +import { awaitJourneyCondition } from "./github-review-browser.js"; + +const liveRunStatuses = new Set(["queued", "running", "scheduled_retry"]); /** The issue run source includes history beyond company list windows. Related * activity can name a run for another task, so hydrate and check direct ownership. */ @@ -13,6 +17,33 @@ export async function readOwnedGitHubReviewRuns(api: Pick, return runs.filter(run => run.issueId === scope.issueId && run.agentId === scope.agentId); } +/** A failed native run can still own a durable retry. Stop it through the + * normal audited route and require acknowledgement, not just terminal status. */ +export async function stopOwnedGitHubReviewRun(api: Pick, runId: string, + scope: { companyId: string; agentId: string; issueId: string }, signal: AbortSignal, timeoutMs = 30_000) { + const read = async () => { + const run = await api.get>(`/api/heartbeat-runs/${runId}`); + if (run.id !== runId || run.companyId !== scope.companyId || run.agentId !== scope.agentId || run.issueId !== scope.issueId) { + throw new ConnectionFailure("cleanup_run_owner_mismatch"); + } + return run; + }; + const run = await read(); + const retry = run.runtimeMode === "native" && run.status === "failed" && run.nativePhase === "retryable_failure"; + if (!liveRunStatuses.has(run.status) && !retry) return; + await api.post(`/api/heartbeat-runs/${runId}/cancel`, run.runtimeMode === "native" ? { cancellationRequestId: randomUUID() } : {}); + await awaitJourneyCondition(async () => { + const stopped = await read(); + if (run.runtimeMode !== "native") return !liveRunStatuses.has(stopped.status); + const intent = stopped.resultJson?.nativeCancellation; + return stopped.status === "cancelled" && intent?.schema === "paperclip.native-cancellation.v1" + && intent.runId === runId && intent.companyId === scope.companyId && intent.issueId === scope.issueId + && intent.scope === "run" && intent.reasonCode === "cancellation_run_only" && typeof intent.dispatched === "boolean" + && intent.dispatchState === "acknowledged" && typeof intent.intentAuditId === "string" && intent.intentAuditId.length > 0 + && typeof intent.acknowledgementAuditId === "string" && intent.acknowledgementAuditId.length > 0; + }, timeoutMs, "owned_run_cancellation_unconfirmed", signal, "failed"); +} + export interface GitHubJourneyResources { endpointId?: string; pullNumber?: number; branch: string; appName: string; appId?: string; appSlug?: string; appSettingsUrl?: string; installationSettingsUrl?: string; From 8415f4a679689eab68af5d41331639cacf7fd6cd Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sat, 24 Oct 2026 21:58:43 -0700 Subject: [PATCH 041/110] fix(github): drain queued pings during active App setup (#17551) ## Thinking Path > - Paperclip connects external work to an agent and its ordinary tasks. > - A dedicated GitHub App must prove signed webhook delivery during setup. > - Cloud queues the original bytes until the tenant can authenticate them. > - An older personal connection can leave a long empty-queue backoff in that tenant. > - Active App setup can then time out before the queued ping is read. > - This change lets active setup request the existing event drain with a short rate limit. > - The same webhook handler still owns signature verification and setup state. ## Linked Issues or Issue Description Refs: #17457, #17513. **What happened?** Cloud accepted a new App's ping, but the tenant read it only after the setup wait timed out and cleanup archived the draft. An existing personal GitHub connection had left an empty-queue backoff. The poller checked that deadline before it read the new App state. **Expected behavior** An active manager setup request must be able to read the queued ping promptly. It must not bypass signature checks or create another App. **Steps to reproduce** 1. Let a personal GitHub connection build its empty-queue backoff. 2. Start a dedicated App and complete its installation. 3. Return to the waiting setup screen while the signed ping is queued. **Paperclip version or commit** This behavior is present on the base commit of this PR. ## What Changed - Let the authenticated wizard request a queue drain only while its Cloud App still lacks signed-delivery verification. Existing manager, credential, and installation checks run first. - Register a narrow callback to the server-owned GitHub poller. Keep provider handling in the GitHub services. Remove the callback on server close. - Share one in-flight attempt between setup and background requests. Limit setup attempts to one per five seconds, including after errors. - Retain the existing passive backoff, sealed queue, acknowledgement rules, and canonical webhook signature handler. - Add regressions for the old backoff, concurrent requests, failed requests, and wizard signature verification. Update the setup documentation and map. ## Verification - Observed the backoff regression fail against the old service: active setup made no additional Cloud lease request. It passes with this fix. - Three focused event-poller tests pass. They use the real admission/backoff code with stubbed SQL and Cloud boundaries. - All 39 startup tests pass. Server TypeScript, map checks, and diff checks pass. - The Postgres integration suites could not start locally because this host exhausted its semaphore limit. They remain required CI checks. This is not a passing local integration result. - Full current-head CI passes, including the Postgres and chat integration suites. Greptile scored this exact head 5/5 with no unresolved findings. - The additional Paperclip review check ended neutral because its execution did not complete. It did not publish a validated assessment. - A fresh deployed setup attempt remains required before live qualification. ## Risks A waiting setup screen now makes a bounded readiness request to Cloud. The existing connector request timeout still applies. Concurrent calls share the same drain, and failures release it for a later retry. The request stops after persisted verification or when the browser stops advancing setup. No timer, durable queue, fleet setting, or sleep blocker is added or removed. The existing background reconciliation path still has its existing sleep restrictions. Live setup-to-review behavior is not established by these local tests. ## Model Used OpenAI Codex, based on GPT-6. The exact runtime model ID and context-window size are not exposed in this session. Used for code execution and regression analysis. ## 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 --- doc/connections/GITHUB-REVIEW-BOT.md | 7 + maps/feature-map/connection-setup.md | 9 + .../chat-channels.integration.test.ts | 25 ++- .../github-connection-events.test.ts | 20 +- server/src/index.ts | 12 +- .../src/services/chat-github-cloud-ingress.ts | 12 ++ server/src/services/chat-github-wizard.ts | 5 + .../services/github-connection-events.test.ts | 74 ++++++++ .../src/services/github-connection-events.ts | 171 ++++++++++-------- 9 files changed, 243 insertions(+), 92 deletions(-) create mode 100644 server/src/services/github-connection-events.test.ts diff --git a/doc/connections/GITHUB-REVIEW-BOT.md b/doc/connections/GITHUB-REVIEW-BOT.md index 2d9dc55197b..f63732c56a4 100644 --- a/doc/connections/GITHUB-REVIEW-BOT.md +++ b/doc/connections/GITHUB-REVIEW-BOT.md @@ -40,6 +40,13 @@ Installation may return before GitHub's separately delivered signed webhook ping. Paperclip keeps the same draft and credentials, shows a waiting state, and continues automatically after authenticating the ping. Refreshing or resuming that draft must not create another App or bypass signature verification. +While this Cloud setup screen is waiting, its authenticated advance request also +drains the existing sealed event queue. It can bypass an older idle-connection +backoff, at most once every five seconds. Setup and background requests share +one in-flight lease. The normal stack webhook handler still authenticates the +original GitHub bytes before setup can continue. This adds no background timer; +closing the screen stops these readiness requests. Existing background recovery +and its sleep restrictions remain unchanged. New connections default to authorized mentions, advisory reviews, linked-member access, guests off, and enabled bot GitHub tools. Existing instructions, explicit diff --git a/maps/feature-map/connection-setup.md b/maps/feature-map/connection-setup.md index 22306048e8a..d27fc36c657 100644 --- a/maps/feature-map/connection-setup.md +++ b/maps/feature-map/connection-setup.md @@ -205,6 +205,15 @@ configuration changes, saved retry deadlines, rollback, and parking pending repair while an endpoint or connection is inactive. The provider responses are fixtures. Settled maintenance leaves no discovery timer or database scans. +GitHub Cloud setup also covers an older empty-queue backoff, concurrent setup and +background leases, and retry after a Cloud error in the +[event poller regression](../../server/src/services/github-connection-events.test.ts). +Channel integration checks that active setup drains its signed ping through the +normal webhook handler; a forged ping still cannot verify the endpoint. These +fixtures do not establish live Cloud delivery. For live proof, start a disposable +App after an idle personal GitHub connection, complete installation, and confirm +that the same draft advances after authenticating the queued ping. + Manual: complete setup for one named provider, reload endpoint settings, link the intended sender, and send a disposable message. Verify one task and a useful reply in the originating conversation. Inspect an unlinked sender's denial and diff --git a/server/src/__tests__/chat-channels.integration.test.ts b/server/src/__tests__/chat-channels.integration.test.ts index 4fd186e6271..beb2c0b436a 100644 --- a/server/src/__tests__/chat-channels.integration.test.ts +++ b/server/src/__tests__/chat-channels.integration.test.ts @@ -24,7 +24,7 @@ import { toolActionRequests, toolInvocations, toolPolicies } from "@paperclipai/ import { GitHubPublicationLeaseLost, withGitHubPublicationLease } from "../services/chat-github-publication-lease.js"; import { secretService } from "../services/secrets.js"; import { githubChatWizardService } from "../services/chat-github-wizard.js"; -import { dispatchGitHubBotCloudEvent } from "../services/chat-github-cloud-ingress.js"; +import { dispatchGitHubBotCloudEvent, registerGitHubBotCloudSetupPoller } from "../services/chat-github-cloud-ingress.js"; import { githubChatManagementService } from "../services/chat-github-management.js"; import { githubChatReviewService } from "../services/chat-github-reviews.js"; import { resolveGitHubReviewInstructions } from "../services/chat-channels/github/review-instructions.js"; @@ -5135,13 +5135,22 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => { (await f.service.get(f.endpoint.id)).setup.webhookVerifiedAt, ).toBeNull(); expect(f.wakeup).not.toHaveBeenCalled(); - event.payload.githubApp.headers["x-hub-signature-256"] = - `sha256=${createHmac("sha256", f.webhookSecret).update(body).digest("hex")}`; - expect(await dispatchGitHubBotCloudEvent(db, event)).toBe(true); - expect( - (await f.service.get(f.endpoint.id)).setup.webhookVerifiedAt, - ).toBeTruthy(); - expect(f.wakeup).not.toHaveBeenCalled(); + const poll = vi.fn(async () => { await dispatchGitHubBotCloudEvent(db, event); }); + const unregister = registerGitHubBotCloudSetupPoller(db, poll); + try { + const waiting = await f.service.githubWizard.advance(f.endpoint.id, "owner-user"); + expect(waiting.state).toBe("verify"); + expect(poll).toHaveBeenCalledOnce(); + expect((await f.service.get(f.endpoint.id)).setup.webhookVerifiedAt).toBeNull(); + event.payload.githubApp.headers["x-hub-signature-256"] = + `sha256=${createHmac("sha256", f.webhookSecret).update(body).digest("hex")}`; + const ready = await f.service.githubWizard.advance(f.endpoint.id, "owner-user"); + expect(ready.state).not.toBe("verify"); + expect((await f.service.get(f.endpoint.id)).setup.webhookVerifiedAt).toBeTruthy(); + expect(f.wakeup).not.toHaveBeenCalled(); + await f.service.githubWizard.advance(f.endpoint.id, "owner-user"); + expect(poll).toHaveBeenCalledTimes(2); + } finally { unregister(); } }); it("legacy name-only registration preserves an explicit empty repository selection", async () => { const fixture = await seedCompany(); diff --git a/server/src/__tests__/github-connection-events.test.ts b/server/src/__tests__/github-connection-events.test.ts index 77d34f15e6a..6bcd2913396 100644 --- a/server/src/__tests__/github-connection-events.test.ts +++ b/server/src/__tests__/github-connection-events.test.ts @@ -7,6 +7,7 @@ import { connectionGrants, createDb, externalObjects, + EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, toolApplications, toolConnections, } from "@paperclipai/db"; @@ -30,7 +31,7 @@ describeEmbeddedPostgres("GitHub connection event delivery", () => { beforeAll(async () => { tempDb = await startEmbeddedPostgresTestDatabase("paperclip-github-events-"); db = createDb(tempDb.connectionString); - }, 20_000); + }, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS); afterEach(async () => { await db.delete(activityLog); @@ -46,7 +47,7 @@ describeEmbeddedPostgres("GitHub connection event delivery", () => { await tempDb?.cleanup(); }); - it("applies a normalized merged PR once while retaining undecryptable siblings for retry", async () => { + it.each([false, true])("applies a normalized merged PR once while retaining undecryptable siblings for retry (active setup=%s)", async activeSetup => { const companyId = randomUUID(); const userId = `github-owner-${randomUUID()}`; const applicationId = randomUUID(); @@ -151,8 +152,21 @@ describeEmbeddedPostgres("GitHub connection event delivery", () => { let currentTime = new Date("2026-09-04T12:00:05.000Z"); const service = githubConnectionEventService(db, { connector, now: () => currentTime }); + if (activeSetup) { + // An existing personal connection can leave a long empty-queue backoff + // before a new dedicated App starts its signed-ping verification. + for (const delay of [0, 10_000, 20_000, 40_000, 80_000]) { + currentTime = new Date(currentTime.getTime() + delay); + vi.mocked(connector.leaseEvents).mockResolvedValueOnce(null); + await service.pollOnce(); + } + currentTime = new Date(currentTime.getTime() + 5_000); + await expect(service.pollOnce()).resolves.toMatchObject({ leased: 0 }); + expect(connector.leaseEvents).toHaveBeenCalledTimes(5); + } + const warning = vi.spyOn(logger, "warn").mockImplementation(() => undefined); - await expect(service.pollOnce()).resolves.toMatchObject({ leased: 2, processed: 1, duplicate: 0, failed: 1 }); + await expect(service.pollOnce({ forSetup: activeSetup })).resolves.toMatchObject({ leased: 2, processed: 1, duplicate: 0, failed: 1 }); expect(warning.mock.calls).toEqual([[{ deliveryId: "undecryptable-delivery", reason: "inner_event_authentication_failed", }, "GitHub connector event retained for retry"]]); diff --git a/server/src/index.ts b/server/src/index.ts index e83d603e2aa..207f342a2ae 100644 --- a/server/src/index.ts +++ b/server/src/index.ts @@ -136,6 +136,7 @@ import { } from "./services/device-login-reaper.js"; import { createProductionSetupTokenReaper } from "./services/setup-token-reaper.js"; import { localAiLoginService } from "./services/local-ai-login.js"; +import { registerGitHubBotCloudSetupPoller } from "./services/chat-github-cloud-ingress.js"; import { resolveWorktreeRunExecutionActivationState } from "./services/instance-settings.js"; import { parseAdapterRegistryEnv, @@ -1419,9 +1420,9 @@ async function startServerWithDatabaseTeardown( ?? process.env.PAPERCLIP_TOOL_RUNTIME_TRUSTED_HOST ?? null, }); - const scheduleGitHubConnectionEventPoll = () => { + const scheduleGitHubConnectionEventPoll = (forSetup = false) => { if (isIdleTaskDrainActive() || heartbeatSchedulerStopped) return; - trackHeartbeatSchedulerWork(githubConnectionEvents.pollOnce() + const work = githubConnectionEvents.pollOnce({ forSetup }) .then((result) => { if (result.leased > 0 || result.failed > 0) { logger.info(result, "GitHub connection event poll completed"); @@ -1429,8 +1430,13 @@ async function startServerWithDatabaseTeardown( }) .catch((err) => { logger.error({ err }, "GitHub connection event poll failed"); - })); + }); + trackHeartbeatSchedulerWork(work); + return work; }; + server.on("close", registerGitHubBotCloudSetupPoller(db, async () => { + await scheduleGitHubConnectionEventPoll(true); + })); const scheduleGitHubConnectionContinuitySweep = () => { if (isIdleTaskDrainActive() || heartbeatSchedulerStopped) return; trackHeartbeatSchedulerWork(tools.sweepGitHubConnectionContinuity() diff --git a/server/src/services/chat-github-cloud-ingress.ts b/server/src/services/chat-github-cloud-ingress.ts index b1493d64779..2f8e75eb8f9 100644 --- a/server/src/services/chat-github-cloud-ingress.ts +++ b/server/src/services/chat-github-cloud-ingress.ts @@ -7,6 +7,18 @@ type Event = SealedConnectorEvents["events"][number]; type Endpoint = typeof chatEndpoints.$inferSelect; type Handler = (endpoint: Endpoint, request: Request) => Promise; const handlers = new WeakMap(); +const setupPollers = new WeakMap Promise>(); + +/** The active wizard reuses the server-owned, serialized event drain. */ +export function registerGitHubBotCloudSetupPoller(db: Db, poll: () => Promise) { + setupPollers.set(db, poll); + return () => { if (setupPollers.get(db) === poll) setupPollers.delete(db); }; +} + +export async function pollGitHubBotCloudSetupEvents(db: Db): Promise { + await setupPollers.get(db)?.(); +} + export function registerGitHubBotCloudIngress(db: Db, handler: Handler) { handlers.set(db, handler); return () => { diff --git a/server/src/services/chat-github-wizard.ts b/server/src/services/chat-github-wizard.ts index 5f63f68db8c..701d77cba51 100644 --- a/server/src/services/chat-github-wizard.ts +++ b/server/src/services/chat-github-wizard.ts @@ -33,6 +33,7 @@ import { type PaperclipCloudConnector, } from "./paperclip-cloud-connector.js"; import { paperclipCloudConnectorEnrollmentStatus } from "./paperclip-cloud-connector-enrollment.js"; +import { pollGitHubBotCloudSetupEvents } from "./chat-github-cloud-ingress.js"; /** Loopback aliases are equivalent locally, but Cloud requires the approved exact origin. */ export function githubWizardBrowserOrigin( @@ -920,6 +921,10 @@ export function githubChatWizardService( // Keep the same vaulted App in the wizard instead of throwing JSON from // the browser callback or relaxing the configure action's signature gate. bot = await endpoint(id, userId); + if (!bot.setup.webhookVerifiedAt && bot.setup.github?.cloudRegistrationId) { + await pollGitHubBotCloudSetupEvents(db); + bot = await endpoint(id, userId); + } if (!bot.setup.webhookVerifiedAt) return { endpointId: id, diff --git a/server/src/services/github-connection-events.test.ts b/server/src/services/github-connection-events.test.ts new file mode 100644 index 00000000000..93031ecae62 --- /dev/null +++ b/server/src/services/github-connection-events.test.ts @@ -0,0 +1,74 @@ +import { describe, expect, it, vi } from "vitest"; +import { chatEndpoints, type Db } from "@paperclipai/db"; +import { githubConnectionEventService } from "./github-connection-events.js"; +import type { PaperclipCloudConnector } from "./paperclip-cloud-connector.js"; + +function fixture() { + let time = Date.parse("2026-09-04T12:00:00Z"); + const bindings = [{ + grant: { id: "grant", companyId: "company", kind: "user", subjectUserId: "owner", status: "active", + providerTenant: { github: { installationIds: ["101"] } } }, + connection: { id: "connection", config: { sourceTemplateKey: "github", oauth: { connectorProfile: "github.code" } } }, + }]; + const bots: Array<{ companyId: string }> = []; + // Only SQL is stubbed. Backoff, lease admission and concurrent execution use + // the real service; relational persistence has its own Postgres suite. + const select = vi.fn(() => ({ from: (table: unknown) => table === chatEndpoints + ? { where: async () => bots } + : { innerJoin: () => ({ where: async () => bindings }) } })); + const leaseEvents = vi.fn().mockResolvedValue(null); + const connector = { leaseEvents } as unknown as PaperclipCloudConnector; + const service = githubConnectionEventService({ select } as unknown as Db, { connector, now: () => new Date(time) }); + return { service, leaseEvents, select, bots, advance: (ms: number) => { time += ms; } }; +} + +describe("GitHub event polling during active App setup", () => { + it("reaches Cloud during an old empty-queue backoff without expanding idle polling", async () => { + const f = fixture(); + for (const delay of [0, 10_000, 20_000, 40_000, 80_000]) { + f.advance(delay); + await f.service.pollOnce(); + } + expect(f.leaseEvents).toHaveBeenCalledTimes(5); + const queries = f.select.mock.calls.length; + f.bots.push({ companyId: "company" }); + f.advance(5_000); + for (let index = 0; index < 3; index++) await f.service.pollOnce(); + expect(f.select).toHaveBeenCalledTimes(queries); + expect(f.leaseEvents).toHaveBeenCalledTimes(5); + await f.service.pollOnce({ forSetup: true }); + expect(f.leaseEvents).toHaveBeenCalledTimes(6); + const setupQueries = f.select.mock.calls.length; + await f.service.pollOnce({ forSetup: true }); + expect(f.leaseEvents).toHaveBeenCalledTimes(6); + expect(f.select).toHaveBeenCalledTimes(setupQueries); + f.advance(5_000); + await f.service.pollOnce({ forSetup: true }); + expect(f.leaseEvents).toHaveBeenCalledTimes(7); + }); + + it("shares one lease between setup and scheduled callers while Cloud is slow", async () => { + const f = fixture(); + let complete!: (value: null) => void; + f.leaseEvents.mockImplementationOnce(() => new Promise(resolve => { complete = resolve; })); + const scheduled = f.service.pollOnce(); + const setup = f.service.pollOnce({ forSetup: true }); + await vi.waitFor(() => expect(f.leaseEvents).toHaveBeenCalledTimes(1)); + expect(complete).toBeTypeOf("function"); + complete(null); + await Promise.all([scheduled, setup]); + expect(f.leaseEvents).toHaveBeenCalledTimes(1); + }); + + it("releases the shared attempt after an error and retries only after the setup throttle", async () => { + const f = fixture(); + f.leaseEvents.mockRejectedValueOnce(new Error("Cloud unavailable")); + await expect(f.service.pollOnce({ forSetup: true })).rejects.toThrow("Cloud unavailable"); + await f.service.pollOnce({ forSetup: true }); + await f.service.pollOnce(); + expect(f.leaseEvents).toHaveBeenCalledTimes(1); + f.advance(5_000); + await f.service.pollOnce({ forSetup: true }); + expect(f.leaseEvents).toHaveBeenCalledTimes(2); + }); +}); diff --git a/server/src/services/github-connection-events.ts b/server/src/services/github-connection-events.ts index 04022c647a1..6848875815f 100644 --- a/server/src/services/github-connection-events.ts +++ b/server/src/services/github-connection-events.ts @@ -221,6 +221,8 @@ export function githubConnectionEventService( const now = options.now ?? (() => new Date()); let nextPollAt = 0; let emptyPolls = 0; + let nextSetupPollAt = 0; + let inFlight: Promise | null = null; async function activeBindings() { const rows = await db.select({ grant: connectionGrants, connection: toolConnections }) @@ -458,88 +460,101 @@ export function githubConnectionEventService( return "processed" as const; } - return { - async pollOnce(): Promise { - if (now().getTime() < nextPollAt) { - return { leased: 0, processed: 0, duplicate: 0, ignored: 0, failed: 0 }; - } - const bindings = await activeBindings(); - const bots = await db.select().from(chatEndpoints).where(and(eq(chatEndpoints.provider, "github"), sql`${chatEndpoints.setup}->'github'->>'cloudRegistrationId' is not null`, sql`${chatEndpoints.status} <> 'archived'`)); - if (bindings.length === 0 && bots.length === 0) { - nextPollAt = now().getTime() + 5_000; - return { leased: 0, processed: 0, duplicate: 0, ignored: 0, failed: 0 }; - } - const config = options.connector ? null : paperclipCloudConnectorConfigFromEnv(options.env); - const connector = options.connector ?? (config ? createPaperclipCloudConnector({ config }) : null); - if (!connector) { - nextPollAt = now().getTime() + 5 * 60_000; - return { leased: 0, processed: 0, duplicate: 0, ignored: 0, failed: 0 }; - } - const first = bindings[0] ?? { subject: "github-bot-events", companyId: bots[0]!.companyId }; - const lease = await connector.leaseEvents({ subject: first.subject, companyId: first.companyId }); - if (!lease) { - emptyPolls += 1; - nextPollAt = now().getTime() + Math.min(bots.length ? 15_000 : 5 * 60_000, 5_000 * (2 ** Math.min(emptyPolls, 6))); - return { leased: 0, processed: 0, duplicate: 0, ignored: 0, failed: 0 }; - } - emptyPolls = 0; + async function runPoll(): Promise { + const bindings = await activeBindings(); + const bots = await db.select().from(chatEndpoints).where(and(eq(chatEndpoints.provider, "github"), sql`${chatEndpoints.setup}->'github'->>'cloudRegistrationId' is not null`, sql`${chatEndpoints.status} <> 'archived'`)); + if (bindings.length === 0 && bots.length === 0) { nextPollAt = now().getTime() + 5_000; - const result: GitHubConnectionEventPollResult = { - leased: lease.events.length + (lease.failedEventIds?.length ?? 0), - processed: 0, - duplicate: 0, - ignored: 0, - failed: lease.failedEventIds?.length ?? 0, - }; - const acknowledge: string[] = []; - for (const event of lease.events) { - if (event.payload.githubApp !== undefined) { - try { await dispatchGitHubBotCloudEvent(db, event); acknowledge.push(event.id); result.processed += 1; } - catch { result.failed += 1; } - continue; - } - const matched = bindings.filter((binding) => event.bindingIds.includes(binding.id)); - if (matched.length === 0) { - result.ignored += 1; - acknowledge.push(event.id); - continue; - } - try { - const companies = new Map(); - for (const binding of matched) companies.set(binding.companyId, [...(companies.get(binding.companyId) ?? []), binding]); - for (const [companyId, companyBindings] of companies) { - const status = await processForCompany(companyId, companyBindings, event); - result[status] += 1; - } - acknowledge.push(event.id); - if (event.event === "installation" && (event.action === "deleted" || event.action === "suspend")) { - await Promise.all(matched.map((binding) => connector.setWebhookBinding({ - subject: binding.subject, - companyId: binding.companyId, - id: binding.id, - installationId: binding.installationId, - connectionId: binding.connectionId, - grantId: binding.grantId, - active: false, - }))); - } - } catch { - result.failed += 1; - } + return { leased: 0, processed: 0, duplicate: 0, ignored: 0, failed: 0 }; + } + const config = options.connector ? null : paperclipCloudConnectorConfigFromEnv(options.env); + const connector = options.connector ?? (config ? createPaperclipCloudConnector({ config }) : null); + if (!connector) { + nextPollAt = now().getTime() + 5 * 60_000; + return { leased: 0, processed: 0, duplicate: 0, ignored: 0, failed: 0 }; + } + const first = bindings[0] ?? { subject: "github-bot-events", companyId: bots[0]!.companyId }; + const lease = await connector.leaseEvents({ subject: first.subject, companyId: first.companyId }); + if (!lease) { + emptyPolls += 1; + nextPollAt = now().getTime() + Math.min(bots.length ? 15_000 : 5 * 60_000, 5_000 * (2 ** Math.min(emptyPolls, 6))); + return { leased: 0, processed: 0, duplicate: 0, ignored: 0, failed: 0 }; + } + emptyPolls = 0; + nextPollAt = now().getTime() + 5_000; + const result: GitHubConnectionEventPollResult = { + leased: lease.events.length + (lease.failedEventIds?.length ?? 0), + processed: 0, + duplicate: 0, + ignored: 0, + failed: lease.failedEventIds?.length ?? 0, + }; + const acknowledge: string[] = []; + for (const event of lease.events) { + if (event.payload.githubApp !== undefined) { + try { await dispatchGitHubBotCloudEvent(db, event); acknowledge.push(event.id); result.processed += 1; } + catch { result.failed += 1; } + continue; } - if (acknowledge.length > 0) { - await connector.acknowledgeEvents({ - subject: first.subject, - companyId: first.companyId, - leaseId: lease.leaseId, - deliveryIds: acknowledge, - }); + const matched = bindings.filter((binding) => event.bindingIds.includes(binding.id)); + if (matched.length === 0) { + result.ignored += 1; + acknowledge.push(event.id); + continue; } - for (const deliveryId of lease.failedEventIds ?? []) { - logger.warn({ deliveryId, reason: "inner_event_authentication_failed" }, - "GitHub connector event retained for retry"); + try { + const companies = new Map(); + for (const binding of matched) companies.set(binding.companyId, [...(companies.get(binding.companyId) ?? []), binding]); + for (const [companyId, companyBindings] of companies) { + const status = await processForCompany(companyId, companyBindings, event); + result[status] += 1; + } + acknowledge.push(event.id); + if (event.event === "installation" && (event.action === "deleted" || event.action === "suspend")) { + await Promise.all(matched.map((binding) => connector.setWebhookBinding({ + subject: binding.subject, + companyId: binding.companyId, + id: binding.id, + installationId: binding.installationId, + connectionId: binding.connectionId, + grantId: binding.grantId, + active: false, + }))); + } + } catch { + result.failed += 1; } - return result; + } + if (acknowledge.length > 0) { + await connector.acknowledgeEvents({ + subject: first.subject, + companyId: first.companyId, + leaseId: lease.leaseId, + deliveryIds: acknowledge, + }); + } + for (const deliveryId of lease.failedEventIds ?? []) { + logger.warn({ deliveryId, reason: "inner_event_authentication_failed" }, + "GitHub connector event retained for retry"); + } + return result; + } + + return { + pollOnce(input: { forSetup?: boolean } = {}): Promise { + // A manager actively awaiting a dedicated App's signed ping must not + // inherit a personal connection's old empty-queue backoff. This is a + // bounded readiness probe, not an additional background polling loop. + if (inFlight) return inFlight; + const time = now().getTime(); + if (time < (input.forSetup ? nextSetupPollAt : nextPollAt)) { + return Promise.resolve({ leased: 0, processed: 0, duplicate: 0, ignored: 0, failed: 0 }); + } + nextSetupPollAt = time + 5_000; + nextPollAt = Math.max(nextPollAt, nextSetupPollAt); + const work = runPoll().finally(() => { if (inFlight === work) inFlight = null; }); + inFlight = work; + return work; }, }; } From 1ad8f25c7793e4e1d94c1afd29942d05d7778d87 Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Sat, 24 Oct 2026 23:53:39 -0700 Subject: [PATCH 042/110] perf(heartbeat): narrow queued comment polling run reads (#17560) Read current control facts and typed issue/adapter bindings for queued-comment polling. Keep full mutation and execution reads, native preparation and steering, authorization, and stored evidence. Validation: full build and typecheck, 160 focused tests plus two assembled route regressions; exact-head Greptile 5/5 (medium), full green CI, zero unresolved threads. Old-route counterfactual transfers 2.5 MB versus less than 2 KB. Co-Authored-By: Paperclip --- doc/DEVELOPING.md | 2 + .../issue-queued-comments-routes.test.ts | 32 +++++++++- server/src/routes/issues.ts | 14 +++-- server/src/services/heartbeat.ts | 6 ++ .../src/services/heartbeat/run-state.test.ts | 59 +++++++++++++++++++ server/src/services/heartbeat/run-state.ts | 25 ++++++++ 6 files changed, 130 insertions(+), 8 deletions(-) diff --git a/doc/DEVELOPING.md b/doc/DEVELOPING.md index e399790fbbb..432eb547d45 100644 --- a/doc/DEVELOPING.md +++ b/doc/DEVELOPING.md @@ -1812,6 +1812,8 @@ It owns bounded run projections, database encoding checks, task session reads an writes, explicit resumes, session compaction, and usage/billing helpers. `createHeartbeatRunState(db)` binds these operations without doing database work during construction. The encoding-check cache belongs to each factory instance. +Queued-comment polling reads current issue control fields, the typed issue binding, +and the selected adapter type. Mutation and execution paths retain their full run reads. `heartbeat.ts` keeps run execution and re-exports the existing public helpers. Keep session policy changes separate from run orchestration changes. diff --git a/server/src/__tests__/issue-queued-comments-routes.test.ts b/server/src/__tests__/issue-queued-comments-routes.test.ts index bb42982787b..60985954bea 100644 --- a/server/src/__tests__/issue-queued-comments-routes.test.ts +++ b/server/src/__tests__/issue-queued-comments-routes.test.ts @@ -4,6 +4,7 @@ import { randomUUID } from "node:crypto"; import express from "express"; import request from "supertest"; import { eq, sql } from "drizzle-orm"; +import { createDatabaseResponseCapture, installDatabaseResponseCapture } from "@paperclipai/db/response-capture"; import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; import { agentRuntimeState, @@ -79,7 +80,7 @@ describeEmbeddedPostgres("issue queued-comment routes", () => { await tempDb?.cleanup(); }); - function app(companyId: string, userId = "queue-owner", agentActor?: { agentId: string; runId: string }) { + function app(companyId: string, userId = "queue-owner", agentActor?: { agentId: string; runId: string }, database = db) { const testApp = express(); testApp.use(express.json()); testApp.use((req, _res, next) => { @@ -94,7 +95,7 @@ describeEmbeddedPostgres("issue queued-comment routes", () => { }; next(); }); - testApp.use("/api", issueRoutes(db, {} as any, {})); + testApp.use("/api", issueRoutes(database, {} as any, {})); testApp.use(errorHandler); return testApp; } @@ -192,6 +193,33 @@ describeEmbeddedPostgres("issue queued-comment routes", () => { return { companyId, agentId, issueId, runId, wakeId, commentIds }; } + it.each([false, true])("polls queued comments without transferring run snapshots (agent fallback: %s)", async fallback => { + const f = await seedQueue(), payload = "saved-execution-input🙂".repeat(25_000); + await db.update(heartbeatRuns).set({ contextSnapshot: { issueId: f.issueId, prompt: payload }, + runnerProfileJson: { adapterDispatch: { adapterType: "paperclip_runner", adapterConfig: { instructions: payload } } }, + stdoutExcerpt: payload, stderrExcerpt: payload, + }).where(eq(heartbeatRuns.id, f.runId)); + if (fallback) await db.update(issues).set({ executionRunId: null }).where(eq(issues.id, f.issueId)); + const [before] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId)); + const observed = createDb(tempDb!.connectionString), events: Array> = [], now = Date.now(); + const capture = createDatabaseResponseCapture({ start: now - 100, end: now + 59_000 }, event => events.push(event)); + installDatabaseResponseCapture(observed, { heartbeatRuns }, capture); + try { + const response = await request(app(f.companyId, "queue-owner", undefined, observed)) + .get(`/api/issues/${f.issueId}/queued-comments`).expect(200); + expect(response.body.queueId).toBe(f.wakeId); + expect(response.body.targetRunId).toBe(f.runId); + expect(response.body.entries.map((entry: { comment: { id: string } }) => entry.comment.id)).toEqual(f.commentIds); + capture.flush(); + const reads = events.filter(event => event.table === "heartbeat_runs" && event.operation === "select"); + expect(reads.length).toBeGreaterThan(0); + expect(reads.reduce((bytes, event) => bytes + Number(event.responseValueBytes), 0)).toBeLessThan(2048); + await request(app(randomUUID(), "queue-owner", undefined, observed)) + .get(`/api/issues/${f.issueId}/queued-comments`).expect(404); + expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId)))[0]).toEqual(before); + } finally { capture.flush(); await observed.$client.end(); } + }); + it.each(["cancelled", "running"])("rejects a late Done from an interrupted %s task run at the write boundary", async status => { const seeded = await seedQueue(); await db.update(heartbeatRuns).set({ status, resultJson: { executionCancellation: { state: "requested" } } }) diff --git a/server/src/routes/issues.ts b/server/src/routes/issues.ts index 9a29f1c9d91..6aa65dfb774 100644 --- a/server/src/routes/issues.ts +++ b/server/src/routes/issues.ts @@ -7247,18 +7247,20 @@ export function issueRoutes( id: string; assigneeAgentId: string | null; executionRunId?: string | null; - }) { + }, options?: { queueStateOnly: true }) { let runToInterrupt = issue.executionRunId - ? await heartbeat.getRun(issue.executionRunId) + ? options?.queueStateOnly + ? await heartbeat.getRunIssueControl(issue.executionRunId) + : await heartbeat.getRun(issue.executionRunId) : null; if ( (!runToInterrupt || runToInterrupt.status !== "running") && issue.assigneeAgentId ) { - const activeRun = await heartbeat.getActiveRunForAgent( - issue.assigneeAgentId, - ); + const activeRun = options?.queueStateOnly + ? await heartbeat.getActiveRunIssueControlForAgent(issue.assigneeAgentId) + : await heartbeat.getActiveRunForAgent(issue.assigneeAgentId); const activeIssueId = activeRun && activeRun.contextSnapshot && @@ -16343,7 +16345,7 @@ export function issueRoutes( const queue = await buildQueuedCommentQueue({ executor: db, issue, - activeRun: await resolveActiveIssueRun(issue), + activeRun: await resolveActiveIssueRun(issue, { queueStateOnly: true }), actor: getActorInfo(req), }); res.json( diff --git a/server/src/services/heartbeat.ts b/server/src/services/heartbeat.ts index 9a18721aaa7..f177921a36d 100644 --- a/server/src/services/heartbeat.ts +++ b/server/src/services/heartbeat.ts @@ -832,6 +832,8 @@ export function heartbeatService( listEvents, getRetryExhaustedReason, getRunIssueSummary, + getRunIssueControl, + getActiveRunIssueControlForAgent, getActiveRunForAgent, getActiveRunIssueSummaryForAgent, } = createHeartbeatRunState(db); @@ -4153,6 +4155,10 @@ export function heartbeatService( getRunIssueSummary, + getRunIssueControl, + + getActiveRunIssueControlForAgent, + getActiveRunForAgent, getActiveRunIssueSummaryForAgent, diff --git a/server/src/services/heartbeat/run-state.test.ts b/server/src/services/heartbeat/run-state.test.ts index ccc91735df4..e42d93d7286 100644 --- a/server/src/services/heartbeat/run-state.test.ts +++ b/server/src/services/heartbeat/run-state.test.ts @@ -20,6 +20,7 @@ import { import * as legacy from "../heartbeat.js"; import * as extracted from "./run-state.js"; import { readRunCancellation } from "../run-cancellation.js"; +import { decideQueuedCommentQueueSteering } from "../issue-queued-comment-queue.js"; // SQL_ASCII needs a separate database cluster. Inspect its selected SQL here; // the PostgreSQL tests below exercise the session queries and transactions. @@ -158,6 +159,64 @@ describePostgres("heartbeat run state database wiring", () => { return { companyId, agent, issue, state: extracted.createHeartbeatRunState(db) }; } + it("reads fresh issue control facts without transferring execution snapshots", async () => { + const { companyId, agent, issue } = await fixture(); + const payload = randomBytes(128 * 1024).toString("base64"); + const [run] = await db.insert(heartbeatRuns).values({ companyId, agentId: agent.id, status: "running", + runtimeMode: "legacy", runtimeModeResolvedAt: null, + startedAt: new Date("2020-01-01T00:00:00Z"), + contextSnapshot: { issueId: issue.id, prompt: payload }, + runnerProfileJson: { adapterDispatch: { adapterType: "paperclip_runner", adapterConfig: { prompt: payload } }, savedInput: payload }, + resultJson: { stdout: payload }, stdoutExcerpt: payload, stderrExcerpt: payload, + }).returning(); + const observed = createDb(database.connectionString); + const events: Array> = [], now = Date.now(); + const capture = createDatabaseResponseCapture({ start: now - 100, end: now + 59_000 }, event => events.push(event)); + installDatabaseResponseCapture(observed, { heartbeatRuns }, capture); + try { + const state = extracted.createHeartbeatRunState(observed); + const direct = await state.getRunIssueControl(run.id), active = await state.getActiveRunIssueControlForAgent(agent.id); + expect(active).toEqual(direct); + expect(direct).toEqual({ id: run.id, companyId, agentId: agent.id, status: "running", runtimeMode: "legacy", + runtimeModeResolvedAt: null, startedAt: run.startedAt, createdAt: run.createdAt, + contextSnapshot: { issueId: issue.id }, runnerProfileJson: { adapterDispatch: { adapterType: "paperclip_runner" } } }); + capture.flush(); + const summary = events.find(event => event.event === "paperclip.db_response_capture.summary.v1")!; + expect(summary.completedQueries).toBe(2); + expect(summary.responseValueBytes).toBeLessThan(2048); + expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, run.id)))[0]).toEqual(run); + await db.update(heartbeatRuns).set({ status: "failed" }).where(eq(heartbeatRuns.id, run.id)); + expect((await state.getRunIssueControl(run.id))?.status).toBe("failed"); + expect(await state.getActiveRunIssueControlForAgent(agent.id)).toBeNull(); + expect(await state.getActiveRunIssueControlForAgent(randomUUID())).toBeNull(); + expect(await state.getRunIssueControl(randomUUID())).toBeNull(); + } finally { capture.flush(); await observed.$client.end(); } + }); + + it("preserves native preparation, legacy steering, and typed issue context in issue control reads", async () => { + const { companyId, agent, issue, state } = await fixture(); + for (const mode of ["native", "legacy"] as const) { + for (const value of [null, false, 42, [], {}, { nested: true }, "paperclip_runner", "process"]) { + const [run] = await db.insert(heartbeatRuns).values({ companyId, agentId: agent.id, status: "running", runtimeMode: mode, + contextSnapshot: { issueId: value }, runnerProfileJson: { adapterDispatch: { adapterType: value } }, + }).returning(); + const narrow = await state.getRunIssueControl(run.id), full = await state.getRun(run.id); + expect(narrow?.contextSnapshot?.issueId).toEqual(value); + expect(narrow?.runnerProfileJson).toEqual({ adapterDispatch: { adapterType: value } }); + for (const queueState of ["queued", "deferred", null] as const) { + const facts = { state: queueState, queueRunRuntimeMode: mode, assignedAgentAdapterType: "paperclip_runner", queuedCommentCount: 1 }; + expect(decideQueuedCommentQueueSteering({ ...facts, activeRun: narrow })) + .toEqual(decideQueuedCommentQueueSteering({ ...facts, activeRun: full })); + } + await db.update(heartbeatRuns).set({ contextSnapshot: { issueId: issue.id }, runtimeModeResolvedAt: new Date("2020-01-01T00:00:00Z") }) + .where(eq(heartbeatRuns.id, run.id)); + const updated = await state.getRunIssueControl(run.id); + expect(updated?.contextSnapshot).toEqual({ issueId: issue.id }); + expect(updated?.runtimeModeResolvedAt).toEqual(new Date("2020-01-01T00:00:00Z")); + } + } + }); + it("reads cleanup and workspace settlement without transferring saved input or changing the run", async () => { const { companyId, agent, issue, state } = await fixture(); const bulk = "cleanup-saved-input-sentinel🙂".repeat(40_000); diff --git a/server/src/services/heartbeat/run-state.ts b/server/src/services/heartbeat/run-state.ts index 1911ad1a25c..3bf92684a1f 100644 --- a/server/src/services/heartbeat/run-state.ts +++ b/server/src/services/heartbeat/run-state.ts @@ -354,6 +354,18 @@ const heartbeatRunLogAccessColumns = { logRef: heartbeatRuns.logRef, } as const; +const heartbeatRunIssueControlColumns = { + id: heartbeatRuns.id, companyId: heartbeatRuns.companyId, agentId: heartbeatRuns.agentId, + status: heartbeatRuns.status, runtimeMode: heartbeatRuns.runtimeMode, + runtimeModeResolvedAt: heartbeatRuns.runtimeModeResolvedAt, + startedAt: heartbeatRuns.startedAt, createdAt: heartbeatRuns.createdAt, + contextSnapshot: sql | null>`case when jsonb_typeof(${heartbeatRuns.contextSnapshot}) = 'object' + then jsonb_build_object('issueId', ${heartbeatRuns.contextSnapshot}->'issueId') else null end`, + runnerProfileJson: sql | null>`case when jsonb_typeof(${heartbeatRuns.runnerProfileJson}) = 'object' + then jsonb_build_object('adapterDispatch', jsonb_build_object('adapterType', ${heartbeatRuns.runnerProfileJson}->'adapterDispatch'->'adapterType')) + else null end`, +} as const; + const heartbeatRunIssueSummaryColumns = { id: heartbeatRuns.id, runtimeMode: heartbeatRuns.runtimeMode, @@ -1955,6 +1967,19 @@ export function createHeartbeatRunState(db: Db) { return run ?? null; }, + getRunIssueControl: async (runId: string) => { + const [run] = await db.select(heartbeatRunIssueControlColumns).from(heartbeatRuns) + .where(eq(heartbeatRuns.id, runId)).limit(1); + return run ?? null; + }, + + getActiveRunIssueControlForAgent: async (agentId: string) => { + const [run] = await db.select(heartbeatRunIssueControlColumns).from(heartbeatRuns) + .where(and(eq(heartbeatRuns.agentId, agentId), eq(heartbeatRuns.status, "running"))) + .orderBy(desc(heartbeatRuns.startedAt)).limit(1); + return run ?? null; + }, + getActiveRunForAgent: async (agentId: string) => { const [run] = await db .select() From e6ec781a1abcdcddb98e712bcb00b201303e44de Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sat, 24 Oct 2026 23:54:27 -0700 Subject: [PATCH 043/110] fix(e2e): verify review outcomes and preserve report measurements (#17556) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip's Product E2E journeys verify user outcomes in the real app and GitHub. > - The review journey must show the score and failed check for its exact reviewed commit, then the visible task status before and after reload. > - GitHub includes a hidden “Re-run failed checks” menu item before the visible check result. > - The journey selected that hidden item and failed even after native work and publication completed. A subsequent attempt exposed the same first-text-match problem with Done in the task UI. > - This change reads the selected check's status header and binds its URL, score, and commit. > - Browser fixtures retain this failure and reject plausible wrong projections. ## Linked Issues or Issue Description Refs: #17457, #17513, #17551. **What happened?** The bot completed its native run and task, then published its summary, inline precision finding, and failed 2/5 check. The browser assertion selected a hidden “Re-run failed checks” menu item before the visible result, so the journey still failed. After that was corrected, the next live attempt passed the check projection but selected hidden Done text before the visible task status. **Expected behavior** Verify the actual selected GitHub check. A hidden menu item or a word in the model's narrative cannot prove its conclusion. **Steps to reproduce** 1. Render a hidden “Re-run failed checks” item before a visible failed check. 2. Use the old first text match for “failed”. 3. Observe the false visibility failure. **Paperclip version or commit** The base includes the journey changes from #17457 and #17513. ## What Changed - Validate the check URL against the configured repository and select its exact check-run ID. - Require the expected score and full reviewed commit inside that check. - Read failure status only from that check's header. - Give each projection step its own phase so failures identify the correct boundary. - Stage the verified persisted screenshot as the standard report final-state artifact, rejecting a passing report if it is absent. - Preserve measured billing summaries during regeneration when raw run usage is absent; newer raw usage takes precedence. - Extend the catalog-wide history fixture to include the new journey evidence contract. - Read task completion from the visible Status property picker before and after reload, with separate phase labels. - Add eighteen isolated browser fixtures to the existing browser-support suite and document both boundaries. ## Verification - Reproduced the old selector failure in the live GitHub page and a credential-free browser fixture before fixing it. - All 60 browser-support cases pass, including eighteen focused projection cases. They reject the wrong check status, score, commit, page, and repository reference, plus hidden or unrelated Done text. - All 163 focused billing, history, accounting, report, and journey tests pass, as does runner E2E typechecking. - A regression reproduced discarded saved token totals. Retained totals now survive per-cell and campaign aggregation while missing dollar prices stay unknown; fresh raw usage still overrides stale summaries. - Diff and credential-value checks pass. - The earlier failed attempts remain failed. A fresh complete QA journey passed all 18 checkpoints and cleanup with a successful native run, a below-threshold review and inline precision finding, the correctly failed check, visible Done status, and reload persistence. The later reference-validation commit changes only browser fixtures; the live driver bytes are unchanged. - A report regression reproduced the missing standard final-state artifact. The packager now aliases only the hash-verified persisted screenshot for passing results; missing final-state proof is rejected. Presentation regeneration preserves the original live grade and dispatches no provider work. ## Risks This depends on GitHub's check-run header structure. A markup change fails the journey instead of accepting narrative text as a result. The product runtime and behavioral oracle stay unchanged. Usage-price coverage remains a separate evidence dimension. A saved billing summary is reused only when raw usage is absent, preserving the recorded coverage and unknown prices. The separate advisory Paperclip Review remains queued after its prior assigned attempt timed out. Its normal Retry control rejected the obsolete failed chat request as unsafe to retry. Required repository gates `ci / verify` and `ci / e2e` pass, all 55 completed CI checks are green, and final-head Greptile is 5/5 with no unresolved findings. The advisory queue is not represented as a completed assessment. ## Model Used OpenAI Codex, based on GPT-6. The exact runtime model ID and context-window size are not exposed in this session. Used for code, browser fixtures, and live evidence analysis. ## 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 Co-authored-by: Paperclip --- tests/runner-e2e/GITHUB-REVIEW-JOURNEY.md | 13 ++- tests/runner-e2e/billing.test.ts | 19 ++++ tests/runner-e2e/billing.ts | 5 +- tests/runner-e2e/github-review-browser.ts | 29 ++++++ tests/runner-e2e/github-review-check.spec.ts | 94 +++++++++++++++++++ tests/runner-e2e/github-review-flow.ts | 13 ++- tests/runner-e2e/github-review-report.test.ts | 28 ++++++ tests/runner-e2e/github-review-report.ts | 6 ++ tests/runner-e2e/history.test.ts | 7 ++ tests/runner-e2e/playwright-support.config.ts | 2 +- 10 files changed, 208 insertions(+), 8 deletions(-) create mode 100644 tests/runner-e2e/github-review-check.spec.ts diff --git a/tests/runner-e2e/GITHUB-REVIEW-JOURNEY.md b/tests/runner-e2e/GITHUB-REVIEW-JOURNEY.md index 12cddb6c387..bc765f21390 100644 --- a/tests/runner-e2e/GITHUB-REVIEW-JOURNEY.md +++ b/tests/runner-e2e/GITHUB-REVIEW-JOURNEY.md @@ -79,6 +79,14 @@ completed state alone is also insufficient: the actual run must succeed and the associated task must reach Done. A native failure after publication fails the journey and retains the publication evidence already observed. +The rendered check must match its exact GitHub run URL, score, and reviewed +commit. Its failure status comes from that check's header. Hidden re-run menu +items, a failure on another check, and words in the model's narrative do not +prove the conclusion. `github-review-check.spec.ts` covers this boundary in the +credential-free `test:e2e:runner:browser-support` suite. Task completion reads +the visible Status property's picker, before and after reload. Hidden controls, +SVG titles, and narrative text saying Done cannot satisfy that UI checkpoint. + Each attempt records endpoint, App, PR/branch, task, and run ownership. Cleanup removes the owned endpoint, closes the owned PR/deletes its branch, and asks for the owned App's removal. App identity must match the created endpoint, company, @@ -122,7 +130,10 @@ cleanup. Missing usage remains unknown. Authentication screens are excluded. `github-review-report.ts` uses the existing evidence sanitizer and manifest, stages only declared screenshots, and verifies screenshot hashes and attempt path ownership. The standard report inputs are `evidence/result.json`, -`evidence/evidence-manifest.json`, and `evidence/snapshots/`. Raw private operator +`evidence/evidence-manifest.json`, and `evidence/snapshots/`. A passing result +also stages the hash-verified persisted checkpoint as `evidence/final-state.png` +for the standard report's final-state requirement. A missing persisted screenshot +rejects that passing report. Raw private operator receipts are outside the manifest. Existing report tooling imports these files; no second runner or report service is required. A presentation repair must use a new directory, preserve the original result/hash and failure, and dispatch no diff --git a/tests/runner-e2e/billing.test.ts b/tests/runner-e2e/billing.test.ts index 48352815c0e..037ccae91ec 100644 --- a/tests/runner-e2e/billing.test.ts +++ b/tests/runner-e2e/billing.test.ts @@ -31,6 +31,25 @@ function result(overrides: Partial = {}): RunnerE2EResult { } describe("runner E2E billing summaries", () => { + it("preserves captured token totals when a retained result has only a billing summary", () => { + const billing = summarizeExecutionBilling(result({ usage: { + inputTokens: 59_989, outputTokens: 4_974, cachedInputTokens: 488_798, costStatus: "unpriced", + } })); + const retained = result({ billing }); + expect(summarizeExecutionBilling(retained)).toEqual(billing); + expect(aggregateCampaignBilling([retained])).toMatchObject({ llm: { + inputTokens: 59_989, outputTokens: 4_974, cachedInputTokens: 488_798, + runsWithTokenUsage: 1, runsWithReportedCost: 0, + }, testsWithCompleteBilling: 0 }); + }); + + it("uses newly captured usage instead of a stale retained billing summary", () => { + const billing = summarizeExecutionBilling(result({ usage: { inputTokens: 100, outputTokens: 10, costStatus: "unpriced" } })); + const fresh = summarizeExecutionBilling(result({ billing, usage: { inputTokens: 200, outputTokens: 20, costStatus: "unpriced" } })); + expect(fresh.llm).toMatchObject({ inputTokens: 200, outputTokens: 20, runsWithReportedCost: 0 }); + expect(fresh.complete).toBe(false); + }); + it("keeps missing agent time separate from attempt duration and measured zero", () => { const interrupted = result({ status: "failed", durationMs: 108_850 }); expect(summarizeExecutionBilling(interrupted).runtime.agentRunDurationMs).toBeNull(); diff --git a/tests/runner-e2e/billing.ts b/tests/runner-e2e/billing.ts index 35f70e83569..766167c0bfb 100644 --- a/tests/runner-e2e/billing.ts +++ b/tests/runner-e2e/billing.ts @@ -278,8 +278,11 @@ export function summarizeExecutionBilling( result: Pick< RunnerE2EResult, "runIds" | "usage" | "environmentId" | "durationMs" | "runtimeUsage" | "firstTaskQuality" | "completionQuality" | "publicMcp" | "productJourney" - > & Partial>, + > & Partial>, ): RunnerE2EBillingSummary { + // Some retained journeys store their measured summary without raw run usage. + // Regeneration must preserve those measurements, including unknown prices. + if (result.usage === undefined && result.billing) return structuredClone(result.billing); const browserOnly = Boolean(result.productJourney && result.runtimeMode === "none" && !result.runIds?.length); const requestedRunCount = browserOnly ? 0 : Math.max(result.runIds?.length ?? 0, 1); const entries = browserOnly ? [] : usageEntries(result.usage, requestedRunCount); diff --git a/tests/runner-e2e/github-review-browser.ts b/tests/runner-e2e/github-review-browser.ts index b064d0ad384..f4749931dc2 100644 --- a/tests/runner-e2e/github-review-browser.ts +++ b/tests/runner-e2e/github-review-browser.ts @@ -10,6 +10,35 @@ export async function enterGitHubJourneyCompany(page: Page, origin: string, comp await page.waitForURL(url => url.origin === origin && url.pathname === pathname); } +export async function assertGitHubJourneyCheck(page: Page, expected: { repository: string; url: string; headSha: string; score: number }, timeout = 30_000) { + let target: URL; + try { target = new URL(expected.url); } + catch { throw new ConnectionFailure("github_check_reference_mismatch"); } + const prefix = `/${expected.repository}/runs/`; + const id = target.pathname.startsWith(prefix) ? target.pathname.slice(prefix.length) : ""; + if (target.origin !== "https://github.com" || target.username || target.password || target.search || target.hash + || !/^[1-9][0-9]*$/.test(id) || !/^[a-f0-9]{40,64}$/.test(expected.headSha) + || !Number.isInteger(expected.score) || expected.score < 1 || expected.score > 5) { + throw new ConnectionFailure("github_check_reference_mismatch"); + } + await expect(page).toHaveURL(target.href, { timeout }); + const check = page.locator(`#check_run_${id}`); + await expect(check.getByRole("heading", { name: `${expected.score}/5`, exact: true })).toBeVisible({ timeout }); + // GitHub keeps a hidden "Re-run failed checks" menu item before the visible + // result. Only the selected check's status header can prove its conclusion. + await expect(check.locator(":scope > .border-bottom").getByText(/failed/i)).toBeVisible({ timeout }); + await expect(check.getByText(expected.headSha, { exact: true })).toBeVisible({ timeout }); +} + +export async function assertGitHubJourneyTaskDone(page: Page, timeout = 30_000) { + const status = page.locator('[data-property-row="true"]:visible') + .filter({ has: page.locator('[data-property-label="Status"]') }) + .locator('[data-property-value="true"]'); + // Status glyphs contain SVG titles, and responsive layouts can retain hidden + // controls. Read the visible status picker rather than the first Done text. + await expect(status.getByRole("button", { name: "Change status (current: Done)", exact: true })).toBeVisible({ timeout }); +} + export interface GitHubRegistrationBoundary { origin: string; pathname: string; passwordRequired: boolean; oneTimeCodeRequired: boolean; reauthenticationRequired: boolean; createControlVisible: boolean; diff --git a/tests/runner-e2e/github-review-check.spec.ts b/tests/runner-e2e/github-review-check.spec.ts new file mode 100644 index 00000000000..705bc5246a9 --- /dev/null +++ b/tests/runner-e2e/github-review-check.spec.ts @@ -0,0 +1,94 @@ +import { expect, test, type Page } from "@playwright/test"; +import { assertGitHubJourneyCheck, assertGitHubJourneyTaskDone } from "./github-review-browser.js"; + +const expected = { repository: "fixture/repo", url: "https://github.com/fixture/repo/runs/123", headSha: "a".repeat(40), score: 2 }; + +async function openCheck(page: Page, input: { status?: string; score?: number; headSha?: string; unrelatedFailure?: boolean; url?: string } = {}) { + const body = ` +
+
Fixture bot / Paperclip Review ${input.status ?? "failed"}
+

${input.score ?? expected.score}/5

+

Reviewed commit: ${input.headSha ?? expected.headSha}

+

Review rationale: failed tests are discussed in the summary.

+
+ ${input.unrelatedFailure ? '
Another check failed

2/5

' : ""}`; + await page.route("https://github.com/**", route => route.fulfill({ contentType: "text/html", body })); + await page.goto(input.url ?? expected.url); +} + +test("accepts the visible failed check despite an earlier hidden re-run menu item", async ({ page }) => { + await openCheck(page); + await expect(page.getByText(/failed/i).first()).toBeHidden(); + await assertGitHubJourneyCheck(page, expected, 150); +}); + +test("rejects a successful check even when its narrative and another check say failed", async ({ page }) => { + await openCheck(page, { status: "succeeded", unrelatedFailure: true }); + await expect(assertGitHubJourneyCheck(page, expected, 150)).rejects.toThrow(); +}); + +test("rejects the wrong reviewed commit", async ({ page }) => { + await openCheck(page, { headSha: "b".repeat(40) }); + await expect(assertGitHubJourneyCheck(page, expected, 150)).rejects.toThrow(); +}); + +test("rejects a different score", async ({ page }) => { + await openCheck(page, { score: 3 }); + await expect(assertGitHubJourneyCheck(page, expected, 150)).rejects.toThrow(); +}); + +test("rejects a page for another repository", async ({ page }) => { + await openCheck(page, { url: "https://github.com/foreign/repo/runs/123" }); + await expect(assertGitHubJourneyCheck(page, expected, 150)).rejects.toThrow(); +}); + +test("rejects a check reference outside the configured repository", async ({ page }) => { + const url = "https://github.com/foreign/repo/runs/123"; + await openCheck(page, { url }); + await expect(assertGitHubJourneyCheck(page, { ...expected, url }, 150)).rejects.toThrow(); +}); + +for (const [name, override] of [ + ["foreign origin", { url: "https://example.com/fixture/repo/runs/123" }], + ["embedded credentials", { url: "https://fixture-user:fixture-password@github.com/fixture/repo/runs/123" }], + ["query suffix", { url: `${expected.url}?x=1` }], + ["hash suffix", { url: `${expected.url}#fragment` }], + ["non-numeric run ID", { url: "https://github.com/fixture/repo/runs/abc" }], + ["short commit", { headSha: "a".repeat(7) }], + ["score below range", { score: 0 }], + ["score above range", { score: 6 }], +] as const) { + test(`rejects a malformed check reference: ${name}`, async ({ page }) => { + // These must reject before navigation or DOM inspection. + await expect(assertGitHubJourneyCheck(page, { ...expected, ...override }, 150)) + .rejects.toThrow("github_check_reference_mismatch"); + }); +} + +function taskStatus(status: string, hidden = false) { + return `
+ Status
+ +
`; +} + +test("accepts visible Done status despite hidden controls and SVG title text", async ({ page }) => { + await page.setContent(`${taskStatus("Done", true)}${taskStatus("Done")}`); + await expect(page.getByText("Done", { exact: true }).first()).toBeHidden(); + await assertGitHubJourneyTaskDone(page, 150); +}); + +test("rejects Done in the narrative when the task is still in progress", async ({ page }) => { + await page.setContent(`

Done

${taskStatus("In Progress")}`); + await expect(assertGitHubJourneyTaskDone(page, 150)).rejects.toThrow(); +}); + +test("rejects hidden Done status when the visible status is in progress", async ({ page }) => { + await page.setContent(`${taskStatus("Done", true)}${taskStatus("In Progress")}`); + await expect(assertGitHubJourneyTaskDone(page, 150)).rejects.toThrow(); +}); + +test("rejects a Done picker in an unrelated property", async ({ page }) => { + await page.setContent(taskStatus("Done").replace('data-property-label="Status">Status', 'data-property-label="Assignee">Assignee')); + await expect(assertGitHubJourneyTaskDone(page, 150)).rejects.toThrow(); +}); diff --git a/tests/runner-e2e/github-review-flow.ts b/tests/runner-e2e/github-review-flow.ts index 5547adf21a2..d43e919ddd8 100644 --- a/tests/runner-e2e/github-review-flow.ts +++ b/tests/runner-e2e/github-review-flow.ts @@ -3,7 +3,7 @@ import type { GitHubTaskReview } from "../../packages/shared/src/types/chat-gith import type { GitHubRepositoryPage } from "../../packages/shared/src/types/chat-channels.js"; import { ConnectionBlock, ConnectionFailure } from "./connection-config.js"; import { ConnectionApi } from "./connection-target.js"; -import { awaitJourneyCondition, createGitHubJourneyPullRequest, enterGitHubJourneyCompany, observeGitHubHead, selectGitHubJourneyRepository, waitForGitHubRegistrationControl, type GitHubRegistrationBoundary } from "./github-review-browser.js"; +import { assertGitHubJourneyCheck, assertGitHubJourneyTaskDone, awaitJourneyCondition, createGitHubJourneyPullRequest, enterGitHubJourneyCompany, observeGitHubHead, selectGitHubJourneyRepository, waitForGitHubRegistrationControl, type GitHubRegistrationBoundary } from "./github-review-browser.js"; import { githubCartFixture, hasOnlyOpenedAutomaticReview, matchesGitHubJourneyEnvironment, retainGitHubReview, verifyGitHubReview, verifyGitHubReviewRun, type GitHubReviewJourneyEvidence } from "./github-review-evidence.js"; import type { GitHubReviewJourneyConfig } from "./github-review-config.js"; import { captureOwnedGitHubApp, readOwnedGitHubReviewRuns, type GitHubJourneyResources } from "./github-review-ownership.js"; @@ -222,17 +222,20 @@ export async function runGitHubReviewFlow(input: { text: await inline.locator(".review-comment .comment-body").filter({ hasText: /precision|decimal|floating|cents/i }).first().innerText() }; await inline.scrollIntoViewIfNeeded(); await input.checkpoint("github_inline_delivery", github); + await input.phase("github_check_projection"); + if (!review!.checkUrl) throw new ConnectionFailure("github_check_reference_missing"); const checkPopup = page.context().waitForEvent("page"); await page.getByRole("link", { name: "Check", exact: true }).click(); const check = await checkPopup; - await expect(check.getByText(`${evidence.score}/5`, { exact: false }).first()).toBeVisible(); - await expect(check.getByText(/failed/i).first()).toBeVisible(); + await assertGitHubJourneyCheck(check, { repository: config.github.repository, url: review!.checkUrl, headSha, score: evidence.score }); await input.checkpoint("check_projection", check); + await input.phase("task_done"); await page.getByRole("link", { name: "Paperclip task", exact: true }).click(); - await expect(page.getByText("Done", { exact: true }).first()).toBeVisible(); + await assertGitHubJourneyTaskDone(page); await input.checkpoint("task_done", page); + await input.phase("persisted"); await page.reload(); await github.reload(); - await expect(page.getByText("Done", { exact: true }).first()).toBeVisible(); + await assertGitHubJourneyTaskDone(page); await expect(github.getByText(`${evidence.score}/5`, { exact: false }).first()).toBeVisible(); await input.checkpoint("persisted", page); } diff --git a/tests/runner-e2e/github-review-report.test.ts b/tests/runner-e2e/github-review-report.test.ts index 8840fcf171d..9ad23acbcd5 100644 --- a/tests/runner-e2e/github-review-report.test.ts +++ b/tests/runner-e2e/github-review-report.test.ts @@ -5,6 +5,7 @@ import path from "node:path"; import { afterEach, expect, it } from "vitest"; import { runnerMatrix } from "./catalog.js"; import { writeGitHubReviewReport } from "./github-review-report.js"; +import { githubJourneyCheckpoints } from "./github-review-evidence.js"; import { validateRetainedRunnerResult } from "./result-validation.js"; import type { RunnerE2EResult } from "./types.js"; @@ -49,3 +50,30 @@ it("refuses an altered screenshot rather than retaining its claimed digest", asy await expect(writeGitHubReviewReport({ output, campaignId: "altered", result: fixture(), resources: { branch: "owned", appName: "owned", runIds: [] }, catalog: runnerMatrix, secrets: [] })) .rejects.toThrow("journey_screenshot_digest_mismatch"); }); + +it("stages the verified persisted checkpoint as the standard report's final state", async () => { + const output = await mkdtemp(path.join(os.tmpdir(), "github-report-test-")); temporary.push(output); + const input = fixture(); + input.status = "passed"; delete input.error; + input.githubReviewJourney!.outcome = "passed"; + input.githubReviewJourney!.checkpoints = Object.fromEntries(githubJourneyCheckpoints.map(id => [id, true])); + input.screenshots = [{ id: "persisted", label: "Persisted completion", file: "persisted.png", sha256: createHash("sha256").update(pixel).digest("hex") }]; + await writeFile(path.join(output, "persisted.png"), pixel); + const result = await writeGitHubReviewReport({ output, campaignId: "passing-journey", result: input, resources: { branch: "owned", appName: "owned", runIds: ["run"] }, catalog: runnerMatrix, secrets: [] }); + expect(result.status).toBe("passed"); + const manifest = JSON.parse(await readFile(path.join(output, "evidence/evidence-manifest.json"), "utf8")); + expect(manifest.files).toContain("final-state.png"); + expect(await readFile(path.join(output, "evidence/final-state.png"))).toEqual(pixel); + expect(await readFile(path.join(output, "evidence/snapshots/persisted.png"))).toEqual(pixel); +}); + +it("refuses a passing report without its persisted screenshot", async () => { + const output = await mkdtemp(path.join(os.tmpdir(), "github-report-test-")); temporary.push(output); + const input = fixture(); + input.status = "passed"; delete input.error; + input.githubReviewJourney!.outcome = "passed"; + input.githubReviewJourney!.checkpoints = Object.fromEntries(githubJourneyCheckpoints.map(id => [id, true])); + await writeFile(path.join(output, "failure.png"), pixel); + await expect(writeGitHubReviewReport({ output, campaignId: "missing-final-state", result: input, resources: { branch: "owned", appName: "owned", runIds: ["run"] }, catalog: runnerMatrix, secrets: [] })) + .rejects.toThrow("journey_final_state_missing"); +}); diff --git a/tests/runner-e2e/github-review-report.ts b/tests/runner-e2e/github-review-report.ts index 6ad2cc05149..7d0e3332619 100644 --- a/tests/runner-e2e/github-review-report.ts +++ b/tests/runner-e2e/github-review-report.ts @@ -29,6 +29,7 @@ export async function writeGitHubReviewReport(input: { try { await mkdir(path.join(stage, "snapshots"), { mode: 0o700 }); const result = structuredClone(input.result); + let finalStateStaged = false; for (const shot of result.screenshots ?? []) { const source = path.resolve(output, shot.file); if (!source.startsWith(`${output}${path.sep}`) || !/^[a-z0-9_-]+$/.test(shot.id) || path.extname(source) !== ".png") throw new Error("unsafe_journey_screenshot_reference"); @@ -37,8 +38,13 @@ export async function writeGitHubReviewReport(input: { if (shot.sha256 && createHash("sha256").update(bytes).digest("hex") !== shot.sha256) throw new Error("journey_screenshot_digest_mismatch"); shot.file = `snapshots/${shot.id}.png`; await writeFile(path.join(stage, shot.file), bytes, { mode: 0o600 }); + if (result.status === "passed" && shot.id === "persisted" && result.githubReviewJourney?.checkpoints.persisted === true) { + await writeFile(path.join(stage, "final-state.png"), bytes, { mode: 0o600 }); + finalStateStaged = true; + } } validateRetainedRunnerResult(result); + if (result.status === "passed" && !finalStateStaged) throw new Error("journey_final_state_missing"); await save(stage, "result.json", result); await save(stage, "snapshots/journey-resources.json", input.resources); await save(stage, "snapshots/journey-evidence.json", result.githubReviewJourney); diff --git a/tests/runner-e2e/history.test.ts b/tests/runner-e2e/history.test.ts index c717441e321..b6216af3745 100644 --- a/tests/runner-e2e/history.test.ts +++ b/tests/runner-e2e/history.test.ts @@ -32,6 +32,7 @@ import { renderRunnerHistoryIndex } from "./history-index.js"; import { renderPublicCampaignSummary } from "./public-summary-image.js"; import { isPublicRunnerScreenshotRoute } from "./screenshot-policy.js"; import { connectionCheckpoints, type ConnectionEvidence } from "./connection-evidence.js"; +import { githubJourneyCheckpoints, type GitHubReviewJourneyEvidence } from "./github-review-evidence.js"; import type { MatrixExecution, RunnerE2EResult } from "./types.js"; const temporaryDirectories: string[] = []; @@ -65,6 +66,12 @@ function result(execution: MatrixExecution, status: "passed" | "failed") { durationMs: 1_000, cleanup: "passed", ...(execution.task.flow === "provider_connection" ? { providerConnection: { version: 1, outcome: status, phase: "finished", assisted: false, authFreshness: "signed-in", target: { mode: "attach", origin: "http://127.0.0.1:3100", commit: "a".repeat(40), deploymentMode: "local_trusted" }, entry: "agent", method: "api-key", checkpoints: Object.fromEntries(connectionCheckpoints.map(key => [key, true])), waits: [] } satisfies ConnectionEvidence } : {}), + ...(execution.task.flow === "github_review_journey" ? { githubReviewJourney: { + version: 1, outcome: status, phase: "finished", setupId: "fixture", hosting: "self-hosted", + targetCommit: "a".repeat(40), assisted: false, dependencies: [], + checkpoints: Object.fromEntries(githubJourneyCheckpoints.map(key => [key, true])), + cleanup: { endpoint: true, pullRequest: true, branch: true, app: true }, + } satisfies GitHubReviewJourneyEvidence } : {}), } satisfies RunnerE2EResult; } diff --git a/tests/runner-e2e/playwright-support.config.ts b/tests/runner-e2e/playwright-support.config.ts index bdaefb27292..0256f9ef884 100644 --- a/tests/runner-e2e/playwright-support.config.ts +++ b/tests/runner-e2e/playwright-support.config.ts @@ -3,7 +3,7 @@ import { defineConfig } from "@playwright/test"; /** Browser-only harness regressions: no Paperclip instance or provider credentials. */ export default defineConfig({ testDir: ".", - testMatch: ["screenshot-readiness.spec.ts", "service-worker-reload.spec.ts", "lost-send.spec.ts", "chat-restart.spec.ts", "settings-toggle.spec.ts", "browser-bootstrap-diagnostics.spec.ts", "service-worker-module-loading.spec.ts", "browser-bootstrap-recovery.spec.ts", "blocker-input.spec.ts", "native-blocker-visible.spec.ts", "copilot-permission-card.spec.ts"], + testMatch: ["screenshot-readiness.spec.ts", "service-worker-reload.spec.ts", "lost-send.spec.ts", "chat-restart.spec.ts", "settings-toggle.spec.ts", "browser-bootstrap-diagnostics.spec.ts", "service-worker-module-loading.spec.ts", "browser-bootstrap-recovery.spec.ts", "blocker-input.spec.ts", "native-blocker-visible.spec.ts", "copilot-permission-card.spec.ts", "github-review-check.spec.ts"], workers: 1, retries: 0, timeout: 10_000, From 08dafde1d65a8f3299237af04df5e2543bb4382d Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Sat, 24 Oct 2026 23:58:43 -0700 Subject: [PATCH 044/110] perf(accounting): narrow locked usage receipt run reads (#17559) Select only the five run fields used by usage receipt persistence under the existing company and row locks. Keep receipt history, replay checks, budget updates, and stored execution evidence intact. Validation: 37 focused tests, full build and typecheck, exact-head Greptile 5/5 (medium), and full green CI with no unresolved threads. The first CI attempt failed an unchanged Runner shutdown test; its qualified local case and same-head failed-lane rerun passed. Co-Authored-By: Paperclip --- .../src/services/usage-receipts-read.test.ts | 81 +++++++++++++++++++ server/src/services/usage-receipts.ts | 5 +- 2 files changed, 85 insertions(+), 1 deletion(-) create mode 100644 server/src/services/usage-receipts-read.test.ts diff --git a/server/src/services/usage-receipts-read.test.ts b/server/src/services/usage-receipts-read.test.ts new file mode 100644 index 00000000000..83ddbed9364 --- /dev/null +++ b/server/src/services/usage-receipts-read.test.ts @@ -0,0 +1,81 @@ +import { randomBytes, randomUUID } from "node:crypto"; +import { eq } from "drizzle-orm"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { agents, companies, createDb, heartbeatRuns, runUsageReceipts, type Db } from "@paperclipai/db"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../__tests__/helpers/embedded-postgres.js"; +import { persistUsageReceipt, type UsageReceiptEnvelope } from "./usage-receipts.js"; + +const support = await getEmbeddedPostgresTestSupport(); +describe.skipIf(!support.supported)("usage receipt PostgreSQL reads", () => { + let database: Awaited>; + let db: Db; + beforeAll(async () => { + database = await startEmbeddedPostgresTestDatabase("usage-receipt-read-"); + db = createDb(database.connectionString); + }, 60_000); + afterAll(async () => { await db?.$client.end(); await database?.cleanup(); }); + + async function fixture() { + const companyId = randomUUID(), agentId = randomUUID(), runId = randomUUID(), sourceId = randomUUID(); + await db.insert(companies).values({ id: companyId, name: "Receipt fixture", issuePrefix: companyId.slice(0, 8) }); + await db.insert(agents).values({ id: agentId, companyId, name: "Receipt agent", adapterType: "process", status: "active" }); + const payload = randomBytes(128 * 1024).toString("base64"); + const evidence = { contextSnapshot: { prompt: payload }, runnerProfileJson: { instructions: payload }, + resultJson: { stdout: payload }, stdoutExcerpt: payload, stderrExcerpt: payload }; + await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, status: "running", ...evidence, + usageJson: { accountingReceiptSourceId: sourceId, accountingReceiptSequence: 0, preserved: "receipt metadata" } }); + const receipt = (sequence: number): UsageReceiptEnvelope => ({ schema: "paperclip/accounting-receipt/v1", + id: randomUUID(), companyId, runId, sourceId, sequence, receivedAt: new Date().toISOString(), adapterType: "process", + receipt: { complete: false, usageBasis: "per_run", costUsd: sequence / 100, billingType: "metered_api" } }); + return { companyId, runId, evidence, receipt }; + } + + it("updates live usage with a small locked read and preserves all execution evidence", async () => { + const f = await fixture(), reads: unknown[][] = []; + const observed = new Proxy(db, { get(target, key) { + if (key !== "transaction") return Reflect.get(target, key); + return (callback: Parameters[0]) => target.transaction(tx => callback(new Proxy(tx, { + get(transaction, property) { + if (property !== "select") return Reflect.get(transaction, property); + return (...fields: Parameters) => { + const builder = transaction.select(...fields), from = builder.from.bind(builder); + builder.from = ((...args: Parameters) => { + const query = from(...args); + if (args[0] === heartbeatRuns) { + const execute = query.execute.bind(query); + query.execute = async (...executeArgs: Parameters) => { + expect(query.toSQL().sql).toContain("for update"); + const rows = await execute(...executeArgs); reads.push(rows); return rows; + }; + } + return query; + }) as typeof builder.from; + return builder; + }; + }, + }))); + } }); + await persistUsageReceipt(observed, f.receipt(1)); + expect(reads).toHaveLength(1); + expect(reads[0]).toHaveLength(1); + expect(Buffer.byteLength(JSON.stringify(reads))).toBeLessThan(2048); + const [stored] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId)); + expect(stored).toMatchObject(f.evidence); + expect(stored.usageJson).toMatchObject({ preserved: "receipt metadata", accountingReceiptSequence: 1, + budgetExposure: { costCents: "1.0000000" } }); + expect(Buffer.byteLength(JSON.stringify(stored))).toBeGreaterThan(512 * 1024); + }); + + it("serializes competing checkpoints and retains replay conflicts and company isolation", async () => { + const f = await fixture(), first = f.receipt(1), second = f.receipt(2); + await Promise.all([persistUsageReceipt(db, first), persistUsageReceipt(db, second)]); + await persistUsageReceipt(db, first); + const [stored] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId)); + expect(stored.usageJson).toMatchObject({ accountingReceiptSequence: 2, budgetExposure: { costCents: "2.0000000" } }); + expect(await db.select().from(runUsageReceipts).where(eq(runUsageReceipts.runId, f.runId))).toHaveLength(2); + await expect(persistUsageReceipt(db, { ...first, receipt: { ...first.receipt, costUsd: 10 } })).rejects.toThrow("Conflicting"); + const foreign = await fixture(); + await expect(persistUsageReceipt(db, { ...f.receipt(3), companyId: foreign.companyId })).rejects.toThrow("not found"); + expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId)))[0]).toEqual(stored); + }); +}); diff --git a/server/src/services/usage-receipts.ts b/server/src/services/usage-receipts.ts index 52bae89f8fb..0f99401d9da 100644 --- a/server/src/services/usage-receipts.ts +++ b/server/src/services/usage-receipts.ts @@ -68,7 +68,10 @@ export async function persistUsageReceipt(db: Db, raw: UsageReceiptEnvelope) { const envelope = envelopeSchema.parse(raw); const hash = receiptFingerprint(envelope); return withAccountingTransaction(db, envelope.companyId, async (tx, publications) => { - const [run] = await tx.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.id, envelope.runId), eq(heartbeatRuns.companyId, envelope.companyId))).for("update"); + const [run] = await tx.select({ + id: heartbeatRuns.id, agentId: heartbeatRuns.agentId, status: heartbeatRuns.status, + usageJson: heartbeatRuns.usageJson, costAccountedAt: heartbeatRuns.costAccountedAt, + }).from(heartbeatRuns).where(and(eq(heartbeatRuns.id, envelope.runId), eq(heartbeatRuns.companyId, envelope.companyId))).for("update"); if (!run) throw notFound("Accounting run not found"); const [existing] = await tx.select().from(runUsageReceipts).where(and(eq(runUsageReceipts.companyId, envelope.companyId), eq(runUsageReceipts.runId, envelope.runId), eq(runUsageReceipts.sourceId, envelope.sourceId), eq(runUsageReceipts.sequence, envelope.sequence))); if (existing && existing.receiptHash !== hash) throw conflict("Conflicting usage checkpoint replay"); From bf142db65aa90eb4c23bf9084e95b33515234637 Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Sun, 25 Oct 2026 00:02:32 -0700 Subject: [PATCH 045/110] perf(server): narrow external review wait context reads (#17562) Project current chat authorization fields for external review-wait discovery instead of saved execution input. Preserve typed source bindings, nested question receipts, candidate eligibility, live revocation checks, and stored context. Validation: 181 native chat integration tests, full build and typecheck, exact-head Greptile 5/5 (medium), full green CI, and no unresolved review threads. The full-context counterfactual fails both direct-chat size regressions. Co-Authored-By: Paperclip --- doc/native-workspace-finalization-recovery.md | 3 ++ .../external-chat-wait.integration.test.ts | 46 +++++++++++++++++++ .../native-runtime/external-review-wait.ts | 21 ++++++++- 3 files changed, 68 insertions(+), 2 deletions(-) diff --git a/doc/native-workspace-finalization-recovery.md b/doc/native-workspace-finalization-recovery.md index c8353239234..5b1ffb5ce98 100644 --- a/doc/native-workspace-finalization-recovery.md +++ b/doc/native-workspace-finalization-recovery.md @@ -492,6 +492,9 @@ binding, and chat source fields under the existing nonblocking share lock. It excludes saved execution input, runner profiles, and log excerpts. Actual retry admission still reads the complete run and its recovery evidence. These reads preserve stored run data, source revocation checks, and JSON value types. +External review-wait discovery selects only chat authorization context fields. +It keeps the current endpoint, membership, resource, and question-receipt checks; +saved prompts remain stored and do not cross this discovery query. Legacy continuation recovery rejects native runs before it loads their saved execution input. The persisted disposition check reads only the task binding diff --git a/server/src/services/native-runtime/external-chat-wait.integration.test.ts b/server/src/services/native-runtime/external-chat-wait.integration.test.ts index b0ee8e0c5f6..70a6933e80a 100644 --- a/server/src/services/native-runtime/external-chat-wait.integration.test.ts +++ b/server/src/services/native-runtime/external-chat-wait.integration.test.ts @@ -4,6 +4,7 @@ import { tmpdir } from "node:os"; import path from "node:path"; import { and, eq, ne, sql } from "drizzle-orm"; +import { createDatabaseResponseCapture, installDatabaseResponseCapture } from "@paperclipai/db/response-capture"; import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; import { agentWakeupRequests, @@ -71,6 +72,7 @@ import { voiceCredentialFingerprint } from "../voice/voice-session-store.js"; import { nativeSha256 } from "./canonical.js"; import { questionResponseDeliveryValues } from "../question-response-delivery.js"; import { resolveExternalChatQuestionResponse } from "./external-chat-question-response.js"; +import { listExternalReviewWaits } from "./external-review-wait.js"; import { materializeExternalChatQuestionResponseInput } from "./external-chat-question-response-input.js"; import * as nativeInteractionBridge from "./native-interaction-bridge.js"; import { defaultGitHubReviewPolicy, type AskUserQuestionsInteraction } from "@paperclipai/shared"; @@ -866,6 +868,50 @@ describe("native external-chat response wait", () => { }; } + it.each(["telegram", "github", "github_board_answer", "slack_board_answer"] as const)( + "reads small current external review waits without saved prompts (%s)", async source => { + const fixture = await (async () => { + if (source === "github_board_answer" || source === "slack_board_answer") { + const answered = await seedBoardAnsweredTurn(true, source === "github_board_answer" ? "github" : "slack"); + await attestAnswer(answered); + return answered; + } + return seedWaitTurn(source); + })(); + const finalized = await finalizeNativeRun({ db, runId: fixture.runId, workspaceFinalizeStatus: "succeeded", projectRunStatus: true }); + expect(finalized.phase).toBe("committed"); + await db.update(statusDecisions).set({ toStatus: "in_review" }).where(eq(statusDecisions.id, finalized.decisionId!)); + await db.update(issues).set({ status: "in_review" }).where(eq(issues.id, fixture.issueId)); + const [decision] = await db.select({ reason: statusDecisions.reasonCode, state: statusDecisions.applicationState }) + .from(statusDecisions).where(eq(statusDecisions.id, finalized.decisionId!)); + const governed = source === "github_board_answer" || source === "slack_board_answer"; + expect(decision).toEqual({ reason: governed ? "governed_response_waiting" : "external_chat_response_waiting", state: "applied" }); + const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, fixture.runId)); + expect(run!.status).toBe("succeeded"); + const contextSnapshot = { ...run!.contextSnapshot, savedPrompt: "external-wait-saved-input🙂".repeat(30_000) }; + await db.update(heartbeatRuns).set({ contextSnapshot }).where(eq(heartbeatRuns.id, fixture.runId)); + await authorizeChatConversationForBoundRun(db, fixture, contextSnapshot, "read"); + const observed = createDb(temporary?.connectionString ?? externalTestDatabaseUrl!); + const events: Array> = [], now = Date.now(); + const capture = createDatabaseResponseCapture({ start: now - 100, end: now + 59_000 }, event => events.push(event)); + installDatabaseResponseCapture(observed, { issues, heartbeatRuns }, capture); + try { + expect(await listExternalReviewWaits(observed, fixture.companyId, [fixture.issueId])).toEqual(governed ? [] : [ + expect.objectContaining({ companyId: fixture.companyId, issueId: fixture.issueId }), + ]); + capture.flush(); + const reads = events.filter(event => event.table === "issues" && event.operation === "select"); + expect(reads.length).toBeGreaterThan(0); + expect(reads.reduce((bytes, event) => bytes + Number(event.responseValueBytes), 0)).toBeLessThan(4096); + expect(await listExternalReviewWaits(observed, randomUUID(), [fixture.issueId])).toEqual([]); + expect(await listExternalReviewWaits(observed, fixture.companyId, [])).toEqual([]); + await db.update(companyMemberships).set({ status: "suspended" }).where(eq(companyMemberships.companyId, fixture.companyId)); + expect(await listExternalReviewWaits(observed, fixture.companyId, [fixture.issueId])).toEqual([]); + expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, fixture.runId)))[0]?.contextSnapshot).toEqual(contextSnapshot); + } finally { capture.flush(); await observed.$client.end(); } + }, + ); + it("resumes an oversized Slack multi-select answered through its Paperclip handoff", async () => { const fixture = await seedBoardAnsweredTurn(true, "slack", true); const [publication] = await db.select().from(chatPublications).where(eq(chatPublications.id, fixture.publicationId)); diff --git a/server/src/services/native-runtime/external-review-wait.ts b/server/src/services/native-runtime/external-review-wait.ts index fe5347a9cea..4a63ad6510d 100644 --- a/server/src/services/native-runtime/external-review-wait.ts +++ b/server/src/services/native-runtime/external-review-wait.ts @@ -1,6 +1,23 @@ -import { and, eq, inArray } from "drizzle-orm"; +import { and, eq, inArray, sql } from "drizzle-orm"; import { chatConversations, chatEndpoints, heartbeatRuns, issues, statusDecisions, type Db } from "@paperclipai/db"; import { authorizeChatConversationForBoundRun } from "./chat-attachment-reuse.js"; +import { EXTERNAL_CHAT_QUESTION_RESPONSE_KEY } from "./external-chat-question-response.js"; + +const authorizationContextKeys = [ + "source", "issueId", "wakeReason", "interactionKind", "interactionStatus", "externalChatContinuation", + "interactionId", "sourceRunId", "sourceCommentId", "wakeCommentId", "wakeCommentIds", + "paperclipHarnessCheckedOut", "paperclipExternalChatExecutionBound", + EXTERNAL_CHAT_QUESTION_RESPONSE_KEY, +] as const; + +const authorizationContext = sql | null>` + case when ${heartbeatRuns.contextSnapshot} is null then null else ( + select coalesce(jsonb_object_agg(field.key, field.value), '{}'::jsonb) + from jsonb_each(case when jsonb_typeof(${heartbeatRuns.contextSnapshot}) = 'object' + then ${heartbeatRuns.contextSnapshot} else '{}'::jsonb end) as field(key, value) + where field.key in (${sql.join(authorizationContextKeys.map(key => sql`${key}`), sql`, `)}) + ) end +`; export async function listExternalReviewWaits(db: Db, companyId: string, issueIds: string[]) { if (!issueIds.length) return []; @@ -12,7 +29,7 @@ export async function listExternalReviewWaits(db: Db, companyId: string, issueId createdAt: statusDecisions.createdAt, runId: heartbeatRuns.id, agentId: heartbeatRuns.agentId, - contextSnapshot: heartbeatRuns.contextSnapshot, + contextSnapshot: authorizationContext, }).from(issues) .innerJoin(statusDecisions, and( eq(statusDecisions.id, issues.lastStatusDecisionId), From 75dbd3050bc2a7f7463ff77e5dffe308871a1f25 Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Sun, 25 Oct 2026 00:09:56 -0700 Subject: [PATCH 046/110] perf(git): filter managed identity connection reads (#17563) Apply the existing exact GitHub source marker predicate in the company-scoped connection query. Keep the JavaScript guard and every current install, grant, consent, identity, and credential check unchanged. Validation: 74 focused tests, full build and typecheck, exact-head Greptile 5/5 (medium), full green CI, and no unresolved threads. Both marker locations, malformed JSON types, changed/disabled connections, and retained unrelated configuration are covered. The unfiltered counterfactual fails both row-count regressions. Co-Authored-By: Paperclip --- .../github-operation-credentials.test.ts | 37 +++++++++++++++++++ server/src/services/git-credentials.ts | 6 ++- 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/server/src/__tests__/github-operation-credentials.test.ts b/server/src/__tests__/github-operation-credentials.test.ts index 02d1c864bcd..d9d1ef0c9d6 100644 --- a/server/src/__tests__/github-operation-credentials.test.ts +++ b/server/src/__tests__/github-operation-credentials.test.ts @@ -6,6 +6,7 @@ import { createRuntimeToolsToken } from "../runtime-tools-token.js"; import { errorHandler } from "../middleware/index.js"; import { randomUUID } from "node:crypto"; import { eq } from "drizzle-orm"; +import { createDatabaseResponseCapture, installDatabaseResponseCapture } from "@paperclipai/db/response-capture"; import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; import { agents, @@ -192,6 +193,42 @@ const support = await getEmbeddedPostgresTestSupport(); }); return { id, connectionId, secretId, definitionId }; } + it.each(["config", "transportConfig"] as const)("reads only current GitHub identity connections via %s", async location => { + const input = await seed(), selected = await grant(input, "A"); + const [connection] = await db.select().from(toolConnections).where(eq(toolConnections.id, selected.connectionId)); + await db.update(toolConnections).set({ config: {}, transportConfig: {}, [location]: { sourceTemplateKey: "github" } }) + .where(eq(toolConnections.id, selected.connectionId)); + const payload = "unrelated-connection-config🙂".repeat(10_000); + const irrelevant = [null, true, 42, ["github"], { name: "github" }, "GitHub", " github ", "other"].map(sourceTemplateKey => { + const id = randomUUID(); + return { id, companyId: input.companyId, applicationId: connection.applicationId, name: id, uid: id, + transport: "mcp_remote" as const, config: { sourceTemplateKey, payload }, transportConfig: { sourceTemplateKey } }; + }); + await db.insert(toolConnections).values(irrelevant); + const observed = createDb(database.connectionString), events: Array> = [], now = Date.now(); + const capture = createDatabaseResponseCapture({ start: now - 100, end: now + 59_000 }, event => events.push(event)); + installDatabaseResponseCapture(observed, { toolConnections }, capture); + try { + expect(await resolveManagedGitHubIdentitySelection(observed, input.companyId, { agentId: input.agentId, responsibleUserId: "A" })) + .toMatchObject({ configured: true, grant: { id: selected.id } }); + capture.flush(); + const reads = events.filter(event => event.table === "tool_connections" && event.operation === "select"); + expect(reads).toHaveLength(1); + expect(reads[0].rows).toBe(1); + expect(reads[0].responseValueBytes).toBeLessThan(8192); + await db.update(toolConnections).set({ enabled: false }).where(eq(toolConnections.id, selected.connectionId)); + expect((await resolveManagedGitHubIdentitySelection(observed, input.companyId, { agentId: input.agentId, responsibleUserId: "A" })).grant) + .toBeUndefined(); + await db.update(toolConnections).set({ [location]: { sourceTemplateKey: "other" } }).where(eq(toolConnections.id, selected.connectionId)); + expect(await resolveManagedGitHubIdentitySelection(observed, input.companyId, { agentId: input.agentId, responsibleUserId: "A" })) + .toEqual({ configured: false }); + expect(await resolveManagedGitHubIdentitySelection(observed, randomUUID(), { agentId: input.agentId, responsibleUserId: "A" })) + .toEqual({ configured: false }); + const saved = await db.select().from(toolConnections).where(eq(toolConnections.companyId, input.companyId)); + for (const row of irrelevant) expect(saved.find(candidate => candidate.id === row.id)?.config).toEqual(row.config); + } finally { capture.flush(); await observed.$client.end(); } + }); + async function switchTo( input: Awaited>, user: string, diff --git a/server/src/services/git-credentials.ts b/server/src/services/git-credentials.ts index 3fce7fc2b50..69bac2c029e 100644 --- a/server/src/services/git-credentials.ts +++ b/server/src/services/git-credentials.ts @@ -10,7 +10,7 @@ import { userSecretDefinitions, type Db, } from "@paperclipai/db"; -import { and, eq, inArray, or } from "drizzle-orm"; +import { and, eq, inArray, or, sql } from "drizzle-orm"; import { isGitHubDotCom } from "./github-fetch.js"; import { secretService } from "./secrets.js"; import { toolAccessService } from "./tool-access.js"; @@ -324,6 +324,10 @@ export async function resolveManagedGitHubIdentitySelection( }> { const connections = await db.select().from(toolConnections).where(and( eq(toolConnections.companyId, companyId), + or( + sql`${toolConnections.config}->'sourceTemplateKey' = '"github"'::jsonb`, + sql`${toolConnections.transportConfig}->'sourceTemplateKey' = '"github"'::jsonb`, + ), )); const githubConnections = connections.filter((connection) => { const config = connection.config && typeof connection.config === "object" ? connection.config as Record : {}; From efa2724f9a464d27bfaa8c82204c13b886287baf Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Sun, 25 Oct 2026 00:11:41 -0700 Subject: [PATCH 047/110] fix(db): pace bounded response capture output (#17564) Close database response measurement at its existing deadline, then emit the bounded metadata at 64 records per second. Preserve group indices, counts, privacy, and query/transaction outcomes. Stop the unreferenced timer when the output queue is empty. Validation: 32 capture and real PostgreSQL tests, full build and typecheck, exact-head Greptile 5/5 (medium), full green CI, and no unresolved comments. A 2,200-query fixture reconciles all 2,048 groups and its summary; dedicated-pool coverage awaits deferred output. Co-Authored-By: Paperclip --- doc/DATABASE.md | 5 +- .../db/src/response-capture-postgres.test.ts | 2 + packages/db/src/response-capture.test.ts | 52 ++++++++++++++++++- packages/db/src/response-capture.ts | 25 ++++++++- 4 files changed, 81 insertions(+), 3 deletions(-) diff --git a/doc/DATABASE.md b/doc/DATABASE.md index aacf4f9f23d..a51b7cb6100 100644 --- a/doc/DATABASE.md +++ b/doc/DATABASE.md @@ -342,7 +342,10 @@ column decoding. It retains the Drizzle builder caller for normal, prepared, transaction, and dedicated-pool execution. It issues no queries. It logs the public server caller locations, static schema table, operation, query/row counts, and response value sizes. It emits at most 2,048 aggregate -groups and a summary at the deadline. It never logs SQL, parameters, result +groups and a summary. Measurement stops at the deadline. Environment-enabled +captures emit at most 64 records per second and can take another 33 seconds to +finish writing the bounded output. Wait for the summary before collecting it. +It never logs SQL, parameters, result values, connection strings, or query errors. In-flight queries continue normally. For a bundled server, keep the linked source maps and enable Node's diff --git a/packages/db/src/response-capture-postgres.test.ts b/packages/db/src/response-capture-postgres.test.ts index 370d738d056..96de91ff913 100644 --- a/packages/db/src/response-capture-postgres.test.ts +++ b/packages/db/src/response-capture-postgres.test.ts @@ -182,6 +182,8 @@ describe.skipIf(!support.supported)("database response capture PostgreSQL behavi expect(await withDedicatedDbConnection(db, async dedicated => dedicated.execute(sql`select ${"dedicated-value"}::text as value`))) .toEqual([{ value: "dedicated-value" }]); capture.flush(); + await vi.waitFor(() => expect(logs.some(line => JSON.parse(line).event === "paperclip.db_response_capture.summary.v1")).toBe(true), + { timeout: 1_000, interval: 5 }); const events = logs.map(line => JSON.parse(line) as Record); expect(summary(events)).toMatchObject({ startedQueries: 1, completedQueries: 1 }); expect(logs.join("\n")).not.toContain("dedicated-value"); diff --git a/packages/db/src/response-capture.test.ts b/packages/db/src/response-capture.test.ts index 9fc1c80f5b1..73d25d8fc3c 100644 --- a/packages/db/src/response-capture.test.ts +++ b/packages/db/src/response-capture.test.ts @@ -1,6 +1,6 @@ import { integer, pgTable } from "drizzle-orm/pg-core"; import { afterEach, describe, expect, it, vi } from "vitest"; -import { createDatabaseResponseCapture, installDatabaseResponseCapture, publicDatabaseCallers, responseCaptureWindow } from "./response-capture.js"; +import { createDatabaseResponseCapture, databaseResponseCaptureFromEnv, installDatabaseResponseCapture, publicDatabaseCallers, responseCaptureWindow } from "./response-capture.js"; const epoch = Date.parse("2020-01-01T00:00:00Z"); const metadata = { operation: "select", table: "capture_fixture", callers: ["services/fixture.ts:4:2"] }; @@ -16,6 +16,56 @@ function fixture(emitOverride?: (event: Record) => void) { } describe("bounded database response capture", () => { + it("paces a complete environment capture without extending the measurement window or leaving timers", () => { + vi.useFakeTimers(); + vi.setSystemTime(epoch); + const emitted: Array<{ at: number; event: Record }> = []; + const log = vi.spyOn(console, "info").mockImplementation(value => emitted.push({ at: Date.now(), event: JSON.parse(value) })); + try { + const capture = databaseResponseCaptureFromEnv({ PAPERCLIP_DB_RESPONSE_CAPTURE_WINDOW: "2020-01-01T00:00:00Z/2020-01-01T00:01:00Z" })!; + captures.push(capture); + const rows = [{ secret: "capture-response-sentinel" }]; + for (let index = 0; index < 2200; index++) { + expect(capture.execute(() => rows, { ...metadata, callers: [`services/capture.ts:${index + 1}:1`] })).toBe(rows); + } + vi.advanceTimersByTime(60_001); + expect(emitted.length).toBeGreaterThan(0); + expect(emitted.length).toBeLessThanOrEqual(64); + expect(capture.active()).toBe(false); + expect(capture.execute(() => rows, metadata)).toBe(rows); + capture.flush(); + vi.advanceTimersByTime(32_000); + expect(emitted).toHaveLength(2049); + const groups = emitted.filter(item => item.event.event === "paperclip.db_response_capture.entry.v1"); + const summary = emitted.at(-1)!.event; + expect(groups).toHaveLength(2048); + expect(summary).toMatchObject({ event: "paperclip.db_response_capture.summary.v1", completedQueries: 2200, + groups: 2048, closedAt: "2020-01-01T00:01:00.000Z" }); + expect(groups.reduce((calls, item) => calls + Number(item.event.calls), 0)).toBe(summary.completedQueries); + expect(groups.reduce((bytes, item) => bytes + Number(item.event.responseValueBytes), 0)).toBe(summary.responseValueBytes); + expect(groups.map(item => item.event.groupIndex)).toEqual(Array.from({ length: 2048 }, (_, index) => index)); + for (const { at } of emitted) expect(emitted.filter(item => item.at >= at && item.at < at + 1000).length).toBeLessThanOrEqual(64); + expect(JSON.stringify(emitted)).not.toContain("capture-response-sentinel"); + expect(vi.getTimerCount()).toBe(0); + vi.advanceTimersByTime(60_000); + expect(emitted).toHaveLength(2049); + } finally { log.mockRestore(); vi.clearAllTimers(); vi.useRealTimers(); } + }); + + it("contains deferred logger failures and finishes its bounded output", () => { + vi.useFakeTimers(); + vi.setSystemTime(epoch + 120_000); + const log = vi.spyOn(console, "info").mockImplementation(() => { throw new Error("fixture logger failure"); }); + try { + const capture = databaseResponseCaptureFromEnv({ PAPERCLIP_DB_RESPONSE_CAPTURE_WINDOW: "2020-01-01T00:02:00Z/2020-01-01T00:03:00Z" })!; + captures.push(capture); + expect(capture.execute(() => 7, metadata)).toBe(7); + expect(() => vi.advanceTimersByTime(60_001)).not.toThrow(); + expect(log).toHaveBeenCalledTimes(2); + expect(vi.getTimerCount()).toBe(0); + } finally { log.mockRestore(); vi.clearAllTimers(); vi.useRealTimers(); } + }); + it.each([undefined, "", "sentinel-invalid-input", "2020-01-01T00:00:00Z", "2020-01-01T00:00:00Z/2020-01-01T00:00:00Z", "2020-01-01T00:00:00Z/2020-01-01T00:01:01Z", "2020-01-01T01:00:00Z/2020-01-01T01:01:00Z", "2020-01-01T00:00:00Z/2020-01-01T00:01:00Z/extra", diff --git a/packages/db/src/response-capture.ts b/packages/db/src/response-capture.ts index 675d57eeb82..d53b5fe0c07 100644 --- a/packages/db/src/response-capture.ts +++ b/packages/db/src/response-capture.ts @@ -143,12 +143,35 @@ export function createDatabaseResponseCapture( type Capture = ReturnType; let environmentCapture: { key: string; capture: Capture } | undefined; + +function pacedCaptureLogger() { + const pending: Event[] = []; + let timer: ReturnType | undefined; + const drain = () => { + timer = undefined; + for (const event of pending.splice(0, 64)) { + try { console.info(JSON.stringify(event)); } catch {} + } + if (pending.length) { + timer = setTimeout(drain, 1_000); + timer.unref(); + } + }; + return (event: Event) => { + pending.push(event); + if (!timer) { + timer = setTimeout(drain, 0); + timer.unref(); + } + }; +} + export function databaseResponseCaptureFromEnv(env: NodeJS.ProcessEnv = process.env): Capture | undefined { const key = env.PAPERCLIP_DB_RESPONSE_CAPTURE_WINDOW; const window = responseCaptureWindow(key); if (!key || !window) return; if (environmentCapture?.key === key) return environmentCapture.capture; - const capture = createDatabaseResponseCapture(window, event => console.info(JSON.stringify(event))); + const capture = createDatabaseResponseCapture(window, pacedCaptureLogger()); environmentCapture = { key, capture }; return capture; } From f978a521ff34f1a7aac94892981db88973743097 Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Sun, 25 Oct 2026 00:21:15 -0700 Subject: [PATCH 048/110] perf(heartbeat): narrow workspace operation access reads (#17565) Read only the current run access fields and typed workspace binding for workspace-operation polling. Keep the current privacy decisions, operation checks, and complete run storage. Verified focused run-state, live-event, and real database privacy-route tests, full build and typecheck, all CI checks, and exact-head Greptile 5/5 with no unresolved threads. Co-Authored-By: Paperclip --- doc/DEVELOPING.md | 2 ++ .../__tests__/agent-live-run-routes.test.ts | 20 +++++++++++++ .../heartbeat-run-privacy-routes.test.ts | 24 ++++++++++++++++ server/src/routes/agents.ts | 5 ++-- server/src/services/heartbeat.ts | 2 ++ .../src/services/heartbeat/run-state.test.ts | 28 +++++++++++++++++++ server/src/services/heartbeat/run-state.ts | 8 ++++++ 7 files changed, 86 insertions(+), 3 deletions(-) diff --git a/doc/DEVELOPING.md b/doc/DEVELOPING.md index 432eb547d45..20b6ce6563d 100644 --- a/doc/DEVELOPING.md +++ b/doc/DEVELOPING.md @@ -1814,6 +1814,8 @@ writes, explicit resumes, session compaction, and usage/billing helpers. during construction. The encoding-check cache belongs to each factory instance. Queued-comment polling reads current issue control fields, the typed issue binding, and the selected adapter type. Mutation and execution paths retain their full run reads. +Workspace-operation polling reads the current run access scope and typed workspace +binding, then applies the existing run and operation permission checks. `heartbeat.ts` keeps run execution and re-exports the existing public helpers. Keep session policy changes separate from run orchestration changes. diff --git a/server/src/__tests__/agent-live-run-routes.test.ts b/server/src/__tests__/agent-live-run-routes.test.ts index 94f6d525268..484b88a63ca 100644 --- a/server/src/__tests__/agent-live-run-routes.test.ts +++ b/server/src/__tests__/agent-live-run-routes.test.ts @@ -16,6 +16,7 @@ const mockHeartbeatService = vi.hoisted(() => ({ getActiveRunIssueSummaryForAgent: vi.fn(), getRunReadAccess: vi.fn(), getRunLogAccess: vi.fn(), + getRunWorkspaceAccess: vi.fn(), readLog: vi.fn(), wakeup: vi.fn(), getRun: vi.fn(), @@ -378,6 +379,10 @@ describe("agent live run routes", () => { logStore: "local_file", logRef: "logs/aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa.ndjson", }); + mockHeartbeatService.getRunWorkspaceAccess.mockResolvedValue({ + id: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", companyId: "company-1", scopeKind: "company", issueId: null, + executionWorkspaceId: null, + }); mockHeartbeatService.readLog.mockResolvedValue({ runId: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", store: "local_file", @@ -687,6 +692,21 @@ describe("agent live run routes", () => { }, ); + it("lists workspace operations using narrow current run access", async () => { + mockHeartbeatService.getRunWorkspaceAccess.mockResolvedValue({ + id: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", companyId: "company-1", scopeKind: "company", issueId: null, + executionWorkspaceId: " workspace-one ", + }); + mockWorkspaceOperationService.listForRun.mockResolvedValue([]); + const response = await requestApp(await createApp(), baseUrl => request(baseUrl) + .get("/api/heartbeat-runs/aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa/workspace-operations")); + expect(response.status).toBe(200); + expect(response.body).toEqual([]); + expect(mockHeartbeatService.getRunWorkspaceAccess).toHaveBeenCalledWith("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + expect(mockHeartbeatService.getRun).not.toHaveBeenCalled(); + expect(mockWorkspaceOperationService.listForRun).toHaveBeenCalledWith("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", "workspace-one"); + }); + it("caps company live run polling by default", async () => { const rows = Array.from({ length: 75 }, (_, index) => ({ id: `run-${index}`, diff --git a/server/src/__tests__/heartbeat-run-privacy-routes.test.ts b/server/src/__tests__/heartbeat-run-privacy-routes.test.ts index 03914cadeda..40d966ed8e8 100644 --- a/server/src/__tests__/heartbeat-run-privacy-routes.test.ts +++ b/server/src/__tests__/heartbeat-run-privacy-routes.test.ts @@ -1,6 +1,7 @@ import { randomUUID } from "node:crypto"; import { eq } from "drizzle-orm"; import { drizzle } from "drizzle-orm/postgres-js"; +import { createDatabaseResponseCapture, installDatabaseResponseCapture } from "@paperclipai/db/response-capture"; import express from "express"; import request from "supertest"; import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; @@ -257,6 +258,29 @@ describeEmbeddedPostgres("heartbeat run privacy routes", { concurrent: false }, return app; } + it("lists workspace operations with small run reads and checks a revoked issue grant again", async () => { + const f = await seedFixture(), payload = "workspace-operation-saved-input🙂".repeat(25_000); + await db.update(heartbeatRuns).set({ contextSnapshot: { issueId: f.issueId, prompt: payload }, + runnerProfileJson: { instructions: payload }, stdoutExcerpt: payload, stderrExcerpt: payload, + }).where(eq(heartbeatRuns.id, f.privateRunId)); + const [before] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.privateRunId)); + const observed = createDb(tempDb!.connectionString), events: Array> = [], now = Date.now(); + const capture = createDatabaseResponseCapture({ start: now - 100, end: now + 59_000 }, event => events.push(event)); + installDatabaseResponseCapture(observed, { heartbeatRuns }, capture); + try { + const app = createApp(f.companyId, f.grantedAgentId, observed); + const response = await request(app).get(`/api/heartbeat-runs/${f.privateRunId}/workspace-operations`).expect(200); + expect(response.body).toEqual([expect.objectContaining({ id: f.operationId })]); + capture.flush(); + const reads = events.filter(event => event.table === "heartbeat_runs" && event.operation === "select"); + expect(reads.length).toBeGreaterThan(0); + expect(reads.reduce((bytes, event) => bytes + Number(event.responseValueBytes), 0)).toBeLessThan(2048); + await db.delete(issueAccessGrants).where(eq(issueAccessGrants.subjectId, f.grantedAgentId)); + await request(app).get(`/api/heartbeat-runs/${f.privateRunId}/workspace-operations`).expect(404); + expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.privateRunId)))[0]).toEqual(before); + } finally { capture.flush(); await observed.$client.end(); } + }); + it("returns 404 for direct private-run content and metadata-only list stubs to a non-member", async () => { const fixture = await seedFixture(); const app = createApp(fixture.companyId, fixture.otherAgentId); diff --git a/server/src/routes/agents.ts b/server/src/routes/agents.ts index 0aba86abb8f..a6b71c93b9d 100644 --- a/server/src/routes/agents.ts +++ b/server/src/routes/agents.ts @@ -7589,13 +7589,12 @@ export function agentRoutes( router.get("/heartbeat-runs/:runId/workspace-operations", async (req, res) => { const runId = readHeartbeatRunId(req); - const run = await getAccessibleResource(req, res, heartbeat.getRun(runId), "Heartbeat run not found"); + const run = await getAccessibleResource(req, res, heartbeat.getRunWorkspaceAccess(runId), "Heartbeat run not found"); if (!run) return; if (!(await assertRunTelemetryReadAllowed(req, res, run.companyId))) return; if (!(await assertRunReadAllowed(req, res, run))) return; - const context = asRecord(run.contextSnapshot); - const executionWorkspaceId = asNonEmptyString(context?.executionWorkspaceId); + const executionWorkspaceId = asNonEmptyString(run.executionWorkspaceId); const operations = await workspaceOperations.listForRun(runId, executionWorkspaceId); const visibleOperations = []; for (const operation of operations) { diff --git a/server/src/services/heartbeat.ts b/server/src/services/heartbeat.ts index f177921a36d..adb10d852c9 100644 --- a/server/src/services/heartbeat.ts +++ b/server/src/services/heartbeat.ts @@ -825,6 +825,7 @@ export function heartbeatService( hasResolvablePriorSessionWorkspaceForWake, getRunReadAccess, getRunLogAccess, + getRunWorkspaceAccess, listRuns, getRuntimeStateWithSessions, listTaskSessions, @@ -3993,6 +3994,7 @@ export function heartbeatService( getRunReadAccess, getRunLogAccess, + getRunWorkspaceAccess, getRuntimeState: getRuntimeStateWithSessions, diff --git a/server/src/services/heartbeat/run-state.test.ts b/server/src/services/heartbeat/run-state.test.ts index e42d93d7286..702f842e464 100644 --- a/server/src/services/heartbeat/run-state.test.ts +++ b/server/src/services/heartbeat/run-state.test.ts @@ -159,6 +159,34 @@ describePostgres("heartbeat run state database wiring", () => { return { companyId, agent, issue, state: extracted.createHeartbeatRunState(db) }; } + it("reads current workspace access without execution snapshots and retains JSON types", async () => { + const { companyId, agent, issue } = await fixture(); + const payload = randomBytes(128 * 1024).toString("base64"), workspaceId = randomUUID(); + const [run] = await db.insert(heartbeatRuns).values({ companyId, agentId: agent.id, scopeKind: "issue", issueId: issue.id, + contextSnapshot: { executionWorkspaceId: workspaceId, prompt: payload }, runnerProfileJson: { instructions: payload }, + resultJson: { stdout: payload }, stdoutExcerpt: payload, stderrExcerpt: payload, + }).returning(); + const observed = createDb(database.connectionString), events: Array> = [], now = Date.now(); + const capture = createDatabaseResponseCapture({ start: now - 100, end: now + 59_000 }, event => events.push(event)); + installDatabaseResponseCapture(observed, { heartbeatRuns }, capture); + try { + const state = extracted.createHeartbeatRunState(observed); + expect(await state.getRunWorkspaceAccess(run.id)).toEqual({ + id: run.id, companyId, scopeKind: "issue", issueId: issue.id, executionWorkspaceId: workspaceId, + }); + capture.flush(); + const summary = events.find(event => event.event === "paperclip.db_response_capture.summary.v1")!; + expect(summary.completedQueries).toBe(1); + expect(summary.responseValueBytes).toBeLessThan(1024); + expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, run.id)))[0]).toEqual(run); + for (const value of [null, true, 42, " workspace-two ", [workspaceId], { id: workspaceId }]) { + await db.update(heartbeatRuns).set({ contextSnapshot: { executionWorkspaceId: value, prompt: payload } }).where(eq(heartbeatRuns.id, run.id)); + expect((await state.getRunWorkspaceAccess(run.id))?.executionWorkspaceId).toEqual(value); + } + expect(await state.getRunWorkspaceAccess(randomUUID())).toBeNull(); + } finally { capture.flush(); await observed.$client.end(); } + }); + it("reads fresh issue control facts without transferring execution snapshots", async () => { const { companyId, agent, issue } = await fixture(); const payload = randomBytes(128 * 1024).toString("base64"); diff --git a/server/src/services/heartbeat/run-state.ts b/server/src/services/heartbeat/run-state.ts index 3bf92684a1f..f870c3957fb 100644 --- a/server/src/services/heartbeat/run-state.ts +++ b/server/src/services/heartbeat/run-state.ts @@ -1182,6 +1182,13 @@ export function createHeartbeatRunState(db: Db) { .then((rows) => rows[0] ?? null); } + async function getRunWorkspaceAccess(runId: string) { + return db.select({ + ...heartbeatRunReadAccessColumns, + executionWorkspaceId: sql`${heartbeatRuns.contextSnapshot}->'executionWorkspaceId'`, + }).from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)).then(rows => rows[0] ?? null); + } + async function getRuntimeState(agentId: string) { return db .select() @@ -1736,6 +1743,7 @@ export function createHeartbeatRunState(db: Db) { getRunStatus, getRunReadAccess, getRunLogAccess, + getRunWorkspaceAccess, listRuns: async ( companyId: string, From 0d73505098ff9980c5a0947b103a999ab55e5b88 Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Sun, 25 Oct 2026 00:31:41 -0700 Subject: [PATCH 049/110] perf(git): narrow operation identity snapshot reads (#17567) Select only the run context used by GitHub operation credential checks. Preserve the default complete identity capture for Muse and other consumers, current trust checks, grants, and saved run evidence. Validation: 72 focused GitHub, identity, Slack, chat-project, and project-route tests; full build and typecheck; exact-head Greptile 5/5 (medium), all CI checks green, and zero unresolved comments. Real PostgreSQL tests prove current revocation and response-size bounds. No live external GitHub push was performed. Co-Authored-By: Paperclip --- doc/execution-github-identity.md | 6 ++++ .../github-operation-credentials.test.ts | 31 +++++++++++++++++++ server/src/__tests__/run-identity.test.ts | 17 ++++++++++ .../services/github-operation-credentials.ts | 2 +- server/src/services/run-identity.ts | 14 +++++++-- 5 files changed, 67 insertions(+), 3 deletions(-) diff --git a/doc/execution-github-identity.md b/doc/execution-github-identity.md index 662f20ef11d..3d179337f17 100644 --- a/doc/execution-github-identity.md +++ b/doc/execution-github-identity.md @@ -14,6 +14,12 @@ Delegated work and interactions persist their originating context. Retries retai Executions with managed GitHub configured receive token-free `git` and `gh` launchers. Each launcher invocation resolves one eligible credential from the current run's accepted identity at operation start. A `gh` command's child Git processes inherit that command's captured identity; later steering does not change already-started operations. +GitHub credential capture reads the current task, project, and retained trust +policy bindings without transferring saved prompts, runner profiles, results, +or log excerpts. It keeps the existing task/run lock order and accepted-identity +reconciliation. Other identity callers retain their complete execution input, +including the native input required by project creation authorization. + Native runners retain a session-owned broker and launcher path across warm turns. The provider keeps an opaque transport token, not a GitHub credential or the previous run's signed capability. After acquiring exclusive session ownership, the controller binds the broker to the current company, agent, task, and run. Requests cannot choose another run or responsible person. The broker rejects requests while idle and discards credential responses if their run binding changed during acquisition. Each operation still rechecks the live run, accepted identity, grants, and trust policy through the shared credential resolver. Changing run IDs alone no longer replaces the provider process; changes to authentication mode, provider credentials, permissions, or other session configuration retain their existing retirement rules. The session broker listens only on controller loopback and accepts only its authenticated GitHub credential operation. Remote executions reach it through the existing authenticated callback bridge. Its transport and launchers are retired with the provider session. If remote bridge startup fails, anonymous launchers keep ordinary work available; the next run retries setup with a fresh session. Controller restart/cold recovery still uses the existing checkpoint and process-recovery rules; the broker's in-memory authority is not persisted for adoption. diff --git a/server/src/__tests__/github-operation-credentials.test.ts b/server/src/__tests__/github-operation-credentials.test.ts index d9d1ef0c9d6..699249b5b58 100644 --- a/server/src/__tests__/github-operation-credentials.test.ts +++ b/server/src/__tests__/github-operation-credentials.test.ts @@ -32,6 +32,7 @@ import { } from "./helpers/embedded-postgres.js"; import { initializeRunIdentity, + captureRunIdentity, reserveSteeredIdentity, acceptSteeredIdentity, } from "../services/run-identity.js"; @@ -229,6 +230,36 @@ const support = await getEmbeddedPostgresTestSupport(); } finally { capture.flush(); await observed.$client.end(); } }); + it("resolves current GitHub credentials without transferring execution snapshots", async () => { + const input = await seed(), selected = await grant(input, "A"); + const payload = "github-credential-saved-input🙂".repeat(25_000); + await db.update(heartbeatRuns).set({ contextSnapshot: { issueId: input.issueId, prompt: payload }, + runnerProfileJson: { nativeExecutionInput: { savedInput: payload }, savedInput: payload }, + resultJson: { stdout: payload }, stdoutExcerpt: payload, stderrExcerpt: payload, + }).where(eq(heartbeatRuns.id, input.runId)); + const [before] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, input.runId)); + const observed = createDb(database.connectionString), events: Array> = [], now = Date.now(); + const capture = createDatabaseResponseCapture({ start: now - 100, end: now + 59_000 }, event => events.push(event)); + installDatabaseResponseCapture(observed, { heartbeatRuns }, capture); + try { + expect(await resolveGitHubOperationCredentials(observed, input)).toMatchObject({ + status: "available", login: "A", grantId: selected.id, + }); + capture.flush(); + const reads = events.filter(event => event.table === "heartbeat_runs" && event.operation === "select"); + expect(reads.length).toBeGreaterThan(0); + expect(reads.reduce((bytes, event) => bytes + Number(event.responseValueBytes), 0)).toBeLessThan(8192); + expect(JSON.stringify(events)).not.toContain("github-credential-saved-input"); + expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, input.runId)))[0]).toEqual(before); + const full = await captureRunIdentity(observed, input); + expect(full.run.runnerProfileJson).toEqual(before.runnerProfileJson); + expect(full.run.resultJson).toEqual(before.resultJson); + expect(full.run.contextSnapshot).toEqual(before.contextSnapshot); + await db.update(connectionGrants).set({ status: "revoked" }).where(eq(connectionGrants.id, selected.id)); + expect(await resolveGitHubOperationCredentials(observed, input)).toMatchObject({ status: "unavailable" }); + } finally { capture.flush(); await observed.$client.end(); } + }); + async function switchTo( input: Awaited>, user: string, diff --git a/server/src/__tests__/run-identity.test.ts b/server/src/__tests__/run-identity.test.ts index d6dbbbfc3ff..b371c59f043 100644 --- a/server/src/__tests__/run-identity.test.ts +++ b/server/src/__tests__/run-identity.test.ts @@ -29,6 +29,23 @@ const support = await getEmbeddedPostgresTestSupport(); } return { companyId, agentId, issueId, runId, messageIds }; } + it("retains typed GitHub trust bindings and keeps other identity reads complete", async () => { + const input = await seed(); + await initializeRunIdentity(db, { ...input, responsibleUserId: "owner", cause: "queued" }); + for (const value of [null, true, 42, " padded ", [], {}, { future: { opaque: true } }]) { + const contextSnapshot = { issueId: input.issueId, projectId: value, executionPolicy: value, savedInput: { retained: true } }; + const runnerProfileJson = { nativeExecutionInput: { opaque: value }, savedInput: "retained" }; + await db.update(heartbeatRuns).set({ contextSnapshot, runnerProfileJson }).where(eq(heartbeatRuns.id, input.runId)); + const narrow = await captureRunIdentity(db, input, { readScope: "github_credentials" }); + expect(narrow.run.contextSnapshot).toEqual({ issueId: input.issueId, taskId: null, projectId: value, executionPolicy: value }); + expect(narrow.run.runnerProfileJson).toBeNull(); + const full = await captureRunIdentity(db, input); + expect(full.run.contextSnapshot).toEqual(contextSnapshot); + expect(full.run.runnerProfileJson).toEqual(runnerProfileJson); + expect(narrow.context).toEqual(full.context); + } + }); + it("retains mixed-author delivery order without rewriting task ownership", async () => { const input = await seed(); await initializeRunIdentity(db, { ...input, responsibleUserId: "owner", cause: "queued" }); diff --git a/server/src/services/github-operation-credentials.ts b/server/src/services/github-operation-credentials.ts index b82e4be4211..c24aeabb5c1 100644 --- a/server/src/services/github-operation-credentials.ts +++ b/server/src/services/github-operation-credentials.ts @@ -112,7 +112,7 @@ export async function resolveGitHubOperationCredentials( runId: string; }, ) { - const { run, context } = await captureRunIdentity(db, input); + const { run, context } = await captureRunIdentity(db, input, { readScope: "github_credentials" }); if (!context) throw forbidden("This run predates managed GitHub credentials"); let summary: GitHubCredentialSummary; let env: Record = {}; diff --git a/server/src/services/run-identity.ts b/server/src/services/run-identity.ts index cc75397a991..b1e27d1ae72 100644 --- a/server/src/services/run-identity.ts +++ b/server/src/services/run-identity.ts @@ -1,4 +1,4 @@ -import { and, asc, desc, eq, inArray, sql } from "drizzle-orm"; +import { and, asc, desc, eq, getTableColumns, inArray, sql } from "drizzle-orm"; import { agentWakeupRequests, heartbeatRuns, @@ -434,12 +434,22 @@ export async function acceptSteeredIdentity( export async function captureRunIdentity( db: Db, input: { companyId: string; runId: string; agentId: string }, + options?: { readScope: "github_credentials" }, ) { // Lock acquisition serializes with steering delivery and its durable acknowledgement. return db.transaction(async (tx) => { await lockIdentityTask(tx, input.companyId, input.runId); const [run] = await tx - .select() + .select(options?.readScope === "github_credentials" ? { + ...getTableColumns(heartbeatRuns), + contextSnapshot: sql | null>`case when jsonb_typeof(${heartbeatRuns.contextSnapshot}) = 'object' + then jsonb_build_object('issueId', ${heartbeatRuns.contextSnapshot}->'issueId', + 'taskId', ${heartbeatRuns.contextSnapshot}->'taskId', 'projectId', ${heartbeatRuns.contextSnapshot}->'projectId', + 'executionPolicy', ${heartbeatRuns.contextSnapshot}->'executionPolicy') else null end`, + runnerProfileJson: sql | null>`null`, + resultJson: sql | null>`null`, + stdoutExcerpt: sql`null`, stderrExcerpt: sql`null`, + } : getTableColumns(heartbeatRuns)) .from(heartbeatRuns) .where( and( From 7494b8dd4c113a9f290e9dc5fbda4f61776f5d67 Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Sun, 25 Oct 2026 00:35:07 -0700 Subject: [PATCH 050/110] perf(auth): batch current run history read decisions (#17569) Reuse the existing authorization batch owner for current run-history read decisions after company-scoped existence checks. Preserve missing-task denial, per-request freshness, and the decide-only adapter path. Validation: 97 focused tests, full build and repository typecheck. A real PostgreSQL fixture returns identical decisions with 4 queries instead of 327; the original path fails the query-bound regression. Exact-head Greptile 5/5 (medium), all CI checks green, and no unresolved comments. Co-Authored-By: Paperclip --- doc/DEVELOPING.md | 9 ++ .../heartbeat-run-privacy-routes.test.ts | 105 +++++++++++++++++- server/src/services/access.ts | 1 + server/src/services/heartbeat-run-privacy.ts | 43 ++++++- 4 files changed, 153 insertions(+), 5 deletions(-) diff --git a/doc/DEVELOPING.md b/doc/DEVELOPING.md index 20b6ce6563d..3cc2067d727 100644 --- a/doc/DEVELOPING.md +++ b/doc/DEVELOPING.md @@ -907,6 +907,15 @@ can update an entry only after the current account's summary confirms access. The first healthy live subscription reconciles domain data without re-fetching session and health; reconnects and visibility recovery retain full reconciliation. +### Run history authorization reads + +Run history reuses the authorization service's batch read API for distinct task +bindings. Existence checks remain company-scoped and use batches of at most 500 +IDs. Missing or foreign tasks stay unreadable in every privacy mode. The batch +snapshot lasts for one request only; the next request checks current grants, +membership, and run restrictions again. Adapters that expose only `decide` +retain the individual-read path with duplicate bindings shared within the request. + ### Local Linux runner qualification Before serving requests, the server reads `getconf GNU_LIBC_VERSION` once with diff --git a/server/src/__tests__/heartbeat-run-privacy-routes.test.ts b/server/src/__tests__/heartbeat-run-privacy-routes.test.ts index 40d966ed8e8..ed10d2548f2 100644 --- a/server/src/__tests__/heartbeat-run-privacy-routes.test.ts +++ b/server/src/__tests__/heartbeat-run-privacy-routes.test.ts @@ -483,6 +483,105 @@ describeEmbeddedPostgres("heartbeat run privacy routes", { concurrent: false }, process.env.PAPERCLIP_ISSUE_PRIVACY_MODE = "enforce"; } }); + it("batches distinct issue bindings without changing current authorization decisions", async () => { + const fixture = await seedFixture(); + const ids = Array.from({ length: 64 }, () => randomUUID()); + await db.insert(issues).values(ids.map((id, index) => ({ + id, companyId: fixture.companyId, title: `History ${index}`, status: "in_progress", + visibility: index % 2 ? "private" : "open", privacyRootIssueId: index % 2 ? id : null, + assigneeAgentId: fixture.ownerAgentId, responsibleUserId: fixture.ownerUserId, + }))); + const queries: string[] = []; + const observedDb = drizzle(db.$client, { schema, logger: { logQuery(query) { queries.push(query); } } }) as typeof db; + const access = authorizationService(observedDb); + const actor = { type: "agent" as const, companyId: fixture.companyId, agentId: fixture.grantedAgentId }; + const bindings = [...ids, fixture.issueId].map(issueId => ({ companyId: fixture.companyId, scopeKind: "issue" as const, issueId })); + const runs = [...bindings, ...bindings, { ...bindings[0], companyId: randomUUID() }, + { ...bindings[0], issueId: randomUUID() }, { companyId: fixture.companyId, scopeKind: "company" as const }, + { companyId: fixture.companyId, scopeKind: "issue" as const }]; + const individual = await getHeartbeatRunReadDecisions(observedDb, { decide: access.decide }, actor, runs); + const individualCount = queries.length; + queries.length = 0; + const batched = await getHeartbeatRunReadDecisions(observedDb, access, actor, runs); + expect(batched).toEqual(individual); + expect(batched.slice(0, 64)).toEqual(ids.map((_, index) => index % 2 === 0)); + expect(batched.at(64)).toBe(true); + expect(batched.slice(-4)).toEqual([false, false, true, false]); + expect(queries.length).toBeLessThan(25); + expect(queries.length).toBeLessThan(individualCount / 4); + await db.update(issueAccessGrants).set({ revokedAt: new Date() }).where(eq(issueAccessGrants.subjectId, fixture.grantedAgentId)); + expect((await getHeartbeatRunReadDecisions(observedDb, access, actor, runs)).at(64)).toBe(false); + }); + + it.each(["enforce", "shadow", "off"])("keeps missing and foreign issue bindings closed in %s mode", async mode => { + const fixture = await seedFixture(); + process.env.PAPERCLIP_ISSUE_PRIVACY_MODE = mode; + try { + const access = authorizationService(db); + const actor = { type: "board" as const, userId: fixture.ownerUserId }; + const binding = { companyId: fixture.companyId, scopeKind: "issue" as const, issueId: fixture.issueId }; + const runs = [binding, { ...binding, issueId: randomUUID() }, { ...binding, companyId: randomUUID() }]; + const expected = await getHeartbeatRunReadDecisions(db, { decide: access.decide }, actor, runs); + expect(await getHeartbeatRunReadDecisions(db, access, actor, runs)).toEqual(expected); + expect(expected).toEqual([true, false, false]); + await db.delete(companyMemberships).where(eq(companyMemberships.principalId, fixture.ownerUserId)); + expect(await getHeartbeatRunReadDecisions(db, access, actor, [binding])).toEqual( + await getHeartbeatRunReadDecisions(db, { decide: access.decide }, actor, [binding]), + ); + } finally { process.env.PAPERCLIP_ISSUE_PRIVACY_MODE = "enforce"; } + }); + + it("checks more than 500 task bindings with bounded company-scoped queries", async () => { + const fixture = await seedFixture(); + const ids = Array.from({ length: 501 }, () => randomUUID()); + await db.insert(issues).values(ids.map((id, index) => ({ + id, companyId: fixture.companyId, title: `Batch ${index}`, visibility: "open", status: "in_progress", + }))); + const queries: { query: string; params: unknown[] }[] = []; + const observedDb = drizzle(db.$client, { schema, logger: { logQuery(query, params) { queries.push({ query, params }); } } }) as typeof db; + const access = authorizationService(observedDb); + const actor = { type: "agent" as const, companyId: fixture.companyId, agentId: fixture.ownerAgentId }; + const runs = ids.map(issueId => ({ companyId: fixture.companyId, scopeKind: "issue" as const, issueId })); + expect(await getHeartbeatRunReadDecisions(observedDb, access, actor, runs)).toEqual(ids.map(() => true)); + const existence = queries.filter(({ query }) => query.startsWith('select "id" from "issues"')); + expect(existence.map(({ params }) => params.length).sort((a, b) => a - b)).toEqual([2, 501]); + expect(existence.every(({ query, params }) => query.includes('"company_id"') && params[0] === fixture.companyId)).toBe(true); + }); + + it("captures batch inputs before awaiting reads and rejects a failed batch", async () => { + const fixture = await seedFixture(); + const access = authorizationService(db); + const actor = { type: "agent" as const, companyId: fixture.companyId, agentId: fixture.ownerAgentId }; + const binding = { companyId: fixture.companyId, scopeKind: "issue" as const, issueId: fixture.issueId }; + const decideReads = vi.spyOn(access, "decideReads"); + const pending = getHeartbeatRunReadDecisions(db, access, actor, [binding, binding]); + binding.issueId = randomUUID(); + expect(await pending).toEqual([true, true]); + expect(decideReads).toHaveBeenCalledExactlyOnceWith(actor, [expect.objectContaining({ issueId: fixture.issueId })]); + const error = new Error("authorization unavailable"); + decideReads.mockRejectedValueOnce(error); + const current = { ...binding, issueId: fixture.issueId }; + await expect(getHeartbeatRunReadDecisions(db, access, actor, [current])).rejects.toBe(error); + const transient = Object.assign(new Error("temporary disconnect"), { code: "CONNECTION_CLOSED" }); + decideReads.mockRejectedValueOnce(transient); + expect(await getHeartbeatRunReadDecisions(db, access, actor, [current])).toEqual([true]); + }); + + it("does no database or authorization work for company-only or empty batches", async () => { + const fixture = await seedFixture(); + const queries: string[] = []; + const observedDb = drizzle(db.$client, { schema, logger: { logQuery(query) { queries.push(query); } } }) as typeof db; + const access = authorizationService(observedDb); + const decideReads = vi.spyOn(access, "decideReads"); + const actor = { type: "agent" as const, companyId: fixture.companyId, agentId: fixture.ownerAgentId }; + expect(await getHeartbeatRunReadDecisions(observedDb, access, actor, [])).toEqual([]); + expect(await getHeartbeatRunReadDecisions(observedDb, access, actor, [ + { companyId: fixture.companyId, scopeKind: "company" }, { companyId: fixture.companyId, scopeKind: "issue" }, + ])).toEqual([true, false]); + expect(queries).toEqual([]); + expect(decideReads).not.toHaveBeenCalled(); + }); + it.each(["owner", "outsider"])("checks concurrent duplicate issue runs once for the %s", async (viewer) => { const fixture = await seedFixture(); const access = authorizationService(db); @@ -493,7 +592,7 @@ describeEmbeddedPostgres("heartbeat run privacy routes", { concurrent: false }, agentId: viewer === "owner" ? fixture.ownerAgentId : fixture.otherAgentId, }; const binding = { companyId: fixture.companyId, scopeKind: "issue" as const, issueId: fixture.issueId }; - const decisions = await getHeartbeatRunReadDecisions(db, access, actor, Array.from({ length: 200 }, () => ({ ...binding }))); + const decisions = await getHeartbeatRunReadDecisions(db, { decide: access.decide }, actor, Array.from({ length: 200 }, () => ({ ...binding }))); expect(decisions).toEqual(Array(200).fill(viewer === "owner")); expect(decide).toHaveBeenCalledTimes(1); decide.mockRestore(); @@ -517,7 +616,7 @@ describeEmbeddedPostgres("heartbeat run privacy routes", { concurrent: false }, const decide = vi.spyOn(access, "decide"); const actor = { type: "agent" as const, companyId: fixture.companyId, agentId: fixture.ownerAgentId }; const binding = { companyId: fixture.companyId, scopeKind: "issue" as const, issueId: fixture.issueId }; - const pending = getHeartbeatRunReadDecisions(db, access, actor, [binding, binding]); + const pending = getHeartbeatRunReadDecisions(db, { decide: access.decide }, actor, [binding, binding]); binding.issueId = randomUUID(); expect(await pending).toEqual([true, true]); expect(decide).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ @@ -591,7 +690,7 @@ describeEmbeddedPostgres("heartbeat run privacy routes", { concurrent: false }, const decide = vi.spyOn(access, "decide").mockRejectedValue(error); const actor = { type: "agent" as const, companyId: fixture.companyId, agentId: fixture.ownerAgentId }; const binding = { companyId: fixture.companyId, scopeKind: "issue" as const, issueId: fixture.issueId }; - await expect(getHeartbeatRunReadDecisions(db, access, actor, Array(20).fill(binding))).rejects.toBe(error); + await expect(getHeartbeatRunReadDecisions(db, { decide: access.decide }, actor, Array(20).fill(binding))).rejects.toBe(error); expect(decide).toHaveBeenCalledTimes(1); decide.mockRestore(); expect(await getHeartbeatRunReadDecisions(db, access, actor, [binding])).toEqual([true]); diff --git a/server/src/services/access.ts b/server/src/services/access.ts index fced6f2c698..d7ae99b09a7 100644 --- a/server/src/services/access.ts +++ b/server/src/services/access.ts @@ -1162,6 +1162,7 @@ export function accessService(db: Db) { return { isInstanceAdmin, decide, + decideReads: authorization.decideReads, projectDiscoveryCandidateIds: authorization.projectDiscoveryCandidateIds, canUser, hasPermission, diff --git a/server/src/services/heartbeat-run-privacy.ts b/server/src/services/heartbeat-run-privacy.ts index 17b61f4cbbd..d1cb41a19a2 100644 --- a/server/src/services/heartbeat-run-privacy.ts +++ b/server/src/services/heartbeat-run-privacy.ts @@ -1,7 +1,7 @@ import type { Db } from "@paperclipai/db"; import { issues, heartbeatRuns } from "@paperclipai/db"; -import { and, eq } from "drizzle-orm"; -import { canActorReadExecutionWorkspace, type AuthorizationActor, type AuthorizationDecision } from "./authorization.js"; +import { and, eq, inArray } from "drizzle-orm"; +import { canActorReadExecutionWorkspace, type AuthorizationActor, type AuthorizationDecision, type authorizationService } from "./authorization.js"; import { retryIdempotentDatabaseOperation } from "../database-retry.js"; type RunIssueBinding = { @@ -13,6 +13,7 @@ type RunIssueBinding = { export async function canActorReadHeartbeatRun( db: Db, access: { + decideReads?: ReturnType["decideReads"]; decide(input: { actor: AuthorizationActor; action: "issue:read"; @@ -66,6 +67,44 @@ export async function getHeartbeatRunReadDecisions( actor: AuthorizationActor, runs: readonly RunIssueBinding[], ): Promise { + const decideReads = access.decideReads; + if (decideReads) { + const bindings = runs.map(run => ({ companyId: run.companyId, scopeKind: run.scopeKind, issueId: run.issueId })); + const key = (companyId: string, issueId: string) => JSON.stringify([companyId, issueId]); + const issuesByCompany = new Map>(); + for (const run of bindings) { + if (run.scopeKind === "company" || !run.issueId) continue; + let ids = issuesByCompany.get(run.companyId); + if (!ids) { ids = new Set(); issuesByCompany.set(run.companyId, ids); } + ids.add(run.issueId); + } + const resources: Parameters[1] = []; + for (const [companyId, issueIds] of issuesByCompany) { + const ids = [...issueIds]; + for (let offset = 0; offset < ids.length; offset += 500) { + const chunk = ids.slice(offset, offset + 500); + const existing = await retryIdempotentDatabaseOperation(() => db + .select({ id: issues.id }) + .from(issues) + .where(and(eq(issues.companyId, companyId), inArray(issues.id, chunk)))); + for (const { id: issueId } of existing) resources.push({ + type: "issue", companyId, issueId, projectId: null, parentIssueId: null, + assigneeAgentId: null, assigneeUserId: null, + }); + } + } + const allowed = new Map(); + if (resources.length) { + const decisions = await retryIdempotentDatabaseOperation(() => decideReads(actor, resources)); + for (let index = 0; index < resources.length; index++) { + const resource = resources[index]; + if (resource.type === "issue" && resource.issueId) { + allowed.set(key(resource.companyId, resource.issueId), decisions[index]?.allowed === true); + } + } + } + return bindings.map(run => run.scopeKind === "company" || Boolean(run.issueId && allowed.get(key(run.companyId, run.issueId)))); + } const decisions = new Map>(); return Promise.all(runs.map(run => { const binding = { companyId: run.companyId, scopeKind: run.scopeKind, issueId: run.issueId }; From 50797ea03ce0b2a84e4df80864ac6e3652382ed5 Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Sun, 25 Oct 2026 00:41:14 -0700 Subject: [PATCH 051/110] perf(issues): narrow queued comment wake display reads (#17570) Read only typed queue display inputs from saved wake payloads and only runtime mode from queued runs. Preserve complete rows for locked edits, discard, steering, and interruption. Validation: 93 focused route and policy tests, full build and repository typecheck. PostgreSQL fixtures preserve identical queue responses and saved input with less than 4 KB of read values; restoring the full wake read fails at about 1.8 MB. Exact-head Greptile 5/5 (medium), all CI checks green, and zero unresolved comments. Co-Authored-By: Paperclip --- doc/DEVELOPING.md | 6 ++++ .../issue-queued-comments-routes.test.ts | 32 +++++++++++++++++++ server/src/routes/issues.ts | 26 ++++++++++++--- 3 files changed, 59 insertions(+), 5 deletions(-) diff --git a/doc/DEVELOPING.md b/doc/DEVELOPING.md index 3cc2067d727..fdfc680c06e 100644 --- a/doc/DEVELOPING.md +++ b/doc/DEVELOPING.md @@ -1816,6 +1816,12 @@ dispatch with cancellation and execution, and re-exports the existing public helpers and configuration-incomplete error class. Keep preparation policy changes in this module and its tests. +Queued-comment display reads select only wake identity, queue state, typed comment +and interaction bindings, the displayed wait reason, and fresh-session flags. +They read only the queued run's runtime mode. Mutation locks retain complete +wake and run rows, so edits, ordering, interruption, and saved execution inputs +keep their existing write contract. + Run retrieval and session state are in `server/src/services/heartbeat/run-state.ts`. It owns bounded run projections, database encoding checks, task session reads and writes, explicit resumes, session compaction, and usage/billing helpers. diff --git a/server/src/__tests__/issue-queued-comments-routes.test.ts b/server/src/__tests__/issue-queued-comments-routes.test.ts index 60985954bea..7b0af0e8a3d 100644 --- a/server/src/__tests__/issue-queued-comments-routes.test.ts +++ b/server/src/__tests__/issue-queued-comments-routes.test.ts @@ -220,6 +220,38 @@ describeEmbeddedPostgres("issue queued-comment routes", () => { } finally { capture.flush(); await observed.$client.end(); } }); + it.each(["deferred", "queued"])("reads only queue display inputs from large %s wake payloads", async state => { + const f = await seedQueue(); + if (state === "queued") await promoteQueue(f); + const client = app(f.companyId); + const path = `/api/issues/${f.issueId}/queued-comments`; + const expected = await request(client).get(path).expect(200); + const [wake] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, f.wakeId)); + const payload = "saved-wake-input🙂".repeat(30_000); + const context = wake.payload?._paperclipWakeContext as Record; + await db.update(agentWakeupRequests).set({ payload: { + ...wake.payload, prompt: payload, + _paperclipWakeContext: { ...context, prompt: payload, nativeExecutionInput: { instructions: payload } }, + } }).where(eq(agentWakeupRequests.id, f.wakeId)); + await db.update(heartbeatRuns).set({ contextSnapshot: { issueId: f.issueId, prompt: payload }, + runnerProfileJson: { instructions: payload }, resultJson: { output: payload }, + }).where(eq(heartbeatRuns.companyId, f.companyId)); + const [before] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, f.wakeId)); + const observed = createDb(tempDb!.connectionString), events: Array> = [], now = Date.now(); + const capture = createDatabaseResponseCapture({ start: now - 100, end: now + 59_000 }, event => events.push(event)); + installDatabaseResponseCapture(observed, { agentWakeupRequests, heartbeatRuns }, capture); + try { + const response = await request(app(f.companyId, "queue-owner", undefined, observed)).get(path).expect(200); + expect(response.body).toEqual(expected.body); + capture.flush(); + const reads = events.filter(event => ["agent_wakeup_requests", "heartbeat_runs"].includes(String(event.table)) && event.operation === "select"); + expect(reads.some(event => event.table === "agent_wakeup_requests")).toBe(true); + expect(reads.reduce((bytes, event) => bytes + Number(event.responseValueBytes), 0)).toBeLessThan(4096); + expect((await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, f.wakeId)))[0]).toEqual(before); + await request(app(randomUUID(), "queue-owner", undefined, observed)).get(path).expect(404); + } finally { capture.flush(); await observed.$client.end(); } + }); + it.each(["cancelled", "running"])("rejects a late Done from an interrupted %s task run at the write boundary", async status => { const seeded = await seedQueue(); await db.update(heartbeatRuns).set({ status, resultJson: { executionCancellation: { state: "requested" } } }) diff --git a/server/src/routes/issues.ts b/server/src/routes/issues.ts index 6aa65dfb774..bb92497ea3b 100644 --- a/server/src/routes/issues.ts +++ b/server/src/routes/issues.ts @@ -7287,9 +7287,9 @@ export function issueRoutes( type IssueQueueWake = typeof agentWakeupRequests.$inferSelect; type IssueQueueRun = typeof heartbeatRuns.$inferSelect; type IssueQueueState = { - wake: IssueQueueWake; + wake: Pick; state: "deferred" | "queued"; - queueRun: IssueQueueRun | null; + queueRun: Pick | null; }; async function findQueuedCommentWake( @@ -7298,7 +7298,23 @@ export function issueRoutes( ): Promise { if (!issue.assigneeAgentId) return null; const rows = await executor - .select() + .select({ + id: agentWakeupRequests.id, companyId: agentWakeupRequests.companyId, + status: agentWakeupRequests.status, runId: agentWakeupRequests.runId, + payload: sql>`jsonb_build_object( + 'issueId', ${agentWakeupRequests.payload}->'issueId', + 'mutation', ${agentWakeupRequests.payload}->'mutation', + 'interactionId', ${agentWakeupRequests.payload}->'interactionId', + 'interactionStatus', ${agentWakeupRequests.payload}->'interactionStatus', + 'externalChatContinuation', ${agentWakeupRequests.payload}->'externalChatContinuation', + 'executionWait', jsonb_build_object( + 'reason', ${agentWakeupRequests.payload}->'executionWait'->'reason', + 'message', ${agentWakeupRequests.payload}->'executionWait'->'message'), + '_paperclipWakeContext', jsonb_build_object( + 'wakeCommentIds', ${agentWakeupRequests.payload}->'_paperclipWakeContext'->'wakeCommentIds', + 'forceFreshSession', ${agentWakeupRequests.payload}->'_paperclipWakeContext'->'forceFreshSession') + )`, + }) .from(agentWakeupRequests) .where( and( @@ -7323,7 +7339,7 @@ export function issueRoutes( } if (!wake.runId) continue; const queueRun = await executor - .select() + .select({ runtimeMode: heartbeatRuns.runtimeMode }) .from(heartbeatRuns) .where( and( @@ -7344,7 +7360,7 @@ export function issueRoutes( async function queueCommentsForWake( executor: IssueQueueDb, issueId: string, - wake: IssueQueueWake | null, + wake: Pick | null, ) { if (wake && queuedInteractionId(wake.payload)) { const response = await readQueuedInteractionResponse(executor as Db, wake.companyId, issueId, wake.payload); From 3f36947e0cf18f58f57f34cefd53b49af54c790c Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Sun, 25 Oct 2026 02:43:17 -0700 Subject: [PATCH 052/110] perf(realtime): batch task and run authorization per event (#17579) Use one fresh authorization batch for each live event task and run binding. Preserve current membership, grant, company, and payload disclosure checks. Build, typecheck, 70 affected local tests, and the complete required CI matrix passed. Greptile scored the exact head 5/5 at medium impact with no unresolved findings. The separate full local suite remains in progress. Co-Authored-By: Paperclip --- doc/DATABASE.md | 6 ++++ .../__tests__/live-events-run-read.test.ts | 31 ++++++++++++++++-- .../src/__tests__/live-events-toast.test.ts | 5 ++- server/src/realtime/live-events-ws.ts | 32 +++++++++---------- 4 files changed, 54 insertions(+), 20 deletions(-) diff --git a/doc/DATABASE.md b/doc/DATABASE.md index a51b7cb6100..dd8126cbcd1 100644 --- a/doc/DATABASE.md +++ b/doc/DATABASE.md @@ -123,6 +123,12 @@ launch context does not travel with each policy or parent-report check. JSON types, task-key precedence, and company and agent identity checks are preserved. Each decision still reads current data; this is not an authorization cache. +WebSocket delivery uses one fresh authorization batch for an event's task and +run bindings. When both bindings name the same task, the batch reads its current +authority once. Different task bindings must both pass. The batch is discarded +after that delivery; later events still recheck grants, membership, task +existence, and company boundaries. + Filesystem preparation uses current task/run and selected-configuration checks. Historical root-reader authorization has been retired; no retained-reader batch is loaded at admission or publication. Workspace-record disclosure still uses task diff --git a/server/src/__tests__/live-events-run-read.test.ts b/server/src/__tests__/live-events-run-read.test.ts index 76704f2f63c..b02b0d4cf45 100644 --- a/server/src/__tests__/live-events-run-read.test.ts +++ b/server/src/__tests__/live-events-run-read.test.ts @@ -58,9 +58,19 @@ describe("live-event run read boundaries", () => { }).returning({ id: heartbeatRuns.id }); const [maintenance] = await db.insert(heartbeatRuns).values({ companyId, agentId: agent.id, scopeKind: "company" }).returning({ id: heartbeatRuns.id }); const [foreign] = await db.insert(heartbeatRuns).values({ companyId: foreignCompanyId, agentId: foreignAgent.id, scopeKind: "company" }).returning({ id: heartbeatRuns.id }); + const hiddenIssueId = randomUUID(); + await db.insert(issues).values({ id: hiddenIssueId, companyId, title: "Other private task", visibility: "private", privacyRootIssueId: hiddenIssueId, responsibleUserId: owner }); + const [hiddenRun] = await db.insert(heartbeatRuns).values({ companyId, agentId: agent.id, scopeKind: "issue", issueId: hiddenIssueId }).returning({ id: heartbeatRuns.id }); const reads: string[] = []; + const queries: string[] = []; let failNextRunRead = false; + let failNextIssueRead = false; const observedDb = drizzle(db.$client, { schema, logger: { logQuery(query) { + queries.push(query); + if (query.startsWith("select ") && query.includes('from "issues"') && failNextIssueRead) { + failNextIssueRead = false; + throw new Error("fixture issue lookup unavailable"); + } if (query.startsWith("select ") && query.includes('from "heartbeat_runs"')) { reads.push(query); if (failNextRunRead) { failNextRunRead = false; throw new Error("fixture run lookup unavailable"); } @@ -78,17 +88,32 @@ describe("live-event run read boundaries", () => { socket.on("message", bytes => messages.push(JSON.parse(bytes.toString()))); try { await once(socket, "open"); - async function deliver(runId: string) { + let deliveries = 0; + async function deliver(runId: string, payloadIssueId?: string) { + deliveries += 1; const start = messages.length; const barrier = randomUUID(); - publishLiveEvent({ companyId, type: "heartbeat.run.status", payload: { runId, status: "running" } }); + publishLiveEvent({ companyId, type: "heartbeat.run.status", payload: { + runId, status: "running", ...(payloadIssueId ? { issueId: payloadIssueId } : {}), + } }); publishLiveEvent({ companyId, type: "agent.status", payload: { agentId: barrier, status: "idle" } }); await expect.poll(() => messages.some(message => message.payload.agentId === barrier)).toBe(true); return messages.slice(start).filter(message => message.type === "heartbeat.run.status"); } expect(await deliver(run.id)).toMatchObject([{ payload: { runId: run.id, status: "running" } }]); + const batchStart = queries.length; + expect(await deliver(run.id, issueId)).toMatchObject([{ payload: { runId: run.id, issueId, status: "running" } }]); + expect(queries.length - batchStart).toBeLessThanOrEqual(6); + expect(queries.slice(batchStart).filter(query => query.startsWith("select ") && query.includes('from "issues"')).length).toBeLessThanOrEqual(2); + expect(await deliver(hiddenRun.id, issueId)).toEqual([]); + expect(await deliver(run.id, hiddenIssueId)).toEqual([]); + expect(await deliver(run.id, randomUUID())).toEqual([]); + failNextIssueRead = true; + expect(await deliver(run.id, issueId)).toEqual([]); + expect(await deliver(run.id, issueId)).toHaveLength(1); await db.update(issueAccessGrants).set({ revokedAt: new Date() }).where(eq(issueAccessGrants.id, grant.id)); + expect(await deliver(run.id, issueId)).toEqual([]); expect(await deliver(run.id)).toEqual([]); expect(await deliver(maintenance.id)).toHaveLength(1); expect(await deliver(foreign.id)).toEqual([]); @@ -101,7 +126,7 @@ describe("live-event run read boundaries", () => { await db.delete(issues).where(eq(issues.id, issueId)); expect(await deliver(run.id)).toEqual([]); - expect(reads).toHaveLength(9); + expect(reads).toHaveLength(deliveries); for (const query of reads) { expect(query).toMatch(/^select "company_id", "scope_kind", "issue_id" from "heartbeat_runs"/); expect(query).not.toMatch(/context_snapshot|runner_profile_json|stdout_excerpt|result_json/); diff --git a/server/src/__tests__/live-events-toast.test.ts b/server/src/__tests__/live-events-toast.test.ts index 5c5fbe7bf6c..e82af433d73 100644 --- a/server/src/__tests__/live-events-toast.test.ts +++ b/server/src/__tests__/live-events-toast.test.ts @@ -14,7 +14,10 @@ vi.mock("../realtime/task-toast-eligibility.js", () => ({ taskToastEligible: vi. vi.mock("../services/authorization.js", () => ({ authorizationService: () => ({ decide: async ({ resource }: { resource: { issueId: string } }) => ({ allowed: resource.issueId !== "hidden" }) }), })); -vi.mock("../services/heartbeat-run-privacy.js", () => ({ canActorReadHeartbeatRun: async () => false })); +vi.mock("../services/heartbeat-run-privacy.js", () => ({ + getHeartbeatRunReadDecisions: async (_db: unknown, _access: unknown, _actor: unknown, runs: { issueId?: string }[]) => + runs.map(run => run.issueId !== "hidden"), +})); vi.mock("../services/case-access.js", () => ({ canActorReadCase: async (_db: unknown, _actor: unknown, record: { id: string }) => record.id !== "hidden-case", })); diff --git a/server/src/realtime/live-events-ws.ts b/server/src/realtime/live-events-ws.ts index 6f299bfe672..95159016122 100644 --- a/server/src/realtime/live-events-ws.ts +++ b/server/src/realtime/live-events-ws.ts @@ -5,7 +5,7 @@ import { createRequire } from "node:module"; import type { Duplex } from "node:stream"; import { and, eq, isNull } from "drizzle-orm"; import type { Db } from "@paperclipai/db"; -import { agentApiKeys, companyMemberships, instanceUserRoles, heartbeatRuns, issues, projects } from "@paperclipai/db"; +import { agentApiKeys, companyMemberships, instanceUserRoles, heartbeatRuns, projects } from "@paperclipai/db"; import type { DeploymentMode, LiveEvent } from "@paperclipai/shared"; import type { BetterAuthSessionResult } from "../auth/better-auth.js"; import { logger } from "../middleware/logger.js"; @@ -45,7 +45,7 @@ const { WebSocket, WebSocketServer } = require("ws") as { }; import { authorizationService, type AuthorizationActor } from "../services/authorization.js"; -import { canActorReadHeartbeatRun } from "../services/heartbeat-run-privacy.js"; +import { getHeartbeatRunReadDecisions } from "../services/heartbeat-run-privacy.js"; import { canActorReadCase } from "../services/case-access.js"; interface UpgradeContext { @@ -301,12 +301,22 @@ export function setupLiveEventsWebSocketServer( const payload = event.payload; const issueId = typeof payload.issueId === "string" ? payload.issueId : payload.entityType === "issue" && typeof payload.entityId === "string" ? payload.entityId : null; + const runId = typeof payload.runId === "string" ? payload.runId + : payload.entityType === "heartbeat_run" && typeof payload.entityId === "string" ? payload.entityId : null; + const readBindings: Parameters[3][number][] = []; if (issueId) { - const [issue] = await db.select({ id: issues.id }).from(issues) - .where(and(eq(issues.id, issueId), eq(issues.companyId, event.companyId))).limit(1); - if (!issue || !(await access.decide({ actor: context!.actor, action: "issue:read", - resource: { type: "issue", companyId: event.companyId, issueId } })).allowed) return null; + readBindings.push({ companyId: event.companyId, scopeKind: "issue", issueId }); } + if (runId) { + const [run] = await db.select({ + companyId: heartbeatRuns.companyId, + scopeKind: heartbeatRuns.scopeKind, + issueId: heartbeatRuns.issueId, + }).from(heartbeatRuns).where(and(eq(heartbeatRuns.id, runId), eq(heartbeatRuns.companyId, event.companyId))); + if (!run) return null; + readBindings.push(run); + } + if ((await getHeartbeatRunReadDecisions(db, access, context!.actor, readBindings)).some(allowed => !allowed)) return null; if (["company_skill", "company_skill_source"].includes(String(payload.entityType)) && typeof payload.entityId === "string") { try { const skills = skillAccessService(db, context!.actor); @@ -320,16 +330,6 @@ export function setupLiveEventsWebSocketServer( if (!project || !(await access.decide({ actor: context!.actor, action: "project:read", resource: { type: "project", companyId: event.companyId, projectId: project.id } })).allowed) return null; } - const runId = typeof payload.runId === "string" ? payload.runId - : payload.entityType === "heartbeat_run" && typeof payload.entityId === "string" ? payload.entityId : null; - if (runId) { - const [run] = await db.select({ - companyId: heartbeatRuns.companyId, - scopeKind: heartbeatRuns.scopeKind, - issueId: heartbeatRuns.issueId, - }).from(heartbeatRuns).where(and(eq(heartbeatRuns.id, runId), eq(heartbeatRuns.companyId, event.companyId))); - if (!run || !(await canActorReadHeartbeatRun(db, access, context!.actor, run))) return null; - } if (event.type.startsWith("heartbeat.run.")) return runId ? event : null; if (event.type === "agent.session.goal.changed") return issueId ? event : null; // Company-wide invalidations carry no task-derived content. Authorized From c4c4f7eecb6af501451a61b11c68d37f95ca4700 Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Sun, 25 Oct 2026 03:20:45 -0700 Subject: [PATCH 053/110] perf(environments): reuse provider schemas after content validation (#17581) Add a separate schema-only provider lookup with current plugin identity and SHA-256 content validation in one statement. Retain bounded schema definitions, return independent objects, and preserve current full driver and secret access paths. Build, repository typecheck, 485 affected tests, the supported-host database tests, and the complete required CI matrix passed. Greptile scored this exact head 5/5 at medium impact with no unresolved findings. Co-Authored-By: Paperclip --- doc/DATABASE.md | 13 ++ .../environment-custom-image-routes.test.ts | 1 + .../environment-instance-routes.test.ts | 1 + .../src/__tests__/environment-probe.test.ts | 2 + .../src/__tests__/environment-routes.test.ts | 2 + .../sandbox-provider-schema-reads.test.ts | 173 ++++++++++++++++++ server/src/services/environment-config.ts | 8 +- .../src/services/plugin-environment-driver.ts | 59 +++++- 8 files changed, 252 insertions(+), 7 deletions(-) create mode 100644 server/src/__tests__/sandbox-provider-schema-reads.test.ts diff --git a/doc/DATABASE.md b/doc/DATABASE.md index dd8126cbcd1..bf4c88a98ca 100644 --- a/doc/DATABASE.md +++ b/doc/DATABASE.md @@ -826,6 +826,19 @@ pnpm secrets:migrate-inline-env --apply Hosted AWS provider notes live in [SECRETS-AWS-PROVIDER.md](./SECRETS-AWS-PROVIDER.md). +Sandbox runtime configuration resolves a provider's secret-reference fields +through its schema-only lookup. Each lookup reads the selected plugin ID +and a SHA-256 hash of its current schema in one database statement. A matching +retained schema is omitted from the query result. Selection order, schema +changes, and deletion remain visible on the next lookup, without a time-based +cache. A database error still fails the lookup. + +The retained schemas are private to one `Db` object, with at most 32 entries of +64 KiB each in serialized form. Larger schemas still work and are read in full. +Callers receive independent schema objects. This reuse stores neither resolved +secrets nor authorization decisions. Default driver lookups still read complete +current plugin records and enforce their existing readiness and worker checks. + ### Persistent agent conversations Migration `0274_agent_chat.sql` adds conversation identity/state and session generation/boundary columns to `issues`, plus idempotent client request IDs and processed session-boundary generations to `issue_comments`. The company/agent/user unique index resolves concurrent first writes to one issue. A check constraint preserves the assigned-agent identity and prevents terminal conversation status. Comment request IDs are unique per issue and user. There is no separate chat/message store. Provider sessions continue to use `agent_task_sessions`; `/new` removes only the matching conversation session, and session writers fence stale generations against the issue row. diff --git a/server/src/__tests__/environment-custom-image-routes.test.ts b/server/src/__tests__/environment-custom-image-routes.test.ts index 82b8eda9d37..43b3ae382e4 100644 --- a/server/src/__tests__/environment-custom-image-routes.test.ts +++ b/server/src/__tests__/environment-custom-image-routes.test.ts @@ -92,6 +92,7 @@ vi.mock("../services/plugin-environment-driver.js", () => ({ REUSABLE_LEASE_WORKER_METHODS: ["environmentResumeLease", "environmentReleaseLease", "environmentDestroyLease"], listReadyPluginEnvironmentDrivers: vi.fn(async () => []), resolvePluginSandboxProviderDriverByKey: vi.fn(async () => null), + resolvePluginSandboxProviderConfigSchema: vi.fn(async () => null), validatePluginEnvironmentDriverConfig: vi.fn(async ({ config }) => config), validatePluginSandboxProviderConfig: vi.fn(async ({ provider, config }) => ({ normalizedConfig: config, diff --git a/server/src/__tests__/environment-instance-routes.test.ts b/server/src/__tests__/environment-instance-routes.test.ts index 51664e01d98..293e12b7876 100644 --- a/server/src/__tests__/environment-instance-routes.test.ts +++ b/server/src/__tests__/environment-instance-routes.test.ts @@ -79,6 +79,7 @@ vi.mock("../services/plugin-environment-driver.js", () => ({ REUSABLE_LEASE_WORKER_METHODS: ["environmentResumeLease", "environmentReleaseLease", "environmentDestroyLease"], listReadyPluginEnvironmentDrivers: vi.fn(async () => []), resolvePluginSandboxProviderDriverByKey: vi.fn(async () => null), + resolvePluginSandboxProviderConfigSchema: vi.fn(async () => null), validatePluginEnvironmentDriverConfig: vi.fn(async ({ config }) => config), validatePluginSandboxProviderConfig: vi.fn(async ({ provider, config }) => ({ normalizedConfig: config, diff --git a/server/src/__tests__/environment-probe.test.ts b/server/src/__tests__/environment-probe.test.ts index e00c2d3eb6f..9474fd8b5a9 100644 --- a/server/src/__tests__/environment-probe.test.ts +++ b/server/src/__tests__/environment-probe.test.ts @@ -25,6 +25,8 @@ vi.mock("../services/plugin-environment-driver.js", () => ({ probePluginEnvironmentDriver: mockProbePluginEnvironmentDriver, probePluginSandboxProviderDriver: mockProbePluginSandboxProviderDriver, resolvePluginSandboxProviderDriverByKey: mockResolvePluginSandboxProviderDriverByKey, + resolvePluginSandboxProviderConfigSchema: async (input: { db: unknown; driverKey: string }) => + (await mockResolvePluginSandboxProviderDriverByKey(input))?.driver?.configSchema ?? null, })); vi.mock("../services/environment-runtime.js", () => ({ diff --git a/server/src/__tests__/environment-routes.test.ts b/server/src/__tests__/environment-routes.test.ts index 07c90052f37..9ad0bf972c4 100644 --- a/server/src/__tests__/environment-routes.test.ts +++ b/server/src/__tests__/environment-routes.test.ts @@ -129,6 +129,8 @@ vi.mock("../services/plugin-environment-driver.js", () => ({ REUSABLE_LEASE_WORKER_METHODS: ["environmentResumeLease", "environmentReleaseLease", "environmentDestroyLease"], listReadyPluginEnvironmentDrivers: mockListReadyPluginEnvironmentDrivers, resolvePluginSandboxProviderDriverByKey: mockResolvePluginSandboxProviderDriverByKey, + resolvePluginSandboxProviderConfigSchema: async (input: { db: unknown; driverKey: string }) => + (await mockResolvePluginSandboxProviderDriverByKey(input))?.driver?.configSchema ?? null, startPluginEnvironmentInteractiveSetup: mockStartPluginEnvironmentInteractiveSetup, getPluginEnvironmentInteractiveSetup: mockGetPluginEnvironmentInteractiveSetup, capturePluginEnvironmentTemplate: mockCapturePluginEnvironmentTemplate, diff --git a/server/src/__tests__/sandbox-provider-schema-reads.test.ts b/server/src/__tests__/sandbox-provider-schema-reads.test.ts new file mode 100644 index 00000000000..55f81f8bfbe --- /dev/null +++ b/server/src/__tests__/sandbox-provider-schema-reads.test.ts @@ -0,0 +1,173 @@ +import { randomBytes, randomUUID } from "node:crypto"; +import { eq, sql, type SQL } from "drizzle-orm"; +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest"; +import { createDb, plugins, type Db } from "@paperclipai/db"; +import { createDatabaseResponseCapture, installDatabaseResponseCapture } from "@paperclipai/db/response-capture"; +import type { PaperclipPluginManifestV1, PluginEnvironmentDriverDeclaration } from "@paperclipai/shared"; +import { resolvePluginSandboxProviderConfigSchema, resolvePluginSandboxProviderDriverByKey } from "../services/plugin-environment-driver.js"; +import { resolveEnvironmentDriverConfigForRuntime, resolveSandboxProviderSecretRefPaths } from "../services/environment-config.js"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; + +const support = await getEmbeddedPostgresTestSupport(); + +describe.skipIf(!support.supported)("sandbox provider schema reads", () => { + let temporary: Awaited>; + let db: Db; + const clients: Db[] = []; + const key = "fixture-schema-provider"; + const driver = (driverKey = key, configSchema: unknown = { type: "object" }) => ({ + driverKey, kind: "sandbox_provider", displayName: "Schema fixture", configSchema, + }) as PluginEnvironmentDriverDeclaration; + const manifest = (id: string, declarations: PluginEnvironmentDriverDeclaration[]): PaperclipPluginManifestV1 => ({ + id: `test.schema.${id}`, apiVersion: 1, version: "1.0.0", displayName: "Schema fixture", + description: "Fixture", author: "Test", categories: ["automation"], + capabilities: ["environment.drivers.register"], entrypoints: { worker: "worker.js" }, environmentDrivers: declarations, + }); + async function seed(declarations = [driver()], installOrder = 0) { + const id = randomUUID(); + await db.insert(plugins).values({ + id, pluginKey: `test.schema.${id}`, packageName: "@test/schema", version: "1.0.0", + installOrder, status: "disabled", manifestJson: manifest(id, declarations), + }); + return id; + } + function observer() { + const observed = createDb(temporary.connectionString); + clients.push(observed); + return observed; + } + const lookup = (client: Db, driverKey = key) => resolvePluginSandboxProviderConfigSchema({ db: client, driverKey }); + async function measure(client: Db, operation: () => Promise) { + const events: Array> = [], now = Date.now(); + const capture = createDatabaseResponseCapture({ start: now - 100, end: now + 59_000 }, event => events.push(event), () => now); + installDatabaseResponseCapture(client, { plugins }, capture); + try { + const value = await operation(); + capture.flush(); + const entries = events.filter(event => event.event === "paperclip.db_response_capture.entry.v1"); + return { value, bytes: entries.reduce((sum, entry) => sum + Number(entry.responseValueBytes), 0), + calls: entries.reduce((sum, entry) => sum + Number(entry.calls), 0) }; + } finally { capture.flush(); } + } + + beforeAll(async () => { + temporary = await startEmbeddedPostgresTestDatabase("sandbox-schema-reads-"); + db = createDb(temporary.connectionString); + }, 120_000); + beforeEach(async () => { await db.delete(plugins); }); + afterEach(async () => { await Promise.all(clients.splice(0).map(client => client.$client.end())); }); + afterAll(async () => { await temporary?.cleanup(); }); + + it("keeps runtime secret paths current without retransferring an unchanged schema", async () => { + const schema = { type: "object", description: randomBytes(16 * 1024).toString("hex"), properties: { + credentials: { type: "object", properties: { token: { type: "string", format: "secret-ref" } } }, + } }; + const id = await seed([driver(key, schema)]), observed = observer(); + const before = await db.select().from(plugins).where(eq(plugins.id, id)); + const cold = await measure(observed, () => resolveSandboxProviderSecretRefPaths(observed, key)); + const warm = await measure(observed, () => resolveSandboxProviderSecretRefPaths(observed, key)); + expect(cold.value).toEqual(new Set(["credentials.token"])); + expect(warm.value).toEqual(cold.value); + expect(cold.calls).toBe(1); + expect(warm.calls).toBe(1); + expect(cold.bytes).toBeGreaterThan(32 * 1024); + expect(warm.bytes).toBeLessThan(256); + const changed = { type: "object", allOf: [{ properties: { apiKey: { type: "string", format: "secret-ref" } } }] }; + await db.update(plugins).set({ manifestJson: manifest(id, [driver(key, changed)]) }).where(eq(plugins.id, id)); + expect(await resolveSandboxProviderSecretRefPaths(observed, key)).toEqual(new Set(["apiKey"])); + const environment = { id: randomUUID(), driver: "sandbox" as const, config: { provider: key, apiKey: randomUUID() } }; + await expect(resolveEnvironmentDriverConfigForRuntime(observed, null, environment)).rejects.toThrow("companyId"); + await db.update(plugins).set({ manifestJson: before[0].manifestJson }).where(eq(plugins.id, id)); + expect(await db.select().from(plugins).where(eq(plugins.id, id))).toEqual(before); + }); + + it("preserves install order, first matching declarations, and default readiness checks", async () => { + const a = await seed([driver(key, { title: "first" }), driver(key, { title: "second" })], 1); + const b = await seed([driver(key, { title: "other plugin" })], 2), observed = observer(); + expect((await lookup(observed))).toEqual({ title: "first" }); + const full = await resolvePluginSandboxProviderDriverByKey({ db: observed, driverKey: key }); + expect(full?.plugin.id).toBe(a); + expect(full?.plugin.status).toBe("disabled"); + expect(await resolvePluginSandboxProviderDriverByKey({ db: observed, driverKey: key, requireRunning: true })).toBeNull(); + await db.update(plugins).set({ installOrder: 0 }).where(eq(plugins.id, b)); + expect((await lookup(observed))).toEqual({ title: "other plugin" }); + await db.delete(plugins).where(eq(plugins.id, b)); + expect((await lookup(observed))).toEqual({ title: "first" }); + await db.update(plugins).set({ manifestJson: manifest(a, [driver("replacement")]) }).where(eq(plugins.id, a)); + expect(await lookup(observed)).toBeNull(); + }); + + it.each([null, true, "invalid", [], undefined])("preserves non-object schema behavior: %s", async value => { + const first = driver(key, value); + if (value === undefined) delete (first as Partial).configSchema; + await seed([first, driver(key, { properties: { secret: { format: "secret-ref" } } })]); + const observed = observer(); + expect(await resolveSandboxProviderSecretRefPaths(observed, key)).toEqual(new Set()); + expect(await resolveSandboxProviderSecretRefPaths(observed, key)).toEqual(new Set()); + }); + + it("returns independent schema objects and keeps separate database clients cold", async () => { + await seed([driver(key, { description: "x".repeat(4096), properties: { token: { format: "secret-ref" } } })]); + const a = observer(), b = observer(); + const first = await lookup(a); + first!.properties = {}; + expect(await resolveSandboxProviderSecretRefPaths(a, key)).toEqual(new Set(["token"])); + const warm = await measure(a, () => lookup(a)), independent = await measure(b, () => lookup(b)); + expect(warm.bytes).toBeLessThan(256); + expect(independent.bytes).toBeGreaterThan(4096); + warm.value!.properties = {}; + expect(await resolveSandboxProviderSecretRefPaths(a, key)).toEqual(new Set(["token"])); + }); + + it("bounds retained schemas and does not retain oversized definitions", async () => { + const declarations = Array.from({ length: 33 }, (_, index) => driver(`provider-${index}`, { description: "x".repeat(2048) })); + declarations.push(driver("oversized", { description: "x".repeat(128 * 1024) })); + await seed(declarations); + const observed = observer(); + for (let index = 0; index < 33; index++) await lookup(observed, `provider-${index}`); + expect((await measure(observed, () => lookup(observed, "provider-32"))).bytes).toBeLessThan(256); + expect((await measure(observed, () => lookup(observed, "provider-0"))).bytes).toBeGreaterThan(2048); + await lookup(observed, "oversized"); + expect((await measure(observed, () => lookup(observed, "oversized"))).bytes).toBeGreaterThan(128 * 1024); + }); + + it("binds unusual keys and never serves retained schemas after a lookup error", async () => { + const unusual = "provider-\"quoted' OR true --"; + await seed([driver(unusual, { title: "exact provider" })]); + const observed = observer(); + let fail = false; + const guarded = { execute: async (query: SQL) => { + if (fail) throw new Error("fixture database unavailable"); + return observed.execute(query); + } } as unknown as Db; + expect((await lookup(guarded, unusual))).toEqual({ title: "exact provider" }); + fail = true; + await expect(lookup(guarded, unusual)).rejects.toThrow("fixture database unavailable"); + fail = false; + expect((await lookup(guarded, unusual))).toEqual({ title: "exact provider" }); + expect(await lookup(guarded, "unknown-provider")).toBeNull(); + }); + + it("keeps each concurrent lookup tied to the database revision it observed", async () => { + const id = await seed([driver(key, { title: "old" })]), observed = observer(); + let pause = false, release!: () => void, reached!: () => void; + const gate = new Promise(resolve => { release = resolve; }); + const paused = new Promise(resolve => { reached = resolve; }); + const raced = { execute: async (query: SQL) => { + const rows = await observed.execute(query); + if (pause) { pause = false; reached(); await gate; } + return rows; + } } as unknown as Db; + expect((await lookup(raced))).toEqual({ title: "old" }); + pause = true; + const oldRead = lookup(raced); + await paused; + try { + await db.update(plugins).set({ manifestJson: manifest(id, [driver(key, { title: "new" })]) }).where(eq(plugins.id, id)); + expect((await lookup(raced))).toEqual({ title: "new" }); + } finally { release(); } + expect((await oldRead)).toEqual({ title: "old" }); + expect((await lookup(raced))).toEqual({ title: "new" }); + expect((await db.execute<{ title: string }>(sql`select ${plugins.manifestJson}->'environmentDrivers'->0->'configSchema'->>'title' as title from ${plugins} where ${plugins.id}=${id}`))[0].title).toBe("new"); + }); +}); diff --git a/server/src/services/environment-config.ts b/server/src/services/environment-config.ts index b9c041a35d1..6431c4802ff 100644 --- a/server/src/services/environment-config.ts +++ b/server/src/services/environment-config.ts @@ -17,7 +17,7 @@ import { unprocessable } from "../errors.js"; import { parseObject } from "../adapters/utils.js"; import { secretService } from "./secrets.js"; import { - resolvePluginSandboxProviderDriverByKey, + resolvePluginSandboxProviderConfigSchema, validatePluginEnvironmentDriverConfig, validatePluginSandboxProviderConfig, } from "./plugin-environment-driver.js"; @@ -179,14 +179,10 @@ async function getSandboxProviderConfigSchema( db: Db, provider: string, ): Promise | null> { - const resolved = await resolvePluginSandboxProviderDriverByKey({ + return resolvePluginSandboxProviderConfigSchema({ db, driverKey: provider, }); - const schema = resolved?.driver.configSchema; - return schema && typeof schema === "object" && !Array.isArray(schema) - ? schema as Record - : null; } export async function resolveSandboxProviderSecretRefPaths( diff --git a/server/src/services/plugin-environment-driver.ts b/server/src/services/plugin-environment-driver.ts index d7f56f2b197..f26f32483ff 100644 --- a/server/src/services/plugin-environment-driver.ts +++ b/server/src/services/plugin-environment-driver.ts @@ -1,4 +1,5 @@ -import type { Db } from "@paperclipai/db"; +import { plugins, type Db } from "@paperclipai/db"; +import { sql } from "drizzle-orm"; import type { EnvironmentProbeResult, PluginEnvironmentConfig, @@ -162,6 +163,62 @@ export async function resolvePluginEnvironmentDriverByKey(input: { }); } +type CachedProviderSchema = { pluginId: string; revision: string; schema: Record | null }; +const providerSchemas = new WeakMap>(); +const MAX_CACHED_PROVIDER_SCHEMAS = 32; +const MAX_CACHED_PROVIDER_SCHEMA_BYTES = 64 * 1024; + +export async function resolvePluginSandboxProviderConfigSchema(input: { + db: Db; driverKey: string; +}): Promise | null> { + const { db, driverKey } = input; + let cache = providerSchemas.get(db); + const cached = cache?.get(driverKey); + const unchanged = sql`coalesce(plugin_id = ${cached?.pluginId ?? null}::uuid + and revision = ${cached?.revision ?? null}, false)`; + const [row] = await db.execute<{ + pluginId: string; revision: string; unchanged: boolean; configSchema: unknown; + }>(sql`with selected_provider as materialized ( + select ${plugins.id} as plugin_id, ( + select declaration.value->'configSchema' + from jsonb_array_elements(${plugins.manifestJson}->'environmentDrivers') + with ordinality as declaration(value, position) + where declaration.value->'driverKey' = to_jsonb(${driverKey}::text) + and declaration.value->>'kind' = 'sandbox_provider' + order by declaration.position limit 1 + ) as schema_value + from ${plugins} + where ${plugins.manifestJson} @> ${JSON.stringify({ environmentDrivers: [{ driverKey, kind: "sandbox_provider" }] })}::jsonb + order by ${plugins.installOrder} limit 1 + ), versioned_provider as materialized ( + select plugin_id, schema_value, + encode(sha256(convert_to(coalesce(schema_value::text, 'null'), 'UTF8')), 'hex') as revision + from selected_provider + ) + select plugin_id as "pluginId", revision, ${unchanged} as unchanged, + case when ${unchanged} then null else schema_value end as "configSchema" + from versioned_provider`); + if (!row) { + cache?.delete(driverKey); + return null; + } + if (row.unchanged) { + if (!cached || cached.pluginId !== row.pluginId || cached.revision !== row.revision) { + throw new Error("Sandbox provider schema revision did not match the retained definition"); + } + return structuredClone(cached.schema); + } + const schema = row.configSchema && typeof row.configSchema === "object" && !Array.isArray(row.configSchema) + ? row.configSchema as Record : null; + cache?.delete(driverKey); + if (Buffer.byteLength(JSON.stringify(schema)) <= MAX_CACHED_PROVIDER_SCHEMA_BYTES) { + if (!cache) { cache = new Map(); providerSchemas.set(db, cache); } + if (cache.size >= MAX_CACHED_PROVIDER_SCHEMAS) cache.delete(cache.keys().next().value!); + cache.set(driverKey, { pluginId: row.pluginId, revision: row.revision, schema: structuredClone(schema) }); + } + return schema; +} + export async function resolvePluginSandboxProviderDriverByKey(input: { db: Db; driverKey: string; From 35d5b0686ab5bcaef733b3741b7cec55048993af Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Sun, 25 Oct 2026 03:45:25 -0700 Subject: [PATCH 054/110] perf(runner): narrow current tool authority reads (#17587) Select the current run fields used by Native tool authority without transferring unused saved profiles or output. Preserve full context, receipts, authorization predicates, and locked mutation reads. Verified with full build and typecheck, 2,358 affected tests across 20 suites, a counterfactual real PostgreSQL byte regression, complete exact-head CI, and Greptile 5/5 Medium with no unresolved comments. Co-Authored-By: Paperclip --- doc/DATABASE.md | 6 +++ .../paperclip-runner-tool-authority.test.ts | 46 +++++++++++++++++++ .../paperclip-runner-tool-authority.ts | 14 +++++- 3 files changed, 64 insertions(+), 2 deletions(-) diff --git a/doc/DATABASE.md b/doc/DATABASE.md index bf4c88a98ca..06cf24c9368 100644 --- a/doc/DATABASE.md +++ b/doc/DATABASE.md @@ -123,6 +123,12 @@ launch context does not travel with each policy or parent-report check. JSON types, task-key precedence, and company and agent identity checks are preserved. Each decision still reads current data; this is not an authorization cache. +Native tool authority lookups select current run identity, status, invocation, +responsible user, context, and receipt data. Saved profiles and output excerpts +stay in storage and are omitted from that read. Task and agent binding, current +status, budget, and task privacy checks retain their existing predicates. +Mutation transactions still lock and read complete run records. + WebSocket delivery uses one fresh authorization batch for an event's task and run bindings. When both bindings name the same task, the batch reads its current authority once. Different task bindings must both pass. The batch is discarded diff --git a/server/src/services/native-runtime/paperclip-runner-tool-authority.test.ts b/server/src/services/native-runtime/paperclip-runner-tool-authority.test.ts index 04a9b79a2cc..76815a76482 100644 --- a/server/src/services/native-runtime/paperclip-runner-tool-authority.test.ts +++ b/server/src/services/native-runtime/paperclip-runner-tool-authority.test.ts @@ -20,6 +20,7 @@ import { issues, } from "@paperclipai/db"; import { startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embedded-postgres.js"; +import { createDatabaseResponseCapture, installDatabaseResponseCapture } from "@paperclipai/db/response-capture"; import { initializeRunIdentity, reserveSteeredIdentity, reconcileSteeredIdentity } from "../run-identity.js"; import { documentService } from "../documents.js"; import { issueService } from "../issues.js"; @@ -198,6 +199,51 @@ describe("PaperclipRunnerToolAuthority", () => { ).rejects.toThrow("paperclip_runner_tool_not_advertised"); }); + it("reads current tool authority without transferring saved profiles or output", async () => { + const binding = { companyId, agentId, issueId, runId }; + const authority = new PaperclipRunnerToolAuthority(db, binding); + const contextCall = { tool: "get_task_context", callId: "context-read-width", arguments: {} }; + const apiCall = { tool: "search_api", callId: "api-read-width", arguments: { query: "read task" } }; + const expectedContext = await authority.execute(contextCall); + const expectedApi = await authority.execute(apiCall); + const [original] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)); + const [actor] = await db.select({ status: agents.status }).from(agents).where(eq(agents.id, agentId)); + const payload = "saved-profile-and-output🙂".repeat(32_768); + await db.update(heartbeatRuns).set({ + runnerProfileJson: { ...original.runnerProfileJson, retainedPayload: payload }, + stdoutExcerpt: payload, + stderrExcerpt: payload, + }).where(eq(heartbeatRuns.id, runId)); + const [expanded] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)); + const observed = createDb(temporary!.connectionString), events: Array> = [], now = Date.now(); + const capture = createDatabaseResponseCapture({ start: now - 100, end: now + 59_000 }, event => events.push(event)); + installDatabaseResponseCapture(observed, { heartbeatRuns, issues, agents, companies }, capture); + try { + const reader = new PaperclipRunnerToolAuthority(observed, binding); + const context = await reader.execute(contextCall), api = await reader.execute(apiCall); + expect(context).toEqual(expectedContext); + expect(api).toEqual(expectedApi); + expect(JSON.stringify([context, api])).not.toContain("saved-profile-and-output"); + capture.flush(); + const reads = events.filter(event => event.table === "heartbeat_runs" && event.operation === "select"); + expect(reads.length).toBeGreaterThan(0); + expect(reads.reduce((bytes, event) => bytes + Number(event.responseValueBytes), 0)).toBeLessThan(16 * 1024); + expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)))[0]).toEqual(expanded); + await db.update(agents).set({ status: "paused" }).where(eq(agents.id, agentId)); + await expect(reader.execute(contextCall)).rejects.toThrow("paperclip_runner_tool_binding_not_authorized"); + await expect(reader.execute(apiCall)).rejects.toThrow("paperclip_runner_tool_binding_not_authorized"); + } finally { + capture.flush(); + await observed.$client.end(); + await db.update(agents).set({ status: actor.status }).where(eq(agents.id, agentId)); + await db.update(heartbeatRuns).set({ + runnerProfileJson: original.runnerProfileJson, + stdoutExcerpt: original.stdoutExcerpt, + stderrExcerpt: original.stderrExcerpt, + }).where(eq(heartbeatRuns.id, runId)); + } + }); + it("preserves platform receipt provenance in both mixed task history readers", async () => { const at = new Date("2026-10-10T12:00:00Z"); const commentIds = Array.from({ length: 4 }, () => randomUUID()); diff --git a/server/src/services/native-runtime/paperclip-runner-tool-authority.ts b/server/src/services/native-runtime/paperclip-runner-tool-authority.ts index 56bccadf0b6..40b140f01b2 100644 --- a/server/src/services/native-runtime/paperclip-runner-tool-authority.ts +++ b/server/src/services/native-runtime/paperclip-runner-tool-authority.ts @@ -1227,7 +1227,17 @@ export class PaperclipRunnerToolAuthority { async #boundContext() { if (this.binding.museRuntime && !this.binding.externalAuthorizingUserId) throw forbidden("Muse authorizer is unavailable"); - const [row] = await this.db.select({ issue: issues, actor: agents, run: heartbeatRuns }) + const [row] = await this.db.select({ issue: issues, actor: agents, run: { + id: heartbeatRuns.id, + companyId: heartbeatRuns.companyId, + agentId: heartbeatRuns.agentId, + runtimeMode: heartbeatRuns.runtimeMode, + status: heartbeatRuns.status, + invocationSource: heartbeatRuns.invocationSource, + responsibleUserId: heartbeatRuns.responsibleUserId, + contextSnapshot: heartbeatRuns.contextSnapshot, + resultJson: heartbeatRuns.resultJson, + } }) .from(heartbeatRuns) .innerJoin(issues, eq(issues.id, this.binding.issueId)) .innerJoin(agents, eq(agents.id, this.binding.agentId)) @@ -2168,7 +2178,7 @@ export class PaperclipRunnerToolAuthority { }); } - async #sourcePlanApproval(context: { issue: typeof issues.$inferSelect; run: typeof heartbeatRuns.$inferSelect }) { + async #sourcePlanApproval(context: { issue: typeof issues.$inferSelect; run: Pick }) { const plan = await handoffPlanContext(this.db, context.issue, this.#privacyActor(context.run)); if (!plan || !this.binding.museRuntime) return plan; const document = await documentService(this.db).getIssueDocumentByKey(plan.sourceIssueId, "plan"); From b7dc594bfaec15c8c87eb97a61931faf2d0aa518 Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Sun, 25 Oct 2026 03:54:59 -0700 Subject: [PATCH 055/110] perf(recovery): narrow saved-message execution-wait reads (#17588) Read current ownership, startup, cancellation, task-binding, and adapter evidence without transferring unused saved profiles, launch context, or output. Preserve normal continuation admission, recovery holds, and locked mutation reads. Verified with full build and typecheck, 537 affected tests across 12 suites, a counterfactual real PostgreSQL byte regression, complete exact-head CI, and Greptile 5/5 Medium with no unresolved comments. Co-Authored-By: Paperclip --- doc/DATABASE.md | 5 ++ server/src/services/heartbeat.ts | 2 + server/src/services/heartbeat/run-control.ts | 9 +-- .../src/services/heartbeat/run-state.test.ts | 61 +++++++++++++++++++ server/src/services/heartbeat/run-state.ts | 28 +++++++++ .../src/services/native-local-process-stop.ts | 3 +- 6 files changed, 103 insertions(+), 5 deletions(-) diff --git a/doc/DATABASE.md b/doc/DATABASE.md index 06cf24c9368..a814c50cfad 100644 --- a/doc/DATABASE.md +++ b/doc/DATABASE.md @@ -140,6 +140,11 @@ Historical root-reader authorization has been retired; no retained-reader batch loaded at admission or publication. Workspace-record disclosure still uses task privacy checks, independently of filesystem access. +Saved-message execution-wait scans read current run state, process ownership, +startup and cancellation receipts, task binding, and the recorded adapter kind. +Saved profiles, output excerpts, and unrelated launch context stay in storage. +Continuation admission and its locked mutation reads retain their existing gates. + The initial agent JWT run lookup reads only the cancellation state and conversation flag from saved run JSON. It does not transfer the full context or result. Run status, responsible-user identity, company and agent boundaries, diff --git a/server/src/services/heartbeat.ts b/server/src/services/heartbeat.ts index adb10d852c9..354f680eb1d 100644 --- a/server/src/services/heartbeat.ts +++ b/server/src/services/heartbeat.ts @@ -812,6 +812,7 @@ export function heartbeatService( resolveSessionBeforeForWakeup, getRun, getRunCleanupState, + getRunExecutionWait, getRunWorkspaceSettlement, getRunStatus, ensureRuntimeState, @@ -1393,6 +1394,7 @@ export function heartbeatService( const runControl = createHeartbeatRunControl(db, { getRun, getRunCleanupState, + getRunExecutionWait, options, envOrchestrator, activeRunExecutions, diff --git a/server/src/services/heartbeat/run-control.ts b/server/src/services/heartbeat/run-control.ts index b4ba5f0ddea..7387da1f74d 100644 --- a/server/src/services/heartbeat/run-control.ts +++ b/server/src/services/heartbeat/run-control.ts @@ -165,7 +165,7 @@ async function withBudgetStopDelivery(db: Db, work: () => Promise): Promis /** Cancellation shares executor ownership and delegates lifecycle and admission effects. */ export interface HeartbeatRunControlDependencies extends Pick, - "getRun" | "getAgent" | "getRunCleanupState">, + "getRun" | "getAgent" | "getRunCleanupState" | "getRunExecutionWait">, Pick, "mergeRunStopMetadataForAgent" | "setRunStatusFromLive" | "setRunStatus" | "setWakeupStatus" | "appendRunEvent">, Pick { @@ -326,6 +326,7 @@ export function createHeartbeatRunControl(db: Db, dependencies: HeartbeatRunCont const { getRun, getRunCleanupState, + getRunExecutionWait, options, envOrchestrator, activeRunExecutions, @@ -509,7 +510,7 @@ export function createHeartbeatRunControl(db: Db, dependencies: HeartbeatRunCont } } - async function resumeRemoteStopComments(run: typeof heartbeatRuns.$inferSelect, requestId?: string) { + async function resumeRemoteStopComments(run: NonNullable>>, requestId?: string) { if (!isHeartbeatRunTerminalStatus(run.status) || adapterExecutionControls.has(run.id)) return; const [preparationCoordinator] = run.runtimeMode === "legacy" && run.status === "cancelled" && !run.runtimeModeResolvedAt ? await db.select().from(nativeRunFinalizations).where(and( @@ -536,7 +537,7 @@ export function createHeartbeatRunControl(db: Db, dependencies: HeartbeatRunCont await acknowledgedNativeStopExecutionHasStopped(db, currentRun) && !(await getExecutionBlocker(db, run.companyId, issueId)); const legacyContinuation = run.runtimeMode === "legacy" && - hasConversationContinuationPolicy((await getRun(run.id, { includeExecutionEvidence: true }))?.resultJson) && + hasConversationContinuationPolicy((await getRunExecutionWait(run.companyId, run.id))?.resultJson) && !(await getExecutionBlocker(db, run.companyId, issueId)); if (run.runtimeMode !== "native" && run.runtimeMode !== "legacy") return; const pending = await db.select().from(agentWakeupRequests).where(and( @@ -803,7 +804,7 @@ export function createHeartbeatRunControl(db: Db, dependencies: HeartbeatRunCont const blocker = await getExecutionBlocker(db, wake.companyId, issueId); const sourceId = blocker?.runId; if (!sourceId || !isUuidLike(sourceId)) continue; - const run = await getRun(sourceId, { includeExecutionEvidence: true }); + const run = await getRunExecutionWait(wake.companyId, sourceId); if (!run || run.companyId !== wake.companyId || run.agentId !== wake.agentId) continue; if (canContinueCancelledRun(run)) { await resumeSavedLegacyComments(wake.companyId, wake.id).catch(err => { diff --git a/server/src/services/heartbeat/run-state.test.ts b/server/src/services/heartbeat/run-state.test.ts index 702f842e464..1b9c4276a61 100644 --- a/server/src/services/heartbeat/run-state.test.ts +++ b/server/src/services/heartbeat/run-state.test.ts @@ -97,6 +97,17 @@ describe("heartbeat run state module", () => { expect(raw.columns[0].resultJson).toBe(heartbeatRuns.resultJson); }); + it.each(["UTF8", "SQL_ASCII"])("keeps execution-wait reads company scoped with %s text handling", async encoding => { + const reader = readingDatabase(encoding), state = extracted.createHeartbeatRunState(reader.db); + expect(await state.getRunExecutionWait("company", "run")).toBeNull(); + expect(await state.getRunExecutionWait("other-company", "run")).toBeNull(); + expect(reader.scopes).toEqual([["company", "run"], ["other-company", "run"]]); + expect(reader.execute).toHaveBeenCalledTimes(1); + if (encoding === "UTF8") expect(reader.columns[0].error).toBe(heartbeatRuns.error); + else expect(new PgDialect().sqlToQuery((reader.columns[0].error as SQL.Aliased).sql).sql).toBe("NULL"); + expect(new PgDialect().sqlToQuery((reader.columns[0].resultJson as SQL.Aliased).sql).sql).toContain("startupPreparationSettledAt"); + }); + it("loads current run status without large fields or an encoding probe", async () => { const binding = { id: "run", companyId: "company", agentId: "agent", status: "running" }; const reader = readingDatabase("SQL_ASCII", [binding], []); @@ -159,6 +170,56 @@ describePostgres("heartbeat run state database wiring", () => { return { companyId, agent, issue, state: extracted.createHeartbeatRunState(db) }; } + it("reads current execution-wait evidence without transferring saved input or output", async () => { + const { companyId, agent, issue } = await fixture(); + const payload = randomBytes(128 * 1024).toString("base64"); + const context = { issueId: issue.id, connectionIntentResolution: "existing_connection", source: "connection_intent.resolved", + interactionKind: "connection_intent", interactionStatus: "expired", mutation: "interaction", interactionId: randomUUID() }; + const result = { startupCancellation: { beforeNativeSelection: true, futureProof: { version: 2 } }, + startupPreparationSettledAt: "2020-01-01T00:00:00Z", cancellation: { source: "provider", expected: false, + initiator: { type: "provider" }, reason: "Cancelled", recordedAt: "2020-01-01T00:00:00Z" }, + acpToolInventoryComplete: true, acpPendingToolCount: 0, stdout: payload }; + const [run] = await db.insert(heartbeatRuns).values({ companyId, agentId: agent.id, status: "cancelled", runtimeMode: "legacy", + startedAt: new Date("2020-01-01T00:00:00Z"), finishedAt: new Date("2020-01-01T00:01:00Z"), + contextSnapshot: { ...context, prompt: payload }, resultJson: result, + runnerProfileJson: { adapterDispatch: { adapterType: "paperclip_runner", adapterConfig: { prompt: payload } }, savedInput: payload }, + stdoutExcerpt: payload, stderrExcerpt: payload, + }).returning(); + const observed = createDb(database.connectionString), events: Array> = [], now = Date.now(); + const capture = createDatabaseResponseCapture({ start: now - 100, end: now + 59_000 }, event => events.push(event)); + installDatabaseResponseCapture(observed, { heartbeatRuns }, capture); + try { + const state = extracted.createHeartbeatRunState(observed); + const read = await state.getRunExecutionWait(companyId, run.id); + capture.flush(); + const summary = events.find(event => event.event === "paperclip.db_response_capture.summary.v1")!; + expect(summary.completedQueries).toBe(2); + expect(summary.responseValueBytes).toBeLessThan(4096); + expect(read).toMatchObject({ id: run.id, companyId, agentId: agent.id, status: "cancelled", contextSnapshot: context, + runnerProfileJson: { adapterDispatch: { adapterType: "paperclip_runner" } }, + resultJson: { startupCancellation: result.startupCancellation, cancellation: result.cancellation, + acpToolInventoryComplete: true, acpPendingToolCount: 0 } }); + expect(JSON.stringify(read)).not.toContain(payload.slice(0, 64)); + expect(read).not.toHaveProperty("stdoutExcerpt"); + expect(read).not.toHaveProperty("stderrExcerpt"); + expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, run.id)))[0]).toEqual(run); + await db.update(heartbeatRuns).set({ status: "running", resultJson: { ...result, acpPendingToolCount: 1 }, + runnerProfileJson: { adapterDispatch: { adapterType: "process" }, savedInput: payload }, + }).where(eq(heartbeatRuns.id, run.id)); + expect(await state.getRunExecutionWait(companyId, run.id)).toMatchObject({ status: "running", + resultJson: { acpPendingToolCount: 1 }, runnerProfileJson: { adapterDispatch: { adapterType: "process" } } }); + expect(await state.getRunExecutionWait(randomUUID(), run.id)).toBeNull(); + expect(await state.getRunExecutionWait(companyId, randomUUID())).toBeNull(); + for (const value of [null, false, 42, [], {}, { nested: true }, "task"]) { + await db.update(heartbeatRuns).set({ contextSnapshot: { ...context, issueId: value }, + runnerProfileJson: { adapterDispatch: { adapterType: value } }, + }).where(eq(heartbeatRuns.id, run.id)); + expect(await state.getRunExecutionWait(companyId, run.id)).toMatchObject({ contextSnapshot: { issueId: value }, + runnerProfileJson: { adapterDispatch: { adapterType: value } } }); + } + } finally { capture.flush(); await observed.$client.end(); } + }); + it("reads current workspace access without execution snapshots and retains JSON types", async () => { const { companyId, agent, issue } = await fixture(); const payload = randomBytes(128 * 1024).toString("base64"), workspaceId = randomUUID(); diff --git a/server/src/services/heartbeat/run-state.ts b/server/src/services/heartbeat/run-state.ts index f870c3957fb..7ac3a3816a2 100644 --- a/server/src/services/heartbeat/run-state.ts +++ b/server/src/services/heartbeat/run-state.ts @@ -1131,6 +1131,33 @@ export function createHeartbeatRunState(db: Db) { .then((rows) => rows[0] ?? null); } + async function getRunExecutionWait(companyId: string, runId: string) { + const safeForLegacyEncoding = await hasUnsafeTextProjectionDatabase(); + return db.select({ + ...heartbeatRunIssueControlColumns, + finishedAt: heartbeatRuns.finishedAt, + errorCode: heartbeatRuns.errorCode, + error: safeForLegacyEncoding ? heartbeatRunSqlAsciiSafeColumns.error : heartbeatRuns.error, + nativeIssueId: heartbeatRuns.nativeIssueId, + nativeSessionId: heartbeatRuns.nativeSessionId, + processPid: heartbeatRuns.processPid, + processGroupId: heartbeatRunProcessGroupIdColumn, + processStartedAt: heartbeatRuns.processStartedAt, + sessionIdAfter: heartbeatRuns.sessionIdAfter, + executionStage: heartbeatRuns.executionStage, + controllerBootId: heartbeatRuns.controllerBootId, + controllerLeaseExpiresAt: heartbeatRuns.controllerLeaseExpiresAt, + resultJson: heartbeatRunExecutionEvidenceColumn, + contextSnapshot: sql | null>`case when jsonb_typeof(${heartbeatRuns.contextSnapshot}) = 'object' + then (select coalesce(jsonb_object_agg(key, value), '{}'::jsonb) + from jsonb_each(${heartbeatRuns.contextSnapshot}) + where key = any(array['issueId', 'connectionIntentResolution', 'source', 'interactionKind', + 'interactionStatus', 'mutation', 'interactionId'])) else null end`, + }).from(heartbeatRuns).where(and( + eq(heartbeatRuns.companyId, companyId), eq(heartbeatRuns.id, runId), + )).then(rows => rows[0] ?? null); + } + async function getRunCleanupState(runId: string) { return db.select({ id: heartbeatRuns.id, companyId: heartbeatRuns.companyId, agentId: heartbeatRuns.agentId, @@ -1730,6 +1757,7 @@ export function createHeartbeatRunState(db: Db) { resolveSessionBeforeForWakeup, getRun, getRunCleanupState, + getRunExecutionWait, getRunWorkspaceSettlement, ensureRuntimeState, getTaskSession, diff --git a/server/src/services/native-local-process-stop.ts b/server/src/services/native-local-process-stop.ts index 7e74b8eca1c..422d2c24f0f 100644 --- a/server/src/services/native-local-process-stop.ts +++ b/server/src/services/native-local-process-stop.ts @@ -22,7 +22,8 @@ function absent(pid: number): boolean { /** A fresh workspace is not process containment. Bind an OS observation to * the original host, process birth, and launch event before accepting it. */ -export async function recordedLocalExecutionStopped(db: Db, run: typeof heartbeatRuns.$inferSelect) { +export async function recordedLocalExecutionStopped(db: Db, run: Pick) { const [identity] = await db.select({ payload: heartbeatRunEvents.payload }).from(heartbeatRunEvents).where(and( eq(heartbeatRunEvents.companyId, run.companyId), eq(heartbeatRunEvents.runId, run.id), eq(heartbeatRunEvents.eventType, PROCESS_IDENTITY_RECORDED), isNull(heartbeatRunEvents.sourceEventId), From bd77ffe78d625bb68c430640f4f30231e9cf48e8 Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Sun, 25 Oct 2026 04:12:14 -0700 Subject: [PATCH 056/110] perf(connections): scope profile rule and binding reads (#17589) Read current company/agent profile bindings and rules matching the exact catalog rows being evaluated. Preserve all five selector kinds, null application matches, exclusions, and the existing access evaluator without a cross-call cache. Verified with full build and typecheck, 652 affected tests across ten suites, all 18 strengthened effective-assignment tests, exclusion mutation and byte counterfactuals, complete exact-head CI, and Greptile 5/5 Medium with no unresolved comments. Co-Authored-By: Paperclip --- doc/DATABASE.md | 7 ++ .../tool-effective-assignments.test.ts | 116 ++++++++++++++++++ .../tool-access/profiles/resolution.ts | 72 ++++++----- 3 files changed, 163 insertions(+), 32 deletions(-) diff --git a/doc/DATABASE.md b/doc/DATABASE.md index a814c50cfad..762ea37f2d9 100644 --- a/doc/DATABASE.md +++ b/doc/DATABASE.md @@ -135,6 +135,13 @@ authority once. Different task bindings must both pass. The batch is discarded after that delivery; later events still recheck grants, membership, task existence, and company boundaries. +Connection-assignment checks select profile bindings for the current company or +agent and read rules that can match the selected connection's catalog rows. +All five selector kinds, null application matching, exclusions, and profile +precedence retain their existing evaluator. Rule filtering uses the catalog +values already read by that check, so a later catalog change cannot drop an +exclusion from the decision being evaluated. There is no cross-call cache. + Filesystem preparation uses current task/run and selected-configuration checks. Historical root-reader authorization has been retired; no retained-reader batch is loaded at admission or publication. Workspace-record disclosure still uses task diff --git a/server/src/__tests__/tool-effective-assignments.test.ts b/server/src/__tests__/tool-effective-assignments.test.ts index 13de5533fbf..4b99a23eec2 100644 --- a/server/src/__tests__/tool-effective-assignments.test.ts +++ b/server/src/__tests__/tool-effective-assignments.test.ts @@ -169,6 +169,122 @@ describeDatabase("effective tool assignments", () => { expect((await service.getConnectionAssignmentsForAgent(f.company.id, f.agent.id, [f.connection.id])).allowedConnectionIds).toEqual([]); }); + it("omits unrelated rules and bindings while retaining current connection decisions", async () => { + const f = await fixture(); + const [otherApplication] = await db.insert(toolApplications).values({ companyId: f.company.id, name: "Other app", type: "mcp_http" }).returning(); + const [otherConnection] = await db.insert(toolConnections).values({ companyId: f.company.id, applicationId: otherApplication.id, + name: "Other connection", uid: randomUUID(), transport: "mcp_remote" }).returning(); + const [otherTool] = await db.insert(toolCatalogEntries).values({ companyId: f.company.id, applicationId: otherApplication.id, + connectionId: otherConnection.id, name: "other", toolName: "other", versionHash: "other", riskLevel: "destructive" }).returning(); + await db.insert(toolProfileEntries).values(Array.from({ length: 200 }, (_, index) => [ + { selectorType: "application" as const, applicationId: otherApplication.id }, + { selectorType: "connection" as const, connectionId: otherConnection.id }, + { selectorType: "catalog_entry" as const, catalogEntryId: otherTool.id }, + { selectorType: "tool_name" as const, toolName: `unrelated_${index}` }, + { selectorType: "risk_level" as const, riskLevel: "destructive" as const }, + ].map(entry => ({ companyId: f.company.id, profileId: f.profile.id, effect: index % 2 ? "include" as const : "exclude" as const, ...entry }))).flat()); + await db.insert(toolProfileBindings).values(Array.from({ length: 200 }, () => ({ companyId: f.company.id, + profileId: f.profile.id, targetType: "agent" as const, targetId: randomUUID() }))); + const [include, exclude] = await db.insert(toolProfileEntries).values([ + { companyId: f.company.id, profileId: f.profile.id, selectorType: "connection", effect: "include", connectionId: f.connection.id }, + { companyId: f.company.id, profileId: f.profile.id, selectorType: "catalog_entry", effect: "exclude", catalogEntryId: f.write.id }, + ]).returning(); + const service = toolAccessService(db), before = await compare(f); + const savedRules = await db.select().from(toolProfileEntries); + const events: Array> = [], now = Date.now(); + const capture = createDatabaseResponseCapture({ start: now - 100, end: now + 59_000 }, event => events.push(event)); + installDatabaseResponseCapture(db, { toolProfileEntries, toolProfileBindings }, capture); + try { + const scoped = await service.getConnectionAssignmentsForAgent(f.company.id, f.agent.id, [f.connection.id]); + capture.flush(); + const rules = events.filter(event => event.event === "paperclip.db_response_capture.entry.v1" && event.table === "tool_profile_entries"); + const bindings = events.filter(event => event.event === "paperclip.db_response_capture.entry.v1" && event.table === "tool_profile_bindings"); + expect(rules).toHaveLength(1); + expect(Number(rules[0].responseValueBytes)).toBeLessThan(4096); + expect(rules[0]).toMatchObject({ calls: 1, rows: 2 }); + expect(bindings).toHaveLength(1); + expect(bindings[0]).toMatchObject({ calls: 1, rows: 1 }); + expect(scoped).toEqual({ allowedConnectionIds: [f.connection.id], installedConnections: before.full.installedConnections }); + expect(await db.select().from(toolProfileEntries)).toEqual(savedRules); + await db.update(toolProfileEntries).set({ effect: "exclude" }).where(eq(toolProfileEntries.id, include.id)); + expect((await service.getConnectionAssignmentsForAgent(f.company.id, f.agent.id, [f.connection.id])).allowedConnectionIds).toEqual([]); + await db.delete(toolProfileEntries).where(eq(toolProfileEntries.id, include.id)); + expect((await service.getConnectionAssignmentsForAgent(f.company.id, f.agent.id, [f.connection.id])).allowedConnectionIds).toEqual([]); + expect((await db.select().from(toolProfileEntries).where(eq(toolProfileEntries.id, exclude.id)))[0]).toEqual(exclude); + } finally { capture.flush(); } + }); + + it("preserves null application matches and exact special-character tool names", async () => { + const f = await fixture(), toolName = "quoted' path\\tool_🙂"; + await db.update(toolCatalogEntries).set({ status: "removed" }).where(eq(toolCatalogEntries.id, f.write.id)); + await db.update(toolCatalogEntries).set({ applicationId: null, toolName }).where(eq(toolCatalogEntries.id, f.read.id)); + await db.update(toolProfiles).set({ defaultAction: "allow" }).where(eq(toolProfiles.id, f.profile.id)); + const [rule] = await db.insert(toolProfileEntries).values({ companyId: f.company.id, profileId: f.profile.id, + selectorType: "application", applicationId: null, effect: "exclude" }).returning(); + const service = toolAccessService(db); + expect((await compare(f)).assignments.allowedTools).toEqual([]); + expect((await service.getConnectionAssignmentsForAgent(f.company.id, f.agent.id, [f.connection.id])).allowedConnectionIds).toEqual([]); + await db.update(toolProfileEntries).set({ selectorType: "tool_name", toolName }).where(eq(toolProfileEntries.id, rule.id)); + expect((await compare(f)).assignments.allowedTools).toEqual([]); + expect((await service.getConnectionAssignmentsForAgent(f.company.id, f.agent.id, [f.connection.id])).allowedConnectionIds).toEqual([]); + await db.update(toolProfileEntries).set({ toolName: `${toolName}different` }).where(eq(toolProfileEntries.id, rule.id)); + expect((await compare(f)).assignments.allowedTools.map(tool => tool.id)).toEqual([f.read.id]); + expect((await service.getConnectionAssignmentsForAgent(f.company.id, f.agent.id, [f.connection.id])).allowedConnectionIds).toEqual([f.connection.id]); + }); + + it.each(["application", "connection", "catalog_entry", "tool_name", "risk_level"] as const)("denies the connection when a %s exclusion blocks its only active tool", async selectorType => { + const f = await fixture(); + await db.update(toolCatalogEntries).set({ status: "removed" }).where(eq(toolCatalogEntries.id, f.write.id)); + await db.update(toolProfiles).set({ defaultAction: "allow" }).where(eq(toolProfiles.id, f.profile.id)); + const [rule] = await db.insert(toolProfileEntries).values({ companyId: f.company.id, profileId: f.profile.id, selectorType, effect: "exclude", + ...(selectorType === "application" ? { applicationId: f.application.id } : {}), + ...(selectorType === "connection" ? { connectionId: f.connection.id } : {}), + ...(selectorType === "catalog_entry" ? { catalogEntryId: f.read.id } : {}), + ...(selectorType === "tool_name" ? { toolName: f.read.toolName } : {}), + ...(selectorType === "risk_level" ? { riskLevel: "read" as const } : {}), + }).returning(); + const service = toolAccessService(db); + expect((await service.getConnectionAssignmentsForAgent(f.company.id, f.agent.id, [f.connection.id])).allowedConnectionIds).toEqual([]); + expect((await compare(f)).assignments.allowedTools).toEqual([]); + await db.delete(toolProfileEntries).where(eq(toolProfileEntries.id, rule.id)); + expect((await service.getConnectionAssignmentsForAgent(f.company.id, f.agent.id, [f.connection.id])).allowedConnectionIds).toEqual([f.connection.id]); + }); + + it("filters rules against the catalog rows being evaluated when the catalog changes during the read", async () => { + const f = await fixture(); + await db.update(toolProfiles).set({ defaultAction: "allow" }).where(eq(toolProfiles.id, f.profile.id)); + await db.update(toolCatalogEntries).set({ status: "removed" }).where(eq(toolCatalogEntries.id, f.write.id)); + await db.insert(toolProfileEntries).values({ companyId: f.company.id, profileId: f.profile.id, + selectorType: "tool_name", toolName: f.read.toolName, effect: "exclude" }); + let changed = false; + const changingDb = new Proxy(db, { get(target, key) { + if (key !== "select") return Reflect.get(target, key); + return (...fields: Parameters) => { + const builder = target.select(...fields), from = builder.from.bind(builder); + builder.from = ((...args: Parameters) => { + const selection = from(...args); + if (args[0] === toolCatalogEntries) { + const execute = selection.execute.bind(selection); + selection.execute = async () => { + const rows = await execute(); + if (!changed) { + changed = true; + await db.update(toolCatalogEntries).set({ toolName: "changed-after-read" }).where(eq(toolCatalogEntries.id, f.read.id)); + } + return rows; + }; + } + return selection; + }) as typeof builder.from; + return builder; + }; + } }); + const service = toolAccessService(changingDb); + expect((await service.getConnectionAssignmentsForAgent(f.company.id, f.agent.id, [f.connection.id])).allowedConnectionIds).toEqual([]); + expect(changed).toBe(true); + expect((await service.getConnectionAssignmentsForAgent(f.company.id, f.agent.id, [f.connection.id])).allowedConnectionIds).toEqual([f.connection.id]); + }); + it("keeps other companies' catalog rows out of scoped assignments", async () => { const f = await fixture(); const other = await fixture(); diff --git a/server/src/services/tool-access/profiles/resolution.ts b/server/src/services/tool-access/profiles/resolution.ts index 3cc4d36df4b..c237636eb2b 100644 --- a/server/src/services/tool-access/profiles/resolution.ts +++ b/server/src/services/tool-access/profiles/resolution.ts @@ -1,4 +1,4 @@ -import { and, asc, eq, inArray } from "drizzle-orm"; +import { and, asc, eq, inArray, or, sql, type AnyColumn } from "drizzle-orm"; import type { Db } from "@paperclipai/db"; import { agents, toolCatalogEntries, toolProfileBindings, toolProfileEntries, toolProfiles } from "@paperclipai/db"; import type { ToolCatalogEntry, ToolConnection, ToolProfileEffectiveSummary, ToolProfileWithDetails } from "@paperclipai/shared"; @@ -10,6 +10,12 @@ type ProfileAssignmentDependencies = { toCatalogEntry(row: typeof toolCatalogEntries.$inferSelect): ToolCatalogEntry; }; +function catalogValuesContain(column: AnyColumn, values: Array) { + const distinct = [...new Set(values)]; + return sql`(${JSON.stringify(distinct.filter(value => value !== null))}::jsonb ? ${column}::text + or (${distinct.includes(null)} and ${column} is null))`; +} + function resolveCatalogAccess( profiles: Array>, entries: Array, @@ -69,20 +75,17 @@ export function createToolProfileResolver(db: Db, { assertOptionalAgent, resolve agentId, "Tool profile effective agent", ); - const allBindings = await db + const matchingBindings = await db .select() .from(toolProfileBindings) - .where(eq(toolProfileBindings.companyId, companyId)) + .where(and(eq(toolProfileBindings.companyId, companyId), or( + and(eq(toolProfileBindings.targetType, "company"), eq(toolProfileBindings.targetId, companyId)), + and(eq(toolProfileBindings.targetType, "agent"), eq(toolProfileBindings.targetId, agentId)), + ))) .orderBy( asc(toolProfileBindings.priority), asc(toolProfileBindings.createdAt), ); - const matchingBindings = allBindings.filter( - (binding) => - (binding.targetType === "company" && - binding.targetId === companyId) || - (binding.targetType === "agent" && binding.targetId === agentId), - ); const candidateProfileIds = profileIdsInBindingOrder(matchingBindings); if (candidateProfileIds.length === 0) return { bindings: [], activeProfiles: [] }; const candidateProfiles = await db @@ -194,29 +197,34 @@ export function createToolProfileResolver(db: Db, { assertOptionalAgent, resolve if (activeProfiles.length === 0 || connectionIds.length === 0) { return { allowedConnectionIds: [], installedConnections: await resolveInstalledConnectionsForAgent(companyId, agentId) }; } - const [entries, catalog] = await Promise.all([ - db.select({ - profileId: toolProfileEntries.profileId, - effect: toolProfileEntries.effect, - selectorType: toolProfileEntries.selectorType, - applicationId: toolProfileEntries.applicationId, - connectionId: toolProfileEntries.connectionId, - catalogEntryId: toolProfileEntries.catalogEntryId, - toolName: toolProfileEntries.toolName, - riskLevel: toolProfileEntries.riskLevel, - }).from(toolProfileEntries).where(and( - eq(toolProfileEntries.companyId, companyId), inArray(toolProfileEntries.profileId, activeProfiles.map(profile => profile.id)), - )), - db.select({ - id: toolCatalogEntries.id, - applicationId: toolCatalogEntries.applicationId, - connectionId: toolCatalogEntries.connectionId, - toolName: toolCatalogEntries.toolName, - riskLevel: toolCatalogEntries.riskLevel, - }).from(toolCatalogEntries).where(and( - eq(toolCatalogEntries.companyId, companyId), eq(toolCatalogEntries.status, "active"), inArray(toolCatalogEntries.connectionId, connectionIds), - )), - ]); + const catalog = await db.select({ + id: toolCatalogEntries.id, + applicationId: toolCatalogEntries.applicationId, + connectionId: toolCatalogEntries.connectionId, + toolName: toolCatalogEntries.toolName, + riskLevel: toolCatalogEntries.riskLevel, + }).from(toolCatalogEntries).where(and( + eq(toolCatalogEntries.companyId, companyId), eq(toolCatalogEntries.status, "active"), inArray(toolCatalogEntries.connectionId, connectionIds), + )); + const entries = catalog.length === 0 ? [] : await db.select({ + profileId: toolProfileEntries.profileId, + effect: toolProfileEntries.effect, + selectorType: toolProfileEntries.selectorType, + applicationId: toolProfileEntries.applicationId, + connectionId: toolProfileEntries.connectionId, + catalogEntryId: toolProfileEntries.catalogEntryId, + toolName: toolProfileEntries.toolName, + riskLevel: toolProfileEntries.riskLevel, + }).from(toolProfileEntries).where(and( + eq(toolProfileEntries.companyId, companyId), inArray(toolProfileEntries.profileId, activeProfiles.map(profile => profile.id)), + or( + and(eq(toolProfileEntries.selectorType, "application"), catalogValuesContain(toolProfileEntries.applicationId, catalog.map(entry => entry.applicationId))), + and(eq(toolProfileEntries.selectorType, "connection"), catalogValuesContain(toolProfileEntries.connectionId, catalog.map(entry => entry.connectionId))), + and(eq(toolProfileEntries.selectorType, "catalog_entry"), catalogValuesContain(toolProfileEntries.catalogEntryId, catalog.map(entry => entry.id))), + and(eq(toolProfileEntries.selectorType, "tool_name"), catalogValuesContain(toolProfileEntries.toolName, catalog.map(entry => entry.toolName))), + and(eq(toolProfileEntries.selectorType, "risk_level"), catalogValuesContain(toolProfileEntries.riskLevel, catalog.map(entry => entry.riskLevel))), + ), + )); const { allowedCatalogIds } = resolveCatalogAccess(activeProfiles, entries, catalog); return { allowedConnectionIds: [...new Set(catalog.filter(entry => allowedCatalogIds.has(entry.id)).map(entry => entry.connectionId))], From 2e47c42fad91df8c040b33d3bda301f4a35264cf Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Sun, 25 Oct 2026 04:21:50 -0700 Subject: [PATCH 057/110] perf(runner): omit unused launch context from tool authority reads (#17591) Omit nine unused named launch values from the unlocked Native authority query. Preserve complete wake payloads, other context, result receipts, stored input, and locked execution and mutation readers. Verified with full build and typecheck, 2,359 affected tests across 20 suites, real PostgreSQL byte/retention/cancellation checks, a counterfactual, complete exact-head CI, and Greptile 5/5 Medium with no unresolved comments. An existing cleanup scheduling test passed on CI retry after its suite passed locally with both base and branch source. Co-Authored-By: Paperclip --- doc/DATABASE.md | 5 ++- .../paperclip-runner-tool-authority.test.ts | 36 +++++++++++++++++++ .../paperclip-runner-tool-authority.ts | 6 +++- 3 files changed, 45 insertions(+), 2 deletions(-) diff --git a/doc/DATABASE.md b/doc/DATABASE.md index 762ea37f2d9..4f16a6e4d87 100644 --- a/doc/DATABASE.md +++ b/doc/DATABASE.md @@ -127,7 +127,10 @@ Native tool authority lookups select current run identity, status, invocation, responsible user, context, and receipt data. Saved profiles and output excerpts stay in storage and are omitted from that read. Task and agent binding, current status, budget, and task privacy checks retain their existing predicates. -Mutation transactions still lock and read complete run records. +Mutation transactions still lock and read complete run records. The unlocked +authority read also omits named launch renderings and preparation data that its +tools do not consume. Full wake payloads, other context, and result receipts +remain available; the complete saved context stays in storage for execution. WebSocket delivery uses one fresh authorization batch for an event's task and run bindings. When both bindings name the same task, the batch reads its current diff --git a/server/src/services/native-runtime/paperclip-runner-tool-authority.test.ts b/server/src/services/native-runtime/paperclip-runner-tool-authority.test.ts index 76815a76482..2558b813555 100644 --- a/server/src/services/native-runtime/paperclip-runner-tool-authority.test.ts +++ b/server/src/services/native-runtime/paperclip-runner-tool-authority.test.ts @@ -244,6 +244,42 @@ describe("PaperclipRunnerToolAuthority", () => { } }); + it("reads tool authority without transferring unused launch renderings", async () => { + const binding = { companyId, agentId, issueId, runId }; + const authority = new PaperclipRunnerToolAuthority(db, binding); + const contextCall = { tool: "get_task_context", callId: "launch-context-read", arguments: {} }; + const apiCall = { tool: "search_api", callId: "launch-api-read", arguments: { query: "read task" } }; + const expectedContext = await authority.execute(contextCall), expectedApi = await authority.execute(apiCall); + const [original] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)); + const payload = "retained-launch-rendering🙂".repeat(8192); + const context = { ...original.contextSnapshot, executionContinuation: { savedInput: payload }, paperclipTaskMarkdown: payload, + paperclipTaskMarkdownCompact: payload, paperclipTaskMarkdownAssignment: payload, paperclipTaskMarkdownAssignmentCompact: payload, + paperclipWorkspace: { savedInput: payload }, paperclipEnvironment: { savedInput: payload }, + paperclipContinuationSummary: payload, paperclipWakeComment: payload }; + await db.update(heartbeatRuns).set({ contextSnapshot: context }).where(eq(heartbeatRuns.id, runId)); + const [expanded] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)); + const observed = createDb(temporary!.connectionString), events: Array> = [], now = Date.now(); + const capture = createDatabaseResponseCapture({ start: now - 100, end: now + 59_000 }, event => events.push(event)); + installDatabaseResponseCapture(observed, { heartbeatRuns, issues, agents, companies }, capture); + try { + const reader = new PaperclipRunnerToolAuthority(observed, binding); + const actualContext = await reader.execute(contextCall), actualApi = await reader.execute(apiCall); + capture.flush(); + const reads = events.filter(event => event.table === "heartbeat_runs" && event.operation === "select"); + expect(reads.length).toBeGreaterThan(0); + expect(reads.reduce((bytes, event) => bytes + Number(event.responseValueBytes), 0)).toBeLessThan(16 * 1024); + expect(actualContext).toEqual(expectedContext); + expect(actualApi).toEqual(expectedApi); + expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)))[0]).toEqual(expanded); + await db.update(heartbeatRuns).set({ status: "cancelled" }).where(eq(heartbeatRuns.id, runId)); + await expect(reader.execute(contextCall)).rejects.toThrow("paperclip_runner_tool_binding_not_authorized"); + await expect(reader.execute(apiCall)).rejects.toThrow("paperclip_runner_tool_binding_not_authorized"); + } finally { + capture.flush(); await observed.$client.end(); + await db.update(heartbeatRuns).set({ contextSnapshot: original.contextSnapshot, status: original.status }).where(eq(heartbeatRuns.id, runId)); + } + }); + it("preserves platform receipt provenance in both mixed task history readers", async () => { const at = new Date("2026-10-10T12:00:00Z"); const commentIds = Array.from({ length: 4 }, () => randomUUID()); diff --git a/server/src/services/native-runtime/paperclip-runner-tool-authority.ts b/server/src/services/native-runtime/paperclip-runner-tool-authority.ts index 40b140f01b2..e257744e545 100644 --- a/server/src/services/native-runtime/paperclip-runner-tool-authority.ts +++ b/server/src/services/native-runtime/paperclip-runner-tool-authority.ts @@ -1235,7 +1235,11 @@ export class PaperclipRunnerToolAuthority { status: heartbeatRuns.status, invocationSource: heartbeatRuns.invocationSource, responsibleUserId: heartbeatRuns.responsibleUserId, - contextSnapshot: heartbeatRuns.contextSnapshot, + contextSnapshot: sql | null>`case when jsonb_typeof(${heartbeatRuns.contextSnapshot}) = 'object' + then ${heartbeatRuns.contextSnapshot} - array['executionContinuation', 'paperclipTaskMarkdown', + 'paperclipTaskMarkdownCompact', 'paperclipTaskMarkdownAssignment', 'paperclipTaskMarkdownAssignmentCompact', + 'paperclipWorkspace', 'paperclipEnvironment', 'paperclipContinuationSummary', 'paperclipWakeComment'] + else ${heartbeatRuns.contextSnapshot} end`, resultJson: heartbeatRuns.resultJson, } }) .from(heartbeatRuns) From 8c6bd5a83bf9d9b5af765be9bbcf60e400889b64 Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Sun, 25 Oct 2026 05:36:43 -0700 Subject: [PATCH 058/110] perf(runner): skip wake payloads in ordinary authority reads (#17600) Omit saved wake payloads from ordinary unlocked Native authority reads. Load the current full wake for mail restrictions. Preserve stored rows, locked mutation reads, and current authorization predicates. Verified with full build and typecheck, 2,360 affected tests, real PostgreSQL byte and response checks, counterfactual performance and mail authorization failures, complete exact-head CI, and Greptile 5/5 Medium with no unresolved comments. Co-Authored-By: Paperclip --- doc/DATABASE.md | 6 ++- .../paperclip-runner-tool-authority.test.ts | 47 +++++++++++++++++-- .../paperclip-runner-tool-authority.ts | 5 +- 3 files changed, 50 insertions(+), 8 deletions(-) diff --git a/doc/DATABASE.md b/doc/DATABASE.md index 4f16a6e4d87..9e432cbfcc0 100644 --- a/doc/DATABASE.md +++ b/doc/DATABASE.md @@ -129,8 +129,10 @@ stay in storage and are omitted from that read. Task and agent binding, current status, budget, and task privacy checks retain their existing predicates. Mutation transactions still lock and read complete run records. The unlocked authority read also omits named launch renderings and preparation data that its -tools do not consume. Full wake payloads, other context, and result receipts -remain available; the complete saved context stays in storage for execution. +tools do not consume. Ordinary tool checks also omit the wake payload. Mail +checks load the current full wake to enforce external-chat restrictions. Other +context and result receipts remain available. The complete saved context stays +in storage for execution. WebSocket delivery uses one fresh authorization batch for an event's task and run bindings. When both bindings name the same task, the batch reads its current diff --git a/server/src/services/native-runtime/paperclip-runner-tool-authority.test.ts b/server/src/services/native-runtime/paperclip-runner-tool-authority.test.ts index 2558b813555..74524c733f3 100644 --- a/server/src/services/native-runtime/paperclip-runner-tool-authority.test.ts +++ b/server/src/services/native-runtime/paperclip-runner-tool-authority.test.ts @@ -1,4 +1,4 @@ -import { connectorToolDefinitionsForSkills } from "../connector-runtime.js"; +import * as connectorRuntime from "../connector-runtime.js"; import * as cloudIdentity from "../cloud-runtime-identity.js"; import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; import { randomUUID } from "node:crypto"; @@ -101,7 +101,7 @@ describe("PaperclipRunnerToolAuthority", () => { }); it("registers pinned connector definitions without discovery and rejects revoked assignments at use", async () => { - const connectorAssignments = connectorToolDefinitionsForSkills(new Set([ + const connectorAssignments = connectorRuntime.connectorToolDefinitionsForSkills(new Set([ "paperclipai/paperclip/slack", "paperclipai/paperclip/browser-use-cloud", "custom/agentmail", ])); expect(connectorAssignments).toHaveLength(1); @@ -244,7 +244,7 @@ describe("PaperclipRunnerToolAuthority", () => { } }); - it("reads tool authority without transferring unused launch renderings", async () => { + it("reads tool authority without transferring unused launch renderings or wake payloads", async () => { const binding = { companyId, agentId, issueId, runId }; const authority = new PaperclipRunnerToolAuthority(db, binding); const contextCall = { tool: "get_task_context", callId: "launch-context-read", arguments: {} }; @@ -255,7 +255,7 @@ describe("PaperclipRunnerToolAuthority", () => { const context = { ...original.contextSnapshot, executionContinuation: { savedInput: payload }, paperclipTaskMarkdown: payload, paperclipTaskMarkdownCompact: payload, paperclipTaskMarkdownAssignment: payload, paperclipTaskMarkdownAssignmentCompact: payload, paperclipWorkspace: { savedInput: payload }, paperclipEnvironment: { savedInput: payload }, - paperclipContinuationSummary: payload, paperclipWakeComment: payload }; + paperclipContinuationSummary: payload, paperclipWakeComment: payload, paperclipWake: { retainedPayload: payload } }; await db.update(heartbeatRuns).set({ contextSnapshot: context }).where(eq(heartbeatRuns.id, runId)); const [expanded] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)); const observed = createDb(temporary!.connectionString), events: Array> = [], now = Date.now(); @@ -280,6 +280,45 @@ describe("PaperclipRunnerToolAuthority", () => { } }); + it("checks the current full wake before mail actions while ordinary tools omit its payload", async () => { + const connectorAssignments = connectorRuntime.connectorToolDefinitionsForSkills(new Set(["paperclipai/paperclip/agentmail"])); + const name = connectorAssignments.flatMap(assignment => assignment.tools).find(tool => tool.name.startsWith("agentmail_"))!.name; + const authority = new PaperclipRunnerToolAuthority(db, { companyId, agentId, issueId, runId, connectorAssignments }); + const [original] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)); + const dispatch = vi.spyOn(connectorRuntime, "executeConnectorTool").mockResolvedValue({ outcome: "mail-dispatched" }); + const wake = { + reason: "External chat message received", externalChatProvider: "github", checkedOutByHarness: true, + issue: { id: issueId, identifier: "RNT-1", title: "Conversation", description: "Task", descriptionTruncated: false, + status: "in_progress", workMode: "standard" }, + commentWindow: { requestedCount: 1, includedCount: 1, missingCount: 0 }, commentIds: ["wake-comment"], + latestCommentId: "wake-comment", comments: [{ id: "wake-comment", issueId, body: "Reply here", bodyTruncated: false, authorType: "user" }], + fallbackFetchNeeded: false, + }; + const call = { tool: name, callId: "current-mail-wake", arguments: {} }; + try { + await db.update(heartbeatRuns).set({ contextSnapshot: { issueId, paperclipWake: wake } }).where(eq(heartbeatRuns.id, runId)); + await expect(authority.execute(call)).rejects.toThrow("Restricted chat runs cannot use email actions"); + expect(dispatch).not.toHaveBeenCalled(); + await expect(authority.execute({ tool: "get_task_context", callId: "chat-task-context", arguments: {} })) + .resolves.toMatchObject({ activeTask: { id: issueId } }); + await db.update(heartbeatRuns).set({ contextSnapshot: { issueId } }).where(eq(heartbeatRuns.id, runId)); + await expect(authority.execute(call)).resolves.toEqual({ outcome: "mail-dispatched" }); + expect(dispatch).toHaveBeenCalledTimes(1); + await db.update(heartbeatRuns).set({ contextSnapshot: { issueId, paperclipWake: { ...wake, checkedOutByHarness: false, + externalChatExecutionBound: true, issue: { ...wake.issue, status: "in_review" } } } }).where(eq(heartbeatRuns.id, runId)); + await expect(authority.execute(call)).rejects.toThrow("Restricted chat runs cannot use email actions"); + expect(dispatch).toHaveBeenCalledTimes(1); + for (const context of [{ issueId, source: "chat:github" }, { issueId, paperclipExternalChatQuestionResponse: true }]) { + await db.update(heartbeatRuns).set({ contextSnapshot: context }).where(eq(heartbeatRuns.id, runId)); + await expect(authority.execute(call)).rejects.toThrow("Restricted chat runs cannot use email actions"); + expect(dispatch).toHaveBeenCalledTimes(1); + } + } finally { + dispatch.mockRestore(); + await db.update(heartbeatRuns).set({ contextSnapshot: original.contextSnapshot }).where(eq(heartbeatRuns.id, runId)); + } + }); + it("preserves platform receipt provenance in both mixed task history readers", async () => { const at = new Date("2026-10-10T12:00:00Z"); const commentIds = Array.from({ length: 4 }, () => randomUUID()); diff --git a/server/src/services/native-runtime/paperclip-runner-tool-authority.ts b/server/src/services/native-runtime/paperclip-runner-tool-authority.ts index e257744e545..31f65f12fcd 100644 --- a/server/src/services/native-runtime/paperclip-runner-tool-authority.ts +++ b/server/src/services/native-runtime/paperclip-runner-tool-authority.ts @@ -449,7 +449,7 @@ export class PaperclipRunnerToolAuthority { } if (isConnectorTool(call.tool)) { if (!(this.binding.connectorAssignments ?? []).some((assignment) => assignment.tools.some((tool) => tool.name === call.tool))) throw forbidden("Connector tool is not available to this run"); - const { run } = await this.#boundContext(); + const { run } = await this.#boundContext({ includeChatWake: call.tool.startsWith("agentmail_") }); const snapshot = record(run.contextSnapshot); if (call.tool.startsWith("agentmail_") && (isPaperclipExternalChatContractTurn(snapshot.paperclipWake) || String(snapshot.source ?? "").startsWith("chat:") || snapshot.paperclipExternalChatQuestionResponse)) throw forbidden("Restricted chat runs cannot use email actions"); return executeConnectorTool(this.db, this.binding, call.tool, call.arguments); @@ -1225,7 +1225,7 @@ export class PaperclipRunnerToolAuthority { ...(this.binding.museRuntime ? { authorizingUserId: this.binding.externalAuthorizingUserId } : {}) }; } - async #boundContext() { + async #boundContext(options: { includeChatWake?: boolean } = {}) { if (this.binding.museRuntime && !this.binding.externalAuthorizingUserId) throw forbidden("Muse authorizer is unavailable"); const [row] = await this.db.select({ issue: issues, actor: agents, run: { id: heartbeatRuns.id, @@ -1239,6 +1239,7 @@ export class PaperclipRunnerToolAuthority { then ${heartbeatRuns.contextSnapshot} - array['executionContinuation', 'paperclipTaskMarkdown', 'paperclipTaskMarkdownCompact', 'paperclipTaskMarkdownAssignment', 'paperclipTaskMarkdownAssignmentCompact', 'paperclipWorkspace', 'paperclipEnvironment', 'paperclipContinuationSummary', 'paperclipWakeComment'] + ${options.includeChatWake ? sql`` : sql`- 'paperclipWake'`} else ${heartbeatRuns.contextSnapshot} end`, resultJson: heartbeatRuns.resultJson, } }) From 6aa711f6c67101252961c1715baafb1bbd88e62f Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Sun, 25 Oct 2026 06:04:09 -0700 Subject: [PATCH 059/110] fix(ui): avoid broad task refreshes after known run progress (#17602) Use the existing live-status cache patch result to skip redundant task and history reads. Keep unknown-run discovery, lifecycle, activity, visibility, and reconnect recovery. Verified with full build and typecheck, 9,047 UI tests, final context tests and counterfactual broad-refetch and missing-fallback failures, complete exact-head CI, and Greptile 5/5 Medium with no unresolved comments. Co-Authored-By: Paperclip --- doc/DATABASE.md | 5 ++ ui/src/context/LiveUpdatesProvider.test.ts | 63 ++++++++++++++++++++++ ui/src/context/LiveUpdatesProvider.tsx | 19 +++---- 3 files changed, 78 insertions(+), 9 deletions(-) diff --git a/doc/DATABASE.md b/doc/DATABASE.md index 9e432cbfcc0..10e7bc7a1e6 100644 --- a/doc/DATABASE.md +++ b/doc/DATABASE.md @@ -140,6 +140,11 @@ authority once. Different task bindings must both pass. The batch is discarded after that delivery; later events still recheck grants, membership, task existence, and company boundaries. +Browser progress events update cached live run status directly. A successful +patch does not refetch task details, activity, or run history. Unknown runs +retain the existing refresh fallback. Run transitions, activity events, and +reconnect recovery still refresh their affected data. + Connection-assignment checks select profile bindings for the current company or agent and read rules that can match the selected connection's catalog rows. All five selector kinds, null application matching, exclusions, and profile diff --git a/ui/src/context/LiveUpdatesProvider.test.ts b/ui/src/context/LiveUpdatesProvider.test.ts index f4f09a518b6..3fc05666db8 100644 --- a/ui/src/context/LiveUpdatesProvider.test.ts +++ b/ui/src/context/LiveUpdatesProvider.test.ts @@ -268,6 +268,69 @@ describe("LiveUpdatesProvider issue invalidation", () => { }); }); + it("patches progress without refetching visible task history but refreshes actual activity and terminal runs", async () => { + vi.stubGlobal("document", { visibilityState: "visible" }); + const client = new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity } } }); + const issue = { id: "issue-1", identifier: "DEMO-1", companyId: "company-1", assigneeAgentId: "agent-1", executionRunId: "run-1" }; + const run = { id: "run-1", agentId: "agent-1", status: "running" }; + const snapshots = [ + [queryKeys.issues.detail("DEMO-1"), issue], + [queryKeys.issues.activity("DEMO-1"), []], + [queryKeys.issues.runs("DEMO-1"), [{ runId: "run-1" }]], + [queryKeys.issues.liveRuns("DEMO-1"), [run]], + [queryKeys.issues.activeRun("DEMO-1"), run], + [queryKeys.issues.comments("DEMO-1"), { pages: [[]], pageParams: [null] }], + ] as const; + const readers = snapshots.map(() => vi.fn(async () => undefined as unknown)); + const observers = snapshots.map(([queryKey, data], index) => { + client.setQueryData(queryKey, data); + readers[index].mockResolvedValue(data); + return new QueryObserver(client, { queryKey, queryFn: readers[index], staleTime: Infinity }); + }); + const unsubscribe = observers.map(observer => observer.subscribe(() => {})); + const gate = { cooldownHits: new Map(), suppressUntil: 0, observedRunOutcomes: new Set() }; + const deliver = (event: Parameters[3]) => + __liveUpdatesTestUtils.handleLiveEvent(client, "company-1", "/DEMO/issues/DEMO-1", event, () => null, gate, + { userId: "viewer", agentId: null }); + try { + for (let id = 1; id <= 3; id++) { + deliver({ id, companyId: "company-1", type: "heartbeat.run.progress", createdAt: "2020-01-01T00:00:00Z", + payload: { runId: "run-1", issueId: "issue-1", agentId: "agent-1", phase: "working", message: `Step ${id}`, + currentToolName: "read_task", updatedAt: "2020-01-01T00:00:00Z" } }); + } + await Promise.resolve(); + expect(readers.map(reader => reader.mock.calls.length)).toEqual([0, 0, 0, 0, 0, 0]); + expect(client.getQueryData(queryKeys.issues.activeRun("DEMO-1"))).toMatchObject({ currentStatusMessage: "Step 3", currentToolName: "read_task" }); + expect(client.getQueryData(queryKeys.issues.liveRuns("DEMO-1"))).toMatchObject([{ currentStatusMessage: "Step 3" }]); + deliver({ id: 4, companyId: "company-1", type: "heartbeat.run.progress", createdAt: "2020-01-01T00:00:01Z", + payload: { runId: "unknown-run", issueId: "issue-1", agentId: "agent-1", message: "New run" } }); + await vi.waitFor(() => { + expect(readers.slice(0, 5).every(reader => reader.mock.calls.length > 0)).toBe(true); + expect(client.isFetching()).toBe(0); + }); + readers.forEach(reader => reader.mockClear()); + deliver({ id: 5, companyId: "company-1", type: "activity.logged", createdAt: "2020-01-01T00:00:02Z", + payload: { entityType: "issue", entityId: "issue-1", action: "issue.comment_added", actorType: "user", actorId: "another-viewer" } }); + await vi.waitFor(() => { + expect(readers[1]).toHaveBeenCalled(); + expect(readers[5]).toHaveBeenCalled(); + expect(client.isFetching()).toBe(0); + }); + readers.forEach(reader => reader.mockClear()); + deliver({ id: 6, companyId: "company-1", type: "heartbeat.run.status", createdAt: "2020-01-01T00:00:03Z", + payload: { runId: "run-1", issueId: "issue-1", agentId: "agent-1", status: "succeeded" } }); + await vi.waitFor(() => { + expect(readers.every(reader => reader.mock.calls.length > 0)).toBe(true); + expect(client.isFetching()).toBe(0); + }); + } finally { + unsubscribe.forEach(stop => stop()); + observers.forEach(observer => observer.destroy()); + client.clear(); + vi.unstubAllGlobals(); + } + }); + it("applies heartbeat progress payloads directly to cached visible issue runs", () => { const cache = new Map([ [JSON.stringify(queryKeys.liveRuns("company-1")), [{ id: "run-1", currentStatusMessage: null }]], diff --git a/ui/src/context/LiveUpdatesProvider.tsx b/ui/src/context/LiveUpdatesProvider.tsx index 48e318d5b0e..5f634a8cdde 100644 --- a/ui/src/context/LiveUpdatesProvider.tsx +++ b/ui/src/context/LiveUpdatesProvider.tsx @@ -1791,14 +1791,14 @@ function handleLiveEvent( event.createdAt, event.type, ); - if (liveStatusPatch) { - applyRunLiveStatusPatchToCaches( - queryClient, - expectedCompanyId, - pathname, - liveStatusPatch, - ); - } + const liveStatusPatched = liveStatusPatch + ? applyRunLiveStatusPatchToCaches( + queryClient, + expectedCompanyId, + pathname, + liveStatusPatch, + ) + : false; if (event.type === "heartbeat.run.log") { return; } @@ -1831,7 +1831,7 @@ function handleLiveEvent( if (event.type === "heartbeat.run.progress") { invalidateHeartbeatProgressQueries(queryClient, expectedCompanyId, payload); - invalidateVisibleIssueRunQueries(queryClient, pathname, payload); + if (!liveStatusPatched) invalidateVisibleIssueRunQueries(queryClient, pathname, payload); return; } @@ -1942,6 +1942,7 @@ export const __liveUpdatesTestUtils = { buildRunStatusToast, closeSocketQuietly, dispatchLiveEventToSubscribers, + handleLiveEvent, LiveEventSubscriptionContext, applyRunLiveStatusPatchToCaches, hydrateVisibleIssueComment, From 3536b3649f98155d92b45cfb5dc3abcc2fea97d6 Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Sun, 25 Oct 2026 06:30:25 -0700 Subject: [PATCH 060/110] Read only task creation provenance fields (#17604) Narrow saved-run provenance reads to current identity, scope, and typed legacy bindings. Preserve binding precedence, current viewer checks, and complete stored runs. Real PostgreSQL and route tests pass 23 cases; legacy full-context and type-coercion regressions are caught. Exact-head required CI is green; Greptile is 5/5 with Low impact and no unresolved comments. Co-Authored-By: Paperclip --- doc/DATABASE.md | 5 + .../issue-creation-source-read.test.ts | 109 ++++++++++++++++++ server/src/services/issue-creation-source.ts | 24 +++- 3 files changed, 135 insertions(+), 3 deletions(-) create mode 100644 server/src/__tests__/issue-creation-source-read.test.ts diff --git a/doc/DATABASE.md b/doc/DATABASE.md index 10e7bc7a1e6..c4d5c72e41e 100644 --- a/doc/DATABASE.md +++ b/doc/DATABASE.md @@ -162,6 +162,11 @@ startup and cancellation receipts, task binding, and the recorded adapter kind. Saved profiles, output excerpts, and unrelated launch context stay in storage. Continuation admission and its locked mutation reads retain their existing gates. +Task creation provenance reads current run identity, scope, and task binding. +Legacy task references retain their typed values and existing precedence. Saved +profiles, output, and unrelated context stay in storage. Viewer access to the +source task and run is still checked before provenance is returned. + The initial agent JWT run lookup reads only the cancellation state and conversation flag from saved run JSON. It does not transfer the full context or result. Run status, responsible-user identity, company and agent boundaries, diff --git a/server/src/__tests__/issue-creation-source-read.test.ts b/server/src/__tests__/issue-creation-source-read.test.ts new file mode 100644 index 00000000000..2b47f3af580 --- /dev/null +++ b/server/src/__tests__/issue-creation-source-read.test.ts @@ -0,0 +1,109 @@ +import { randomUUID } from "node:crypto"; +import { activityLog, agents, companies, createDb, heartbeatRuns, issues } from "@paperclipai/db"; +import { createDatabaseResponseCapture, installDatabaseResponseCapture } from "@paperclipai/db/response-capture"; +import { eq } from "drizzle-orm"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; +import { resolveIssueCreationSource, runBoundIssueReference } from "../services/issue-creation-source.js"; + +const support = await getEmbeddedPostgresTestSupport(); + +describe.skipIf(!support.supported)("creation source run projections", () => { + const companyId = randomUUID(), otherCompanyId = randomUUID(), agentId = randomUUID(); + const sourceId = randomUUID(), secondId = randomUUID(), foreignId = randomUUID(); + let database: Awaited>; + let db: ReturnType; + let childNumber = 100; + + beforeAll(async () => { + database = await startEmbeddedPostgresTestDatabase("creation-source-read-"); + db = createDb(database.connectionString); + await db.insert(companies).values([ + { id: companyId, name: "Creation source fixture", issuePrefix: "CSR" }, + { id: otherCompanyId, name: "Foreign source fixture", issuePrefix: "FSR" }, + ]); + await db.insert(agents).values({ id: agentId, companyId, name: "Source agent", adapterType: "process" }); + await db.insert(issues).values([ + { id: sourceId, companyId, title: "Source task", identifier: "CSR-1", issueNumber: 1 }, + { id: secondId, companyId, title: "Second source task", identifier: "CSR-2", issueNumber: 2 }, + { id: foreignId, companyId: otherCompanyId, title: "Foreign task", identifier: "FSR-1", issueNumber: 1 }, + ]); + }, 60_000); + + afterAll(async () => { + await db?.$client.end(); + await database?.cleanup(); + }); + + async function fixture(values: Partial) { + const [run] = await db.insert(heartbeatRuns).values({ companyId, agentId, status: "succeeded", ...values }).returning(); + const number = childNumber++; + const [child] = await db.insert(issues).values({ companyId, title: "Created task", identifier: `CSR-${number}`, + issueNumber: number, originRunId: run.id }).returning(); + return { run, child }; + } + + it.each(["scoped", "legacy task key", "legacy nested identifier"])("omits saved run payloads for %s bindings while preserving provenance and storage", async (binding) => { + const bulk = "retained-source-context🙂".repeat(32_768); + const contextSnapshot = binding === "scoped" + ? { issueId: sourceId, paperclipIssue: { id: sourceId, retainedDescription: bulk }, retainedLaunchInput: bulk } + : binding === "legacy task key" + ? { taskKey: "CSR-1", paperclipIssue: { retainedDescription: bulk }, retainedLaunchInput: bulk } + : { paperclipIssue: { id: "CSR-1", retainedDescription: bulk }, retainedLaunchInput: bulk }; + const { run, child } = await fixture({ contextSnapshot, + runnerProfileJson: { retainedInput: bulk }, stdoutExcerpt: bulk, stderrExcerpt: bulk, resultJson: { retainedReceipt: bulk } }); + expect(run.issueId).toBe(binding === "scoped" ? sourceId : null); + expect(run.nativeIssueId).toBeNull(); + const observed = createDb(database.connectionString), events: Array> = [], now = Date.now(); + const capture = createDatabaseResponseCapture({ start: now - 100, end: now + 59_000 }, event => events.push(event)); + installDatabaseResponseCapture(observed, { heartbeatRuns, issues }, capture); + try { + const result = await resolveIssueCreationSource(observed, child); + capture.flush(); + const reads = events.filter(event => event.table === "heartbeat_runs" && event.operation === "select"); + expect(reads.reduce((count, event) => count + Number(event.calls), 0)).toBe(1); + expect(reads.reduce((bytes, event) => bytes + Number(event.responseValueBytes), 0)).toBeLessThan(8192); + expect(result).toMatchObject({ run: { id: run.id, companyId, agentId }, sourceIssue: { id: sourceId } }); + expect(runBoundIssueReference(result!.run)).toBe(binding === "scoped" ? sourceId : "CSR-1"); + for (const key of ["runnerProfileJson", "stdoutExcerpt", "stderrExcerpt", "resultJson"]) expect(result!.run).not.toHaveProperty(key); + expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, run.id)))[0]).toEqual(run); + expect(JSON.stringify(events)).not.toContain("retained-source-context"); + } finally { + capture.flush(); + await observed.$client.end(); + } + }); + + it.each([ + { label: "native identity", nativeIssueId: sourceId, issueId: secondId, contextSnapshot: { issueId: secondId }, expected: sourceId }, + { label: "issue scope", issueId: sourceId, contextSnapshot: { issueId: secondId }, expected: sourceId }, + { label: "legacy issue id", contextSnapshot: { issueId: sourceId, taskId: secondId }, expected: sourceId }, + { label: "typed task id fallback", contextSnapshot: { issueId: 42, taskId: sourceId }, expected: sourceId }, + { label: "nested issue identifier", contextSnapshot: { issueId: " ", paperclipIssue: { id: "CSR-1", ignored: "payload" }, taskKey: "CSR-2" }, expected: sourceId }, + { label: "typed nested id fallback", contextSnapshot: { paperclipIssue: { id: 42 }, taskKey: "CSR-1" }, expected: sourceId }, + { label: "foreign context", contextSnapshot: { taskId: foreignId }, expected: null }, + { label: "null context", contextSnapshot: null, expected: null }, + ])("preserves binding precedence for $label", async ({ label: _label, expected, ...values }) => { + const { child } = await fixture(values); + expect((await resolveIssueCreationSource(db, child))?.sourceIssue.id ?? null).toBe(expected); + }); + + it.each([42, "scalar", ["issueId", sourceId]])("does not invent a task binding from malformed context %j", async (context) => { + const { child } = await fixture({ contextSnapshot: context as unknown as Record }); + expect(await resolveIssueCreationSource(db, child)).toBeNull(); + }); + + it("preserves historical activity lookup, current bindings, and missing or foreign source denial", async () => { + const { run, child } = await fixture({ contextSnapshot: { taskKey: "CSR-1" } }); + await db.update(issues).set({ originRunId: null }).where(eq(issues.id, child.id)); + await db.insert(activityLog).values({ companyId, actorType: "system", actorId: "fixture", action: "issue.created", + entityType: "issue", entityId: child.id, runId: run.id }); + expect((await resolveIssueCreationSource(db, { ...child, originRunId: null }))?.sourceIssue.id).toBe(sourceId); + await db.update(heartbeatRuns).set({ contextSnapshot: { taskKey: "CSR-2" } }).where(eq(heartbeatRuns.id, run.id)); + expect((await resolveIssueCreationSource(db, child))?.sourceIssue.id).toBe(secondId); + expect(await resolveIssueCreationSource(db, { ...child, companyId: otherCompanyId })).toBeNull(); + expect(await resolveIssueCreationSource(db, { ...child, originRunId: randomUUID() })).toBeNull(); + await db.update(heartbeatRuns).set({ contextSnapshot: { taskId: child.id } }).where(eq(heartbeatRuns.id, run.id)); + expect(await resolveIssueCreationSource(db, child)).toBeNull(); + }); +}); diff --git a/server/src/services/issue-creation-source.ts b/server/src/services/issue-creation-source.ts index 42f5ce816a7..c40c898fd39 100644 --- a/server/src/services/issue-creation-source.ts +++ b/server/src/services/issue-creation-source.ts @@ -1,14 +1,17 @@ -import { and, asc, eq, inArray, isNotNull } from "drizzle-orm"; +import { and, asc, eq, inArray, isNotNull, sql } from "drizzle-orm"; import type { Db } from "@paperclipai/db"; import { activityLog, agents, heartbeatRuns, issues } from "@paperclipai/db"; import { isUuidLike } from "@paperclipai/shared"; type IssueRow = typeof issues.$inferSelect; type HeartbeatRunRow = typeof heartbeatRuns.$inferSelect; +type CreationSourceRun = Pick & { + contextSnapshot: { issueId: unknown; taskId: unknown; taskKey: unknown; paperclipIssue: { id: unknown } } | null; +}; /** The task a run was executing when it created another task. */ export interface IssueCreationSourceRecord { - run: HeartbeatRunRow; + run: CreationSourceRun; sourceIssue: IssueRow; } @@ -86,7 +89,22 @@ export async function resolveIssueCreationSource( } if (!runId || !isUuidLike(runId)) return null; const [run] = await db - .select() + .select({ + id: heartbeatRuns.id, + companyId: heartbeatRuns.companyId, + agentId: heartbeatRuns.agentId, + scopeKind: heartbeatRuns.scopeKind, + nativeIssueId: heartbeatRuns.nativeIssueId, + issueId: heartbeatRuns.issueId, + contextSnapshot: sql`case + when coalesce(${heartbeatRuns.nativeIssueId}, ${heartbeatRuns.issueId}) is not null then null + else jsonb_build_object( + 'issueId', ${heartbeatRuns.contextSnapshot}->'issueId', + 'taskId', ${heartbeatRuns.contextSnapshot}->'taskId', + 'taskKey', ${heartbeatRuns.contextSnapshot}->'taskKey', + 'paperclipIssue', jsonb_build_object('id', ${heartbeatRuns.contextSnapshot}->'paperclipIssue'->'id') + ) end`, + }) .from(heartbeatRuns) .where(and(eq(heartbeatRuns.id, runId), eq(heartbeatRuns.companyId, issue.companyId))) .limit(1); From aec86c794b207fd7796d9e9281a0f9ffc3e60f72 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sun, 25 Oct 2026 09:01:24 -0500 Subject: [PATCH 061/110] fix(runner): preserve native work through controller outages (#17594) Keep remote native work under its authenticated connection lease through controller outages. Hold durable ACPX tools through reconnection, align the native Claude HTTP MCP client budget, and wait for the recovered handler before dispatch. Preserve Stop, cancellation, exact identity and artifact checks. Verified with real-process regressions and a real Claude Opus 5.5 Daytona workflow: 125 seconds offline during useful work, original process and lease retained, no failed native tool calls, queued follow-up completed, independently verified ZIP and committed workspace receipts. All current-head CI gates pass and Greptile is 5/5 with all findings resolved. Co-Authored-By: Paperclip --- .dockerignore | 1 + doc/evals.md | 6 + doc/execution-semantics.md | 24 ++++ packages/paperclip-runner/acpx-profiles.json | 8 +- .../runner-core/src/acpx_provider_backend.rs | 3 +- .../src/generated_acpx_profiles.rs | 4 +- .../tests/native_provider_backend.rs | 2 +- .../scripts/copilot-profile-identity.mjs | 4 +- .../src/cli/acpx-runtime-sidecar.test.ts | 53 +++++++++ .../src/cli/acpx-runtime-sidecar.ts | 12 +- .../control-plane/runner-execution-driver.ts | 4 + .../drivers/acpx/copilot-installation.test.ts | 14 ++- .../src/drivers/acpx/environment.test.ts | 7 ++ .../src/drivers/acpx/environment.ts | 1 + .../src/drivers/acpx/generated-profiles.ts | 8 +- .../src/drivers/acpx/pi-installation.test.ts | 41 ++++--- .../src/drivers/acpx/profile-compatibility.ts | 6 +- .../src/drivers/runner-tool-bridge.test.ts | 21 +++- .../src/drivers/runner-tool-bridge.ts | 16 +-- .../src/live/runnerd-codex-transport.ts | 29 ++++- .../live/runnerd-controller-outage.test.ts | 110 ++++++++++++++++++ ...runnerd-semantic-handler-readiness.test.ts | 54 +++++++++ .../pi-acp/profile-v29-identity.json | 51 ++++++++ .../copilot-profile-v59-identity.json | 85 ++++++++++++++ scripts/pi-public-install-probe.mjs | 4 +- .../native-runtime/native-session-executor.ts | 7 +- tests/runner-e2e/EVERYDAY-WORKFLOWS.md | 13 ++- tests/runner-e2e/README.md | 10 ++ tests/runner-e2e/SECURITY.md | 6 +- tests/runner-e2e/catalog.test.ts | 6 +- tests/runner-e2e/catalog.ts | 14 ++- tests/runner-e2e/everyday-flow.ts | 11 +- .../everyday-remote-restart.test.ts | 20 +++- tests/runner-e2e/everyday-remote-restart.ts | 22 +++- tests/runner-e2e/live-fixtures.ts | 4 +- tests/runner-e2e/runner.spec.ts | 6 +- tests/runner-e2e/server.ts | 16 ++- 37 files changed, 628 insertions(+), 75 deletions(-) create mode 100644 packages/paperclip-runner/src/live/runnerd-controller-outage.test.ts create mode 100644 packages/paperclip-runner/src/live/runnerd-semantic-handler-readiness.test.ts create mode 100644 packages/paperclip-runner/test-fixtures/pi-acp/profile-v29-identity.json create mode 100644 packages/paperclip-runner/test/fixtures/copilot-profile-v59-identity.json diff --git a/.dockerignore b/.dockerignore index 83ef4daeb0d..3bf8e79b7b1 100644 --- a/.dockerignore +++ b/.dockerignore @@ -88,6 +88,7 @@ packages/grok-acp/bin !packages/paperclip-runner/test-fixtures/pi-acp/profile-v27-identity.json !packages/paperclip-runner/test-fixtures/pi-acp/profile-v28-identity.json +!packages/paperclip-runner/test-fixtures/pi-acp/profile-v29-identity.json !packages/paperclip-runner/test/fixtures/copilot-profile-v23-identity.json diff --git a/doc/evals.md b/doc/evals.md index 2c0af7e5ec7..78304500307 100644 --- a/doc/evals.md +++ b/doc/evals.md @@ -1,5 +1,11 @@ # Paperclip evaluation guide +The explicit-only [Daytona restart continuity journey](../tests/runner-e2e/README.md) +extends the existing native restart oracle to a 125-second controller outage, +using the recorded Claude and Codex models in disposable development fixtures. +It requires same-process adoption, saved files and finalization without replay; +local regression checks and catalog discovery are separate from live acceptance. + The explicit-only [GitHub review bot journey](../tests/runner-e2e/GITHUB-REVIEW-JOURNEY.md) converts the Ponytail walkthrough into attended App setup, scoped installation, automatic PR review, and independent two-service checks. It supports attached diff --git a/doc/execution-semantics.md b/doc/execution-semantics.md index b4d63b5687f..52dbcac821e 100644 --- a/doc/execution-semantics.md +++ b/doc/execution-semantics.md @@ -1676,6 +1676,30 @@ waiting for provider startup. An abrupt controller exit during session opening can then recover through the same exact process-identity checks as an active turn. Both graceful and hot restarts detach the old controller from native sessions. +Remote Runner processes use their authenticated connection lease as the bound +on disconnected lifetime. The controller's shorter connection-recovery budget +limits its own attempt; it must not terminate the remote owner while another +controller is starting or classifying runs. Lease expiry still shuts down the +provider, and exact identity, authentication, Stop and revocation checks remain +required before any recovery or new execution. +Native ACPX semantic tool calls wait on their durable PRP invocation across a +controller outage. Their provider-side MCP bridge does not impose a separate +request deadline that could make the provider retry an already queued write. +Runner lease expiry, turn cancellation and bridge closure still end those waits. +Ordinary bridge callers retain their request deadline. Repeating the same call +identity returns its one retained result; it does not execute the operation again. +The native Claude sidecar also sets its HTTP MCP client budget to one hour, +matching the Runner connection lease budget. This prevents Claude's default +60-second HTTP deadline from aborting an otherwise pending durable request. +The setting applies to that native Claude session's MCP client; other provider +sessions and ordinary bridge deadlines remain unchanged. Explicit cancellation +and Runner shutdown still take precedence over that client budget. +An adopted transport can receive authenticated queued semantic calls before +the driver publishes its recovered session and tool handler. It holds those +calls until the handler is installed, then rechecks the original authority and +turn epoch before dispatch. Transport failure, close or controller detachment +ends that wait without invoking a late handler. Missing startup wiring is not +reported to the provider as the result of an external operation. If shutdown begins while a provider session is opening, its eventual publication honors the pending detachment before dispatching a turn. Once detached, an old execution finalizer cannot suspend or signal the durable runner: the next diff --git a/packages/paperclip-runner/acpx-profiles.json b/packages/paperclip-runner/acpx-profiles.json index 6b28b8dad51..fdf1b06255c 100644 --- a/packages/paperclip-runner/acpx-profiles.json +++ b/packages/paperclip-runner/acpx-profiles.json @@ -14,12 +14,12 @@ "requiresProviderPolicy": false }, "pi": { - "agentProfileVersion": 28, + "agentProfileVersion": 29, "agentServerPackage": "pi-acp", "agentServerVersion": "0.0.33", "agentRuntimePackage": "@earendil-works/pi-coding-agent", "agentRuntimeVersion": "1.0.0", - "commandDigest": "sha256:4918a4d5472d66b22b1ec642b68b5c60a8092a39c84ec1ab1c9ad0289cb8c68c", + "commandDigest": "sha256:e80c6dc7bde12790371345ee5a12f0201d30941d26f1a780aec3d090545b2a06", "requiresProviderPolicy": true }, "cursor": { @@ -32,12 +32,12 @@ "requiresProviderPolicy": true }, "copilot": { - "agentProfileVersion": 58, + "agentProfileVersion": 59, "agentServerPackage": "@github/copilot", "agentServerVersion": "1.0.88", "agentRuntimePackage": null, "agentRuntimeVersion": null, - "commandDigest": "sha256:d490dacdab02051d24c84aae49ac6fb12b8226cf8a47b014ec53f3d3a8410a94", + "commandDigest": "sha256:2f39ffe54a6af832d044b5098c31df9e08d4d27aee0ac675ba4b0c9da7445c40", "requiresProviderPolicy": true }, "claude": { diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/acpx_provider_backend.rs b/packages/paperclip-runner/runner/crates/runner-core/src/acpx_provider_backend.rs index c3f53e20b84..212852476cd 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/src/acpx_provider_backend.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/src/acpx_provider_backend.rs @@ -3212,7 +3212,7 @@ mod tests { #[test] fn pi_profile_matches_published_identity_and_rejects_prior_profiles() { let published: Value = serde_json::from_str(include_str!( - "../../../../test-fixtures/pi-acp/profile-v28-identity.json" + "../../../../test-fixtures/pi-acp/profile-v29-identity.json" )) .unwrap(); let mut value = descriptor("codex"); @@ -3229,6 +3229,7 @@ mod tests { current.validate(&context()).unwrap(); for prior in [ + include_str!("../../../../test-fixtures/pi-acp/profile-v28-identity.json"), include_str!("../../../../test-fixtures/pi-acp/profile-v24-identity.json"), include_str!("../../../../test-fixtures/pi-acp/profile-v23-identity.json"), include_str!("../../../../test-fixtures/pi-acp/profile-v15-identity.json"), diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/generated_acpx_profiles.rs b/packages/paperclip-runner/runner/crates/runner-core/src/generated_acpx_profiles.rs index 128ec81306e..eb6c82cefcb 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/src/generated_acpx_profiles.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/src/generated_acpx_profiles.rs @@ -29,7 +29,7 @@ pub(crate) fn acpx_release_profile(agent: &str) -> Option { agent_runtime_package: Some("@earendil-works/pi-coding-agent"), agent_runtime_version: Some("1.0.0"), command_digest: - "sha256:4918a4d5472d66b22b1ec642b68b5c60a8092a39c84ec1ab1c9ad0289cb8c68c", + "sha256:e80c6dc7bde12790371345ee5a12f0201d30941d26f1a780aec3d090545b2a06", requires_provider_policy: true, }, "cursor" => AcpxReleaseProfile { @@ -47,7 +47,7 @@ pub(crate) fn acpx_release_profile(agent: &str) -> Option { agent_runtime_package: None, agent_runtime_version: None, command_digest: - "sha256:d490dacdab02051d24c84aae49ac6fb12b8226cf8a47b014ec53f3d3a8410a94", + "sha256:2f39ffe54a6af832d044b5098c31df9e08d4d27aee0ac675ba4b0c9da7445c40", requires_provider_policy: true, }, "claude" => AcpxReleaseProfile { diff --git a/packages/paperclip-runner/runner/crates/runner-core/tests/native_provider_backend.rs b/packages/paperclip-runner/runner/crates/runner-core/tests/native_provider_backend.rs index 872935a3a03..615a2e74839 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/tests/native_provider_backend.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/tests/native_provider_backend.rs @@ -17,7 +17,7 @@ use sha2::{Digest, Sha256}; const CODEX_ACPX_DIGEST: &str = "sha256:443491f4e814501a5dc47347e4510e84faeec9c9382e2d4e53bfe69386d5aabc"; const PI_ACPX_DIGEST: &str = - "sha256:4918a4d5472d66b22b1ec642b68b5c60a8092a39c84ec1ab1c9ad0289cb8c68c"; + "sha256:e80c6dc7bde12790371345ee5a12f0201d30941d26f1a780aec3d090545b2a06"; fn temporary_directory(label: &str) -> PathBuf { let nonce = SystemTime::now() diff --git a/packages/paperclip-runner/scripts/copilot-profile-identity.mjs b/packages/paperclip-runner/scripts/copilot-profile-identity.mjs index 4d55c9f8367..7f43d83e8af 100644 --- a/packages/paperclip-runner/scripts/copilot-profile-identity.mjs +++ b/packages/paperclip-runner/scripts/copilot-profile-identity.mjs @@ -7,9 +7,9 @@ import { fileURLToPath } from "node:url"; import { resolve, dirname } from "node:path"; const root = resolve(dirname(fileURLToPath(import.meta.url)), ".."); -const fixture = resolve(root, "test/fixtures/copilot-profile-v58-identity.json"); +const fixture = resolve(root, "test/fixtures/copilot-profile-v59-identity.json"); const historical = JSON.parse(readFileSync(resolve(root, "test/fixtures/copilot-profile-v12-identity.json"), "utf8")); -const declaration = { ...historical.declaration, agentProfileVersion: 58 }; +const declaration = { ...historical.declaration, agentProfileVersion: 59 }; delete declaration.permissionIdentitySourceSha256; const sources = { displayEventSourceSha256: "src/drivers/acpx/copilot-events.ts", diff --git a/packages/paperclip-runner/src/cli/acpx-runtime-sidecar.test.ts b/packages/paperclip-runner/src/cli/acpx-runtime-sidecar.test.ts index 62dc7e15321..28a0c5814b2 100644 --- a/packages/paperclip-runner/src/cli/acpx-runtime-sidecar.test.ts +++ b/packages/paperclip-runner/src/cli/acpx-runtime-sidecar.test.ts @@ -12,6 +12,7 @@ import { createHash, randomUUID } from "node:crypto"; import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process"; import { readFileSync } from "node:fs"; import { fileURLToPath } from "node:url"; +import { createAcpxSidecarHostEnvironment, createSanitizedAcpxSpawnInput } from "../drivers/acpx/environment.js"; import { afterEach, describe, expect, it, vi } from "vitest"; @@ -93,6 +94,22 @@ afterEach(async () => { }); describe("qualified ACPX runtime sidecar", () => { + it("gives native Claude HTTP tools the Runner lease budget without changing sibling providers", () => { + const source = readFileSync(new URL("./acpx-runtime-sidecar.ts", import.meta.url), "utf8"); + const start = source.indexOf(" environment:"); + const end = source.indexOf(" expectedIdentity:", start); + expect(start).toBeGreaterThan(0); expect(end).toBeGreaterThan(start); + const create = new Function("process", "params", "createAcpxSidecarHostEnvironment", `return ({ ${source.slice(start, end)} }).environment;`); + const original = { MCP_TOOL_TIMEOUT: "1000", ANTHROPIC_API_KEY: "selected-key", UNRELATED_SECRET: "private" }; + const claude = create({ env: original }, { agent: "claude", normalizedSessionId: "session" }, createAcpxSidecarHostEnvironment); + expect(createSanitizedAcpxSpawnInput(claude, "claude").env).toMatchObject({ MCP_TOOL_TIMEOUT: "3600000", ANTHROPIC_API_KEY: "selected-key" }); + expect(createSanitizedAcpxSpawnInput(claude, "claude").env).not.toHaveProperty("UNRELATED_SECRET"); + expect(original.MCP_TOOL_TIMEOUT).toBe("1000"); + const codex = create({ env: original }, { agent: "codex", normalizedSessionId: "session" }, createAcpxSidecarHostEnvironment); + expect(codex).toBe(original); + expect(createSanitizedAcpxSpawnInput(codex, "codex").env).not.toHaveProperty("MCP_TOOL_TIMEOUT"); + }); + it("projects the actual sidecar terminal diagnostic block without authoritative accounting", () => { const source = readFileSync(new URL("./acpx-runtime-sidecar.ts", import.meta.url), "utf8"); const start = source.indexOf(" try {", source.indexOf(" const usageAfter = await readSidecarHostStatusWithin(activeHost);")); @@ -279,6 +296,42 @@ describe("qualified ACPX runtime sidecar", () => { for (const agent of ["cursor", "codex", "pi"]) expect(create({ agent, tools: [] }, evidence, () => undefined).captureSemanticReceipt).toBeUndefined(); }); + it("keeps a native tool pending through controller downtime without a duplicate side effect", async () => { + const source = readFileSync(new URL("./acpx-runtime-sidecar.ts", import.meta.url), "utf8"); + const start = source.indexOf(" semanticTools: {"); + const end = source.indexOf(" onGoalUpdate:", start); + expect(start).toBeGreaterThan(0); expect(end).toBeGreaterThan(start); + const create = new Function("params", "activeCopilotEvidence", "waitForTool", `return ({ ${source.slice(start, end)} }).semanticTools;`); + let admitted!: () => void, complete!: (value: unknown) => void; + const started = new Promise(resolve => { admitted = resolve; }); + const result = new Promise(resolve => { complete = resolve; }); + let signal: AbortSignal | undefined; + const handler = vi.fn((call: RunnerToolCall) => { signal = call.signal; admitted(); return result; }); + const bridge = await startRunnerToolBridge(create({ agent: "claude", tools: [{ name: "register_deliverable", inputSchema: { type: "object" } }] }, undefined, handler)); + const call = () => fetch(bridge.url, { method: "POST", headers: { Authorization: `Bearer ${bridge.secret}`, "Content-Type": "application/json" }, + body: JSON.stringify({ jsonrpc: "2.0", id: "saved-call", method: "tools/call", params: { name: "register_deliverable", arguments: {} } }) }).then(response => response.json()); + let first: Promise | undefined; + try { + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); + first = call(); + await started; + await vi.advanceTimersByTimeAsync(125_000); + expect(signal?.aborted).toBe(false); + // The same pending invocation can be read again after reconnect. It must + // share the original result rather than create another external write. + const duplicate = call(); + complete({ artifactId: "saved-artifact" }); + expect(await first).toMatchObject({ result: { content: [{ text: '{"artifactId":"saved-artifact"}' }] } }); + expect(await duplicate).toEqual(await first); + expect(handler).toHaveBeenCalledOnce(); + } finally { + complete({ artifactId: "saved-artifact" }); + await first?.catch(() => undefined); + await bridge.close(); + vi.useRealTimers(); + } + }); + it.each(["forwarded", "emit-failed"])("binds native v2 receipts to actual sidecar-normalized input: %s", async mode => { const raw = { reportedWorkDisposition: "done", summary: "Complete", evidence: [], verification: [], completionClaim: { contractRevision: "1", objectiveSatisfied: true, criteria: [], remainingWork: [] } }; diff --git a/packages/paperclip-runner/src/cli/acpx-runtime-sidecar.ts b/packages/paperclip-runner/src/cli/acpx-runtime-sidecar.ts index 2b728b2027e..bc1ffb523c3 100644 --- a/packages/paperclip-runner/src/cli/acpx-runtime-sidecar.ts +++ b/packages/paperclip-runner/src/cli/acpx-runtime-sidecar.ts @@ -305,12 +305,22 @@ async function dispatch( providerPolicy: params.providerPolicy, systemInstructions: params.systemInstructions, runtimeContext: params.runtimeContext, - environment: createAcpxSidecarHostEnvironment(process.env, params.agent, params.normalizedSessionId), + environment: params.agent === "claude" ? { + ...createAcpxSidecarHostEnvironment(process.env, params.agent, params.normalizedSessionId), + // Claude's HTTP MCP client otherwise aborts at 60s, before the + // native Runner connection lease. Cancellation and Runner shutdown + // still revoke the pending call; this is not a new authority lease. + MCP_TOOL_TIMEOUT: String(60 * 60 * 1_000), + } : createAcpxSidecarHostEnvironment(process.env, params.agent, params.normalizedSessionId), expectedIdentity: params.expectedIdentity, assignedMcpTransport: "prp", semanticTools: { tools: params.tools, handler: waitForTool, + // These calls are durable PRP requests. A controller outage must not + // turn a queued write into a provider-visible failure and retry. + // Runner lease expiry, turn cancellation and bridge close own them. + timeoutMs: null, ...(params.agent === "copilot" ? { captureSemanticReceipt: () => activeCopilotEvidence?.captureSemanticReceipt() } : {}), }, onGoalUpdate: (goal) => { diff --git a/packages/paperclip-runner/src/control-plane/runner-execution-driver.ts b/packages/paperclip-runner/src/control-plane/runner-execution-driver.ts index 06e94abc778..7a55b20b843 100644 --- a/packages/paperclip-runner/src/control-plane/runner-execution-driver.ts +++ b/packages/paperclip-runner/src/control-plane/runner-execution-driver.ts @@ -47,6 +47,10 @@ export interface RunnerExecutionDriver { }) => Promise>; /** Active-connection recovery budget. Omitted for the existing local mode. */ runnerReconnectGraceMs?: number; + /** Process lifetime while disconnected. Defaults to the active-connection + * recovery budget for compatibility. Null uses the authenticated connection + * lease as the lifetime bound, so controller downtime cannot kill its owner. */ + runnerProcessReconnectGraceMs?: number | null; /** * A verified Runner that outlived its controller. Adoption registers * the durable authority and waits for this exact process to reconnect; it diff --git a/packages/paperclip-runner/src/drivers/acpx/copilot-installation.test.ts b/packages/paperclip-runner/src/drivers/acpx/copilot-installation.test.ts index 6df0af8afb3..8bdf9b3950d 100644 --- a/packages/paperclip-runner/src/drivers/acpx/copilot-installation.test.ts +++ b/packages/paperclip-runner/src/drivers/acpx/copilot-installation.test.ts @@ -87,9 +87,19 @@ vi.mock("./installation-integrity.js", () => ({ verifyNativeAcpxInstallation: vi describe("Copilot build-owned installation", () => { it("admits the current profile with environment launch preparation", () => { - expect(QUALIFIED_ACPX_PROFILES.copilot.agentProfileVersion).toBe(58); + expect(QUALIFIED_ACPX_PROFILES.copilot.agentProfileVersion).toBe(59); expect(QUALIFIED_ACPX_PROFILES.copilot.qualificationStatus).toBeUndefined(); - expect(QUALIFIED_ACPX_PROFILES.copilot.commandDigest).toBe("sha256:d490dacdab02051d24c84aae49ac6fb12b8226cf8a47b014ec53f3d3a8410a94"); + expect(QUALIFIED_ACPX_PROFILES.copilot.commandDigest).toBe("sha256:2f39ffe54a6af832d044b5098c31df9e08d4d27aee0ac675ba4b0c9da7445c40"); + }); + + it("preserves v58 while binding the separate remote process reconnect policy in v59", () => { + const prior = JSON.parse(readFileSync(new URL("../../../test/fixtures/copilot-profile-v58-identity.json", import.meta.url), "utf8")); + const current = JSON.parse(readFileSync(new URL("../../../test/fixtures/copilot-profile-v59-identity.json", import.meta.url), "utf8")); + expect(Object.keys(current.declaration).filter(key => current.declaration[key] !== prior.declaration[key]).sort()).toEqual([ + "agentProfileVersion", "credentialBindingSourceSha256", "nativeInstructionsSourceSha256", "nativeSessionRuntimeSourceSha256", "profileCompatibilitySourceSha256", "runtimeRequestBridgeSourceSha256", "semanticBridgeSourceSha256", "semanticSidecarSourceSha256", "transportContractSourceSha256", + ]); + expect(isSupportedAcpxProfileVersion("copilot", 58)).toBe(true); + expect(current.commandDigest).not.toBe(prior.commandDigest); }); it("preserves v57 while binding the shared Pi setup and launch repairs in v58", () => { diff --git a/packages/paperclip-runner/src/drivers/acpx/environment.test.ts b/packages/paperclip-runner/src/drivers/acpx/environment.test.ts index 3bc038a101e..3c7cdee2fe9 100644 --- a/packages/paperclip-runner/src/drivers/acpx/environment.test.ts +++ b/packages/paperclip-runner/src/drivers/acpx/environment.test.ts @@ -6,6 +6,13 @@ afterEach(() => vi.unstubAllEnvs()); import { ACPX_CREDENTIAL_BINDING_ENV, createAcpxCredentialBinding, createAcpxSidecarHostEnvironment, createSanitizedAcpxSpawnInput } from "./environment.js"; describe("ACPX launch environment", () => { + it("retains an explicit Claude MCP timeout without inheriting an ambient or sibling setting", () => { + vi.stubEnv("MCP_TOOL_TIMEOUT", "999999"); + expect(createSanitizedAcpxSpawnInput(undefined, "claude").env).not.toHaveProperty("MCP_TOOL_TIMEOUT"); + expect(createSanitizedAcpxSpawnInput({ MCP_TOOL_TIMEOUT: "120000" }, "claude").env.MCP_TOOL_TIMEOUT).toBe("120000"); + expect(createSanitizedAcpxSpawnInput({ MCP_TOOL_TIMEOUT: "120000" }, "codex").env).not.toHaveProperty("MCP_TOOL_TIMEOUT"); + }); + it("excludes general IAM from the Pi sidecar and launch, including selected task values", () => { const iam = { AWS_ACCESS_KEY_ID: "general-key", AWS_SECRET_ACCESS_KEY: "general-secret", AWS_SESSION_TOKEN: "general-session" }; const source = { ...iam, ...configuredEnvironmentProjection({ ...iam, CUSTOM_SETTING: "allowed" }), AWS_BEARER_TOKEN_BEDROCK: "provider-key" }; diff --git a/packages/paperclip-runner/src/drivers/acpx/environment.ts b/packages/paperclip-runner/src/drivers/acpx/environment.ts index 1fb79afba46..f11aeacfa08 100644 --- a/packages/paperclip-runner/src/drivers/acpx/environment.ts +++ b/packages/paperclip-runner/src/drivers/acpx/environment.ts @@ -131,6 +131,7 @@ export function createSanitizedAcpxSpawnInput( ...(environment === undefined ? [] : ["PAPERCLIP_AGENT_KEY_ID", "PAPERCLIP_AGENT_PUBLIC_KEY", "PAPERCLIP_AGENT_PRIVATE_KEY"]), ...credentialNames, ...(agent === "claude" ? CLAUDE_ROUTING_ENV_KEYS : []), + ...(agent === "claude" && environment !== undefined ? ["MCP_TOOL_TIMEOUT"] : []), ...(usesPreconfiguredHome(source) ? [...PRECONFIGURED_HOME_KEYS, "PAPERCLIP_RUNNER_HOME_MODE", "ACPX_CLAUDE_INCLUDE_USER_SETTINGS"] : []), ]); let retainedBytes = 0; diff --git a/packages/paperclip-runner/src/drivers/acpx/generated-profiles.ts b/packages/paperclip-runner/src/drivers/acpx/generated-profiles.ts index ca6e53d79d7..36f2bdf29e1 100644 --- a/packages/paperclip-runner/src/drivers/acpx/generated-profiles.ts +++ b/packages/paperclip-runner/src/drivers/acpx/generated-profiles.ts @@ -22,12 +22,12 @@ export const QUALIFIED_ACPX_PROFILE_DATA = { "protocolVersion": 1, "acpxVersion": "0.13.1", "agent": "pi", - "agentProfileVersion": 28, + "agentProfileVersion": 29, "agentServerPackage": "pi-acp", "agentServerVersion": "0.0.33", "agentRuntimePackage": "@earendil-works/pi-coding-agent", "agentRuntimeVersion": "1.0.0", - "commandDigest": "sha256:4918a4d5472d66b22b1ec642b68b5c60a8092a39c84ec1ab1c9ad0289cb8c68c", + "commandDigest": "sha256:e80c6dc7bde12790371345ee5a12f0201d30941d26f1a780aec3d090545b2a06", "permissionPolicy": "interactive" }, "cursor": { @@ -48,12 +48,12 @@ export const QUALIFIED_ACPX_PROFILE_DATA = { "protocolVersion": 1, "acpxVersion": "0.13.1", "agent": "copilot", - "agentProfileVersion": 58, + "agentProfileVersion": 59, "agentServerPackage": "@github/copilot", "agentServerVersion": "1.0.88", "agentRuntimePackage": null, "agentRuntimeVersion": null, - "commandDigest": "sha256:d490dacdab02051d24c84aae49ac6fb12b8226cf8a47b014ec53f3d3a8410a94", + "commandDigest": "sha256:2f39ffe54a6af832d044b5098c31df9e08d4d27aee0ac675ba4b0c9da7445c40", "permissionPolicy": "interactive" }, "claude": { diff --git a/packages/paperclip-runner/src/drivers/acpx/pi-installation.test.ts b/packages/paperclip-runner/src/drivers/acpx/pi-installation.test.ts index 7695e64219c..8d81addb3cf 100644 --- a/packages/paperclip-runner/src/drivers/acpx/pi-installation.test.ts +++ b/packages/paperclip-runner/src/drivers/acpx/pi-installation.test.ts @@ -155,11 +155,20 @@ describe("Pi installation factory", () => { expect(current.commandDigest).not.toBe(prior.commandDigest); }); + it("preserves profile 28 while binding the Claude-only explicit MCP client budget source in profile 29", async () => { + const read = async (version: number) => JSON.parse(await readFile(new URL(`../../../test-fixtures/pi-acp/profile-v${version}-identity.json`, import.meta.url), "utf8")); + const prior = await read(28), current = await read(29); + expect(Object.keys(current.declaration).filter(key => JSON.stringify(current.declaration[key]) !== JSON.stringify(prior.declaration[key])).sort()) + .toEqual(["agentProfileVersion", "credentialEnvironmentSourceSha256"]); + expect(current.declaration.closure).toEqual(prior.declaration.closure); + expect(current.commandDigest).not.toBe(prior.commandDigest); + }); + it("binds the profile declaration to the reviewed patch and platform closure pins", async () => { const hash = (bytes: string | Uint8Array) => createHash("sha256").update(bytes).digest("hex"); const canonical = (value: any): string => Array.isArray(value) ? `[${value.map(canonical).join(",")}]` : value && typeof value === "object" ? `{${Object.keys(value).sort().map(key => `${JSON.stringify(key)}:${canonical(value[key])}`).join(",")}}` : JSON.stringify(value); - const identity = JSON.parse(await readFile(new URL("../../../test-fixtures/pi-acp/profile-v28-identity.json", import.meta.url), "utf8")); + const identity = JSON.parse(await readFile(new URL("../../../test-fixtures/pi-acp/profile-v29-identity.json", import.meta.url), "utf8")); const declaration = identity.declaration; expect(declaration.sharedRuntimeContract).toBe("paperclip.acpx-runtime-contract.v1"); expect(identity.commandDigest).toBe(`sha256:${hash(canonical(declaration))}`); @@ -190,21 +199,21 @@ describe("Pi installation factory", () => { it("rejects legacy profiles and tampered executable identities", () => { expect(() => assertPiInstallationProfile(candidate())).not.toThrow(); - expect(() => assertPiInstallationProfile({ ...candidate(), agentProfileVersion: 1 })).toThrow("version 28"); - expect(() => assertPiInstallationProfile({ ...candidate(), agentProfileVersion: 2 })).toThrow("version 28"); - expect(() => assertPiInstallationProfile({ ...candidate(), agentProfileVersion: 3 })).toThrow("version 28"); - expect(() => assertPiInstallationProfile({ ...candidate(), agentProfileVersion: 4 })).toThrow("version 28"); - expect(() => assertPiInstallationProfile({ ...candidate(), agentProfileVersion: 5 })).toThrow("version 28"); - expect(() => assertPiInstallationProfile({ ...candidate(), agentProfileVersion: 6 })).toThrow("version 28"); - expect(() => assertPiInstallationProfile({ ...candidate(), agentProfileVersion: 7 })).toThrow("version 28"); - expect(() => assertPiInstallationProfile({ ...candidate(), agentProfileVersion: 8 })).toThrow("version 28"); - expect(() => assertPiInstallationProfile({ ...candidate(), agentProfileVersion: 9 })).toThrow("version 28"); - expect(() => assertPiInstallationProfile({ ...candidate(), agentProfileVersion: 10 })).toThrow("version 28"); - expect(() => assertPiInstallationProfile({ ...candidate(), agentProfileVersion: 11 })).toThrow("version 28"); - expect(() => assertPiInstallationProfile({ ...candidate(), agentProfileVersion: 12 })).toThrow("version 28"); - expect(() => assertPiInstallationProfile({ ...candidate(), agentProfileVersion: 13 })).toThrow("version 28"); - expect(() => assertPiInstallationProfile({ ...candidate(), agentProfileVersion: 14 })).toThrow("version 28"); - for (const priorVersion of [15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27]) expect(() => assertPiInstallationProfile({ ...candidate(), agentProfileVersion: priorVersion })).toThrow("version 28"); + expect(() => assertPiInstallationProfile({ ...candidate(), agentProfileVersion: 1 })).toThrow("version 29"); + expect(() => assertPiInstallationProfile({ ...candidate(), agentProfileVersion: 2 })).toThrow("version 29"); + expect(() => assertPiInstallationProfile({ ...candidate(), agentProfileVersion: 3 })).toThrow("version 29"); + expect(() => assertPiInstallationProfile({ ...candidate(), agentProfileVersion: 4 })).toThrow("version 29"); + expect(() => assertPiInstallationProfile({ ...candidate(), agentProfileVersion: 5 })).toThrow("version 29"); + expect(() => assertPiInstallationProfile({ ...candidate(), agentProfileVersion: 6 })).toThrow("version 29"); + expect(() => assertPiInstallationProfile({ ...candidate(), agentProfileVersion: 7 })).toThrow("version 29"); + expect(() => assertPiInstallationProfile({ ...candidate(), agentProfileVersion: 8 })).toThrow("version 29"); + expect(() => assertPiInstallationProfile({ ...candidate(), agentProfileVersion: 9 })).toThrow("version 29"); + expect(() => assertPiInstallationProfile({ ...candidate(), agentProfileVersion: 10 })).toThrow("version 29"); + expect(() => assertPiInstallationProfile({ ...candidate(), agentProfileVersion: 11 })).toThrow("version 29"); + expect(() => assertPiInstallationProfile({ ...candidate(), agentProfileVersion: 12 })).toThrow("version 29"); + expect(() => assertPiInstallationProfile({ ...candidate(), agentProfileVersion: 13 })).toThrow("version 29"); + expect(() => assertPiInstallationProfile({ ...candidate(), agentProfileVersion: 14 })).toThrow("version 29"); + for (const priorVersion of [15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28]) expect(() => assertPiInstallationProfile({ ...candidate(), agentProfileVersion: priorVersion })).toThrow("version 29"); for (const changed of [{ agentServerVersion: "latest" }, { commandDigest: `sha256:${"0".repeat(64)}` }, { agentRuntimePackage: "ambient-pi" }]) { expect(() => assertPiInstallationProfile({ ...candidate(), ...changed })).toThrow("trusted declaration"); } diff --git a/packages/paperclip-runner/src/drivers/acpx/profile-compatibility.ts b/packages/paperclip-runner/src/drivers/acpx/profile-compatibility.ts index 1119594c0ed..56a5878aa39 100644 --- a/packages/paperclip-runner/src/drivers/acpx/profile-compatibility.ts +++ b/packages/paperclip-runner/src/drivers/acpx/profile-compatibility.ts @@ -2,13 +2,13 @@ import { QUALIFIED_ACPX_PROFILE_DATA } from "./generated-profiles.js"; /** Decodable historical profile revisions, not permission to launch them. * Exact current profile/package/digest admission is checked separately. */ -type HistoricalAcpxProfileVersion = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57; +type HistoricalAcpxProfileVersion = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58; type CurrentAcpxProfileVersion = typeof QUALIFIED_ACPX_PROFILE_DATA[keyof typeof QUALIFIED_ACPX_PROFILE_DATA]["agentProfileVersion"]; export type AcpxProfileVersion = HistoricalAcpxProfileVersion | CurrentAcpxProfileVersion; const historicalVersions: Readonly> = { - pi: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27], claude: [1, 2, 3, 4, 5], codex: [1, 2, 3, 4, 5], - grok: [1, 2, 3, 4, 5], copilot: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57], + pi: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28], claude: [1, 2, 3, 4, 5], codex: [1, 2, 3, 4, 5], + grok: [1, 2, 3, 4, 5], copilot: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58], cursor: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], }; diff --git a/packages/paperclip-runner/src/drivers/runner-tool-bridge.test.ts b/packages/paperclip-runner/src/drivers/runner-tool-bridge.test.ts index 152b8a9b6ea..4b212476c49 100644 --- a/packages/paperclip-runner/src/drivers/runner-tool-bridge.test.ts +++ b/packages/paperclip-runner/src/drivers/runner-tool-bridge.test.ts @@ -246,7 +246,7 @@ describe("runner semantic MCP bridge", () => { }); }); - it("honors MCP cancellation after the handler starts", async () => { + it.each([60_000, null])("honors MCP cancellation after the handler starts (timeout=%s)", async timeoutMs => { let markStarted!: () => void; const started = new Promise((resolve) => { markStarted = resolve; @@ -254,7 +254,7 @@ describe("runner semantic MCP bridge", () => { const aborted = vi.fn(); const bridge = await startRunnerToolBridge({ tools: [tool("documents.read")], - timeoutMs: 60_000, + timeoutMs, handler: ({ signal }) => new Promise((_resolve, reject) => { signal.addEventListener("abort", () => { aborted(); @@ -291,6 +291,23 @@ describe("runner semantic MCP bridge", () => { expect(aborted).toHaveBeenCalledOnce(); }); + it("cancels a lease-owned native tool when its bridge closes", async () => { + let admitted!: () => void; + const started = new Promise(resolve => { admitted = resolve; }); + let signal: AbortSignal | undefined; + const bridge = await startRunnerToolBridge({ tools: [tool("documents.read")], timeoutMs: null, + handler: call => { signal = call.signal; admitted(); return new Promise(() => {}); }, + }); + bridges.push(bridge); + const pending = rpc(bridge, { id: "close-me", method: "tools/call", params: { name: "documents.read", arguments: {} } }); + await started; + await bridge.close(); + expect(signal?.aborted).toBe(true); + expect(await (await pending).json()).toMatchObject({ result: { isError: true, + content: [{ text: "Paperclip tool call cancelled" }], + } }); + }); + it("preserves successful mutation identity when the result is oversized", async () => { const result = { text: `snowman-${"☃".repeat(65 * 1024)}` }; const handler = vi.fn(async () => result); diff --git a/packages/paperclip-runner/src/drivers/runner-tool-bridge.ts b/packages/paperclip-runner/src/drivers/runner-tool-bridge.ts index 3a82d69d209..624569fa195 100644 --- a/packages/paperclip-runner/src/drivers/runner-tool-bridge.ts +++ b/packages/paperclip-runner/src/drivers/runner-tool-bridge.ts @@ -45,7 +45,9 @@ export interface RunnerToolBridgeOptions { handler(call: RunnerToolCall): Promise; /** Copilot-only opt-in; capture the active invocation scope before dispatch. */ captureSemanticReceipt?: () => ((receipt: SemanticToolReceipt) => void) | undefined; - timeoutMs?: number; + /** Null delegates the wait to an owning durable runtime's lease and close. + * Ordinary callers retain the bounded request timeout. */ + timeoutMs?: number | null; privateToolTimeoutMs?: number; maxBodyBytes?: number; /** Internal test seam; production bounds headers and body reads to 30 seconds. */ @@ -143,7 +145,7 @@ export async function startRunnerToolBridge( controllers, handler: options.handler, captureSemanticReceipt: options.captureSemanticReceipt, - timeoutMs: positiveBoundedInteger( + timeoutMs: options.timeoutMs === null ? null : positiveBoundedInteger( options.timeoutMs, DEFAULT_TIMEOUT_MS, 1, @@ -214,7 +216,7 @@ async function handleRequest( controllers: Map; handler: RunnerToolBridgeOptions["handler"]; captureSemanticReceipt: RunnerToolBridgeOptions["captureSemanticReceipt"]; - timeoutMs: number; + timeoutMs: number | null; privateToolTimeoutMs: number; privateToolNames: ReadonlySet; maxBodyBytes: number; @@ -599,24 +601,24 @@ function closeServer(server: Server): Promise { function withCancellationAndTimeout( promise: Promise, controller: AbortController, - timeoutMs: number, + timeoutMs: number | null, ): Promise { return new Promise((resolve, reject) => { let settled = false; const finish = (callback: () => void) => { if (settled) return; settled = true; - clearTimeout(timer); + if (timer !== undefined) clearTimeout(timer); controller.signal.removeEventListener("abort", onAbort); callback(); }; const onAbort = () => finish(() => reject(new Error("Paperclip tool call cancelled"))); - const timer = setTimeout(() => { + const timer = timeoutMs === null ? undefined : setTimeout(() => { finish(() => reject(new Error("Paperclip tool call timed out"))); controller.abort(); }, timeoutMs); - timer.unref(); + timer?.unref(); controller.signal.addEventListener("abort", onAbort, { once: true }); promise.then( (value) => finish(() => resolve(value)), diff --git a/packages/paperclip-runner/src/live/runnerd-codex-transport.ts b/packages/paperclip-runner/src/live/runnerd-codex-transport.ts index 21452870d1a..b70954e9aa8 100644 --- a/packages/paperclip-runner/src/live/runnerd-codex-transport.ts +++ b/packages/paperclip-runner/src/live/runnerd-codex-transport.ts @@ -857,6 +857,11 @@ function runnerCloseGraceMs(options: Pick; + #resolveHandlerReady!: () => void; #core: DurablePrpControlPlane | null = null; #handle: RunnerProcessHandle | null = null; #adoptedRunnerMonitor: NodeJS.Timeout | null = null; @@ -3622,6 +3630,9 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { this.#failureSignal = new Promise((_resolve, reject) => { this.#rejectFailureSignal = reject; }); + this.#handlerReady = new Promise(resolve => { + this.#resolveHandlerReady = resolve; + }); this.#closedSignal = new Promise(resolve => { this.#resolveClosedSignal = resolve; }); @@ -3997,6 +4008,8 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { setServerRequestHandler(handler: CodexServerRequestHandler): void { this.#handler = handler; + this.#handlerInstalled = true; + this.#resolveHandlerReady(); } async #awaitWarmRunAttachmentReady(): Promise { @@ -5074,7 +5087,7 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { maxOutboxBytes: RUNNERD_MAX_OUTBOX_BYTES, p0ReserveBytes: RUNNERD_P0_RESERVE_BYTES, maxRuntimeMs: 0, - reconnectGraceMs: this.options.runnerReconnectGraceMs, + reconnectGraceMs: runnerProcessReconnectGraceMs(this.options), lifecyclePolicy: this.options.lifecyclePolicy, runnerBinaryPath, runnerVersion: runnerArtifact.version, @@ -5759,7 +5772,7 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { maxOutboxBytes: RUNNERD_MAX_OUTBOX_BYTES, p0ReserveBytes: RUNNERD_P0_RESERVE_BYTES, maxRuntimeMs: 0, - reconnectGraceMs: this.options.runnerReconnectGraceMs, + reconnectGraceMs: runnerProcessReconnectGraceMs(this.options), lifecyclePolicy: this.options.lifecyclePolicy, runnerBinaryPath, runnerVersion: runnerArtifact.version, @@ -5915,6 +5928,18 @@ class DurablePrpCodexTransport implements CodexAppServerTransport { : await Promise.race([admission.settled, this.#failureSignal]).catch(() => { throw new SemanticToolNotDispatchedError(); }); + // An adopted Runner can authenticate and deliver queued tools before the + // driver has finished reconstructing its session. Handler publication is + // the dispatch barrier; the default RPC diagnostic is not a tool outcome. + // The owning startup/transport lifetime bounds this wait, and the original + // authority/epoch checks below still apply after it becomes ready. + if (!this.#handlerInstalled) { + await Promise.race([ + this.#handlerReady, + this.#failureSignal, + this.#closedSignal.then(() => { throw new SemanticToolNotDispatchedError(); }), + ]).catch(() => { throw new SemanticToolNotDispatchedError(); }); + } try { this.#throwIfFailed(); } catch { diff --git a/packages/paperclip-runner/src/live/runnerd-controller-outage.test.ts b/packages/paperclip-runner/src/live/runnerd-controller-outage.test.ts new file mode 100644 index 00000000000..2988e4845a9 --- /dev/null +++ b/packages/paperclip-runner/src/live/runnerd-controller-outage.test.ts @@ -0,0 +1,110 @@ +import { createServer } from "node:http"; +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { expect, it, vi } from "vitest"; +import type { DurablePrpControlPlane } from "../control-plane/durable-prp-control-plane.js"; +import { codexSemanticToolSpecs } from "../drivers/codex/codex-app-server-driver.js"; +import { + createCapabilityRunnerdCodexTransport, + defaultCapabilityRunnerdBinary, +} from "./runnerd-codex-transport.js"; + +it.each([ + { policy: "connection lease", processGraceMs: null, survives: true }, + { policy: "explicit process deadline", processGraceMs: 500, survives: false }, +])("preserves the $policy policy across controller downtime beyond the connection recovery budget", async ({ processGraceMs, survives }) => { + const root = await mkdtemp(join(tmpdir(), "runner-controller-outage-")); + const server = createServer(); + let authority: DurablePrpControlPlane | null = null; + server.on("upgrade", (request, socket, head) => { + if (!authority) { socket.destroy(); return; } + authority.handleUpgrade(request, socket, "/runner", head); + }); + await new Promise(resolveListen => server.listen(0, "127.0.0.1", resolveListen)); + const address = server.address(); + if (!address || typeof address === "string") throw new Error("Missing outage test listener"); + const registration = async (next: DurablePrpControlPlane) => { + authority = next; + return { + connectUrl: `ws://127.0.0.1:${address.port}/runner`, + release: () => { if (authority === next) authority = null; }, + }; + }; + const shared = { + runnerBinary: defaultCapabilityRunnerdBinary(), + codexCommand: resolve(import.meta.dirname, "../../runner/target/debug/fake-codex-app-server"), + codexArgs: ["--state-file", join(root, "provider-state.json"), "--hold-first-durable-turn"], + stateDirectory: root, + prpIdentity: { + runnerInstanceId: "runner-outage", environmentLeaseId: "lease-outage", runId: "run-outage", + normalizedSessionId: "session-outage", turnId: "turn-outage", itemId: "item-outage", + }, + // Scale the production 120-second reconnect budget down. The live process + // must be bounded by its authenticated connection lease, independently of + // how long a controller spends retrying a connection or booting its server. + runnerReconnectGraceMs: 500, + runnerProcessReconnectGraceMs: processGraceMs, + controlPlaneRegistration: registration, + }; + const first = createCapabilityRunnerdCodexTransport(shared); + let adopted: ReturnType | undefined; + let pid: number | null = null; + try { + const opened = await first.transport.request("thread/start", { + cwd: root, dynamicTools: codexSemanticToolSpecs(), + }); + await first.transport.request("turn/start", { input: [{ type: "text", text: "Keep this task active." }] }); + for await (const notification of first.transport.notifications()) { + if (notification.method === "turn/started") break; + } + pid = first.evidence().runnerPid; + const providerPid = first.evidence().codexPid; + expect(pid).toEqual(expect.any(Number)); + expect(providerPid).toEqual(expect.any(Number)); + await writeFile(join(root, "saved-work.txt"), "completed work survives controller replacement"); + await first.detachControllerForRestart(); + // The deliberate fault is an offline controller, not a slow test assertion. + await new Promise(resolveWait => setTimeout(resolveWait, 1_250)); + const runnerState = JSON.parse(await readFile(join(root, "runner", "runner-state.json"), "utf8")); + if (!survives) { + expect(runnerState.recoverableFailure).toBe("transport_reconnect_grace_exceeded"); + await vi.waitFor(() => expect(() => process.kill(pid!, 0)).toThrow()); + return; + } + expect(runnerState.recoverableFailure).not.toBe("transport_reconnect_grace_exceeded"); + expect(() => process.kill(pid!, 0)).not.toThrow(); + expect(() => process.kill(providerPid!, 0)).not.toThrow(); + const duplicateLaunch = vi.fn(() => { throw new Error("Must adopt the existing runner"); }); + const thread = opened.thread as Record; + adopted = createCapabilityRunnerdCodexTransport({ + ...shared, + runnerReconnectGraceMs: 5_000, + resumeDynamicTools: codexSemanticToolSpecs(), + resumeProviderSession: { driverSessionId: String(thread.id), providerSessionId: String(thread.sessionId) }, + runnerProcessLauncher: duplicateLaunch, + adoptExistingRunner: { + pid: pid!, processGroupId: pid, startedAt: new Date().toISOString(), + isAlive: () => { try { process.kill(pid!, 0); return true; } catch { return false; } }, + signal: signal => { try { process.kill(-pid!, signal); return true; } catch { return false; } }, + }, + }); + adopted.transport.setServerRequestHandler(async () => ({ success: true, contentItems: [] })); + const restored = await adopted.transport.request("thread/read", {}); + expect(restored.thread).toMatchObject({ id: thread.id, sessionId: thread.sessionId }); + expect(adopted.evidence()).toMatchObject({ runnerPid: pid, codexPid: providerPid, runnerExited: false }); + expect(duplicateLaunch).not.toHaveBeenCalled(); + expect(await readFile(join(root, "saved-work.txt"), "utf8")).toBe("completed work survives controller replacement"); + // A real Stop still reaches the adopted owner; the lease-only disconnect + // policy cannot turn a detached process into an uncancellable executor. + await adopted.transport.close(); + expect(adopted.evidence().runnerExited).toBe(true); + } finally { + await first.transport.close().catch(() => undefined); + await adopted?.transport.close().catch(() => undefined); + if (pid) { try { process.kill(-pid, "SIGKILL"); } catch { /* already stopped */ } } + server.closeAllConnections(); + if (server.listening) await new Promise(resolveClose => server.close(() => resolveClose())); + await rm(root, { recursive: true, force: true }); + } +}, 30_000); diff --git a/packages/paperclip-runner/src/live/runnerd-semantic-handler-readiness.test.ts b/packages/paperclip-runner/src/live/runnerd-semantic-handler-readiness.test.ts new file mode 100644 index 00000000000..f669c4d4aca --- /dev/null +++ b/packages/paperclip-runner/src/live/runnerd-semantic-handler-readiness.test.ts @@ -0,0 +1,54 @@ +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { expect, it, vi } from "vitest"; +import type { DurablePrpControlPlane } from "../control-plane/durable-prp-control-plane.js"; +import type { CodexRpcServerRequest } from "../drivers/codex/app-server-transport.js"; +import { createCapabilityRunnerdCodexTransport, defaultCapabilityRunnerdBinary } from "./runnerd-codex-transport.js"; + +it.each(["install", "close", "detach"] as const)("holds an authenticated semantic call until handler readiness or %s", async mode => { + const root = await mkdtemp(join(tmpdir(), "runner-handler-readiness-")); + let core!: DurablePrpControlPlane; + const bundle = createCapabilityRunnerdCodexTransport({ + runnerBinary: defaultCapabilityRunnerdBinary(), + codexCommand: resolve(import.meta.dirname, "../../runner/target/debug/fake-codex-app-server"), + codexArgs: ["--state-file", join(root, "provider.json"), "--emit-tool-call"], + stateDirectory: root, + controlPlaneRegistration: async authority => { + core = authority; + await authority.start(); + return { release: () => undefined }; + }, + }); + const handler = vi.fn(async (_request: CodexRpcServerRequest) => ({ success: true, contentItems: [{ type: "inputText", text: "one retained result" }] })); + let pid: number | null = null; + try { + await bundle.transport.request("thread/start", { cwd: root, dynamicTools: [{ name: "get_task_context", description: "Read the task.", inputSchema: { type: "object", properties: {}, additionalProperties: false } }] }); + await bundle.transport.request("turn/start", { input: [{ type: "text", text: "Read the task." }] }); + pid = bundle.evidence().runnerPid; + expect(bundle.evidence().runnerProcessGroupId).toBe(pid); + await vi.waitFor(() => expect(core.store.state.committedEvents.some(event => event.eventType === "semantic_tool.input")).toBe(true)); + // The authenticated provider is already asking for a tool, but the driver + // has not published its recovered session/handler yet. No error result may + // be manufactured in this gap, and no external effect has been dispatched. + await new Promise(resolveWait => setTimeout(resolveWait, 50)); + expect(core.store.state.commands.filter(command => command.type === "semantic_tool.result")).toHaveLength(0); + expect(core.semanticToolResultsSettled()).toBe(false); + if (mode === "close") await bundle.transport.close(); + if (mode === "detach") await bundle.detachControllerForRestart(); + bundle.transport.setServerRequestHandler(handler); + if (mode === "install") { + await vi.waitFor(() => expect(handler).toHaveBeenCalledOnce()); + await vi.waitFor(() => expect(core.store.state.commands.filter(command => command.type === "semantic_tool.result")).toHaveLength(1)); + expect(core.store.state.commands.find(command => command.type === "semantic_tool.result")?.payload).toMatchObject({ isError: false }); + expect(handler.mock.calls[0]?.[0]).toMatchObject({ method: "item/tool/call", params: { tool: "get_task_context" } }); + } else { + await new Promise(resolveWait => setTimeout(resolveWait, 50)); + expect(handler).not.toHaveBeenCalled(); + } + } finally { + await bundle.transport.close().catch(() => undefined); + if (pid) { try { process.kill(-pid, "SIGKILL"); } catch { /* owned child already stopped */ } } + await rm(root, { recursive: true, force: true }); + } +}, 20_000); diff --git a/packages/paperclip-runner/test-fixtures/pi-acp/profile-v29-identity.json b/packages/paperclip-runner/test-fixtures/pi-acp/profile-v29-identity.json new file mode 100644 index 00000000000..664c0ab00c7 --- /dev/null +++ b/packages/paperclip-runner/test-fixtures/pi-acp/profile-v29-identity.json @@ -0,0 +1,51 @@ +{ + "commandDigest": "sha256:e80c6dc7bde12790371345ee5a12f0201d30941d26f1a780aec3d090545b2a06", + "declaration": { + "schema": "paperclip.acpx_profile_declaration.v1", + "agent": "pi", + "agentProfileVersion": 29, + "acpxVersion": "0.13.1", + "agentServerVersion": "0.0.33", + "agentRuntimeVersion": "1.0.0", + "nodeVersion": "24.21.0", + "closure": { + "darwin-arm64": "282022db10150c6632b3444df421342e7d534bdf5d5fb1097a2e79d0625a2bcf", + "darwin-x64": "64e251e19009f755c0b04f73ce2138246faab71a961b0f13d75ebfcc34bef12e", + "linux-x64": "713b1fdff42fb56a1518bdc084f181d70bee8ebadc3e4b1d76321ed9108c8410" + }, + "wrapperSha256": "9d129b3d38772e93e97080aa6c4e574ac5df4e47ce5bc331a484a9fbf8188b36", + "helperSha256": "41e0490b617da0d60e0c8ec58ef311236f945129d99f816cff6897f78da7f91d", + "extensionSha256": "f5818573a355702388072b28926897db546a5cf346b5171f646582ce5f9102a4", + "agentFilesBinding": "registered-runtime-context-v1", + "nativeQuestions": "select-confirm-input-editor-v4-root-field-types", + "pathPolicy": "sdk-normalization-v1", + "mcpToolNames": "provider-safe-exact-source-v1", + "acpxPatchSha256": "00d6af17216cb0cad902b48633eb19bf0ec6b05837a984cb24661fca593f09c1", + "nativeAssistantMessages": "pi1-rpc-deltas-v3-bound-message-and-tool-receipts", + "nativeNotices": "session-extension-v2-bounded-runtime-failure", + "messageProjectionSha256": "17d1e91b948dfa6a56e1905645add52b502041ad843c8d50a13b07956f22aadd", + "noticeProjectionSha256": "014485adc690998e395d334ea3ae67f72be6060a2fc78a1185df7b8d1da28fbf", + "sharedRuntimeContract": "paperclip.acpx-runtime-contract.v1", + "nativeInputDisposition": "queued-only-v1", + "cacheWarming": "disabled-owned-decision-v1", + "thinkingLevel": { + "supported": [ + "off", + "low", + "high", + "max" + ], + "newConfigurationDefault": "low", + "admission": "explicit-native-effective-before-prompt-v1", + "recovery": "mode-bound-v1" + }, + "modelSelection": "caller-selected-native-verified-v1", + "providerConfigurationSourceSha256": "75a9a13f13f224dc092bd8ebf49e8747162172943761e44476c8eb18d80c52d4", + "credentialEnvironmentSourceSha256": "7586d44b47c83395498dc8806287cd3538ef58177ba7c5949f5766ed105a0161", + "runtimeSandboxSourceSha256": "92dfa53f5a3ed0062913ae417eeccec243b430d444495efde2a8e9c4c02e78ea", + "recoveryIdentitySourceSha256": "d2c9fc161fcc135fb9760110bfa3d984ee2bb38d87fa5ce7cb7418a49dd89e66", + "nativeCancellation": "acknowledged-cancelled-terminal-preserves-usage-v1", + "dependencySecurityPatchSha256": "5273a195b952f233336122842faaf650193c04f36b9359d20d4d63079b0ce814", + "openRouterAttributionSourceSha256": "1211191529d6073b733b311c3d69cada4973eede0f3e540c46e261f78e0b90f9" + } +} diff --git a/packages/paperclip-runner/test/fixtures/copilot-profile-v59-identity.json b/packages/paperclip-runner/test/fixtures/copilot-profile-v59-identity.json new file mode 100644 index 00000000000..b087d433186 --- /dev/null +++ b/packages/paperclip-runner/test/fixtures/copilot-profile-v59-identity.json @@ -0,0 +1,85 @@ +{ + "commandDigest": "sha256:2f39ffe54a6af832d044b5098c31df9e08d4d27aee0ac675ba4b0c9da7445c40", + "declaration": { + "schema": "paperclip.acpx_profile_declaration.v1", + "agent": "copilot", + "agentProfileVersion": 59, + "acpxVersion": "0.13.1", + "agentServerVersion": "1.0.88", + "protocolPolicyRevision": "copilot-agent-manual-v1", + "acpxPatchSha256": "00d6af17216cb0cad902b48633eb19bf0ec6b05837a984cb24661fca593f09c1", + "policySha256": "a4be69be43db84052560420a3ca546a665c9165573c24d543eb33d144ba138a3", + "distributionSourceSha256": "c0a65e247fc47b263bd369a3d5ab505c4b323d4e6493be8a9ecbeb0e9dbb9107", + "agentFilesBinding": "registered-runtime-context-v1", + "systemInstructionDelivery": "COPILOT_HOME/copilot-instructions.md:replace-under-lifetime-lease-before-launch:v1", + "sharedRuntimeContract": "paperclip.acpx-runtime-contract.v1", + "innerDistributionSourceSha256": "9bb08347eed01f1ab44e065c8b06ead9be3a25973d6e6329dc4c0a099096279a", + "upstreamAppSha256": "7b48282a19b5b0814a0c96ad5e3a125173d792cc55f9525b2effea962f6063c0", + "patchedAppSha256": "61f8eebe0c30cc03b311c6818b2acb158a6d16ca58c8bfac5ebd42db095c2679", + "messageIdentityContract": "copilot-native-message-id-v1", + "ownedDistributionDelivery": "COPILOT_CLI_DIST_DIR:lease-owned-guarded-inner-distribution:v1", + "permissionContextContract": "copilot-edit-permission-context-v1", + "permissionContextSourceSha256": "de2d38d702b3c574161af0c0c04790fb6f6347916eb3916ce7a131a8c229121b", + "permissionAdapterSourceSha256": "ee5929ed2ee647ad0369465dee9d51a00b2dd28e1ff735b43e969ddc9c164668", + "permissionLocationsSourceSha256": "f39a81da395b6e23aa2a1a45572a28846e5e81bfd3d764d9a456f74a79c752e9", + "permissionRedactionSourceSha256": "ad6770c69269087951790e2e87e22ac088e3d432769adf17ebc865ed512e6c4f", + "permissionClassifierSourceSha256": "1161eabd82e26133e3b3db3ab567f65d52808b03f176e93497e02c8330349fb4", + "semanticToolReceiptContract": "paperclip.semantic_tool_receipt.v2", + "semanticReceiptSourceSha256": "b2795726b2234a663fec1a6ca11f0551ae69882fe9e82aa39686e952d036e791", + "semanticBridgeSourceSha256": "8764b8c9032fdc7d1415b01e75a9fc57c550e7a5e11da4bed7d9100082872ae5", + "toolEvidenceSourceSha256": "6eef5039afc75bb851eaf9cd82a6f099e4bd398ca2deb59dd66f5b2a81a7a706", + "semanticNormalizedInputContract": "validated-forwarded-input-commit-v1", + "semanticSidecarSourceSha256": "17361d1782c0dcebb2b7972635f45c890f2a4081f8bc0ef2d2276550e0b91629", + "semanticDirectDriverSourceSha256": "ff572638f2cb5d9f8249ff8e2f412311c1e3af209ef0bf7e5ea9f10a21d91103", + "semanticValidationSourceSha256": "02fbb92681c78c5de5d2f1aae25aabc25a0e5df6b0ff4baccac652192a8da975", + "semanticNormalizationSourceSha256": "8b628b82e8eacc91cdcc6fdca2210ba4cf282f01e9c6f74e95ff271655b5047e", + "semanticCompletionContractSourceSha256": "3343df6362252d44d12b079ff78c8f6539d1544f3ce5ec36ff36db70ab0fac31", + "semanticValidatorsSourceSha256": "f22d9caf2035b600abc1a6625ae23ca97f1409d7e29ed5b7264bb8f9784c7dc9", + "semanticSchemaBundleSourceSha256": "016391a087cc217aafed4ba1f4efafc6e4881a7525952dce824b7f4d24530603", + "semanticSidecarProtocolSourceSha256": "03c0c95b900f9dc18f29f6be27b8c79bc0bcab29780190d46a74e95328081236", + "semanticSidecarReceiptCommitContract": "correlated-tool-resolve-v1", + "displayEventSourceSha256": "d72f9a6035c247bc6a42c067c05753076c54322c4b58984e93922f3325dc6877", + "displayProjectionSourceSha256": "75952606b26dd93bbc582c1f0a4424487377272ea745fb3a27ceae031fd5dc7e", + "configuredEnvironmentSourceSha256": "5c9008d121979a3a8987e6b8a5752172eafdc4a2b5d725a73f3bbb8fb83be8ff", + "configuredEnvironmentRustSourceSha256": "85c87fae62b8a9377e4f0a4c00302c7519fae4397b1c48253f8f2b7ba7faf994", + "profileActivitySourceSha256": "4fdb6b0f9125fd8372ba6f27945fa5c8a3d3b2ec891df544092e3dc7a75d5282", + "profileExtensionsSourceSha256": "a80ddc95eb4505095bfdbbf85c758199949ab20be9c84b34c77f762eb7180571", + "profileInstallationSourceSha256": "3e61c4cdd4b78e38fcb16eaadae4f1fd65ce3c7127184ea7a80948c8e5d77f88", + "attachmentPolicySourceSha256": "4f7638b7cc64e18f6a4ba33fd46de2b3d49225e32aeab41f5c695b268fa4f8e2", + "singleReadEvidenceSourceSha256": "4069393405089bde613cecec04f5123c426594811da4c668bd96f0e7e283550f", + "nativeSessionRuntimeSourceSha256": "1fe6fa9e6b96d84d70432b85a57c473f833606d4a521563d5022b4d3c41576ce", + "nativeRuntimeContextSourceSha256": "71607f80dbb8dc5cc6c123d0b8f3995d6c5407277695a8c82cbedc90fb8f4842", + "nativeRuntimePromptsSourceSha256": "103b83066da72434602e9e461e6278dfb40bb993d2f3b49b2e93df81bbb08b72", + "nativeSessionContractSourceSha256": "22a8c96ce41ba4f03e976fc37f0cc7c5d05cee99fa789941da31ee1dab440b90", + "harnessSessionContractSourceSha256": "03f4cd7f76f34f6d82e009b66aa51f18f6e23dc235b660778060e35b6ea07412", + "harnessBackendSourceSha256": "dc827e281ae6731545b166ee4d709a4f67f594a556dcbe63c70fe8f1aca26249", + "harnessSessionSourceSha256": "81361733e86b56dd5a66415aefc6f72e69be24acc8d3417370154ebb7fef6e94", + "transportContractSourceSha256": "03fca93d36a89b0cc0917335e293ad097fdf04356d21b307827bb0ea4c13f523", + "nativeBackendSourceSha256": "972c08e6e320d1384221e180391fe817ea1ba632db687201e457d64e68ef4360", + "nativeBackendFactorySourceSha256": "7e431c926b76d53c4c08e3a4105353dcd34bd940f6588a1a68f79631f6feeb44", + "nativeInstructionsSourceSha256": "9173ebccf09cb56a781d2bf5c7eb27fdafb13d3450d99342c6aff86b42d6b43a", + "providerLaunchSourceSha256": "d4f4a69baeeb2f3b2f350840f81f711e40f08588c28ea28039748dde90302a51", + "launchPreparationStoreSourceSha256": "ff6025568bbc0aa6ce545772d73dfca2d3da226740bd3a7b386b069e76cff296", + "runtimeRequestBridgeSourceSha256": "7497083b6cf1fc0268187aff948352f3bce6e054ac6e845005846473efdaff15", + "runtimeRequestFacadeSourceSha256": "d0ed28e0c5ddad34db8f437e704c8a755eb0b47f27e08e44185f66d1d2205295", + "runtimeRequestNotificationSourceSha256": "6196c6175f11c69295dc00fc773201f4fdeca26c500653870253c43b81e65211", + "guardedInstallationSourceSha256": "56a177d3e702914818dca4ca50e061f0d25f988bfc4c0582c36ce23c1696d82f", + "nativeExecutionSourceSha256": "fc7c6568feb0d8d709e9baa51839420c9b90336b4865a9b8405aba06e4d1e9c4", + "profileCompatibilitySourceSha256": "6a26b102b78f282137ff93b0f75eb8788c603fc177802c58715c5ad7b2f3b9e3", + "installationSourceSha256": "a1c7c6f103b898216973e77ffbac0ef7572e250aa574d1a4065270e9dfa0dc2d", + "assetOwnershipSourceSha256": "1785e3f31e5dad5a13b53e25d8cf9482a9bd89a27b6c127830aed6b81acc605c", + "assetInstallerSourceSha256": "d3bd9514e5920d0cc3567aa50487fb534c57a6f66b8da0d3f22c5f6e499c841f", + "credentialBindingSourceSha256": "7586d44b47c83395498dc8806287cd3538ef58177ba7c5949f5766ed105a0161", + "sidecarErrorSourceSha256": "b09af4577f8bf42eee7036b2ad9842202cfc763e72b53c3287f82c6090cdad80", + "profileSourceSha256": "f5538b3dbefa7634a332b87d5ededcefb56aa7e5790cede1c7a0d948a548a456", + "metadataProbeSourceSha256": "be4c8416edd27061109bc1f33d0c26071b4facbb3f651beaae6b3c0275cce727", + "permissionToolIdentitySourceSha256": "770b47305e571a81f344883057d0e4a482a1cd59ac77d045836593a8e739deb1", + "semanticContinuationSourceSha256": "d248e47a0fe7f2536d1e64cea0b0b410f34104800cd643d995b4473104ecc8e0", + "runtimeHostSourceSha256": "94a73749267f5a80b5df19413a65b4b9263c00a9bf7e98fda00f00b8f9fd32ec", + "runtimeAdapterSourceSha256": "e4c764c2c3c7dd655a965b39472bd1ad8d577d1e7258b25594b171c9429752b8", + "runtimeSandboxSourceSha256": "92dfa53f5a3ed0062913ae417eeccec243b430d444495efde2a8e9c4c02e78ea", + "cancellationSourceSha256": "a07d1a9e982dec0ae130c1ad1efa5bc75c6a39e013b730ba3ee45256f09ceeca", + "agentFilesSourceSha256": "fb32f6badc13dfa22f231479509b631b2f0eba0c99b1ab9f3cd5c0c601aa03ba", + "nativeDistributionSourceSha256": "aed327c389e957483a503cb1bb8b247ee7cd7ff4b528fb4567c39bcb4577690b" + } +} diff --git a/scripts/pi-public-install-probe.mjs b/scripts/pi-public-install-probe.mjs index 5e6672cc68f..945d8c902de 100644 --- a/scripts/pi-public-install-probe.mjs +++ b/scripts/pi-public-install-probe.mjs @@ -52,8 +52,8 @@ assert.equal(JSON.parse(await readFile(join(server, 'package.json'), 'utf8')).na const { resolvePaperclipRunnerBinary } = await import(pathToFileURL(join(server, 'dist/services/native-runtime/native-codex-runner.js'))); const { createCapabilityRunnerdCodexTransport } = await import(pathToFileURL(join(server, 'dist/vendor/paperclip-runner/live/runnerd-codex-transport.js'))); const { QUALIFIED_ACPX_PROFILES } = await import(pathToFileURL(join(server, 'dist/vendor/paperclip-runner/drivers/acpx/qualified-profiles.js'))); -assert.equal(QUALIFIED_ACPX_PROFILES.pi.agentProfileVersion, 28); -assert.equal(QUALIFIED_ACPX_PROFILES.pi.commandDigest, 'sha256:4918a4d5472d66b22b1ec642b68b5c60a8092a39c84ec1ab1c9ad0289cb8c68c'); +assert.equal(QUALIFIED_ACPX_PROFILES.pi.agentProfileVersion, 29); +assert.equal(QUALIFIED_ACPX_PROFILES.pi.commandDigest, 'sha256:e80c6dc7bde12790371345ee5a12f0201d30941d26f1a780aec3d090545b2a06'); assert.equal(Object.hasOwn(QUALIFIED_ACPX_PROFILES.pi, 'qualificationModel'), false); assert.equal(Object.hasOwn(QUALIFIED_ACPX_PROFILES.pi, 'reportedModelId'), false); const daemon = resolvePaperclipRunnerBinary(); diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index ccf020f577b..62118309e9d 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -11999,7 +11999,8 @@ async function createRunnerdBackendWithinSessionClaim( claudeEffort: "claudeEffort" in provider ? provider.claudeEffort : undefined, acpxPermissionModePinned: true } : {}), ...(provider.kind === "opencode" ? { opencodePermissionMode: provider.permissionMode } : {}), - runnerReconnectGraceMs: 120_000, lifecyclePolicy: input.execution.session.lifecyclePolicy, + runnerReconnectGraceMs: 120_000, runnerProcessReconnectGraceMs: null, + lifecyclePolicy: input.execution.session.lifecyclePolicy, runtimeContext: "runtimeContext" in input.execution ? input.execution.runtimeContext : null, externallySandboxed: true, baseInstructions: recovery?.baseInstructions, resumeDynamicTools: dynamicTools, resumeCompletionContract: { revision: input.execution.completionContract.contract.revision, @@ -13494,6 +13495,10 @@ async function createRunnerdBackendWithinSessionClaim( ? resolveSourceCodexHome(resolveNativeProviderEnvironment(input.execution.provider, runnerEnvironment)) : undefined, runnerReconnectGraceMs: remoteTarget ? 120_000 : undefined, + // A controller's bounded reconnect attempt is not the remote owner's + // lifetime. Retain it through restarts until its authenticated lease + // expires or explicit Stop/suspension proves that execution ended. + runnerProcessReconnectGraceMs: remoteTarget ? null : undefined, environment: effectiveRunnerEnvironment, observability: input.observability, onDiagnostic: (message) => { diff --git a/tests/runner-e2e/EVERYDAY-WORKFLOWS.md b/tests/runner-e2e/EVERYDAY-WORKFLOWS.md index 567f365adeb..a9e395f53bb 100644 --- a/tests/runner-e2e/EVERYDAY-WORKFLOWS.md +++ b/tests/runner-e2e/EVERYDAY-WORKFLOWS.md @@ -16,7 +16,7 @@ exact execution ID explicitly. | Decide on an installed service action | `service-approve`, `service-decline` | Assign an authenticated local MCP fixture with Ask first; match its tool action and connection ID; no provider call before approval; exactly one after approval and a verified document; none after decline. | | Decline a new connection | `connection-decline` | Start without service connections; match a Notion connection intent; click Not now; verify the saved rejection, no new connection or repeated request, and an explanation followed by Done. | | Request an email address | `agentmail-setup` | Enable Chat connectors, ask for an email address, and require a durable AgentMail card for the requesting agent and user. Reload and verify one password field, the direct API-key link, and no access selectors or modal. Decline and verify no connection or repeated request. | -| Continue work after a controller restart | `recover-controller` | Observe saved source, persist a user message, restart the isolated controller, and independently test the delivered result. | +| Continue work after a controller restart | `recover-controller` | Observe saved source, persist a user message, restart the isolated controller, and independently test the delivered result. Native Daytona cases keep the controller offline for 125 seconds before restarting. | | Stop work and change direction | `stop-redirect` | Click Stop, send one new request, reload, observe exactly one stored user message and the new answer, and reach Done. | | Create and edit a company skill | `create-skill-studio` | Create one skill through the runner, verify its persisted library entry and activity-feed card, open Skill Studio, save an edit, and verify the edit after returning. Local Codex, local ACPX Claude, and warm Daytona cells are explicit. | @@ -47,8 +47,10 @@ restart, a verified first download supplies the persistence checkpoint; the controller is interrupted during a subsequent revision with another queued requirement. -The native Codex Daytona restart cell now requires a completed native tool -receipt while that revision is still running. Before and after restart it pins +The native Codex and ACPX Daytona restart cells require a completed native tool +receipt while that revision is still running. They keep the controller offline +for 125 seconds after its health listener stops, then start its replacement. +Before and after restart each pins the same run, normalized session, Runner identity, PID/start time, and active sandbox lease. The original receipt prefix must remain unchanged. A run that ends before either active observation leaves the fault boundary unexercised; @@ -56,7 +58,10 @@ it cannot pass from the final ZIP alone. The cell no longer exempts an original Codex remote run that fails with `process_lost` and is replaced. Completion requires one original provider turn and control-plane terminal, -the same native receipt prefix, no duplicate completed tool execution IDs, +the same native receipt prefix, no failed native tool receipts, and consistent +results for every stable completed tool identity. Reattached activity can +redeliver an identical start or tool receipt; changed content or a second +submission fails. It also requires a committed run and successful `workspace_finalize` receipt, and no pending workspace operation or recovery. Existing independent ZIP and preserved-download checks still apply. These receipt checks do not prove that arbitrary external diff --git a/tests/runner-e2e/README.md b/tests/runner-e2e/README.md index 129f75c4e31..c6ed181c3e5 100644 --- a/tests/runner-e2e/README.md +++ b/tests/runner-e2e/README.md @@ -1,5 +1,15 @@ # Paid runner full-stack E2E +The explicit-only `daytona-restart-continuity` suite runs the existing +`recover-controller` journey with the recorded Codex and Claude staging models +on fresh Daytona fixtures. After a completed task tool in an active revision +turn, it keeps the owned development controller offline for 125 seconds, beyond +the controller's two-minute reconnect budget. The existing independent oracle +requires the original process, native session, sandbox lease and receipt prefix, +one completion and successful workspace finalization, plus verified downloaded +work. It permits one attempt per cell and retains failed evidence. This is +development API-key acceptance, distinct from staging subscription recovery. + The explicit-only [GitHub review bot journey](GITHUB-REVIEW-JOURNEY.md) tests attended bot setup and an automatic PR review against an attached deployment. Private account bindings and setup receipts live in the private eval repository. diff --git a/tests/runner-e2e/SECURITY.md b/tests/runner-e2e/SECURITY.md index afbcf8dd494..555a6673b20 100644 --- a/tests/runner-e2e/SECURITY.md +++ b/tests/runner-e2e/SECURITY.md @@ -53,13 +53,17 @@ changes. ## GitHub authorization -The Everyday remote Codex restart oracle reads only the existing public run, +The Everyday remote native restart oracle reads only the existing public run, event, environment-lease, workspace-operation and recovery APIs. It does not execute commands in a provider sandbox or signal a provider process. Its new evidence projects closed receipt metadata and hashes the provider sandbox ID and full native event content. Provider text, tool arguments and command output do not enter these snapshots. Existing image admission, credentials, billing, retention and cleanup rules continue to apply. +The isolated server's private restart request may delay its replacement by at +most five minutes. This fault injection never stops a hosted instance or a +provider sandbox. The explicit Daytona continuity suite has one attempt and +1,000-cent company and agent hard stops. Set `RUNNER_E2E_ALLOWED_ACTOR_IDS` to a non-empty JSON array of numeric GitHub user IDs. Keep the list equal to the owners of `.github/**` in diff --git a/tests/runner-e2e/catalog.test.ts b/tests/runner-e2e/catalog.test.ts index 4f36708a091..4b87cac677d 100644 --- a/tests/runner-e2e/catalog.test.ts +++ b/tests/runner-e2e/catalog.test.ts @@ -219,10 +219,10 @@ describe("runner E2E catalog", () => { expect(localIntegrityTasks).toHaveLength(2); expect(openRouterBreadthTasks).toHaveLength(3); expect(runnerSuites.map((suite) => suite.expectedMatrixSize)).toEqual([ - 1, 3, 2, 2, 4, 4, 4, 4, 4, 4, 8, 10, 6, 63, 12, 6, 4, 2, 4, 2, 30, 3, 16, 16, 2, 6, 8, 46, 2, 23, 15, 52, 6, 6, 20, 26, 52, 28, 18, 2, 6, 6, 13, 10, 2, 48, 16, 10, 2, 1, 1, 4, 116, 2, 2, + 2, 1, 3, 2, 2, 4, 4, 4, 4, 4, 4, 8, 10, 6, 63, 12, 6, 4, 2, 4, 2, 30, 3, 16, 16, 2, 6, 8, 46, 2, 23, 15, 52, 6, 6, 20, 26, 52, 28, 18, 2, 6, 6, 13, 10, 2, 48, 16, 10, 2, 1, 1, 4, 116, 2, 2, ]); - expect(validateRunnerCatalog()).toHaveLength(765); - expect(new Set(runnerMatrix.map((entry) => entry.id)).size).toBe(765); + expect(validateRunnerCatalog()).toHaveLength(767); + expect(new Set(runnerMatrix.map((entry) => entry.id)).size).toBe(767); expect( runnerMatrix.filter((entry) => entry.suite.id === "core-compatibility"), ).toHaveLength(48); diff --git a/tests/runner-e2e/catalog.ts b/tests/runner-e2e/catalog.ts index 84c733fe035..a824e9b9dd4 100644 --- a/tests/runner-e2e/catalog.ts +++ b/tests/runner-e2e/catalog.ts @@ -1155,6 +1155,17 @@ const repositoryModelProfiles = [ ]; export const runnerSuites: readonly RunnerSuiteFixture[] = [ + { + id: "daytona-restart-continuity", label: "Daytona controller outage continuity", manualOnly: true, + description: "Keep the original active native runner, task tools and saved files through more than two minutes without a controller, then commit the result without replay.", + groups: [], profiles: repositoryModelProfiles.map(({ native }) => productionStoryProfile(native)), + environments: runnerEnvironments.filter(environment => environment.id === "daytona"), + tasks: everydayTasks.filter(task => task.id === "recover-controller") + .map(task => ({ ...task, automaticRetryPolicy: "single_attempt" as const })), expectedMatrixSize: 2, + definitionMetadata: { version: 2, scheduling: "explicit-only", controllerDowntimeMs: 125_000, + maximumAttemptsPerCell: 1, budgetMonthlyCents: 1000, instructions: "production", grading: "same-active-process-lease-native-prefix-and-workspace-receipt", + authentication: "api-key", stagingAuthentication: "subscription", stagingQualification: false }, + }, { id: "codie-latency-diagnostic", label: "Native Codex latency diagnostic", @@ -1514,7 +1525,8 @@ export const runnerSuites: readonly RunnerSuiteFixture[] = [ ...(["hire-reuse", "delegate-feedback"].includes(task.id) ? [] : [`everyday-workflows.runner-opencode.local.${task.id}`]), ]), ], - definitionMetadata: { version: 7, instructions: "production", grading: "outcome-and-invariants", scheduling: "explicit-only", + definitionMetadata: { version: 9, instructions: "production", grading: "outcome-and-invariants", scheduling: "explicit-only", + remoteControllerDowntimeMs: 125_000, remoteCodexRestart: "same-active-process-lease-native-prefix-and-workspace-receipt", procedureCases: { ids: ["hire-reuse", "delegate-feedback"], maximumAttemptsPerCell: 1, companyAndLeadBudgetCents: 1_000 } }, }, diff --git a/tests/runner-e2e/everyday-flow.ts b/tests/runner-e2e/everyday-flow.ts index 3dc84a29769..bebc81eacff 100644 --- a/tests/runner-e2e/everyday-flow.ts +++ b/tests/runner-e2e/everyday-flow.ts @@ -89,7 +89,7 @@ interface Input { workspacePath: string; privateDir: string; deadlineAt: number; - restart(): Promise; + restart(controllerDowntimeMs?: number): Promise; observe(issue: StoryIssue, runs: StoryRun[]): void; capture(id: string, label: string, file: string): Promise; evidence(name: string, value: unknown): Promise; @@ -169,7 +169,8 @@ export async function runEverydayFlow(input: Input) { let project = fixtures.project; const caseId = execution.task.id; const requireRemoteRestart = caseId === "recover-controller" && execution.environment.id === "daytona" - && execution.profile.generation === "native" && execution.profile.provider === "codex"; + && execution.profile.generation === "native" && (execution.profile.provider === "codex" + || execution.profile.provider === "acpx"); const providerChoice = caseId === "provider-decline" || caseId === "provider-second"; const nativeProviderCase = caseId === "provider-native"; let aggregatorFixture: Awaited> | undefined; @@ -949,7 +950,7 @@ export async function runEverydayFlow(input: Input) { ev.remoteRestart = { before }; await input.evidence("remote-restart-before.json", before); } else ev.allowedInterruptedRuns.push(active.id); - await input.restart(); + await input.restart(requireRemoteRestart ? 125_000 : undefined); note("controller-restarted"); await openParent(); if (requireRemoteRestart) { @@ -1643,7 +1644,9 @@ export async function runEverydayFlow(input: Input) { ev.remoteRestart!.final = final; return final; }, accept: final => gradeRemoteRestart({ ...ev.remoteRestart, final }).every(check => check.passed), - reject: final => ["failed", "cancelled", "timed_out"].includes(final.run.status) ? "Original remote run failed after restart" : undefined }); + reject: final => ["failed", "cancelled", "timed_out"].includes(final.run.status) ? "Original remote run failed after restart" + : final.run.status === "succeeded" && final.run.nativePhase === "committed" + && !gradeRemoteRestart({ ...ev.remoteRestart, final })[1]!.passed ? "Original remote turn completed with failed tools or conflicting/repeated execution receipts" : undefined }); await input.evidence("remote-restart-final.json", final); } ev.checks.push( diff --git a/tests/runner-e2e/everyday-remote-restart.test.ts b/tests/runner-e2e/everyday-remote-restart.test.ts index 938c9b30bf6..c492e4f9e72 100644 --- a/tests/runner-e2e/everyday-remote-restart.test.ts +++ b/tests/runner-e2e/everyday-remote-restart.test.ts @@ -111,11 +111,27 @@ describe("remote restart lifecycle evidence", () => { expect(gradeRemoteRestart(missingPrefix)[1]!.passed).toBe(false); }); - it.each(["replacement", "second submission", "duplicate tool receipt", "missing terminal"])("rejects %s at completion", fault => { + it("rejects failed native tool calls even when the original turn eventually succeeds", () => { + const { evidence, event } = fixture(); + const rows = [...fixture().afterRows, event(6, "tool.execution.completed", { executionId: "failed-write", status: "failed", output: "private timeout" }), + event(7, "turn.completed"), event(8, "run.result.accepted", {}, "control_plane", 1), event(9, "run.terminal", {}, "control_plane", 2)]; + evidence.final.events = projectRemoteRestartEvents(evidence.final.run, rows); + expect(gradeRemoteRestart(evidence).every(check => check.passed)).toBe(false); + }); + + it("accepts identical activity receipt redelivery without treating it as another submission", () => { + const { evidence } = fixture(); + evidence.final.events.push({ ...evidence.final.events[1]!, seq: 10, sourceSeq: 10, sourceEventId: "runner:run:10" }, + { ...evidence.final.events[3]!, seq: 11, sourceSeq: 11, sourceEventId: "runner:run:11" }); + expect(gradeRemoteRestart(evidence).every(check => check.passed)).toBe(true); + }); + + it.each(["replacement", "second submission", "changed tool receipt", "changed start receipt", "missing terminal"])("rejects %s at completion", fault => { const { evidence } = fixture(); if (fault === "replacement") evidence.final.run.id = "replacement"; if (fault === "second submission") evidence.final.events.push({ ...evidence.final.events[0]!, seq: 10, sourceSeq: 10, sourceEventId: "runner:run:10" }); - if (fault === "duplicate tool receipt") evidence.final.events.push({ ...evidence.final.events[3]!, seq: 10, sourceSeq: 10, sourceEventId: "runner:run:10" }); + if (fault === "changed tool receipt") evidence.final.events.push({ ...evidence.final.events[3]!, seq: 10, sourceSeq: 10, sourceEventId: "runner:run:10", payloadSha256: "0".repeat(64) }); + if (fault === "changed start receipt") evidence.final.events.push({ ...evidence.final.events[1]!, seq: 10, sourceSeq: 10, sourceEventId: "runner:run:10", payloadSha256: "0".repeat(64) }); if (fault === "missing terminal") evidence.final.events.pop(); expect(gradeRemoteRestart(evidence)[1]!.passed).toBe(false); }); diff --git a/tests/runner-e2e/everyday-remote-restart.ts b/tests/runner-e2e/everyday-remote-restart.ts index 59c1db429e8..9b50934eec6 100644 --- a/tests/runner-e2e/everyday-remote-restart.ts +++ b/tests/runner-e2e/everyday-remote-restart.ts @@ -12,7 +12,8 @@ const digest = (value: unknown) => createHash("sha256").update(canonicalJson(val export interface RemoteRestartEvent { seq: number; sourceSeq: number; sourceEventId: string; eventType: string; sourceKind: "runner" | "control_plane"; turnId: string | null; - toolExecutionId: string | null; toolCompleted: boolean; sha256: string; + toolExecutionId: string | null; toolCompleted: boolean; toolFailed: boolean; + payloadSha256: string; sha256: string; } export interface RemoteRestartBoundary { identity: { runId: string; companyId: string; agentId: string; issueId: string; @@ -78,6 +79,8 @@ export function projectRemoteRestartEvents(run: StoryRun, rows: readonly Row[]): turnId: id(event.turnId) ? event.turnId : null, toolExecutionId: id(payload.executionId) ? payload.executionId : null, toolCompleted: event.eventType === "tool.execution.completed" && payload.status === "completed", + toolFailed: event.eventType === "tool.execution.completed" && payload.status !== "completed", + payloadSha256: digest(payload), sha256: digest(event) }; }); } @@ -132,12 +135,23 @@ export function gradeRemoteRestart(evidence: RemoteRestartEvidence | undefined): const events = final?.events ?? []; const turnId = before?.events.find(event => event.eventType === "turn.started")?.turnId; const once = (kind: string, source: RemoteRestartEvent["sourceKind"]) => events.filter(event => event.eventType === kind && event.sourceKind === source).length === 1; - const completedTools = events.filter(event => event.toolCompleted).map(event => event.toolExecutionId); + // Reattachment can redeliver an already-observed activity notification. Its + // stable identity and exact payload must agree; a new submission, changed + // result or failed tool is not receipt replay and must never pass this cell. + const starts = events.filter(event => event.eventType === "turn.started" && event.sourceKind === "runner"); + const tools = events.filter(event => event.toolCompleted); + const toolResults = new Map(); + let consistentToolResults = true; + for (const event of tools) { + if (!event.toolExecutionId || (toolResults.has(event.toolExecutionId) && toolResults.get(event.toolExecutionId) !== event.payloadSha256)) consistentToolResults = false; + else toolResults.set(event.toolExecutionId, event.payloadSha256); + } const nativeCompletion = finalIdentity && Boolean(before && after && retainsPrefix(after.events, events)) - && once("turn.submitted", "runner") && once("turn.started", "runner") && once("turn.completed", "runner") + && once("turn.submitted", "runner") && starts.length > 0 && new Set(starts.map(event => event.payloadSha256)).size === 1 + && once("turn.completed", "runner") && once("run.result.accepted", "control_plane") && once("run.terminal", "control_plane") && events.filter(event => event.eventType.startsWith("turn.")).every(event => event.turnId === turnId || (event.eventType === "turn.submitted" && event.turnId === null)) - && new Set(completedTools).size === completedTools.length; + && consistentToolResults && !events.some(event => event.toolFailed); const operations = final?.operations ?? []; const saved = finalIdentity && run?.status === "succeeded" && run.nativePhase === "committed" && run.resultJson?.finalizationPhase === "committed" && run.resultJson.workspaceFinalizeStatus === "succeeded" diff --git a/tests/runner-e2e/live-fixtures.ts b/tests/runner-e2e/live-fixtures.ts index cc861c6232c..c5d27531b43 100644 --- a/tests/runner-e2e/live-fixtures.ts +++ b/tests/runner-e2e/live-fixtures.ts @@ -171,7 +171,7 @@ export async function setupLiveFixtures(input: { : ["native-completion", "native-instruction-consolidation", "native-connection-guidance"].includes(execution.suite.id) || (execution.suite.id === "everyday-workflows" && ["hire-reuse", "delegate-feedback"].includes(execution.task.id)) ? NATIVE_COMPLETION_BUDGET_CENTS : execution.suite.id === "task-titles" ? TASK_TITLE_BUDGET_CENTS - : ["stock-harness", "task-workspaces", "case-handoffs", "feedback-persistence"].includes(execution.suite.id) ? 1_000 : 0, + : ["stock-harness", "task-workspaces", "case-handoffs", "feedback-persistence", "daytona-restart-continuity"].includes(execution.suite.id) ? 1_000 : 0, }); await input.onCompanyCreated?.(company.id); return company; @@ -365,7 +365,7 @@ export async function setupLiveFixtures(input: { setupProbe.defaultRunner = selected.defaultRunner; } } - if (["stock-harness", "native-connection-guidance", "feedback-persistence"].includes(execution.suite.id) + if (["stock-harness", "native-connection-guidance", "feedback-persistence", "daytona-restart-continuity"].includes(execution.suite.id) || (execution.suite.id === "everyday-workflows" && ["hire-reuse", "delegate-feedback"].includes(execution.task.id))) { agent.budgetMonthlyCents = 1_000; } diff --git a/tests/runner-e2e/runner.spec.ts b/tests/runner-e2e/runner.spec.ts index 420d8c97cf5..8836e27dfe8 100644 --- a/tests/runner-e2e/runner.spec.ts +++ b/tests/runner-e2e/runner.spec.ts @@ -264,6 +264,7 @@ async function restartIsolatedPaperclipServer(input: { deadlineAt: number; preserveRunner?: RestartRunnerIdentity; crashAfterResult?: FinalizationCrashBinding; + controllerDowntimeMs?: number; }): Promise { const { controlDirectory, @@ -274,7 +275,8 @@ async function restartIsolatedPaperclipServer(input: { const temporaryRequestPath = `${requestPath}.${process.pid}.${input.requestId}.tmp`; await writeFile( temporaryRequestPath, - JSON.stringify({ requestId: input.requestId, ...(input.preserveRunner ? { preserveRunner: input.preserveRunner } : {}), + JSON.stringify({ requestId: input.requestId, ...(input.controllerDowntimeMs !== undefined ? { controllerDowntimeMs: input.controllerDowntimeMs } : {}), + ...(input.preserveRunner ? { preserveRunner: input.preserveRunner } : {}), ...(input.crashAfterResult ? { crashAfterResult: input.crashAfterResult } : {}) }), { encoding: "utf8", mode: 0o600 }, ); @@ -1240,7 +1242,7 @@ for (const execution of executions) { const story = await runEverydayFlow({ page, api, fixtures, execution, nonce, workspacePath, privateDir, deadlineAt: startedAtMs + deadlineMs, - restart: () => restartIsolatedPaperclipServer({ api, requestId: `story-${nonce}`, deadlineAt: startedAtMs + deadlineMs }), + restart: controllerDowntimeMs => restartIsolatedPaperclipServer({ api, requestId: `story-${nonce}`, deadlineAt: startedAtMs + deadlineMs, controllerDowntimeMs }), observe: (storyIssue, storyRuns) => { issue = storyIssue; selectedRuns = storyRuns; }, capture: captureScreenshot, evidence: (name, data) => writeSanitizedJson(snapshotsDir, name, data, secrets), diff --git a/tests/runner-e2e/server.ts b/tests/runner-e2e/server.ts index 8956ac3f5aa..451ed91e034 100644 --- a/tests/runner-e2e/server.ts +++ b/tests/runner-e2e/server.ts @@ -293,6 +293,7 @@ async function waitForHealthToStop() { interface RestartRequest { requestId: string; + controllerDowntimeMs?: number; preserveRunner?: RestartRunnerIdentity; crashAfterResult?: FinalizationCrashBinding; } @@ -321,9 +322,15 @@ async function readRestartRequest(): Promise { return null; } const preserveRunner = (value as { preserveRunner?: unknown }).preserveRunner; + const controllerDowntimeMs = (value as { controllerDowntimeMs?: unknown }).controllerDowntimeMs; + if (controllerDowntimeMs !== undefined && (!Number.isSafeInteger(controllerDowntimeMs) + || Number(controllerDowntimeMs) < 0 || Number(controllerDowntimeMs) > 300_000)) { + throw new Error("Controller downtime must be an integer between zero and five minutes"); + } const crashAfterResult = (value as { crashAfterResult?: unknown }).crashAfterResult; if (crashAfterResult !== undefined && preserveRunner !== undefined) throw new Error("A finalization crash cannot preserve a running provider"); - return { requestId, ...(preserveRunner === undefined ? {} : { preserveRunner: parseRestartRunnerIdentity(preserveRunner) }), + return { requestId, ...(controllerDowntimeMs === undefined ? {} : { controllerDowntimeMs: Number(controllerDowntimeMs) }), + ...(preserveRunner === undefined ? {} : { preserveRunner: parseRestartRunnerIdentity(preserveRunner) }), ...(crashAfterResult === undefined ? {} : { crashAfterResult: parseFinalizationCrashBinding(crashAfterResult) }) }; } @@ -348,7 +355,7 @@ async function writeRestartAck( await rename(temporaryAckPath, restartAckPath); } -async function restartServer({ requestId, preserveRunner, crashAfterResult }: RestartRequest) { +async function restartServer({ requestId, preserveRunner, crashAfterResult, controllerDowntimeMs = 0 }: RestartRequest) { activeRestartRequestId = requestId; appendLog(`\nRestart request ${requestId}: stopping Paperclip\n`); const previous = child; @@ -365,6 +372,11 @@ async function restartServer({ requestId, preserveRunner, crashAfterResult }: Re // Do not mistake an orphaned old server for a healthy replacement. The port // must stop answering before the next launcher is allowed to start. await waitForHealthToStop(); + const downtimeDeadline = Date.now() + controllerDowntimeMs; + while (Date.now() < downtimeDeadline) { + if (shutdownRequested()) throw new Error("Wrapper shutdown interrupted controller downtime"); + await delay(Math.min(250, downtimeDeadline - Date.now())); + } if (shutdownRequested()) { throw new Error("Wrapper shutdown interrupted the Paperclip restart"); } From a09ef344b3ff6ce1686a1f515820353345462c7b Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Sun, 25 Oct 2026 07:38:18 -0700 Subject: [PATCH 062/110] perf(agents): avoid duplicate configuration reads (#17612) Reuse one complete company roster for list responses and narrow other-agent eligibility checks to their five consumed fields. Preserve full selected-agent configuration, terminated-manager evidence, current spend, authorization, and fresh reads. Verified with 170 affected tests, four rejected regression mutations, build and typecheck, exact-head Greptile 5/5, and green required CI. Co-Authored-By: Paperclip --- doc/DATABASE.md | 7 + .../agent-record-read-projections.test.ts | 132 ++++++++++++++++++ server/src/lib/agent-records.ts | 15 +- server/src/services/agents.ts | 14 +- .../services/plugin-agent-runtime-state.ts | 2 +- 5 files changed, 156 insertions(+), 14 deletions(-) create mode 100644 server/src/__tests__/agent-record-read-projections.test.ts diff --git a/doc/DATABASE.md b/doc/DATABASE.md index c4d5c72e41e..6c47e5d7495 100644 --- a/doc/DATABASE.md +++ b/doc/DATABASE.md @@ -231,6 +231,13 @@ The benchmark loads the baseline authorization module with current dependencies, compares complete workspace rows, and prints five warm samples and query plans. It measures SQL execution, not the full repository admission or agent startup. +Agent lists read the complete company roster once and use that same snapshot for +termination filtering and organization-chain normalization. Detail and plugin runtime reads +load only identity, company, name, status, and manager from other company agents +for chain checks. The selected agent's full configuration, current monthly spend, +and existing response redaction remain available. Every call reads current data; +these lookups do not cache authorization or agent configuration. + ## 1. Embedded PostgreSQL — zero config If you don't set `DATABASE_URL`, the server automatically starts an embedded PostgreSQL instance and manages a local data directory. diff --git a/server/src/__tests__/agent-record-read-projections.test.ts b/server/src/__tests__/agent-record-read-projections.test.ts new file mode 100644 index 00000000000..bf0a5183202 --- /dev/null +++ b/server/src/__tests__/agent-record-read-projections.test.ts @@ -0,0 +1,132 @@ +import { randomUUID } from "node:crypto"; +import { agents, companies, costEvents, createDb } from "@paperclipai/db"; +import { createDatabaseResponseCapture, installDatabaseResponseCapture } from "@paperclipai/db/response-capture"; +import { eq } from "drizzle-orm"; +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; +import { agentRecordQueries } from "../lib/agent-records.js"; +import { agentService } from "../services/agents.js"; + +const support = await getEmbeddedPostgresTestSupport(); + +describe.skipIf(!support.supported)("agent roster read projections", () => { + let database: Awaited>; + let db: ReturnType; + + beforeAll(async () => { + database = await startEmbeddedPostgresTestDatabase("agent-roster-read-"); + db = createDb(database.connectionString); + }, 60_000); + + beforeEach(() => { + vi.useFakeTimers({ toFake: ["Date"] }); + vi.setSystemTime(new Date("2020-06-15T12:00:00Z")); + }); + + afterEach(() => { vi.useRealTimers(); }); + + afterAll(async () => { + await db?.$client.end(); + await database?.cleanup(); + }); + + async function fixture() { + const companyId = randomUUID(), foreignCompanyId = randomUUID(); + const managerId = randomUUID(), workerId = randomUUID(), unrelatedId = randomUUID(), archivedId = randomUUID(), foreignId = randomUUID(); + await db.insert(companies).values([ + { id: companyId, name: "Roster fixture", issuePrefix: `R${companyId.slice(0, 7).toUpperCase()}` }, + { id: foreignCompanyId, name: "Foreign roster", issuePrefix: `F${foreignCompanyId.slice(0, 7).toUpperCase()}` }, + ]); + const bulk = "retained-other-agent-configuration🙂".repeat(32_768); + await db.insert(agents).values([ + { id: managerId, companyId, name: "Manager", status: "terminated", adapterType: "process", adapterConfig: { instructions: bulk } }, + { id: unrelatedId, companyId, name: "Other worker", status: "idle", adapterType: "process", adapterConfig: { instructions: bulk } }, + { id: archivedId, companyId, name: "Archived worker", status: "terminated", adapterType: "process", runtimeConfig: { retained: bulk } }, + { id: foreignId, companyId: foreignCompanyId, name: "Foreign manager", status: "idle", adapterType: "process", adapterConfig: { instructions: bulk } }, + ]); + const [worker] = await db.insert(agents).values({ id: workerId, companyId, name: "Selected worker", status: "idle", + reportsTo: managerId, adapterType: "process", adapterConfig: { instructions: "selected instructions", model: "fixture-model" }, + runtimeConfig: { heartbeat: { enabled: false } }, metadata: { retained: "selected metadata" }, + permissions: { canCreateAgents: true }, spentMonthlyCents: 999, + }).returning(); + const now = new Date(); + await db.insert(costEvents).values([ + { companyId, agentId: workerId, provider: "fixture", model: "fixture-model", costCents: 19.5, occurredAt: now }, + { companyId, agentId: workerId, provider: "fixture", model: "fixture-model", costCents: 50, + occurredAt: new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() - 1, 15)) }, + { companyId: foreignCompanyId, agentId: foreignId, provider: "fixture", model: "fixture-model", costCents: 100, occurredAt: now }, + ]); + return { companyId, foreignCompanyId, managerId, workerId, unrelatedId, archivedId, foreignId, worker, bulk }; + } + + async function observe(run: (observed: ReturnType) => Promise) { + const observed = createDb(database.connectionString), events: Array> = [], now = Date.now(); + const capture = createDatabaseResponseCapture({ start: now - 100, end: now + 59_000 }, event => events.push(event)); + installDatabaseResponseCapture(observed, { agents, costEvents }, capture); + try { + const result = await run(observed); + capture.flush(); + const reads = events.filter(event => event.table === "agents" && event.operation === "select"); + return { result, calls: reads.reduce((n, event) => n + Number(event.calls), 0), + bytes: reads.reduce((n, event) => n + Number(event.responseValueBytes), 0), events }; + } finally { + capture.flush(); + await observed.$client.end(); + } + } + + it.each([false, true])("reads one full roster for list, preserving terminated-manager evidence and configurations (includeTerminated=%s)", async includeTerminated => { + const f = await fixture(); + const captured = await observe(observed => agentService(observed).list(f.companyId, { includeTerminated })); + expect(captured.calls).toBe(1); + expect(captured.result.map(row => row.id).sort()).toEqual((includeTerminated + ? [f.workerId, f.managerId, f.archivedId, f.unrelatedId] : [f.workerId, f.unrelatedId]).sort()); + const selected = captured.result.find(row => row.id === f.workerId)!; + expect(selected).toMatchObject({ adapterConfig: f.worker.adapterConfig, runtimeConfig: f.worker.runtimeConfig, + metadata: f.worker.metadata, permissions: { canCreateAgents: true }, spentMonthlyCents: 19.5, + orgChainHealth: { status: "invalid_org_chain", reason: "terminated_ancestor", firstInvalidAncestor: { id: f.managerId } } }); + expect(captured.result.find(row => row.id === f.unrelatedId)?.adapterConfig.instructions).toBe(f.bulk); + if (includeTerminated) expect(captured.result.find(row => row.id === f.archivedId)?.runtimeConfig.retained).toBe(f.bulk); + expect((await db.select().from(agents).where(eq(agents.id, f.workerId)))[0]).toEqual(f.worker); + expect(JSON.stringify(captured.events)).not.toContain("retained-other-agent-configuration"); + }); + + it("keeps detail reads small while returning the selected agent's complete current configuration", async () => { + const f = await fixture(); + const captured = await observe(observed => agentRecordQueries(observed).getById(f.workerId)); + expect(captured.calls).toBe(2); + expect(captured.bytes).toBeLessThan(8192); + expect(captured.result).toMatchObject({ id: f.workerId, companyId: f.companyId, adapterConfig: f.worker.adapterConfig, + runtimeConfig: f.worker.runtimeConfig, metadata: f.worker.metadata, permissions: { canCreateAgents: true }, spentMonthlyCents: 19.5, + orgChainHealth: { reason: "terminated_ancestor", firstInvalidAncestor: { id: f.managerId, name: "Manager" } } }); + expect((await db.select().from(agents).where(eq(agents.id, f.workerId)))[0]).toEqual(f.worker); + }); + + it("projects only current company chain fields for plugin normalization", async () => { + const f = await fixture(); + const captured = await observe(observed => agentRecordQueries(observed).listCompanyAgentEligibilityRows(f.companyId)); + expect(captured.calls).toBe(1); + expect(captured.bytes).toBeLessThan(4096); + expect(captured.result.map(row => row.id).sort()).toEqual([f.workerId, f.managerId, f.unrelatedId, f.archivedId].sort()); + for (const row of captured.result) expect(Object.keys(row).sort()).toEqual(["companyId", "id", "name", "reportsTo", "status"]); + const normalized = agentRecordQueries(db).normalizeAgentRow(f.worker, captured.result); + expect(normalized).toMatchObject({ adapterConfig: f.worker.adapterConfig, metadata: f.worker.metadata, + orgChainHealth: { reason: "terminated_ancestor", firstInvalidAncestor: { id: f.managerId } } }); + expect(await agentRecordQueries(db).listCompanyAgentEligibilityRows(randomUUID())).toEqual([]); + expect(await agentRecordQueries(db).getById(randomUUID())).toBeNull(); + }); + + it("rechecks manager status, name, selected configuration, missing managers, and cycles on later reads", async () => { + const f = await fixture(), records = agentRecordQueries(db); + expect((await records.getById(f.workerId))?.orgChainHealth.reason).toBe("terminated_ancestor"); + await db.update(agents).set({ status: "paused", name: "Current manager" }).where(eq(agents.id, f.managerId)); + await db.update(agents).set({ adapterConfig: { instructions: "changed instructions" } }).where(eq(agents.id, f.workerId)); + expect(await records.getById(f.workerId)).toMatchObject({ adapterConfig: { instructions: "changed instructions" }, + orgChainHealth: { status: "healthy", pausedAncestors: [{ id: f.managerId, name: "Current manager", status: "paused" }] } }); + await db.update(agents).set({ reportsTo: f.foreignId }).where(eq(agents.id, f.workerId)); + expect((await records.getById(f.workerId))?.orgChainHealth.reason).toBe("missing_manager"); + await db.update(agents).set({ reportsTo: f.managerId }).where(eq(agents.id, f.workerId)); + await db.update(agents).set({ reportsTo: f.workerId }).where(eq(agents.id, f.managerId)); + expect((await records.getById(f.workerId))?.orgChainHealth.reason).toBe("cycle"); + }); +}); diff --git a/server/src/lib/agent-records.ts b/server/src/lib/agent-records.ts index 786f61af550..25c0ed7c9f5 100644 --- a/server/src/lib/agent-records.ts +++ b/server/src/lib/agent-records.ts @@ -98,6 +98,8 @@ export interface CreateAgentOptions { claudeLogin?: ClaudeLoginContext; } +type AgentEligibilityRow = Pick; + interface AgentShortnameRow { id: string; name: string; @@ -340,7 +342,7 @@ export function agentRecordQueries(db: Db) { }; } - function normalizeAgentRows(rows: (typeof agents.$inferSelect)[], allCompanyRows = rows) { + function normalizeAgentRows(rows: (typeof agents.$inferSelect)[], allCompanyRows: AgentEligibilityRow[] = rows) { const eligibilityAgents = allCompanyRows.map(toEligibilityAgent); return rows.map((row) => { const base = normalizeAgentBaseRow(row); @@ -357,7 +359,7 @@ export function agentRecordQueries(db: Db) { }); } - function normalizeAgentRow(row: typeof agents.$inferSelect, allCompanyRows?: (typeof agents.$inferSelect)[]) { + function normalizeAgentRow(row: typeof agents.$inferSelect, allCompanyRows?: AgentEligibilityRow[]) { return normalizeAgentRows([row], allCompanyRows)[0]!; } @@ -365,6 +367,11 @@ export function agentRecordQueries(db: Db) { return db.select().from(agents).where(eq(agents.companyId, companyId)); } + async function listCompanyAgentEligibilityRows(companyId: string): Promise { + return db.select({ id: agents.id, companyId: agents.companyId, name: agents.name, + status: agents.status, reportsTo: agents.reportsTo }).from(agents).where(eq(agents.companyId, companyId)); + } + async function getMonthlySpendByAgentIds(companyId: string, agentIds: string[]) { if (agentIds.length === 0) return new Map(); const { start, end } = currentUtcMonthWindow(); @@ -405,7 +412,7 @@ export function agentRecordQueries(db: Db) { .then((rows) => rows[0] ?? null); if (!row) return null; const [companyRows, hydrated] = await Promise.all([ - listCompanyAgentRows(row.companyId), + listCompanyAgentEligibilityRows(row.companyId), hydrateAgentSpend([row]).then((rows) => rows[0]!), ]); return normalizeAgentRow(hydrated, companyRows); @@ -472,6 +479,6 @@ export function agentRecordQueries(db: Db) { }); } - return { normalizeAgentRows, normalizeAgentRow, listCompanyAgentRows, hydrateAgentSpend, + return { normalizeAgentRows, normalizeAgentRow, listCompanyAgentRows, listCompanyAgentEligibilityRows, hydrateAgentSpend, getById, ensureManager, assertNoCycle, assertCompanyShortnameAvailable, assertBuiltInAgentMetadataMutationAllowed }; } diff --git a/server/src/services/agents.ts b/server/src/services/agents.ts index 4c4cbd7248f..c9dd824f495 100644 --- a/server/src/services/agents.ts +++ b/server/src/services/agents.ts @@ -1,6 +1,6 @@ import { type BudgetServiceHooks } from "./budgets.js"; -import { and, desc, eq, inArray, ne } from "drizzle-orm"; +import { and, desc, eq, inArray } from "drizzle-orm"; import type { Db } from "@paperclipai/db"; import { agents, agentConfigRevisions, agentApiKeys, heartbeatRuns } from "@paperclipai/db"; import { isUuidLike, normalizeAgentApiKeyScope, normalizeAgentUrlKey, type AgentApiKeyScope } from "@paperclipai/shared"; @@ -31,14 +31,10 @@ export function agentService(db: Db, budgetHooks: BudgetServiceHooks = {}) { createAgentLifecycle(db, budgetHooks).updateConfiguration(...args); return { list: async (companyId: string, options?: { includeTerminated?: boolean }) => { - const conditions = [eq(agents.companyId, companyId)]; - if (!options?.includeTerminated) { - conditions.push(ne(agents.status, "terminated")); - } - const [rows, allCompanyRows] = await Promise.all([ - db.select().from(agents).where(and(...conditions)), - listCompanyAgentRows(companyId), - ]); + const allCompanyRows = await listCompanyAgentRows(companyId); + const rows = options?.includeTerminated + ? allCompanyRows + : allCompanyRows.filter((row) => row.status !== "terminated"); const hydrated = await hydrateAgentSpend(rows); return normalizeAgentRows(hydrated, allCompanyRows); }, diff --git a/server/src/services/plugin-agent-runtime-state.ts b/server/src/services/plugin-agent-runtime-state.ts index a1a4ce22ca7..0770246ef14 100644 --- a/server/src/services/plugin-agent-runtime-state.ts +++ b/server/src/services/plugin-agent-runtime-state.ts @@ -36,7 +36,7 @@ async function readState(db: Db, pluginId: string, companyId: string, agentId: s }; const instructions = await agentInstructionsService().getBundleLocation(agent); const records = agentRecordQueries(tx as unknown as Db); - const companyAgents = await records.listCompanyAgentRows(companyId); + const companyAgents = await records.listCompanyAgentEligibilityRows(companyId); return { revision: String(latest?.id ?? 0), agent: records.normalizeAgentRow(agent, companyAgents) as PluginAgentRuntimeState["agent"], instructionsRootPath: instructions.rootPath, instructionsEntryFile: instructions.entryFile, From bf9a8551c33fad7315fb635781483be260b14fde Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Sun, 25 Oct 2026 07:51:28 -0700 Subject: [PATCH 063/110] perf(issues): filter queued comment wakes by task (#17613) Apply the existing typed task identity filter in PostgreSQL before returning queued-comment wake controls. Preserve queue selection, ordering, payloads, and current run ownership checks. All 84 route tests, build, typecheck, exact-head Greptile 5/5, and required CI pass. The old source fails the new deferred and queued byte budgets; corrected reads preserve the complete response and all saved rows. Co-Authored-By: Paperclip --- doc/DATABASE.md | 5 +++ .../issue-queued-comments-routes.test.ts | 39 +++++++++++++++++++ server/src/routes/issues.ts | 1 + 3 files changed, 45 insertions(+) diff --git a/doc/DATABASE.md b/doc/DATABASE.md index 6c47e5d7495..780247fc5c8 100644 --- a/doc/DATABASE.md +++ b/doc/DATABASE.md @@ -238,6 +238,11 @@ for chain checks. The selected agent's full configuration, current monthly spend and existing response redaction remain available. Every call reads current data; these lookups do not cache authorization or agent configuration. +Queued-comment display filters wake requests by the current company, assigned +agent, status, and exact JSON string task identity in SQL. Other tasks' comment +identifiers stay in the database. The display projection, ordering, current run +ownership checks, and persisted wake payloads retain their existing contract. + ## 1. Embedded PostgreSQL — zero config If you don't set `DATABASE_URL`, the server automatically starts an embedded PostgreSQL instance and manages a local data directory. diff --git a/server/src/__tests__/issue-queued-comments-routes.test.ts b/server/src/__tests__/issue-queued-comments-routes.test.ts index 7b0af0e8a3d..e02d9708a38 100644 --- a/server/src/__tests__/issue-queued-comments-routes.test.ts +++ b/server/src/__tests__/issue-queued-comments-routes.test.ts @@ -252,6 +252,45 @@ describeEmbeddedPostgres("issue queued-comment routes", () => { } finally { capture.flush(); await observed.$client.end(); } }); + it.each(["deferred", "queued"])("filters unrelated task wakes before reading the %s comment queue", async state => { + const f = await seedQueue(); + if (state === "queued") await promoteQueue(f); + const path = `/api/issues/${f.issueId}/queued-comments`; + const expected = await request(app(f.companyId)).get(path).expect(200); + const unrelated = Array.from({ length: 80 }, (_, index) => ({ + companyId: f.companyId, agentId: f.agentId, source: "issue_comment", + status: index % 2 ? "queued" : "deferred_issue_execution", + requestedAt: new Date("2020-01-01T00:00:00Z"), + payload: { issueId: randomUUID(), _paperclipWakeContext: { + wakeCommentIds: Array.from({ length: 60 }, () => randomUUID()), + } }, + })); + const malformed = [null, [f.issueId], { id: f.issueId }, f.issueId.toUpperCase()]; + await db.insert(agentWakeupRequests).values([ + ...unrelated, + ...malformed.map(issueId => ({ companyId: f.companyId, agentId: f.agentId, + source: "issue_comment", status: "deferred_issue_execution", + requestedAt: new Date("2020-01-01T00:00:00Z"), + payload: { issueId, _paperclipWakeContext: { wakeCommentIds: f.commentIds } }, + })), + ]); + const observed = createDb(tempDb!.connectionString), events: Array> = [], now = Date.now(); + const capture = createDatabaseResponseCapture({ start: now - 100, end: now + 59_000 }, event => events.push(event)); + installDatabaseResponseCapture(observed, { agentWakeupRequests }, capture); + try { + const response = await request(app(f.companyId, "queue-owner", undefined, observed)).get(path).expect(200); + expect(response.body).toEqual(expected.body); + capture.flush(); + const reads = events.filter(event => event.table === "agent_wakeup_requests" && event.operation === "select"); + expect(reads.length).toBeGreaterThan(0); + expect(reads.reduce((bytes, event) => bytes + Number(event.responseValueBytes), 0)).toBeLessThan(4096); + expect(reads.reduce((rows, event) => rows + Number(event.rows), 0)).toBe(1); + expect(await db.select({ id: agentWakeupRequests.id }).from(agentWakeupRequests) + .where(eq(agentWakeupRequests.companyId, f.companyId))).toHaveLength(85); + await request(app(randomUUID(), "queue-owner", undefined, observed)).get(path).expect(404); + } finally { capture.flush(); await observed.$client.end(); } + }); + it.each(["cancelled", "running"])("rejects a late Done from an interrupted %s task run at the write boundary", async status => { const seeded = await seedQueue(); await db.update(heartbeatRuns).set({ status, resultJson: { executionCancellation: { state: "requested" } } }) diff --git a/server/src/routes/issues.ts b/server/src/routes/issues.ts index bb92497ea3b..bbdfdfb031b 100644 --- a/server/src/routes/issues.ts +++ b/server/src/routes/issues.ts @@ -7320,6 +7320,7 @@ export function issueRoutes( and( eq(agentWakeupRequests.companyId, issue.companyId), eq(agentWakeupRequests.agentId, issue.assigneeAgentId), + sql`${agentWakeupRequests.payload}->'issueId' = to_jsonb(${issue.id}::text)`, inArray(agentWakeupRequests.status, [ "deferred_issue_execution", "queued", From e33526556879e0720e95cd112a5faa3bffac8ce2 Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Sun, 25 Oct 2026 07:54:47 -0700 Subject: [PATCH 064/110] fix(ui): stop idle task run polling with live updates (#17608) Stop successful empty assigned-task run queries from polling only while the matching company and session connection is open. Preserve active, pending, failed, and disconnected cadence. Share one lifecycle refresh owner between the task and chat views, discover reviewer events without task identity, and refresh after older in-flight reads settle. All 175 focused tests, 9,079 UI tests, build, typecheck, exact-head Greptile 5/5, and required CI pass. Regression mutations catch reviewer discovery, duplicate reads, readiness, failure state, missing refreshes, and scope cleanup. Earlier E2E cleanup deadlock and server cleanup timeout remain documented; failed-only reruns passed on their same commits. Co-Authored-By: Paperclip --- doc/DATABASE.md | 15 + .../LiveUpdatesProvider.recovery.test.tsx | 359 +++++++++++++++++- ui/src/context/LiveUpdatesProvider.tsx | 86 ++++- ui/src/lib/live-runs-cache.test.ts | 18 +- ui/src/lib/live-runs-cache.ts | 10 + ui/src/pages/IssueDetail.tsx | 14 +- 6 files changed, 481 insertions(+), 21 deletions(-) diff --git a/doc/DATABASE.md b/doc/DATABASE.md index 780247fc5c8..8056e2468c3 100644 --- a/doc/DATABASE.md +++ b/doc/DATABASE.md @@ -145,6 +145,21 @@ patch does not refetch task details, activity, or run history. Unknown runs retain the existing refresh fallback. Run transitions, activity events, and reconnect recovery still refresh their affected data. +Task run queries stop interval polling only after a successful empty response +and an open shared live connection for the current company and session. Initial +reads, active work, errors, connection setup, and disconnections retain their +existing polling cadence. Company or session changes require a new connection. +Views without an assigned agent retain polling. Matching run lifecycle events +refresh the displayed task's run queries independently of route and window +focus. Events that omit task identity conservatively refresh these queries, +including reviewer runs from another agent. One parent view owns both query +observers and reuses refreshes already covered by the focused-route handler. A +matching event that overlaps an older request queues a fresh read after that +request settles. Connection readiness also reconciles the displayed run +queries after any older request. Follow-up reads belong to the current mounted +scope and stop when it changes or unmounts. The first open and reconnect still +reconcile missed events. + Connection-assignment checks select profile bindings for the current company or agent and read rules that can match the selected connection's catalog rows. All five selector kinds, null application matching, exclusions, and profile diff --git a/ui/src/context/LiveUpdatesProvider.recovery.test.tsx b/ui/src/context/LiveUpdatesProvider.recovery.test.tsx index b63381e9b44..591e735fa49 100644 --- a/ui/src/context/LiveUpdatesProvider.recovery.test.tsx +++ b/ui/src/context/LiveUpdatesProvider.recovery.test.tsx @@ -5,18 +5,19 @@ import { QueryClient, QueryClientProvider, useQuery } from "@tanstack/react-quer import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { queryKeys } from "../lib/queryKeys"; -const { pushToast } = vi.hoisted(() => ({ pushToast: vi.fn() })); +const { pushToast, companySelection, routeSelection } = vi.hoisted(() => ({ pushToast: vi.fn(), companySelection: { id: "company-1" }, routeSelection: { pathname: "/tasks" } })); const { sessionRead, healthRead } = vi.hoisted(() => ({ sessionRead: vi.fn(), healthRead: vi.fn() })); vi.mock("./CompanyContext", () => ({ - useCompany: () => ({ selectedCompanyId: "company-1", selectedCompany: { id: "company-1" } }), + useCompany: () => ({ selectedCompanyId: companySelection.id, selectedCompany: { id: companySelection.id } }), })); vi.mock("./ToastContext", () => ({ useToastActions: () => ({ pushToast }) })); -vi.mock("../lib/router", () => ({ useLocation: () => ({ pathname: "/tasks" }) })); +vi.mock("../lib/router", () => ({ useLocation: () => routeSelection })); vi.mock("../api/auth", () => ({ authApi: { getSession: sessionRead }, })); vi.mock("../api/health", () => ({ healthApi: { get: healthRead } })); -import { LiveUpdatesProvider } from "./LiveUpdatesProvider"; +import { LiveUpdatesProvider, useHasCompanyLiveConnection, useTaskRunLiveUpdates } from "./LiveUpdatesProvider"; +import { liveRunRefetchInterval } from "../lib/live-runs-cache"; (globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; @@ -25,8 +26,8 @@ class Socket { readyState = 1; onopen: (() => void) | null = null; onclose: (() => void) | null = null; - onmessage = null; - onerror = null; + onmessage: ((message: { data: string }) => void) | null = null; + onerror: (() => void) | null = null; constructor() { Socket.instances.push(this); } close() { this.readyState = 3; } } @@ -36,9 +37,13 @@ describe("LiveUpdatesProvider connection recovery", () => { let container: HTMLDivElement; let client: QueryClient; const read = vi.fn(async () => "current task data"); + const pollRead = vi.fn<() => Promise>(); beforeEach(() => { vi.useFakeTimers(); + companySelection.id = "company-1"; + routeSelection.pathname = "/tasks"; + pollRead.mockReset().mockResolvedValue([]); vi.spyOn(document, "visibilityState", "get").mockReturnValue("visible"); read.mockReset(); read.mockResolvedValue("current task data"); @@ -71,6 +76,348 @@ describe("LiveUpdatesProvider connection recovery", () => { await act(async () => vi.advanceTimersByTimeAsync(1)); } + function IdleRuns({ companyId }: { companyId: string }) { + const connected = useHasCompanyLiveConnection(companyId); + useQuery({ + queryKey: [companyId, "idle-run-fixture"], + queryFn: pollRead, + refetchInterval: (query) => liveRunRefetchInterval(connected, query.state, 1000), + }); + return {connected ? "connected" : "fallback"}; + } + + async function renderPolling(companyId = companySelection.id, withProvider = true) { + const child = ; + await act(async () => root.render( + + {withProvider ? {child} : child} + , + )); + await act(async () => vi.advanceTimersByTimeAsync(1)); + } + + async function advancePolls(count: number) { + for (let i = 0; i < count; i += 1) { + await act(async () => vi.advanceTimersByTimeAsync(1001)); + } + } + + it.each([null, []])("keeps setup polling, then stops known-empty polling after connection for %j", async (data) => { + vi.stubGlobal("WebSocket", Socket); + pollRead.mockResolvedValue(data); + await renderPolling(); + expect(container.textContent).toBe("fallback"); + pollRead.mockClear(); + await advancePolls(3); + expect(pollRead.mock.calls.length).toBeGreaterThanOrEqual(3); + await act(async () => Socket.instances[0].onopen?.()); + await act(async () => vi.advanceTimersByTimeAsync(1)); + expect(container.textContent).toBe("connected"); + const readsAfterOpen = pollRead.mock.calls.length; + await advancePolls(10); + expect(pollRead).toHaveBeenCalledTimes(readsAfterOpen); + }); + + it.each([[{ id: "run-1" }], { id: "run-1" }])("keeps active work polling while connected for %j", async (data) => { + vi.stubGlobal("WebSocket", Socket); + pollRead.mockResolvedValue(data); + await renderPolling(); + await act(async () => Socket.instances[0].onopen?.()); + pollRead.mockClear(); + await advancePolls(3); + expect(pollRead.mock.calls.length).toBeGreaterThanOrEqual(3); + }); + + it("keeps polling a failed query with previously empty data until it recovers", async () => { + vi.stubGlobal("WebSocket", Socket); + await renderPolling(); + await act(async () => Socket.instances[0].onopen?.()); + pollRead.mockRejectedValue(new Error("Read unavailable")); + await act(async () => { await client.invalidateQueries({ queryKey: ["company-1", "idle-run-fixture"] }); }); + expect(client.getQueryState(["company-1", "idle-run-fixture"])?.status).toBe("error"); + pollRead.mockClear(); + await advancePolls(3); + expect(pollRead.mock.calls.length).toBeGreaterThanOrEqual(3); + pollRead.mockResolvedValue([]); + await advancePolls(1); + expect(client.getQueryState(["company-1", "idle-run-fixture"])?.status).toBe("success"); + const afterRecovery = pollRead.mock.calls.length; + await advancePolls(5); + expect(pollRead).toHaveBeenCalledTimes(afterRecovery); + }); + + it("retains an initial pending read until it resolves after the connection opens", async () => { + vi.stubGlobal("WebSocket", Socket); + let resolveRead!: (value: unknown) => void; + pollRead.mockImplementation(() => new Promise((resolve) => { resolveRead = resolve; })); + await renderPolling(); + await act(async () => Socket.instances[0].onopen?.()); + expect(container.textContent).toBe("connected"); + expect(client.getQueryState(["company-1", "idle-run-fixture"])?.status).toBe("pending"); + expect(pollRead).toHaveBeenCalledTimes(1); + await act(async () => resolveRead([])); + await act(async () => vi.advanceTimersByTimeAsync(1)); + expect(client.getQueryData(["company-1", "idle-run-fixture"])).toEqual([]); + await advancePolls(5); + expect(pollRead).toHaveBeenCalledTimes(1); + }); + + it("resumes local polling on error before close, and stops it after recovery", async () => { + vi.stubGlobal("WebSocket", Socket); + await renderPolling(); + const first = Socket.instances[0]; + await act(async () => first.onopen?.()); + await act(async () => first.onerror?.()); + expect(container.textContent).toBe("fallback"); + pollRead.mockClear(); + await advancePolls(3); + expect(pollRead.mock.calls.length).toBeGreaterThanOrEqual(3); + await act(async () => first.onclose?.()); + await advancePolls(2); + expect(Socket.instances.length).toBeGreaterThan(1); + await act(async () => Socket.instances.at(-1)?.onopen?.()); + expect(container.textContent).toBe("connected"); + const afterRecovery = pollRead.mock.calls.length; + await advancePolls(10); + expect(pollRead).toHaveBeenCalledTimes(afterRecovery); + }); + + it.each(["company", "session"])("requires a new connection after a %s change and ignores stale callbacks", async (scope) => { + vi.stubGlobal("WebSocket", Socket); + await renderPolling(); + const first = Socket.instances[0]; + await act(async () => first.onopen?.()); + const oldOpen = first.onopen, oldClose = first.onclose, oldError = first.onerror; + if (scope === "company") { + companySelection.id = "company-2"; + await renderPolling(); + } else { + const nextSession = { user: { id: "viewer" }, session: { id: "replacement-session", userId: "viewer" } }; + sessionRead.mockResolvedValue(nextSession); + await act(async () => client.setQueryData(queryKeys.auth.session, nextSession)); + await act(async () => vi.advanceTimersByTimeAsync(1)); + } + expect(container.textContent).toBe("fallback"); + await act(async () => oldOpen?.()); + expect(container.textContent).toBe("fallback"); + pollRead.mockClear(); + await advancePolls(2); + expect(pollRead.mock.calls.length).toBeGreaterThanOrEqual(2); + await act(async () => Socket.instances.at(-1)?.onopen?.()); + expect(container.textContent).toBe("connected"); + await act(async () => { oldClose?.(); oldError?.(); }); + expect(container.textContent).toBe("connected"); + const afterOpen = pollRead.mock.calls.length; + await advancePolls(5); + expect(pollRead).toHaveBeenCalledTimes(afterOpen); + }); + + it("discovers matching new runs after empty polling stops on an unfocused non-task route", async () => { + vi.stubGlobal("WebSocket", Socket); + vi.spyOn(document, "hasFocus").mockReturnValue(false); + const queryRef = "DEMO-1"; + const runRead = vi.fn<() => Promise>().mockResolvedValue([]); + const activeRead = vi.fn<() => Promise>().mockResolvedValue(null); + function TaskRuns() { + const connected = useTaskRunLiveUpdates({ companyId: "company-1", issueId: "issue-1", issueQueryRef: queryRef, assigneeAgentId: "agent-1" }); + const runs = useQuery({ queryKey: queryKeys.issues.liveRuns(queryRef), queryFn: runRead, + refetchInterval: (query) => liveRunRefetchInterval(connected, query.state, 1000) }); + useQuery({ queryKey: queryKeys.issues.activeRun(queryRef), queryFn: activeRead, + refetchInterval: (query) => liveRunRefetchInterval(connected, query.state, 1000) }); + return {JSON.stringify(runs.data)}; + } + await act(async () => root.render()); + await act(async () => vi.advanceTimersByTimeAsync(1)); + const socket = Socket.instances[0]; + await act(async () => socket.onopen?.()); + runRead.mockClear(); activeRead.mockClear(); + await advancePolls(5); + expect(runRead).not.toHaveBeenCalled(); + expect(activeRead).not.toHaveBeenCalled(); + const deliver = async (companyId: string, payload: Record) => { + await act(async () => socket.onmessage?.({ data: JSON.stringify({ id: 1, companyId, + type: "heartbeat.run.queued", createdAt: "2020-01-01T00:00:00Z", payload }) })); + await act(async () => vi.advanceTimersByTimeAsync(1)); + }; + await deliver("company-2", { issueId: "issue-1", agentId: "agent-1", runId: "foreign" }); + await deliver("company-1", { issueId: "other-issue", agentId: "agent-1", runId: "other" }); + expect(runRead).not.toHaveBeenCalled(); + expect(activeRead).not.toHaveBeenCalled(); + runRead.mockResolvedValue([{ id: "new-run", status: "running" }]); + activeRead.mockResolvedValue({ id: "new-run", status: "running" }); + await deliver("company-1", { issueId: "issue-1", agentId: "new-agent", runId: "new-run" }); + expect(runRead).toHaveBeenCalledTimes(1); + expect(activeRead).toHaveBeenCalledTimes(1); + expect(container.textContent).toContain("new-run"); + await deliver("company-1", { agentId: "reviewer-agent", runId: "reviewer-run-without-task-id" }); + expect(runRead).toHaveBeenCalledTimes(2); + expect(activeRead).toHaveBeenCalledTimes(2); + }); + + it.each(["initial", "background", "connection setup"])("refetches after an older empty %s read settles when run events arrive during it", async (phase) => { + vi.stubGlobal("WebSocket", Socket); + vi.spyOn(document, "hasFocus").mockReturnValue(false); + const queryKey = queryKeys.issues.liveRuns("DEMO-1"); + const runRead = vi.fn<() => Promise>().mockResolvedValue([]); + let resolveOlder!: (value: unknown) => void; + const older = new Promise((resolve) => { resolveOlder = resolve; }); + if (phase !== "background") runRead.mockImplementationOnce(() => older); + function TaskRuns() { + const connected = useTaskRunLiveUpdates({ companyId: "company-1", issueId: "issue-1", issueQueryRef: "DEMO-1", assigneeAgentId: "agent-1" }); + const { data } = useQuery({ queryKey, queryFn: runRead, + refetchInterval: (query) => liveRunRefetchInterval(connected, query.state, 1000) }); + return {JSON.stringify(data)}; + } + await act(async () => root.render()); + await act(async () => vi.advanceTimersByTimeAsync(1)); + const socket = Socket.instances[0]; + await act(async () => socket.onopen?.()); + if (phase === "background") { + runRead.mockClear(); + runRead.mockImplementationOnce(() => older); + await act(async () => { void client.invalidateQueries({ queryKey }); }); + } + runRead.mockResolvedValue([{ id: "new-run", status: "running" }]); + expect(runRead).toHaveBeenCalledTimes(1); + await act(async () => { + for (let id = 1; phase !== "connection setup" && id <= 3; id += 1) socket.onmessage?.({ data: JSON.stringify({ id, + companyId: "company-1", type: "heartbeat.run.queued", createdAt: "2020-01-01T00:00:00Z", + payload: { issueId: "issue-1", agentId: "agent-1", runId: "new-run" } }) }); + }); + expect(runRead).toHaveBeenCalledTimes(1); + await act(async () => resolveOlder([])); + await act(async () => vi.advanceTimersByTimeAsync(1)); + expect(runRead).toHaveBeenCalledTimes(2); + expect(client.getQueryData(queryKey)).toEqual([{ id: "new-run", status: "running" }]); + expect(container.textContent).toContain("new-run"); + }); + + it.each(["unmount", "disconnect", "company", "session", "task"])("discards the old follow-up refresh after %s during an older read", async (change) => { + vi.stubGlobal("WebSocket", Socket); + let resolveOlder!: (value: unknown) => void; + const older = new Promise((resolve) => { resolveOlder = resolve; }); + const runRead = vi.fn<() => Promise>().mockResolvedValue([]).mockImplementationOnce(() => older); + function TaskRuns({ task = "1" }: { task?: string }) { + const queryRef = `DEMO-${task}`; + const connected = useTaskRunLiveUpdates({ companyId: "company-1", issueId: `issue-${task}`, issueQueryRef: queryRef, assigneeAgentId: "agent-1" }); + useQuery({ queryKey: queryKeys.issues.liveRuns(queryRef), queryFn: runRead, + refetchInterval: (query) => liveRunRefetchInterval(connected, query.state, 1000) }); + return null; + } + const render = async (task = "1") => { + await act(async () => root.render()); + await act(async () => vi.advanceTimersByTimeAsync(1)); + }; + await render(); + const socket = Socket.instances[0]; + await act(async () => socket.onopen?.()); + await act(async () => socket.onmessage?.({ data: JSON.stringify({ id: 1, companyId: "company-1", + type: "heartbeat.run.queued", createdAt: "2020-01-01T00:00:00Z", + payload: { issueId: "issue-1", agentId: "agent-1", runId: "new-run" } }) })); + if (change === "unmount") await act(async () => root.unmount()); + if (change === "disconnect") await act(async () => socket.onerror?.()); + if (change === "company") { companySelection.id = "company-2"; await render(); } + if (change === "task") await render("2"); + if (change === "session") { + const nextSession = { user: { id: "viewer" }, session: { id: "replacement-session", userId: "viewer" } }; + sessionRead.mockResolvedValue(nextSession); + await act(async () => client.setQueryData(queryKeys.auth.session, nextSession)); + await act(async () => vi.advanceTimersByTimeAsync(1)); + } + const readsAfterChange = runRead.mock.calls.length; + const invalidate = vi.spyOn(client, "invalidateQueries"); + await act(async () => resolveOlder([])); + await act(async () => vi.advanceTimersByTimeAsync(1)); + expect(runRead).toHaveBeenCalledTimes(readsAfterChange); + expect(invalidate).not.toHaveBeenCalled(); + }); + + it.each(["focused", "unfocused"])("refreshes once for a start event with two run observers on a %s task view", async focus => { + vi.stubGlobal("WebSocket", Socket); + vi.spyOn(document, "hasFocus").mockReturnValue(focus === "focused"); + routeSelection.pathname = "/DEMO/issues/DEMO-1"; + const queryRef = "DEMO-1"; + client.setQueryData(queryKeys.issues.detail(queryRef), { id: "issue-1", companyId: "company-1", assigneeAgentId: "agent-1" }); + const runRead = vi.fn<() => Promise>().mockResolvedValue([]); + const activeRead = vi.fn<() => Promise>().mockResolvedValue(null); + function Reads({ connected, interval }: { connected: boolean; interval: number }) { + useQuery({ queryKey: queryKeys.issues.liveRuns(queryRef), queryFn: runRead, + refetchInterval: query => liveRunRefetchInterval(connected, query.state, interval) }); + useQuery({ queryKey: queryKeys.issues.activeRun(queryRef), queryFn: activeRead, + refetchInterval: query => liveRunRefetchInterval(connected, query.state, interval) }); + return null; + } + function TaskRuns() { + const connected = useTaskRunLiveUpdates({ companyId: "company-1", issueId: "issue-1", issueQueryRef: queryRef, assigneeAgentId: "agent-1" }); + return <>; + } + await act(async () => root.render()); + await act(async () => vi.advanceTimersByTimeAsync(1)); + const socket = Socket.instances[0]; + await act(async () => socket.onopen?.()); + await act(async () => vi.advanceTimersByTimeAsync(301)); + runRead.mockClear(); activeRead.mockClear(); + await act(async () => socket.onmessage?.({ data: JSON.stringify({ id: 1, companyId: "company-1", + type: "heartbeat.run.queued", createdAt: "2020-01-01T00:00:00Z", + payload: { agentId: "agent-1", runId: "new-run" } }) })); + await act(async () => vi.advanceTimersByTimeAsync(301)); + expect(runRead).toHaveBeenCalledTimes(1); + expect(activeRead).toHaveBeenCalledTimes(1); + }); + + it("keeps polling unassigned tasks even with a healthy shared connection", async () => { + vi.stubGlobal("WebSocket", Socket); + function UnassignedTask() { + const connected = useTaskRunLiveUpdates({ companyId: "company-1", issueId: "issue-1", issueQueryRef: "issue-1", assigneeAgentId: null }); + useQuery({ queryKey: queryKeys.issues.liveRuns("issue-1"), queryFn: pollRead, + refetchInterval: (query) => liveRunRefetchInterval(connected, query.state, 1000) }); + return {connected ? "connected" : "fallback"}; + } + await act(async () => root.render()); + await act(async () => vi.advanceTimersByTimeAsync(1)); + await act(async () => Socket.instances[0].onopen?.()); + expect(container.textContent).toBe("fallback"); + pollRead.mockClear(); + await advancePolls(2); + expect(pollRead.mock.calls.length).toBeGreaterThanOrEqual(2); + }); + + it("retains polling for another company and outside the provider", async () => { + vi.stubGlobal("WebSocket", Socket); + await renderPolling("company-2"); + await act(async () => Socket.instances[0].onopen?.()); + expect(container.textContent).toBe("fallback"); + pollRead.mockClear(); + await advancePolls(2); + expect(pollRead.mock.calls.length).toBeGreaterThanOrEqual(2); + await renderPolling("company-2", false); + expect(container.textContent).toBe("fallback"); + pollRead.mockClear(); + await advancePolls(2); + expect(pollRead.mock.calls.length).toBeGreaterThanOrEqual(2); + }); + + it("drops readiness while hidden and does not poll or retry after unmount", async () => { + vi.stubGlobal("WebSocket", Socket); + await renderPolling(); + await act(async () => Socket.instances[0].onopen?.()); + const visibility = vi.spyOn(document, "visibilityState", "get"); + await act(async () => { + visibility.mockReturnValue("hidden"); + document.dispatchEvent(new Event("visibilitychange")); + }); + expect(container.textContent).toBe("fallback"); + pollRead.mockClear(); + const count = Socket.instances.length; + await advancePolls(5); + expect(pollRead).not.toHaveBeenCalled(); + expect(Socket.instances).toHaveLength(count); + await act(async () => root.unmount()); + await advancePolls(5); + expect(pollRead).not.toHaveBeenCalled(); + expect(Socket.instances).toHaveLength(count); + }); + it("reconciles updates between the initial query and the first socket connection", async () => { vi.stubGlobal("WebSocket", Socket); await render(); diff --git a/ui/src/context/LiveUpdatesProvider.tsx b/ui/src/context/LiveUpdatesProvider.tsx index 5f634a8cdde..d24879ba378 100644 --- a/ui/src/context/LiveUpdatesProvider.tsx +++ b/ui/src/context/LiveUpdatesProvider.tsx @@ -7,6 +7,7 @@ import { useEffect, useMemo, useRef, + useState, type ReactNode, } from "react"; import { @@ -87,6 +88,13 @@ interface LiveEventSubscription { const LiveEventSubscriptionContext = createContext(null); +const CompanyLiveConnectionContext = createContext(null); + +export function useHasCompanyLiveConnection(companyId: string | null | undefined): boolean { + const connectedCompanyId = useContext(CompanyLiveConnectionContext); + return Boolean(companyId && connectedCompanyId === companyId); +} + function dispatchLiveEventToSubscribers( subscribers: Set, expectedCompanyId: string, @@ -126,6 +134,51 @@ export function useCompanyLiveEvent(handler: CompanyLiveEventHandler): void { }, [subscription]); } +export function useTaskRunLiveUpdates(scope: { + companyId: string | null | undefined; + issueId: string | null | undefined; + issueQueryRef: string; + assigneeAgentId: string | null | undefined; +}): boolean { + const connected = useHasCompanyLiveConnection(scope.companyId); + const queryClient = useQueryClient(); + const location = useLocation(); + const refreshOwner = useRef<{ active: boolean } | null>(null); + const refreshRuns = useCallback((coveredByVisibleRoute = false) => { + const owner = refreshOwner.current; + if (!owner?.active) return; + for (const queryKey of [queryKeys.issues.liveRuns(scope.issueQueryRef), queryKeys.issues.activeRun(scope.issueQueryRef)]) { + const query = queryClient.getQueryCache().find({ queryKey }); + if (query?.state.fetchStatus === "fetching") { + void (query.promise ?? queryClient.invalidateQueries({ queryKey }, { cancelRefetch: false })) + .catch(() => undefined).then(() => { + if (owner.active) return queryClient.invalidateQueries({ queryKey }, { cancelRefetch: false }); + }); + } else if (!coveredByVisibleRoute) { + void queryClient.invalidateQueries({ queryKey }, { cancelRefetch: false }); + } + } + }, [queryClient, scope.issueQueryRef]); + useEffect(() => { + const owner = { active: true }; + refreshOwner.current = owner; + if (connected && scope.issueId && scope.assigneeAgentId) refreshRuns(); + return () => { owner.active = false; }; + }, [connected, refreshRuns, scope.companyId, scope.issueId, scope.assigneeAgentId]); + useCompanyLiveEvent((event) => { + if (event.companyId !== scope.companyId || !scope.issueId || + (event.type !== "heartbeat.run.queued" && event.type !== "heartbeat.run.status")) return; + const issueId = readString(event.payload.issueId); + const matches = issueId + ? issueId === scope.issueId || issueId === scope.issueQueryRef + : true; + if (!matches) return; + const visible = resolveVisibleIssueRouteContext(queryClient, location.pathname); + refreshRuns(Boolean(visible?.issueRefs.has(scope.issueQueryRef) && runEventMatchesVisibleIssue(visible, event.payload))); + }); + return connected && Boolean(scope.issueId && scope.assigneeAgentId); +} + function readString(value: unknown): string | null { return typeof value === "string" && value.length > 0 ? value : null; } @@ -476,6 +529,13 @@ function shouldSuppressRunStatusToastForVisibleIssue( ); } +function runEventMatchesVisibleIssue(context: VisibleIssueRouteContext, payload: Record): boolean { + const runId = readString(payload.runId); + const agentId = readString(payload.agentId); + return (runId !== null && context.runIds.has(runId)) || + Boolean(agentId && context.assigneeAgentId && agentId === context.assigneeAgentId); +} + function invalidateVisibleIssueRunQueries( queryClient: QueryClient, pathname: string, @@ -490,13 +550,7 @@ function invalidateVisibleIssueRunQueries( if (!context) return false; const runId = readString(payload.runId); - const agentId = readString(payload.agentId); - const matchesVisibleIssue = - (runId !== null && context.runIds.has(runId)) || - (!!agentId && - !!context.assigneeAgentId && - agentId === context.assigneeAgentId); - if (!matchesVisibleIssue) return false; + if (!runEventMatchesVisibleIssue(context, payload)) return false; const status = readString(payload.status); if (runId && status && TERMINAL_RUN_STATUSES.has(status)) { @@ -1988,7 +2042,9 @@ export function LiveUpdatesProvider({ children }: { children: ReactNode }) { const currentUserId = session?.user?.id ?? session?.session?.userId ?? (health?.deploymentMode === "local_trusted" ? "local-board" : null); const socketAuthKey = session?.session?.id ?? currentUserId ?? "signed_out"; + const [connectedScopeKey, setConnectedScopeKey] = useState(null); const liveCompanyId = resolveLiveCompanyId(selectedCompanyId, selectedCompany?.id ?? null); + const socketScopeKey = JSON.stringify([liveCompanyId, socketAuthKey]); const canConnectSocket = canUseLiveSession(sessionStatus, session != null, health?.deploymentMode) && liveCompanyId !== null; const currentActorRef = useRef<{ userId: string | null; agentId: string | null }>({ userId: currentUserId, @@ -2104,6 +2160,7 @@ export function LiveUpdatesProvider({ children }: { children: ReactNode }) { closeSocketQuietly(nextSocket, "stale_connection"); return; } + setConnectedScopeKey(socketScopeKey); stopPolling(); if (reconnectAttempt > 0) { gateRef.current.suppressUntil = Date.now() + RECONNECT_SUPPRESS_MS; @@ -2155,6 +2212,8 @@ export function LiveUpdatesProvider({ children }: { children: ReactNode }) { }; nextSocket.onerror = () => { + if (closed || socket !== nextSocket) return; + setConnectedScopeKey((current) => current === socketScopeKey ? null : current); // Wait for onclose to drive the reconnect. Self-closing here is what // produces the "closed before connection established" browser noise. }; @@ -2163,6 +2222,7 @@ export function LiveUpdatesProvider({ children }: { children: ReactNode }) { if (socket !== nextSocket) return; socket = null; if (closed) return; + setConnectedScopeKey((current) => current === socketScopeKey ? null : current); startPolling(); scheduleReconnect(); }; @@ -2175,6 +2235,7 @@ export function LiveUpdatesProvider({ children }: { children: ReactNode }) { return () => { closed = true; + setConnectedScopeKey((current) => current === socketScopeKey ? null : current); window.clearTimeout(connectTimer); clearReconnect(); stopPolling(); @@ -2191,11 +2252,16 @@ export function LiveUpdatesProvider({ children }: { children: ReactNode }) { pushToast, canConnectSocket, socketAuthKey, + socketScopeKey, ]); return ( - - {children} - + + + {children} + + ); } diff --git a/ui/src/lib/live-runs-cache.test.ts b/ui/src/lib/live-runs-cache.test.ts index fc388e1ee24..c908e44c590 100644 --- a/ui/src/lib/live-runs-cache.test.ts +++ b/ui/src/lib/live-runs-cache.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; import type { LiveRunForIssue } from "../api/heartbeats"; -import { patchRunStatusInList, removeRunFromList } from "./live-runs-cache"; +import { liveRunRefetchInterval, patchRunStatusInList, removeRunFromList } from "./live-runs-cache"; function run(id: string, status: string): LiveRunForIssue { return { @@ -62,3 +62,19 @@ describe("patchRunStatusInList", () => { expect(next).toBeUndefined(); }); }); + +describe("liveRunRefetchInterval", () => { + it.each(["pending", "error"] as const)("keeps polling %s queries with retained empty data", (status) => { + expect(liveRunRefetchInterval(true, { status, data: [] }, 1000)).toBe(1000); + expect(liveRunRefetchInterval(true, { status, data: null }, 3000)).toBe(3000); + }); + it.each([null, []])("stops known-empty polling with a connected company for %j", (data) => { + expect(liveRunRefetchInterval(true, { status: "success", data }, 1000)).toBe(false); + expect(liveRunRefetchInterval(false, { status: "success", data }, 1000)).toBe(1000); + }); + + it.each([undefined, {}, [run("active", "running")], "invalid", 0])("preserves polling for unknown or active data %j", (data) => { + expect(liveRunRefetchInterval(true, { status: "success", data }, 3000)).toBe(3000); + expect(liveRunRefetchInterval(false, { status: "success", data }, 3000)).toBe(3000); + }); +}); diff --git a/ui/src/lib/live-runs-cache.ts b/ui/src/lib/live-runs-cache.ts index f0533d20c6d..77b09ba29de 100644 --- a/ui/src/lib/live-runs-cache.ts +++ b/ui/src/lib/live-runs-cache.ts @@ -47,3 +47,13 @@ export function patchRunStatusInList( // or its status already matched) so redundant events don't trigger re-renders. return { next: changed ? next : runs, present }; } + +export function liveRunRefetchInterval( + connected: boolean, + state: { status: "pending" | "error" | "success"; data: unknown }, + fallbackMs: number, +): number | false { + return connected && state.status === "success" && (state.data === null || (Array.isArray(state.data) && state.data.length === 0)) + ? false + : fallbackMs; +} diff --git a/ui/src/pages/IssueDetail.tsx b/ui/src/pages/IssueDetail.tsx index abac74816d5..7394e3180c3 100644 --- a/ui/src/pages/IssueDetail.tsx +++ b/ui/src/pages/IssueDetail.tsx @@ -1,3 +1,5 @@ +import { useTaskRunLiveUpdates } from "../context/LiveUpdatesProvider"; +import { liveRunRefetchInterval } from "../lib/live-runs-cache"; import { useTaskRetry } from "../hooks/useTaskRetry"; import { grokBotApi } from "@/api/grokBot"; import { WorkspaceBaseRefRecoveryProvider } from "../components/WorkspaceBaseRefRecovery"; @@ -1204,6 +1206,7 @@ type IssueDetailChatTabProps = { interruption?: Issue["interruption"]; retryPreparing?: boolean; queryIssueId?: string; + hasLiveConnection: boolean; browsers?: import("@paperclipai/shared").TaskBrowser[]; onOpenBrowser?: (browserId: string) => void; onOpenSkill?: (skillId: string, name: string) => void; @@ -1365,6 +1368,7 @@ const IssueDetailChatTab = memo(function IssueDetailChatTab({ interruption, retryPreparing, queryIssueId, + hasLiveConnection, browsers, onOpenBrowser, onOpenSkill, @@ -1498,7 +1502,7 @@ const IssueDetailChatTab = memo(function IssueDetailChatTab({ queryKey: queryKeys.issues.liveRuns(issueQueryRef), queryFn: () => heartbeatsApi.liveRunsForIssue(issueQueryRef), enabled: !!issueId, - refetchInterval: 1000, + refetchInterval: (query) => liveRunRefetchInterval(hasLiveConnection, query.state, 1000), placeholderData: keepPreviousDataForSameQueryTail(issueQueryRef), }); @@ -1515,7 +1519,7 @@ const IssueDetailChatTab = memo(function IssueDetailChatTab({ queryKey: queryKeys.issues.activeRun(issueQueryRef), queryFn: () => heartbeatsApi.activeRunForIssue(issueQueryRef), enabled: activeRunQueryEnabled, - refetchInterval: liveRunCount > 0 ? false : 1000, + refetchInterval: (query) => liveRunCount > 0 ? false : liveRunRefetchInterval(hasLiveConnection, query.state, 1000), placeholderData: keepPreviousDataForSameQueryTail( issueQueryRef, ), @@ -3275,6 +3279,7 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS !hasLegacyIssueDetailQuery(location.search) )); const resolvedCompanyId = issue?.companyId ?? selectedCompanyId; + const hasLiveConnection = useTaskRunLiveUpdates({ companyId: resolvedCompanyId, issueId: issue?.id ?? issueId, issueQueryRef: issueId ?? "pending", assigneeAgentId: issue?.assigneeAgentId }); const externalObjectsState = useIssueExternalObjects(conversation && !conversation.issue ? null : issue?.id ?? null); // A closed isolated workspace no longer blocks the composer. The server reopens // the workspace when the next comment or resume arrives, so the composer stays @@ -3414,7 +3419,7 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS queryKey: queryKeys.issues.liveRuns(issueId!), queryFn: () => heartbeatsApi.liveRunsForIssue(issueId!), enabled: !!issueId, - refetchInterval: 3000, + refetchInterval: (query) => liveRunRefetchInterval(hasLiveConnection, query.state, 3000), select: (runs) => runs.length, placeholderData: keepPreviousDataForSameQueryTail( issueId ?? "pending", @@ -3431,7 +3436,7 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS queryFn: () => heartbeatsApi.activeRunForIssue(issueId!), enabled: !!issueId && (!!issue?.executionRunId || issue?.status === "in_progress"), - refetchInterval: liveRunCount > 0 ? false : 3000, + refetchInterval: (query) => liveRunCount > 0 ? false : liveRunRefetchInterval(hasLiveConnection, query.state, 3000), select: (run) => !!run, placeholderData: keepPreviousDataForSameQueryTail( issueId ?? "pending", @@ -8150,6 +8155,7 @@ export function TaskDetailSurface({ conversation, tasksTab }: { tasksTab?: TaskS interruption={issue.interruption} retryPreparing={taskRetry.optimistic} queryIssueId={issueId ?? issue.id} + hasLiveConnection={hasLiveConnection} onOpenSkill={handleOpenSkill} browsers={browserQuery.data} onOpenBrowser={(id) => { setOpenBrowserId(id); if (isMobile) setMobilePropsOpen(true); else openTaskSidePanel(); }} From 7ebf98eafd2fea1413fa72876ac705d1d59ae37d Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Sun, 25 Oct 2026 08:22:53 -0700 Subject: [PATCH 065/110] fix(recovery): avoid duplicate terminal run status notifications (#17614) Retain pending status deliveries when Native or legacy terminal recovery projects the same state. Preserve completion time on unchanged Native terminal status. Real state, metadata, error, explicit patch, and retained-file changes still notify. The publisher acknowledgement, accepted results, retry deadlines, recovery holds, ownership checks, and workspace cleanup remain intact. Correct the queued Retry browser fixture race by releasing its old-process guard at the exact Retry request, requiring a successful response, and retaining fixture cleanup after failure. Validated by 159 focused tests, 653 wider Native recovery tests, six real Chromium/PostgreSQL browser cases, five queued Retry repeats, build/typecheck, exact-head Apex 5/5, and green required CI. The original detached-button CI timeout is documented in the PR. The additional full local repository Vitest command is still running and is not claimed complete. Co-Authored-By: Paperclip --- doc/DATABASE.md | 11 ++ .../legacy-workspace-restore-recovery.test.ts | 63 ++++++++- .../src/services/legacy-execution-recovery.ts | 14 +- .../native-runtime/native-run-finalizer.ts | 43 +++--- .../native-terminal-status-projection.test.ts | 132 ++++++++++++++++++ tests/e2e/legacy-failure-continuation.spec.ts | 26 +++- 6 files changed, 262 insertions(+), 27 deletions(-) create mode 100644 server/src/services/native-runtime/native-terminal-status-projection.test.ts diff --git a/doc/DATABASE.md b/doc/DATABASE.md index 8056e2468c3..e5478530c02 100644 --- a/doc/DATABASE.md +++ b/doc/DATABASE.md @@ -246,6 +246,17 @@ The benchmark loads the baseline authorization module with current dependencies, compares complete workspace rows, and prints five warm samples and query plans. It measures SQL execution, not the full repository admission or agent startup. +Native finalization retries preserve a run's terminal completion time when its +status is unchanged. A retry mints another status delivery only when the current +run's status, finalization metadata, phase, error fields, or missing completion +time changes. An unchanged projection retains its existing pending delivery ID, +including after a publish failure. Status delivery stays at least once; retry +deadlines, recovery, accepted results, and workspace cleanup still run normally. +Legacy recovery also retains the pending delivery when status is unchanged and +no patch was supplied. Explicit patches, new terminal statuses, and newly +retained workspace evidence still create a delivery. File retention, ownership +checks, failed write conditions, lock cleanup, and recovery holds still apply. + Agent lists read the complete company roster once and use that same snapshot for termination filtering and organization-chain normalization. Detail and plugin runtime reads load only identity, company, name, status, and manager from other company agents diff --git a/server/src/__tests__/legacy-workspace-restore-recovery.test.ts b/server/src/__tests__/legacy-workspace-restore-recovery.test.ts index 493304a72fe..4629092e10e 100644 --- a/server/src/__tests__/legacy-workspace-restore-recovery.test.ts +++ b/server/src/__tests__/legacy-workspace-restore-recovery.test.ts @@ -1,6 +1,6 @@ import { randomUUID } from "node:crypto"; import { and, eq, sql } from "drizzle-orm"; -import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; import { agents, companies, createDb, environmentLeases, environments, executionWorkspaces, heartbeatRuns, issueRecoveryActions, issues, projects } from "@paperclipai/db"; import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; import { recordLegacyWorkspaceRestoreFailure, legacyExecutionNeedsReconciliationWithEvidence, terminalizeLegacyExecution } from "../services/legacy-execution-recovery.js"; @@ -8,6 +8,7 @@ import { hasConversationContinuationPolicy, conversationRecoveryActionPredicate import { preserveWorkspaceRestoreRecoveryMetadataSql } from "../services/legacy-workspace-restore-recovery.js"; import { hasConfirmedSandboxStopAndRetain, prepareSandboxStopAndRetain, settleStopOnlyCleanup } from "../services/sandbox-stop-and-retain.js"; import { environmentService } from "../services/environments.js"; +import { deliverExecutionStatuses } from "../services/execution-status-delivery.js"; import { hasRequiredWorkspaceRecovery } from "../services/workspace-restore-recovery-state.js"; const externalTestDatabaseUrl = process.env.PAPERCLIP_TEST_DATABASE_URL?.trim(); @@ -45,6 +46,66 @@ const support = externalTestDatabaseUrl ? { supported: true } : await getEmbedde } }; const readLease = async (id: string) => (await db.select().from(environmentLeases).where(eq(environmentLeases.id, id)))[0]; + it("preserves pending and acknowledged status delivery on unpatched legacy recovery retries", async () => { + await deliverExecutionStatuses(db, { publish: vi.fn() }); + const f = await seed(); + const failed = (await terminalizeLegacyExecution({ db, run: f.run, status: "failed", patch }))!; + const holds = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, f.issueId)); + expect(holds).toHaveLength(1); + expect(hasRequiredWorkspaceRecovery(failed.resultJson)).toBe(true); + const repeated = (await terminalizeLegacyExecution({ db, run: failed, status: "failed" }))!; + expect(repeated.executionStatusDeliveryId).toBe(failed.executionStatusDeliveryId); + const publish = vi.fn(); + await deliverExecutionStatuses(db, { publish }); + await terminalizeLegacyExecution({ db, run: failed, status: "failed" }); + await deliverExecutionStatuses(db, { publish }); + expect(publish.mock.calls.filter(([event]) => event.payload.runId === f.runId)).toHaveLength(1); + const after = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, f.issueId)); + expect(after).toHaveLength(1); + expect(after[0]).toMatchObject({ id: holds[0].id, status: holds[0].status, outcome: holds[0].outcome, + ownerType: holds[0].ownerType, wakePolicy: null, evidence: { ...holds[0].evidence, + automaticRecovery: expect.objectContaining({ policy: "preserve_without_replay_v1", replay: "blocked", + runId: f.runId, actionOutcome: "unknown" }), + } }); + expect(await readLease(f.lease.id)).toMatchObject({ status: "pending_cleanup", leasePolicy: "retain_on_failure" }); + expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId)))[0].resultJson).toEqual(failed.resultJson); + }); + + it("delivers new retained workspace evidence even when legacy run status is unchanged", async () => { + await deliverExecutionStatuses(db, { publish: vi.fn() }); + const f = await seed(); + const failed = (await terminalizeLegacyExecution({ db, run: f.run, status: "failed", patch }))!; + const publish = vi.fn(); + await deliverExecutionStatuses(db, { publish }); + const [added] = await db.insert(environmentLeases).values({ ...f.lease, id: randomUUID(), providerLeaseId: randomUUID() }).returning(); + const updated = (await terminalizeLegacyExecution({ db, run: failed, status: "failed" }))!; + expect(updated.executionStatusDeliveryId).toBeTruthy(); + expect(updated.executionStatusDeliveryId).not.toBe(failed.executionStatusDeliveryId); + expect(updated.resultJson?.workspaceRestoreRecovery).toMatchObject({ leaseIds: expect.arrayContaining([f.lease.id, added.id]) }); + await deliverExecutionStatuses(db, { publish }); + expect(publish.mock.calls.filter(([event]) => event.payload.runId === f.runId)).toHaveLength(2); + await terminalizeLegacyExecution({ db, run: updated, status: "failed" }); + await deliverExecutionStatuses(db, { publish }); + expect(publish.mock.calls.filter(([event]) => event.payload.runId === f.runId)).toHaveLength(2); + }); + + it("retains write conditions and delivers an explicit patch on unchanged legacy status", async () => { + await deliverExecutionStatuses(db, { publish: vi.fn() }); + const f = await seed(); + const failed = (await terminalizeLegacyExecution({ db, run: f.run, status: "failed", patch }))!; + const publish = vi.fn(); + await deliverExecutionStatuses(db, { publish }); + const holds = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, f.issueId)); + expect(await terminalizeLegacyExecution({ db, run: failed, status: "failed", writeConditions: [sql`false`] })).toBeNull(); + await deliverExecutionStatuses(db, { publish }); + expect(publish.mock.calls.filter(([event]) => event.payload.runId === f.runId)).toHaveLength(1); + expect(await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, f.issueId))).toEqual(holds); + const patched = (await terminalizeLegacyExecution({ db, run: failed, status: "failed", patch: { error: "Retained workspace still needs repair" } }))!; + expect(patched.error).toBe("Retained workspace still needs repair"); + await deliverExecutionStatuses(db, { publish }); + expect(publish.mock.calls.filter(([event]) => event.payload.runId === f.runId)).toHaveLength(2); + }); + async function stopAndRetain(f: Awaited>, retry = false) { let stopping = (await prepareSandboxStopAndRetain(db, f.lease))!; expect(stopping.status).toBe("pending_cleanup"); diff --git a/server/src/services/legacy-execution-recovery.ts b/server/src/services/legacy-execution-recovery.ts index f1b16bd0e49..5bbea0e61a5 100644 --- a/server/src/services/legacy-execution-recovery.ts +++ b/server/src/services/legacy-execution-recovery.ts @@ -115,7 +115,8 @@ export async function terminalizeLegacyExecution(input: { .set({ status: input.recordRestoreFailureOnly ? current.status : status, ...patch, - executionStatusDeliveryId: randomUUID(), + executionStatusDeliveryId: input.recordRestoreFailureOnly || current.status !== status || Object.keys(patch ?? {}).length > 0 + ? randomUUID() : current.executionStatusDeliveryId, updatedAt: new Date(), }) .where( @@ -131,10 +132,15 @@ export async function terminalizeLegacyExecution(input: { const retainedLeaseIds = await preserveLegacyWorkspaceRestoreSources(tx as unknown as Db, input.recordRestoreFailureOnly ? { ...updated, status: "failed" } : updated, input.workspaceRestoreSource); if (retainedLeaseIds.length) { - [updated] = await tx.update(heartbeatRuns).set({ resultJson: { + const retainedResult = { ...updated.resultJson, - workspaceRestoreRecovery: { schema: LEGACY_WORKSPACE_RECOVERY_SCHEMA, leaseIds: retainedLeaseIds }, - } }).where(and(eq(heartbeatRuns.id, updated.id), eq(heartbeatRuns.companyId, updated.companyId))).returning(); + workspaceRestoreRecovery: { schema: LEGACY_WORKSPACE_RECOVERY_SCHEMA, leaseIds: [...retainedLeaseIds].sort() }, + }; + [updated] = await tx.update(heartbeatRuns).set({ + resultJson: retainedResult, + executionStatusDeliveryId: sql`case when ${heartbeatRuns.resultJson} is distinct from ${JSON.stringify(retainedResult)}::jsonb + then ${randomUUID()}::uuid else ${heartbeatRuns.executionStatusDeliveryId} end`, + }).where(and(eq(heartbeatRuns.id, updated.id), eq(heartbeatRuns.companyId, updated.companyId))).returning(); } const needsRecovery = input.recordRestoreFailureOnly ? retainedLeaseIds.length > 0 || hasRequiredWorkspaceRecovery(updated.resultJson) diff --git a/server/src/services/native-runtime/native-run-finalizer.ts b/server/src/services/native-runtime/native-run-finalizer.ts index 7d60d73e0d7..805fd623d18 100644 --- a/server/src/services/native-runtime/native-run-finalizer.ts +++ b/server/src/services/native-runtime/native-run-finalizer.ts @@ -1608,33 +1608,42 @@ export async function finalizeNativeRun(input: { statusVersionAfter: Number(committed.issue.statusVersion), workspaceFinalizeStatus: input.workspaceFinalizeStatus, }; + const projectedStatus = terminalState === "succeeded" ? "succeeded" as const + : terminalState === "cancelled" ? "cancelled" as const : "failed" as const; + const projectedResult = sql`coalesce(${heartbeatRuns.resultJson}, '{}'::jsonb) + || ${JSON.stringify(finalizationMetadata)}::jsonb + || ${clearExecutionFailure ? recoveredExecutionFailureMetadata() : sql`'{}'::jsonb`}`; + const projectedError = providerFailure ? sql`coalesce(${heartbeatRuns.error}, ${providerFailure.errorMessage})` + : clearExecutionFailure ? sql`null` : heartbeatRuns.error; + const projectedErrorCode = providerFailure ? sql`coalesce(${heartbeatRuns.errorCode}, ${providerFailure.errorCode})` + : clearExecutionFailure ? sql`null` : heartbeatRuns.errorCode; + const projectionChanged = or( + sql`${heartbeatRuns.nativePhase} is distinct from ${finalizationPhase}`, + sql`${heartbeatRuns.resultJson} is distinct from ${projectedResult}`, + sql`${heartbeatRuns.error} is distinct from ${projectedError}`, + sql`${heartbeatRuns.errorCode} is distinct from ${projectedErrorCode}`, + ...(input.projectRunStatus ? [ + sql`${heartbeatRuns.status} is distinct from ${projectedStatus}`, + isNull(heartbeatRuns.finishedAt), + ] : []), + ); const projectRun = (tx: Db) => tx .update(heartbeatRuns) .set({ - executionStatusDeliveryId: randomUUID(), + executionStatusDeliveryId: sql`case when ${projectionChanged} + then ${randomUUID()}::uuid else ${heartbeatRuns.executionStatusDeliveryId} end`, ...(input.projectRunStatus ? { - status: - terminalState === "succeeded" - ? "succeeded" - : terminalState === "cancelled" - ? "cancelled" - : "failed", - finishedAt: now, + status: projectedStatus, + finishedAt: sql`case when ${heartbeatRuns.status} is distinct from ${projectedStatus} + then ${now.toISOString()}::timestamptz else coalesce(${heartbeatRuns.finishedAt}, ${now.toISOString()}::timestamptz) end`, } : {}), nativePhase: finalizationPhase, nativePhaseUpdatedAt: now, ...(clearExecutionFailure ? { error: null, errorCode: null } : {}), - ...(providerFailure ? { - // Recovery can finalize before heartbeat saves the adapter result. - // Retain any independently recorded execution/cleanup failure. - error: sql`coalesce(${heartbeatRuns.error}, ${providerFailure.errorMessage})`, - errorCode: sql`coalesce(${heartbeatRuns.errorCode}, ${providerFailure.errorCode})`, - } : {}), - resultJson: sql`coalesce(${heartbeatRuns.resultJson}, '{}'::jsonb) - || ${JSON.stringify(finalizationMetadata)}::jsonb - || ${clearExecutionFailure ? recoveredExecutionFailureMetadata() : sql`'{}'::jsonb`}`, + ...(providerFailure ? { error: projectedError, errorCode: projectedErrorCode } : {}), + resultJson: projectedResult, updatedAt: now, }) .where(eq(heartbeatRuns.id, run.id)) diff --git a/server/src/services/native-runtime/native-terminal-status-projection.test.ts b/server/src/services/native-runtime/native-terminal-status-projection.test.ts new file mode 100644 index 00000000000..ec23c45f1b6 --- /dev/null +++ b/server/src/services/native-runtime/native-terminal-status-projection.test.ts @@ -0,0 +1,132 @@ +import { randomUUID } from "node:crypto"; +import { eq } from "drizzle-orm"; +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; +import { agents, companies, completionContracts, createDb, heartbeatRuns, issues, + nativeRunFinalizations, nativeRunResults } from "@paperclipai/db"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embedded-postgres.js"; +import { deliverExecutionStatuses } from "../execution-status-delivery.js"; +import { buildIssueMonitorTriggeredPatch, normalizeIssueExecutionPolicy } from "../issue-execution-policy.js"; +import { PaperclipRunnerToolAuthority } from "./paperclip-runner-tool-authority.js"; +import { finalizeNativeRun } from "./native-run-finalizer.js"; + +const support = await getEmbeddedPostgresTestSupport(); +describe.skipIf(!support.supported)("native terminal status projection", () => { + let temporary: Awaited>; + let db: ReturnType; + beforeAll(async () => { + temporary = await startEmbeddedPostgresTestDatabase("native-terminal-status-"); + db = createDb(temporary.connectionString); + }); + afterAll(async () => { await temporary?.cleanup(); }); + + async function fixture() { + await deliverExecutionStatuses(db, { publish: vi.fn() }); + const companyId = randomUUID(), agentId = randomUUID(), issueId = randomUUID(), runId = randomUUID(); + const contractId = randomUUID(), resultId = randomUUID(); + await db.insert(companies).values({ id: companyId, name: "Monitor status", issuePrefix: `S${companyId.slice(0, 7)}` }); + await db.insert(agents).values({ id: agentId, companyId, name: "Worker", adapterType: "paperclip_runner", status: "active" }); + await db.insert(issues).values({ id: issueId, companyId, title: "Saved check", status: "in_progress", assigneeAgentId: agentId }); + await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, nativeIssueId: issueId, + runtimeMode: "native", status: "running", contextSnapshot: { issueId } }); + await db.update(issues).set({ executionRunId: runId }).where(eq(issues.id, issueId)); + const authority = new PaperclipRunnerToolAuthority(db, { companyId, agentId, issueId, runId }); + await authority.execute({ tool: "set_task_monitor", callId: randomUUID(), arguments: { + idempotencyKey: "saved-monitor", monitor: { nextCheckAt: new Date(Date.now() + 60_000).toISOString(), notes: "Check the saved result." }, + } }); + await db.insert(completionContracts).values({ id: contractId, companyId, issueId, revision: 1, + schemaVersion: "paperclip.completion-contract.v1", policyVersion: "test", risk: "standard", + completionAuthority: "server_arbiter", incompleteCriteriaPolicy: "preserve_non_terminal", + contractJson: { revision: "test", criteria: [] }, canonicalSha256: randomUUID(), + createdByActorType: "system", createdByActorId: "test" }); + const accepted = { result: { schema: "paperclip.run_result.v1", reportedWorkDisposition: "yielded", + summary: "Wait for the saved check.", completionClaim: { contractRevision: "test", objectiveSatisfied: false, + criteria: [], remainingWork: [{ description: "Check again", blocksCompletion: true }] }, + continuation: { kind: "monitor", summary: "Wait for the check", idempotencyKey: "provider-selected" }, + evidence: [], verification: [], attentionRequests: [], artifacts: [] }, + terminal: { schema: "paperclip.prp.terminal.v1", runTerminalState: "succeeded", turnTerminalState: "completed", reportedWorkDisposition: "yielded" } }; + const finishedAt = new Date("2020-01-01T00:00:00Z"); + await db.update(heartbeatRuns).set({ status: "succeeded", finishedAt, completionContractId: contractId }).where(eq(heartbeatRuns.id, runId)); + await db.insert(nativeRunResults).values({ id: resultId, companyId, issueId, runId, completionContractId: contractId, + serverFingerprint: randomUUID(), canonicalSha256: randomUUID(), schemaStatus: "accepted", resultJson: accepted }); + await db.insert(nativeRunFinalizations).values({ companyId, issueId, runId, phase: "retryable_failure", resultId }); + const [task] = await db.select().from(issues).where(eq(issues.id, issueId)); + await db.update(issues).set({ ...buildIssueMonitorTriggeredPatch({ issue: task!, + policy: normalizeIssueExecutionPolicy(task!.executionPolicy), triggeredAt: new Date() }), executionRunId: null, checkoutRunId: null, + }).where(eq(issues.id, issueId)); + const finalize = () => finalizeNativeRun({ db, runId, workspaceFinalizeStatus: "succeeded", projectRunStatus: true }); + const read = async () => (await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)))[0]!; + return { runId, companyId, issueId, finishedAt, resultId, accepted, finalize, read }; + } + + it("preserves the original completion time while retrying an accepted monitor result", async () => { + const f = await fixture(); + await f.finalize(); + expect((await f.read()).finishedAt).toEqual(f.finishedAt); + await f.finalize(); + expect((await f.read()).finishedAt).toEqual(f.finishedAt); + const [coordinator] = await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, f.runId)); + expect(coordinator).toMatchObject({ phase: "retryable_failure", failureCode: "monitor_wait_authority_lost", resultId: f.resultId }); + expect(coordinator.nextAttemptAt!.getTime()).toBeGreaterThan(Date.now()); + expect((await db.select().from(nativeRunResults).where(eq(nativeRunResults.id, f.resultId)))[0].resultJson).toEqual(f.accepted); + }); + + it("retains an unacknowledged status delivery across unchanged finalization retries", async () => { + const f = await fixture(); + await f.finalize(); + const before = await f.read(); + expect(before.executionStatusDeliveryId).toBeTruthy(); + await f.finalize(); + expect((await f.read()).executionStatusDeliveryId).toBe(before.executionStatusDeliveryId); + const publish = vi.fn(); + await expect(deliverExecutionStatuses(db, { publish, failpoint: () => { throw new Error("after publish"); } })).rejects.toThrow("after publish"); + await f.finalize(); + expect((await f.read()).executionStatusDeliveryId).toBe(before.executionStatusDeliveryId); + await deliverExecutionStatuses(db, { publish }); + const deliveries = publish.mock.calls.filter(([event]) => event.payload.runId === f.runId); + expect(deliveries).toHaveLength(2); + expect(deliveries[0][0].payload.deliveryId).toBe(deliveries[1][0].payload.deliveryId); + }); + + it("preserves a pending status notification created by another producer", async () => { + const f = await fixture(); + await f.finalize(); + const newer = randomUUID(); + await db.update(heartbeatRuns).set({ executionStatusDeliveryId: newer }).where(eq(heartbeatRuns.id, f.runId)); + await f.finalize(); + expect((await f.read()).executionStatusDeliveryId).toBe(newer); + }); + + it.each(["metadata", "status", "missing_completion_time"])("broadcasts a changed terminal projection after acknowledgement (%s)", async change => { + const f = await fixture(); + await f.finalize(); + const publish = vi.fn(); + await deliverExecutionStatuses(db, { publish }); + if (change === "metadata") { + await finalizeNativeRun({ db, runId: f.runId, workspaceFinalizeStatus: "failed", projectRunStatus: true }); + expect((await f.read()).resultJson?.workspaceFinalizeStatus).toBe("failed"); + } else { + await db.update(heartbeatRuns).set(change === "status" ? { status: "failed" } : { finishedAt: null }) + .where(eq(heartbeatRuns.id, f.runId)); + await f.finalize(); + expect(await f.read()).toMatchObject({ status: "succeeded", finishedAt: expect.any(Date) }); + } + await deliverExecutionStatuses(db, { publish }); + expect(publish.mock.calls.filter(([event]) => event.payload.runId === f.runId)).toHaveLength(2); + }); + + it("does not broadcast an unchanged terminal projection after acknowledgement or a new DB client", async () => { + const f = await fixture(); + await f.finalize(); + const publish = vi.fn(); + await deliverExecutionStatuses(db, { publish }); + await f.finalize(); + await deliverExecutionStatuses(db, { publish }); + const reopened = createDb(temporary.connectionString); + try { + await finalizeNativeRun({ db: reopened, runId: f.runId, workspaceFinalizeStatus: "succeeded", projectRunStatus: true }); + await deliverExecutionStatuses(reopened, { publish }); + } finally { await reopened.$client.end(); } + expect(publish.mock.calls.filter(([event]) => event.payload.runId === f.runId)).toHaveLength(1); + expect((await f.read()).executionStatusDeliveryId).toBeNull(); + }); +}); diff --git a/tests/e2e/legacy-failure-continuation.spec.ts b/tests/e2e/legacy-failure-continuation.spec.ts index 4eaa73092f9..b04ca8e1e22 100644 --- a/tests/e2e/legacy-failure-continuation.spec.ts +++ b/tests/e2e/legacy-failure-continuation.spec.ts @@ -92,8 +92,18 @@ for (const action of ["task_retry", "retry_after_reload", "inbox_retry", "messag await expect(page.getByRole("button", { name: "Steer", exact: true })).toHaveCount(0); const retry = page.getByRole("button", { name: "Retry", exact: true }); await expect(retry).toBeEnabled(); - await db.update(heartbeatRuns).set({ processPid: 999999999 }).where(eq(heartbeatRuns.id, sourceRunId)); - await retry.click(); + await page.route((url) => url.pathname === `/api/issues/${issue.id}/retry`, async route => { + if (route.request().method() !== "POST") return route.continue(); + await db.update(heartbeatRuns).set({ processPid: 999999999 }).where(eq(heartbeatRuns.id, sourceRunId)); + await route.continue(); + }, { times: 1 }); + const [response] = await Promise.all([ + page.waitForResponse(response => response.request().method() === "POST" && + new URL(response.url()).pathname === `/api/issues/${issue.id}/retry` && + response.request().postDataJSON()?.observedRunId === sourceRunId), + retry.click(), + ]); + expect(response.ok(), `${response.status()} ${await response.text()}`).toBe(true); } else if (action === "automatic_message") { // No Retry, duplicate message, or status change: the saved input runs. } else if (action === "message") { @@ -131,9 +141,15 @@ for (const action of ["task_retry", "retry_after_reload", "inbox_retry", "messag await page.reload(); await expect(page.getByText("Answered the pending follow-up once.", { exact: false })).toBeVisible(); } finally { - await request.patch(`/api/companies/${company.id}`, { data: { status: "archived" } }); - await closeRegisteredClients(url); - await rm(root, { recursive: true, force: true }); + try { + await request.patch(`/api/companies/${company.id}`, { data: { status: "archived" } }); + } finally { + try { + await closeRegisteredClients(url); + } finally { + await rm(root, { recursive: true, force: true }); + } + } } }); } From 34409a92c4c1b4ff18299286d8228563bc098bec Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Sun, 25 Oct 2026 08:51:39 -0700 Subject: [PATCH 066/110] fix(native-runtime): stop failover backups from carrying throwaway provider state (#17618) ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Native runner sessions on managed sandboxes keep a failover backup of provider state, so a replacement sandbox can resume the session > - Each backup copies the provider's runtime directory, with a per-directory sha256 manifest, minus `excludeEntries` > - Codex already excludes credentials and re-downloadable plugin caches; OpenCode excluded nothing, and ACPX excluded only per-agent credentials > - OpenCode also leaked a temporary HOME on every launch, because removing it failed on the read-only skill snapshot inside and the error was swallowed > - So every backup carried every earlier launch's HOME (with its npm cache) plus re-installable plugin `node_modules` > - This pull request removes those homes correctly, sweeps homes left by earlier versions, and excludes the throwaway entries from OpenCode and ACPX backups > - The benefit is much smaller backups and live session directories, while session history is still backed up and restored ## Linked Issues or Issue Description Bug report described in-PR (bug report template). **What happened?** On one instance, current native failover backups totalled 24 GB across about 300 sessions. For OpenCode sessions: - `opencode//home-XXXXXX/`: 170 per-launch HOME directories across 67 sessions, 9.3 GB. Each held `.npm` (about 111 MB of npm cache), `.claude` (the skill snapshot) and `.local`. - `opencode//config/opencode/node_modules`: 68 sessions, 4.3 GB of OpenCode plugin installs. One ACPX session also carried `acpx//data/pnpm/store` (229 MB in the current backup, several GB in older copies). Cause of the leaked homes: `startRuntime` in the OpenCode driver creates a fresh `mkdtemp` HOME for each launch and seals the assigned skills inside it (directories `0555`, files `0444`). `close()` and the startup-failure paths removed it with `rm(..., { recursive: true, force: true }).catch(() => undefined)`. That fails with `EACCES` on the sealed directories, and the failure was ignored, so each launch left its HOME behind. **Expected behavior** Per-launch homes are removed when the runtime closes, and backups hold only state needed to resume a session. Caches that the provider re-creates are left out. **Steps to reproduce** 1. Run an OpenCode native session with at least one assigned skill on a managed sandbox, over several turns or runs. 2. Inspect `/` in the OpenCode runtime directory: one `home-XXXXXX` per launch remains. 3. Inspect `failover-backups/current/opencode//`: the same homes and `config/opencode/node_modules` are in the backup. **Paperclip version or commit:** `master` at e3352655687. **Deployment mode:** any with native OpenCode/ACPX sessions on managed sandboxes. **Agent adapter(s) involved:** OpenCode (native), ACPX. ## What Changed - OpenCode driver (`packages/paperclip-runner/src/drivers/opencode/opencode-server-driver.ts`): - `removeIsolatedHome` unseals the skill snapshot with the existing `releaseMaterializedNativeRuntimeSkills`, then removes the HOME. Close and every startup-failure path use it. It only unseals when `.claude` is a real directory, not a symlink. - Per-launch homes are now created under `/homes/home-XXXXXX`, so one exact path can be excluded. - When a session opens, `home-*` directories left at the session root by earlier versions are removed. History is not in them: OpenCode keeps it in `XDG_DATA_HOME` (`/data/opencode/opencode.db`), and HOME only holds caches, state locks and the skill copy. - Exports `opencodeRuntimeSessionDirectoryName` (the existing session-directory naming) and `OPENCODE_ISOLATED_HOMES_DIRECTORY` for the server. - `resolveNativeHarnessPersistenceProfile` (`server/src/services/native-runtime/native-session-executor.ts`): - OpenCode excludes `/homes` and `/config/opencode/node_modules`. - ACPX (every agent) excludes `acpx//home/.npm` and `acpx//data/pnpm/store`, in addition to the existing per-agent entries. - `excludeEntries` are matched as exact relative paths (wildcards are rejected), so the session directory is computed in the same way as the existing ACPX entries. - Exposes the two new exports through the server's runner vendor shim. No code comments were added. ## Verification - `pnpm exec vitest run src/drivers/opencode src/drivers/runtime-context-materializer` (in `packages/paperclip-runner/`): 108 passed. The 1 failure, `uses provider structure rather than prose length to select a post-tool answer`, also fails on unmodified `master`. - The existing skill-tree test, with and without a startup retry, now asserts that homes are created under `homes/` and that `homes/` is empty after close. - New test: a sealed legacy `home-*` at the session root is removed when the session reopens, and `data/opencode/opencode.db` is kept. - `pnpm exec vitest run src/services/native-runtime/ src/__tests__/native-harness-backup-expiration.test.ts` (in `server/`): 5080 passed. `plugin-runner-probe` could not run locally because of a cargo manifest-path problem in this environment; it is unrelated to this change. - Profile tests cover the new OpenCode and ACPX exclusions, including a session id that needs sanitizing. - New checkpoint/restore round-trip tests for OpenCode and ACPX. They use `syncRemoteRunnerDirectoryOut` for the backup and `stageRemoteRunnerDirectory` for the replacement. Excluded caches are absent from both the backup and the replacement, while history, config and workspace files are restored and the live directory is unchanged. - **Mutation checks**, each failing its test: - removing the skill unsealing (homes leak again; 3 runner tests fail); - removing the legacy sweep (1 test fails); - emptying the OpenCode/ACPX exclusion lists (4 server tests fail). - Checked by hand against the bundled OpenCode 1.18.34 binary, with the driver's environment: - launching with a fresh HOME and no `config/opencode/node_modules` still lists earlier sessions; - OpenCode reinstalls the plugin dependencies on launch. - `pnpm run typecheck` in `server/` and `packages/paperclip-runner/`: pass. - Not run: server build and boot smoke. ## Risks - **Rollout:** existing backups still contain legacy `home-*` directories. After a restore, the sweep removes them when the session opens, and the next backup no longer carries them. - **First launch after restore:** OpenCode reinstalls its plugin dependencies and npm repopulates its cache. This needs network access to the npm registry, the same as a brand-new session. - **Crash leftovers:** a HOME left behind by a hard crash (the runner killed before `close()`) stays under `homes/` until the session directory is removed. It is still excluded from backups. Homes under `homes/` are not swept on open, to avoid touching a HOME that a concurrently running runtime might still use. - **pnpm store:** dropping the pnpm store from ACPX backups means the next `pnpm install` in a replacement sandbox downloads packages again. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), 1M context, through Claude Code with tool use (shell, file edits, tests, and running the real OpenCode binary to check what state it reads on resume). ## 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 - [ ] I will address all Greptile and reviewer comments before requesting merge Co-authored-by: Paperclip --- .../opencode/opencode-server-driver.test.ts | 55 +++++++- .../opencode/opencode-server-driver.ts | 64 ++++++--- .../native-session-executor.test.ts | 125 +++++++++++++++++- .../native-runtime/native-session-executor.ts | 24 +++- server/src/vendor/paperclip-runner/index.ts | 4 + 5 files changed, 247 insertions(+), 25 deletions(-) diff --git a/packages/paperclip-runner/src/drivers/opencode/opencode-server-driver.test.ts b/packages/paperclip-runner/src/drivers/opencode/opencode-server-driver.test.ts index a63abc777f8..5d568eddf86 100644 --- a/packages/paperclip-runner/src/drivers/opencode/opencode-server-driver.test.ts +++ b/packages/paperclip-runner/src/drivers/opencode/opencode-server-driver.test.ts @@ -1513,7 +1513,7 @@ describe("OpenCodeServerDriver", () => { ); const isolatedHome = runtimeEnvironment.home; expect(startupFailurePending).toBe(false); - expect(dirname(isolatedHome)).toBe(sessionRoot); + expect(dirname(isolatedHome)).toBe(join(sessionRoot, "homes")); expect(basename(isolatedHome)).toMatch(/^home-/); await expect( readFile( @@ -1553,6 +1553,59 @@ describe("OpenCodeServerDriver", () => { readFile(join(instructionRoot, "sibling.md"), "utf8"), ).resolves.toBe("instruction sibling\n"); await session.close({ reason: "test" }); + await expect(readdir(join(sessionRoot, "homes"))).resolves.toEqual([]); + }); + + it("removes isolated homes left by earlier launches when a session reopens", async () => { + await chmod(fixture, 0o755); + const root = await mkdtemp(join(tmpdir(), "paperclip-opencode-legacy-home-")); + const workspace = await mkdtemp( + join(tmpdir(), "paperclip-opencode-legacy-home-workspace-"), + ); + const skillRoot = join(root, "skill-source"); + const instructionRoot = join(root, "instruction-source"); + roots.push(root, workspace); + await Promise.all([ + mkdir(skillRoot, { recursive: true }), + mkdir(instructionRoot, { recursive: true }), + ]); + await writeFile(join(skillRoot, "SKILL.md"), "# Assigned\n"); + await writeFile(join(instructionRoot, "AGENTS.md"), "instructions\n"); + const sessionRoot = join(root, "legacy"); + const legacyHome = join(sessionRoot, "home-AbC123"); + const sealedSkill = join(legacyHome, ".claude", "skills", "assigned"); + await mkdir(sealedSkill, { recursive: true }); + await mkdir(join(legacyHome, ".npm", "_cacache"), { recursive: true }); + await writeFile(join(legacyHome, ".npm", "_cacache", "entry"), "cache"); + await writeFile(join(sealedSkill, "SKILL.md"), "# Assigned\n"); + await chmod(join(sealedSkill, "SKILL.md"), 0o444); + await chmod(sealedSkill, 0o555); + await mkdir(join(sessionRoot, "data", "opencode"), { recursive: true }); + await writeFile(join(sessionRoot, "data", "opencode", "opencode.db"), "history"); + const driver = new OpenCodeServerDriver({ + model: "openrouter/deepseek/deepseek-v4-flash-0731", + runtimeDirectory: root, + command: fixture, + runtimeContext: runtimeContext(skillRoot, instructionRoot), + environment: { + PATH: process.env.PATH, + OPENROUTER_API_KEY: "fixture-key", + }, + }); + const session = await driver.openSession({ + runId: "run-legacy-home", + normalizedSessionId: "legacy", + workingDirectory: workspace, + }); + await expect(lstat(legacyHome)).rejects.toMatchObject({ code: "ENOENT" }); + await session.close({ reason: "test" }); + expect( + (await readdir(sessionRoot)).filter((entry) => entry.startsWith("home-")), + ).toEqual([]); + await expect(readdir(join(sessionRoot, "homes"))).resolves.toEqual([]); + await expect( + readFile(join(sessionRoot, "data", "opencode", "opencode.db"), "utf8"), + ).resolves.toBe("history"); }); it("resends system instructions without repeating the task envelope on recovery", async () => { diff --git a/packages/paperclip-runner/src/drivers/opencode/opencode-server-driver.ts b/packages/paperclip-runner/src/drivers/opencode/opencode-server-driver.ts index a7f80aac85e..4ab25b38b83 100644 --- a/packages/paperclip-runner/src/drivers/opencode/opencode-server-driver.ts +++ b/packages/paperclip-runner/src/drivers/opencode/opencode-server-driver.ts @@ -6,6 +6,7 @@ import { accessSync, constants, readFileSync, realpathSync, statSync } from "nod import { createRequire } from "node:module"; import { chmod, + lstat, mkdir, mkdtemp, readFile, @@ -85,7 +86,10 @@ import { type OpenCodeMcpBridge, } from "./mcp-bridge.js"; import { nativeMcpLaunchBinding } from "../native-mcp.js"; -import { materializeNativeRuntimeSkills } from "../runtime-context-materializer.js"; +import { + materializeNativeRuntimeSkills, + releaseMaterializedNativeRuntimeSkills, +} from "../runtime-context-materializer.js"; export const OPENCODE_SERVER_DRIVER_KIND = "opencode_server" as const; export const QUALIFIED_OPENCODE_VERSION = "1.18.34" as const; @@ -369,6 +373,7 @@ export class OpenCodeServerDriver implements HarnessDriver { ); await mkdir(root, { recursive: true, mode: 0o700 }); await writeFile(join(root, "workspace"), `${cwd}\n`, { mode: 0o600 }); + await removeLegacyIsolatedHomes(root); const trace = await createProviderTraceFileSink({ path: this.#options.environment?.PAPERCLIP_PROVIDER_TRACE_PATH, provider: "opencode", @@ -2281,7 +2286,9 @@ async function startRuntime(input: { // HOME contains a read-only skill snapshot, whose destination must be fresh. // Keep OpenCode's XDG data stable for provider-session recovery while giving // every launch (including retries and recovery) a new isolated HOME. - const isolatedHome = await mkdtemp(join(input.root, "home-")); + const homesRoot = join(input.root, OPENCODE_ISOLATED_HOMES_DIRECTORY); + await mkdir(homesRoot, { recursive: true, mode: 0o700 }); + const isolatedHome = await mkdtemp(join(homesRoot, "home-")); await chmod(isolatedHome, 0o700); try { await materializeNativeRuntimeSkills( @@ -2289,18 +2296,14 @@ async function startRuntime(input: { join(isolatedHome, ".claude", "skills"), ); } catch (error) { - await rm(isolatedHome, { recursive: true, force: true }).catch( - () => undefined, - ); + await removeIsolatedHome(isolatedHome).catch(() => undefined); throw error; } const bridge = await startOpenCodeMcpBridge({ tools: input.options.dynamicTools, handler: input.dispatch, }).catch(async (error) => { - await rm(isolatedHome, { recursive: true, force: true }).catch( - () => undefined, - ); + await removeIsolatedHome(isolatedHome).catch(() => undefined); throw error; }); const assignedMcp = nativeMcpLaunchBinding( @@ -2335,7 +2338,7 @@ async function startRuntime(input: { const providerProxy = modelProvider === "paperclip" && input.options.environment?.PAPERCLIP_AI_PROVIDER_URL ? await startOpenCodeProviderProxy(input.options.environment.PAPERCLIP_AI_PROVIDER_URL, input.options.environment.PAPERCLIP_AI_PROVIDER_KEY ?? "", providerModelId, input.options.environment).catch(async error => { await bridge.close().catch(() => {}); - await rm(isolatedHome, { recursive: true, force: true }).catch(() => {}); + await removeIsolatedHome(isolatedHome).catch(() => {}); throw error; }) : null; @@ -2568,9 +2571,7 @@ async function startRuntime(input: { await rm(join(configHome, "opencode", "opencode.json"), { force: true, }).catch(() => undefined); - await rm(isolatedHome, { recursive: true, force: true }).catch( - () => undefined, - ); + await removeIsolatedHome(isolatedHome).catch(() => undefined); if (closeInput.finalizeTrace !== false) { await input.trace?.finish({ reason: closeInput.reason ?? null }); } @@ -2585,9 +2586,7 @@ async function startRuntime(input: { await rm(join(configHome, "opencode", "opencode.json"), { force: true, }).catch(() => undefined); - await rm(isolatedHome, { recursive: true, force: true }).catch( - () => undefined, - ); + await removeIsolatedHome(isolatedHome).catch(() => undefined); throw error; } } @@ -2962,8 +2961,9 @@ function sanitizedEnvironmentKeys(): string[] { ]; } -function sessionRoot( - runtimeDirectory: string, +export const OPENCODE_ISOLATED_HOMES_DIRECTORY = "homes"; + +export function opencodeRuntimeSessionDirectoryName( normalizedSessionId: string, ): string { const safe = normalizedSessionId @@ -2971,7 +2971,35 @@ function sessionRoot( .slice(0, 120); if (!safe || safe === "." || safe === "..") throw new Error("Invalid normalized OpenCode session id"); - return join(resolve(runtimeDirectory), safe); + return safe; +} + +function sessionRoot( + runtimeDirectory: string, + normalizedSessionId: string, +): string { + return join( + resolve(runtimeDirectory), + opencodeRuntimeSessionDirectoryName(normalizedSessionId), + ); +} + +async function removeIsolatedHome(home: string): Promise { + const skillsParent = await lstat(join(home, ".claude")).catch(() => null); + if (skillsParent?.isDirectory()) { + await releaseMaterializedNativeRuntimeSkills( + join(home, ".claude", "skills"), + ).catch(() => undefined); + } + await rm(home, { recursive: true, force: true }); +} + +async function removeLegacyIsolatedHomes(root: string): Promise { + const entries = await readdir(root, { withFileTypes: true }).catch(() => []); + for (const entry of entries) { + if (!entry.isDirectory() || !entry.name.startsWith("home-")) continue; + await removeIsolatedHome(join(root, entry.name)).catch(() => undefined); + } } function validateWorkspace(value: string): string { diff --git a/server/src/services/native-runtime/native-session-executor.test.ts b/server/src/services/native-runtime/native-session-executor.test.ts index bfb1f4f309f..5c8c3e211f7 100644 --- a/server/src/services/native-runtime/native-session-executor.test.ts +++ b/server/src/services/native-runtime/native-session-executor.test.ts @@ -1880,13 +1880,35 @@ describe("native harness persistence profiles", () => { }); }); - it("excludes only nested Codex launch state from ACPX recovery", () => { + it("excludes per-launch OpenCode homes and re-installable plugins from OpenCode recovery", () => { + const opencode = resolveNativeHarnessPersistenceProfile({ + provider: { kind: "opencode" }, + session: { + driverKind: "opencode_server", + normalizedSessionId: "company:agent/session 1", + protocolVersion: 1, + lifecyclePolicy: { mode: "per_turn", idleTimeoutMs: null }, + }, + } as unknown as NativeExecutionInputV1); + expect( + opencode.directories.find((directory) => directory.name === "opencode"), + ).toMatchObject({ + excludeEntries: [ + "company_agent_session_1/homes", + "company_agent_session_1/config/opencode/node_modules", + ], + }); + }); + + it("excludes only nested Codex launch state and package caches from ACPX recovery", () => { const acpx = profile({ kind: "acpx", agent: "codex" }, "acpx_runtime"); const sessionDirectory = acpxRuntimeSessionDirectoryName("session"); expect( acpx.directories.find((directory) => directory.name === "acpx"), ).toMatchObject({ excludeEntries: [ + `acpx/${sessionDirectory}/home/.npm`, + `acpx/${sessionDirectory}/data/pnpm/store`, `acpx/${sessionDirectory}/codex-home/tmp`, `acpx/${sessionDirectory}/codex-home/.tmp`, `acpx/${sessionDirectory}/codex-home/auth.json`, @@ -1907,7 +1929,12 @@ describe("native harness persistence profiles", () => { { kind: "acpx", agent: "claude" }, "acpx_runtime", ).directories.find((directory) => directory.name === "acpx"), - ).toMatchObject({ excludeEntries: [] }); + ).toMatchObject({ + excludeEntries: [ + `acpx/${sessionDirectory}/home/.npm`, + `acpx/${sessionDirectory}/data/pnpm/store`, + ], + }); }); }); @@ -2623,6 +2650,100 @@ describe("remote provider checkpoint snapshots", () => { expect(await readFile(join(home, "logs", "unified.jsonl"), "utf8")).toBe("AUTH_SENTINEL"); } finally { await rm(root, { recursive: true, force: true }); } }); + it.each<{ + name: string; + provider: Record; + driverKind: string; + directory: string; + sessionPath: string; + kept: Record; + omitted: Record; + }>([ + { + name: "OpenCode", + provider: { kind: "opencode" }, + driverKind: "opencode_server", + directory: "opencode", + sessionPath: "company_agent_session_1", + kept: { + "workspace": "/workspace\n", + "data/opencode/opencode.db": "history", + "config/opencode/opencode.json": "{}", + "config/opencode/package.json": "{}", + "home-legacy/.local/state/opencode/locks/lock": "legacy", + }, + omitted: { + "homes/home-AbC123/.npm/_cacache/index": "npm-cache", + "homes/home-AbC123/.claude/skills/assigned/SKILL.md": "skill", + "config/opencode/node_modules/@opencode-ai/plugin/package.json": "plugin", + }, + }, + { + name: "ACPX", + provider: { kind: "acpx", agent: "pi" }, + driverKind: "acpx_runtime", + directory: "acpx", + sessionPath: `acpx/${acpxRuntimeSessionDirectoryName("company:agent/session 1")}`, + kept: { + "workspace": "/workspace\n", + "pi-home/sessions/session.jsonl": "history", + "data/pnpm/config.json": "{}", + "home/.profile": "profile", + }, + omitted: { + "home/.npm/_cacache/index": "npm-cache", + "data/pnpm/store/v10/files/00/blob": "pnpm-store", + }, + }, + ])("omits disposable $name package caches from the checkpoint and restores the session without them", async ({ + provider, driverKind, directory, sessionPath, kept, omitted, + }) => { + const root = await mkdtemp(join(tmpdir(), "provider-cache-checkpoint-")); + try { + const live = join(root, "live", directory); + const backup = join(root, "backup", directory); + const replacement = join(root, "replacement", directory); + const files: Record = { ...kept, ...omitted }; + for (const [path, contents] of Object.entries(files)) { + await mkdir(join(live, sessionPath, path, ".."), { recursive: true }); + await writeFile(join(live, sessionPath, path), contents); + } + const persistence = resolveNativeHarnessPersistenceProfile({ + provider, + session: { normalizedSessionId: "company:agent/session 1", driverKind }, + } as unknown as NativeExecutionInputV1); + const excludeEntries = persistence.directories.find(entry => entry.name === directory)!.excludeEntries; + const execute = async ({ command, args }: { command: string; args: string[] }) => ({ + exitCode: 0, timedOut: false, stdout: execFileSync(command, args, { encoding: "utf8" }), stderr: "", + }); + const copy = async (operations: Array<{ files: Array<{ sourcePath: string; targetPath: string }> }>) => { + for (const operation of operations) for (const file of operation.files) + await cp(file.sourcePath, file.targetPath, { recursive: true }); + }; + await syncRemoteRunnerDirectoryOut({ runner: { execute, syncOut: copy } as never, + sourcePath: live, targetPath: backup, mode: 0o700, excludeEntries }); + for (const [path, contents] of Object.entries(kept)) + expect(await readFile(join(backup, sessionPath, path), "utf8")).toBe(contents); + for (const path of Object.keys(omitted)) + await expect(access(join(backup, sessionPath, path))).rejects.toMatchObject({ code: "ENOENT" }); + for (const [path, contents] of Object.entries(omitted)) + expect(await readFile(join(live, sessionPath, path), "utf8")).toBe(contents); + + await stageRemoteRunnerDirectory({ + target: { kind: "remote", transport: "provider", remoteCwd: root, runner: { syncIn: copy } } as never, + runner: { syncIn: copy } as never, + sourcePath: backup, + targetPath: replacement, + mode: 0o700, + excludeEntries, + }); + for (const [path, contents] of Object.entries(kept)) + expect(await readFile(join(replacement, sessionPath, path), "utf8")).toBe(contents); + for (const path of Object.keys(omitted)) + await expect(access(join(replacement, sessionPath, path))).rejects.toMatchObject({ code: "ENOENT" }); + } finally { await rm(root, { recursive: true, force: true }); } + }); + it("keeps Codex session state while omitting re-downloadable remote plugins from the checkpoint", async () => { const root = await mkdtemp(join(tmpdir(), "codex-plugin-checkpoint-")); try { diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index 62118309e9d..7f67a8aa2fc 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -109,6 +109,8 @@ import { completeRetainedNativeSessionCleanup, completeTerminatedLocalNativeSessionCleanup, acpxRuntimeSessionDirectoryName, + OPENCODE_ISOLATED_HOMES_DIRECTORY, + opencodeRuntimeSessionDirectoryName, createNativeSessionBackend, createRunnerdCodexTransport, executeNativeSession, @@ -410,6 +412,14 @@ const CODEX_HOME_CHECKPOINT_EXCLUDED_ENTRIES = [ ...CODEX_HOME_NON_PERSISTENT_ENTRIES, ...CODEX_HOME_REDOWNLOADABLE_ENTRIES, ] as const; +const OPENCODE_RUNTIME_CHECKPOINT_EXCLUDED_ENTRIES = [ + OPENCODE_ISOLATED_HOMES_DIRECTORY, + "config/opencode/node_modules", +] as const; +const ACPX_RUNTIME_CHECKPOINT_EXCLUDED_ENTRIES = [ + "home/.npm", + "data/pnpm/store", +] as const; const RUNNERD_CONTROL_PLANE_STATE_SCHEMA = "paperclip.runner.durable.control-plane-state.v1"; const RUNNERD_STATE_SCHEMA = "paperclip.runner.durable.state.v1"; @@ -5646,7 +5656,10 @@ export function resolveNativeHarnessPersistenceProfile( ? { name: "opencode", location: "filesystem", - excludeEntries: [], + excludeEntries: OPENCODE_RUNTIME_CHECKPOINT_EXCLUDED_ENTRIES.map( + (entry) => + `${opencodeRuntimeSessionDirectoryName(nativeSessionKey(execution))}/${entry}`, + ), } : execution.provider.kind === "acpx" ? { @@ -5658,8 +5671,10 @@ export function resolveNativeHarnessPersistenceProfile( // nor necessary to restore. Credentials and launch-time config // are also re-materialized in the replacement sandbox. Grok // diagnostics can contain auth fields and are not session state. - excludeEntries: - execution.provider.agent === "grok" + excludeEntries: [ + ...ACPX_RUNTIME_CHECKPOINT_EXCLUDED_ENTRIES.map((entry) => + `acpx/${acpxRuntimeSessionDirectoryName(nativeSessionKey(execution))}/${entry}`), + ...(execution.provider.agent === "grok" ? ["auth.json", "auth-refresh.json", "auth-refresh.json.tmp", "config.toml", "logs"].map((entry) => `acpx/${acpxRuntimeSessionDirectoryName(nativeSessionKey(execution))}/grok-home/${entry}`) : execution.provider.agent === "codex" @@ -5667,7 +5682,8 @@ export function resolveNativeHarnessPersistenceProfile( (entry) => `acpx/${acpxRuntimeSessionDirectoryName(nativeSessionKey(execution))}/codex-home/${entry}`, ) - : [], + : []), + ], } : null; return { diff --git a/server/src/vendor/paperclip-runner/index.ts b/server/src/vendor/paperclip-runner/index.ts index 2252b5daf6b..571daf6a929 100644 --- a/server/src/vendor/paperclip-runner/index.ts +++ b/server/src/vendor/paperclip-runner/index.ts @@ -107,6 +107,10 @@ export const PAPERCLIP_EXECUTION_PROMPT_REVISION = runner.PAPERCLIP_EXECUTION_PROMPT_REVISION; export const acpxRuntimeSessionDirectoryName = runner.acpxRuntimeSessionDirectoryName; +export const OPENCODE_ISOLATED_HOMES_DIRECTORY = + runner.OPENCODE_ISOLATED_HOMES_DIRECTORY; +export const opencodeRuntimeSessionDirectoryName = + runner.opencodeRuntimeSessionDirectoryName; export const canonicalNativeRuntimeContextDigest = runner.canonicalNativeRuntimeContextDigest; export const createNativeSessionBackend = runner.createNativeSessionBackend; From b792165ba4ce16d753f7a68f8c8c3685d198d6e7 Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Sun, 25 Oct 2026 09:20:30 -0700 Subject: [PATCH 067/110] Expire native runner continuity archives and quarantine (#17616) ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Native runner sessions keep durable state under `/runtime/paperclip-runner/durable-sessions/` > - When a session starts a fresh provider session, the retired state is moved into `/continuity-breaks/-/`; when state loses authority, it is moved into `quarantine/..../` > - Nothing ever removes either, and each can hold a full Codex home of several gigabytes > - A sleep-aware sweep already expires failover backup copies in the same tree > - This pull request extends that sweep to remove both kinds of evidence after a retention window, while keeping anything recovery may still read > - The benefit is that native runner disk use stops growing without bound ## Linked Issues or Issue Description Bug report described in-PR (bug report template). **What happened?** On one instance, one day of native runs produced 20 continuity-break archives totaling 4.8 GB, one session alone holding 4 GB. The quarantine folder held 12 entries totaling 2.1 GB, the oldest a month old. Neither is read again by normal operation (continuity-break archives are written by `archiveContinuityState` and never read), and nothing deletes them. They were removed by hand to free space and will regrow. **Expected behavior** Evidence older than a bounded window is removed automatically, as failover backup copies already are, without removing anything a live session or recovery path still needs. **Steps to reproduce** 1. Run a native Codex session that hits a continuity break (fresh provider session), or whose state is quarantined (for example `identity_indeterminate`). 2. Inspect `durable-sessions//continuity-breaks/` and `durable-sessions/quarantine/`. 3. Wait any length of time: the entries stay forever. **Paperclip version or commit:** `master` at e3352655687. **Deployment mode:** any with native runner sessions. **Agent adapter(s) involved:** native runner (Codex, and any provider whose state lands in these folders). ## What Changed - `server/src/services/native-runtime/native-harness-backup-expiration.ts`: the existing tick also retires evidence. - **Continuity-break archives** (`-` under each session): removed when older than the window. Age is the epoch in the name, or the folder mtime when that epoch is in the future. `archiveContinuityState` refuses to archive state with warm-transition evidence, and no code path reads `continuity-breaks`. - **Quarantine entries** (`....`): removed by the same age rule. Native cleanup source archives (`.identity_indeterminate.cleanup.`) are referenced from recovery history, have no epoch, and keep their original inode's mtime, so they are always kept. - Every entry is skipped while its session is executing, initializing, warm, or closing in this process; this is checked again just before removal. Symlinked entries and symlinked `continuity-breaks`/`quarantine` folders are reported as `unsafe_path` and never followed. - Removal renames to `.expired-` in the same folder and then deletes; later sweeps finish interrupted deletions. An empty `continuity-breaks` folder is removed. - Archives, quarantine entries, and leftover deletions count toward `maxEntries` and `maxRemovals`, and stop on `shouldContinue`. Paging resumes inside a session's archives and then in quarantine, so a bounded or dry-run batch always makes progress and never recounts a session's backup. - New result fields: `evidenceCandidates`, `evidenceCandidateBytes`, `evidenceRemoved`, `evidenceReclaimedBytes`, and skip reasons `recent_evidence` and `cleanup_archive`. The service also exposes `noteEvidence(writtenAt)`. - `server/src/services/native-runtime/native-runner-evidence-signal.ts` (new): a process-local signal. `native-session-executor.ts` raises it with the entry's epoch right after `archiveContinuityState` creates an archive and after `quarantineRunnerdStateRoot` moves state into quarantine; `server/src/index.ts` subscribes the sweep and unsubscribes on shutdown. - `server/src/config.ts`: `PAPERCLIP_NATIVE_RUNNER_EVIDENCE_RETENTION_DAYS` (default `7`, minimum `1`). - `server/src/index.ts`: passes the window and logs a batch when it found evidence candidates. - `doc/recoverable-disk-cleanup.md`, `doc/DEVELOPING.md`: document the variable and behavior. **Sleep-aware background work** (`rules/sleep-aware-background-work.mdc`): - *Trigger:* each entry's own expiry deadline (its epoch plus the window), plus a direct call from the executor when it writes new evidence. No timer, interval, or polling loop is added; the pass runs inside the existing sweep's tick and keeps its drain, warm-standby, and shutdown handling. - *Source of truth:* the filesystem entries themselves. After a restart the first sweep reconstructs the next deadline from them. - *Pending-work predicate / next deadline:* after a full pass the sweep keeps the earliest due time of the entries it retained; ticks before that time skip the evidence pass entirely (no readdir, no SQL). A busy session, a failed removal, or a full batch makes it due on the next sweep while that obligation remains. - *Quiet condition:* no evidence, or only evidence not yet due. The pass never queries the database, so retained evidence never causes recurring SQL. Dry run reports each candidate once rather than every hour. No code comments were added. ## Verification - `pnpm exec vitest run src/__tests__/native-harness-backup-expiration` (in `server/`, embedded Postgres): 52 passed. New cases: - old archives and quarantine entries are removed, recent ones kept; the empty `continuity-breaks` folder is removed; - age comes from the name, with mtime used for a future epoch; non-archive folders are ignored; - a busy session keeps its evidence, including when it becomes busy after the first check, and it is retried on the next tick; - dry run reports candidates and bytes, changes nothing (including leftovers), and reports each candidate once until new evidence comes due; - symlinked entries and symlinked evidence folders are skipped without touching the target; - an old quarantine entry is removed even when its session's issue is still open; cleanup source archives are kept; - the pass stays quiet until retained evidence is due, and a `noteEvidence` signal schedules newly written evidence; - inspected archives and leftovers count against `maxEntries`, and leftover removal stops on `shouldContinue` and resumes next tick; - a due pass stopped by drain before any session stays pending; one-entry batches finish without recounting a resumed session; - interrupted `.expired-*` deletions are finished; paging across ticks with `maxRemovals`, in normal and dry run, with no recount of the backup when resuming. - `native-session-executor.test.ts`: quarantining a legacy root raises the evidence signal with the epoch in the entry name. - `native-harness-backup-expiration-config`: default, explicit, minimum, and fallback parsing. - **Mutation checks**, each failing at least one test: removing the age check, the future-epoch fallback, either busy check, the busy retry deadline, the recent-entry deadline, the due gate, the `noteEvidence` update, merging the pass deadline, the entry and both folder symlink checks, the dry-run return, the dry-run leftover guard, leftover removal, the leftover budget check and its retry deadline, counting archives against `maxEntries`, the cleanup-archive skip, the empty-folder removal, the resume cursor, the per-archive budget check, the resume skip of the backup pass, not charging a resumed session, keeping the pass active across drain, and the executor's quarantine signal. - `pnpm exec vitest run config native-harness native-workspace-sync-retention native-session-executor server-startup` (in `server/`): 1272 passed on the previous commit; `config native-harness native-workspace-sync-retention server-startup`: 450 passed on the head commit. - `pnpm run typecheck` (in `server/`): pass. - Not run: server build and boot smoke. The continuity-archive signal call is exercised only by a runner integration test that needs the runnerd binary. ## Risks - **Quarantine as a fail-closed fence:** recovery (`recoverQuiescentRunnerdState`) and failed-run retry (`nativeFailedRunRetryStateIsSafe`) treat a quarantined entry for a session as a reason not to bootstrap fresh. Once such an entry ages out, a later run of that session can start a fresh provider session instead of failing with `quarantine_owner_unverified`. This applies only after the window, matching what backup expiry already accepts for closed work. - **Signal coverage:** the signal is process-local. Evidence written by another process sharing the same state directory is picked up when the next retained deadline is due or after a restart, not immediately. - **Legacy-path quarantine:** entries quarantined from legacy roots carry a legacy digest, so the in-process busy check cannot match them; they are removed by age only. - **Remote sandboxes:** archives moved aside on a remote runner (`.continuity-break-`) are outside this sweep. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), 1M context, through Claude Code with tool use (shell, file edits, tests). ## 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 --- doc/DEVELOPING.md | 5 + doc/recoverable-disk-cleanup.md | 33 ++ ...e-harness-backup-expiration-config.test.ts | 11 + .../native-harness-backup-expiration.test.ts | 374 ++++++++++++++++++ server/src/config.ts | 3 + server/src/index.ts | 6 +- .../native-harness-backup-expiration.ts | 282 +++++++++++-- .../native-runner-evidence-signal.ts | 12 + .../native-session-executor.test.ts | 6 +- .../native-runtime/native-session-executor.ts | 9 +- 10 files changed, 712 insertions(+), 29 deletions(-) create mode 100644 server/src/services/native-runtime/native-runner-evidence-signal.ts diff --git a/doc/DEVELOPING.md b/doc/DEVELOPING.md index fdfc680c06e..f8d408cdff9 100644 --- a/doc/DEVELOPING.md +++ b/doc/DEVELOPING.md @@ -2627,6 +2627,11 @@ Environment overrides: negative, empty, or non-numeric value falls back to the default. `PAPERCLIP_NATIVE_HARNESS_BACKUP_EXPIRATION_ENABLED=false` turns expiry off, and `PAPERCLIP_NATIVE_HARNESS_BACKUP_EXPIRATION_DRY_RUN=true` only reports candidates. +- `PAPERCLIP_NATIVE_RUNNER_EVIDENCE_RETENTION_DAYS=` sets how long native + session continuity-break archives and quarantined session state are kept (see + `doc/recoverable-disk-cleanup.md`). The default is `7` and the minimum is `1`. A + negative, empty, or non-numeric value falls back to the default. The backup + expiration enabled and dry-run switches apply to it as well. - `PAPERCLIP_NATIVE_WORKSPACE_SYNC_RETENTION_DAYS=` sets how long a settled run's native workspace sync folder (descriptor, manifest and seed archives under `/native-workspace-sync/`) is kept (see diff --git a/doc/recoverable-disk-cleanup.md b/doc/recoverable-disk-cleanup.md index b33a0cc74fd..93f9ccb6fef 100644 --- a/doc/recoverable-disk-cleanup.md +++ b/doc/recoverable-disk-cleanup.md @@ -89,10 +89,43 @@ The rest of the session directory, including its control-plane state, is kept. | `PAPERCLIP_NATIVE_HARNESS_BACKUP_EXPIRATION_ENABLED` | `true` | Set `false` to stop expiring copies | | `PAPERCLIP_NATIVE_HARNESS_BACKUP_EXPIRATION_DRY_RUN` | `false` | Set `true` to report candidates without deleting copies or task sessions | | `PAPERCLIP_NATIVE_HARNESS_BACKUP_EXPIRATION_DAYS` | `7` | Days an issue must be closed before its sessions' copies expire (minimum `1`) | +| `PAPERCLIP_NATIVE_RUNNER_EVIDENCE_RETENTION_DAYS` | `7` | Days continuity-break archives and quarantined session state are kept (minimum `1`) | Each batch that finds candidates logs them with candidate and reclaimed allocated bytes, cleared task sessions, and skip reasons. +### Continuity-break archives and quarantined session state + +The same sweep also removes two kinds of evidence that native sessions leave behind +under the same root: + +- `/continuity-breaks/-/`, written when a session starts a + fresh provider session and moves the retired session's state aside. Nothing reads + these archives again. +- `quarantine/..../`, written when a session's + state loses authority. Recovery and failed-run retry still consult these entries. + +An entry's age comes from the epoch in its name, or from its modification time when +that epoch is in the future. An entry is removed once it is older than +`PAPERCLIP_NATIVE_RUNNER_EVIDENCE_RETENTION_DAYS` and its session is not executing, +initializing, warm, or closing in this process. Quarantine entries created by +native cleanup (`.identity_indeterminate.cleanup.`) are referenced +from recovery history and kept. Symlinks are never followed or removed. Once a +quarantined entry is removed, recovery and failed-run retry no longer see it, so a +later run of that session may start a fresh provider session instead of refusing. + +The evidence check runs on the sweep only when something is due: once at startup, +then when the oldest retained entry, or an entry the executor has written since, +reaches the window, and on the next sweep after a busy session, a failed removal, +or a full batch. It only reads the filesystem and never queries the +database. A dry run reports each candidate once until newly written evidence comes due. + +An entry is renamed to `.expired-` in its folder before it is deleted, and a +later sweep finishes an interrupted deletion. An empty `continuity-breaks` folder +is removed. Archives, quarantine entries, and leftovers count toward the batch +limits of 200 entries and 50 removals shared with backup copies, and +`PAPERCLIP_NATIVE_HARNESS_BACKUP_EXPIRATION_ENABLED` and `_DRY_RUN` apply to both. + ## Native workspace sync folders Each native run that syncs a workspace with a remote sandbox writes a folder at diff --git a/server/src/__tests__/native-harness-backup-expiration-config.test.ts b/server/src/__tests__/native-harness-backup-expiration-config.test.ts index 81967a9bdad..0b79c92e542 100644 --- a/server/src/__tests__/native-harness-backup-expiration-config.test.ts +++ b/server/src/__tests__/native-harness-backup-expiration-config.test.ts @@ -37,4 +37,15 @@ describe("native harness backup expiration config parsing", () => { vi.stubEnv("PAPERCLIP_NATIVE_HARNESS_BACKUP_EXPIRATION_DAYS", "0"); expect(loadConfig()).toMatchObject({ nativeHarnessBackupExpirationDays: 1 }); }); + + it("keeps native runner evidence for seven days by default and at least one day", () => { + vi.stubEnv("PAPERCLIP_NATIVE_RUNNER_EVIDENCE_RETENTION_DAYS", undefined); + expect(loadConfig()).toMatchObject({ nativeRunnerEvidenceRetentionDays: 7 }); + vi.stubEnv("PAPERCLIP_NATIVE_RUNNER_EVIDENCE_RETENTION_DAYS", "14"); + expect(loadConfig()).toMatchObject({ nativeRunnerEvidenceRetentionDays: 14 }); + vi.stubEnv("PAPERCLIP_NATIVE_RUNNER_EVIDENCE_RETENTION_DAYS", "0"); + expect(loadConfig()).toMatchObject({ nativeRunnerEvidenceRetentionDays: 1 }); + vi.stubEnv("PAPERCLIP_NATIVE_RUNNER_EVIDENCE_RETENTION_DAYS", "many"); + expect(loadConfig()).toMatchObject({ nativeRunnerEvidenceRetentionDays: 7 }); + }); }); diff --git a/server/src/__tests__/native-harness-backup-expiration.test.ts b/server/src/__tests__/native-harness-backup-expiration.test.ts index b6330409e72..0123d816a86 100644 --- a/server/src/__tests__/native-harness-backup-expiration.test.ts +++ b/server/src/__tests__/native-harness-backup-expiration.test.ts @@ -301,4 +301,378 @@ describeEmbeddedPostgres("native harness backup expiration", () => { expect(await exists(leftover)).toBe(false); expect(await exists(session.current)).toBe(true); }); + async function seedArchive(root: string, input: { stampedDaysAgo?: number; mtimeDaysAgo?: number; name?: string } = {}) { + const stampedAt = now.getTime() - (input.stampedDaysAgo ?? 10) * DAY_MS; + const archive = path.join(root, "continuity-breaks", input.name ?? `${stampedAt}-${randomUUID()}`); + await fs.mkdir(path.join(archive, "codex-home"), { recursive: true }); + await fs.writeFile(path.join(archive, "codex-home", "history.jsonl"), "x".repeat(64 * 1024)); + const mtime = new Date(now.getTime() - (input.mtimeDaysAgo ?? input.stampedDaysAgo ?? 10) * DAY_MS); + await fs.utimes(archive, mtime, mtime); + return archive; + } + + async function seedQuarantine( + scope: string, + input: { stampedDaysAgo?: number; name?: string } = {}, + ) { + if (!stateBase) stateBase = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-durable-sessions-")); + const stampedAt = now.getTime() - (input.stampedDaysAgo ?? 10) * DAY_MS; + const entry = path.join( + stateBase, + "quarantine", + input.name ?? `${scope}.identity_indeterminate.${stampedAt}.4242.${randomUUID()}`, + ); + await fs.mkdir(path.join(entry, "control-plane"), { recursive: true }); + await fs.writeFile(path.join(entry, "history.jsonl"), "x".repeat(64 * 1024)); + return entry; + } + + function evidenceService(overrides: Parameters[1] = {}) { + return nativeHarnessBackupExpirationService(db, { + stateBase, + now, + evidenceRetentionDays: 7, + isSessionBusy: () => false, + ...overrides, + }); + } + + async function emptyStateBase() { + if (!stateBase) stateBase = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-durable-sessions-")); + return createHash("sha256").update(randomUUID()).digest("hex"); + } + + it("removes continuity archives older than the retention window and keeps recent ones", async () => { + const session = await seedSession({ issueStatus: "in_progress" }); + const old = await seedArchive(session.root, { stampedDaysAgo: 9 }); + const recent = await seedArchive(session.root, { stampedDaysAgo: 2 }); + + const result = await evidenceService().tick(); + + expect(result).toMatchObject({ evidenceCandidates: 1, evidenceRemoved: 1, failed: 0 }); + expect(result.evidenceReclaimedBytes).toBeGreaterThan(0); + expect(result.skipped.recent_evidence).toBe(1); + expect(await exists(old)).toBe(false); + expect(await exists(recent)).toBe(true); + expect(await exists(session.current)).toBe(true); + }); + + it("removes the continuity-breaks folder once its archives are gone", async () => { + const session = await seedSession({ issueStatus: "in_progress" }); + await seedArchive(session.root); + + expect(await evidenceService().tick()).toMatchObject({ evidenceRemoved: 1 }); + expect(await exists(path.join(session.root, "continuity-breaks"))).toBe(false); + }); + + it("ages a continuity archive by its name and falls back to mtime for a future stamp", async () => { + const session = await seedSession({ issueStatus: "in_progress" }); + const stampedRecently = await seedArchive(session.root, { stampedDaysAgo: 1, mtimeDaysAgo: 30 }); + const futureStamp = await seedArchive(session.root, { + name: `${now.getTime() + DAY_MS}-${randomUUID()}`, + mtimeDaysAgo: 30, + }); + const futureRecent = await seedArchive(session.root, { + name: `${now.getTime() + 2 * DAY_MS}-${randomUUID()}`, + mtimeDaysAgo: 1, + }); + + expect(await evidenceService().tick()).toMatchObject({ evidenceRemoved: 1 }); + expect(await exists(stampedRecently)).toBe(true); + expect(await exists(futureStamp)).toBe(false); + expect(await exists(futureRecent)).toBe(true); + }); + + it("ignores folders that are not continuity archives", async () => { + const session = await seedSession({ issueStatus: "in_progress" }); + const other = await seedArchive(session.root, { name: "notes", stampedDaysAgo: 30 }); + + expect(await evidenceService().tick()).toMatchObject({ evidenceCandidates: 0 }); + expect(await exists(other)).toBe(true); + }); + + it("keeps the evidence of a session that is executing in this process", async () => { + const session = await seedSession({ issueStatus: "in_progress" }); + const archive = await seedArchive(session.root); + const quarantine = await seedQuarantine(session.scope); + + const result = await evidenceService({ isSessionBusy: (scope) => scope === session.scope }).tick(); + + expect(result).toMatchObject({ evidenceCandidates: 0, evidenceRemoved: 0 }); + expect(result.skipped.session_active).toBe(3); + expect(await exists(archive)).toBe(true); + expect(await exists(quarantine)).toBe(true); + }); + + it("keeps evidence when its session starts while the removal is being prepared", async () => { + const scope = await emptyStateBase(); + const root = path.join(stateBase, scope); + const archive = await seedArchive(root); + let checks = 0; + + const result = await evidenceService({ isSessionBusy: () => ++checks > 1 }).tick(); + + expect(result).toMatchObject({ evidenceCandidates: 1, evidenceRemoved: 0 }); + expect(result.skipped.session_active).toBe(1); + expect(await exists(archive)).toBe(true); + }); + + it("reports evidence without deleting it in dry run", async () => { + const session = await seedSession({ issueStatus: "in_progress" }); + const archive = await seedArchive(session.root); + const quarantine = await seedQuarantine(session.scope); + const leftover = path.join(session.root, "continuity-breaks", `.expired-${randomUUID()}`); + await fs.mkdir(leftover); + + const result = await evidenceService({ dryRun: true }).tick(); + + expect(result).toMatchObject({ evidenceCandidates: 2, evidenceRemoved: 0, evidenceReclaimedBytes: 0 }); + expect(result.evidenceCandidateBytes).toBeGreaterThan(0); + expect(await exists(archive)).toBe(true); + expect(await exists(quarantine)).toBe(true); + expect(await exists(leftover)).toBe(true); + }); + + it("skips symlinked evidence without following it", async () => { + const session = await seedSession({ issueStatus: "in_progress" }); + const outside = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-evidence-outside-")); + try { + await fs.writeFile(path.join(outside, "keep.txt"), "keep"); + const stampedAt = now.getTime() - 10 * DAY_MS; + await fs.mkdir(path.join(session.root, "continuity-breaks"), { recursive: true }); + const archiveLink = path.join(session.root, "continuity-breaks", `${stampedAt}-${randomUUID()}`); + await fs.symlink(outside, archiveLink); + await fs.mkdir(path.join(stateBase, "quarantine"), { recursive: true }); + const quarantineLink = path.join( + stateBase, + "quarantine", + `${session.scope}.identity_indeterminate.${stampedAt}.4242.${randomUUID()}`, + ); + await fs.symlink(outside, quarantineLink); + + const result = await evidenceService().tick(); + + expect(result).toMatchObject({ evidenceCandidates: 0, evidenceRemoved: 0 }); + expect(result.skipped.unsafe_path).toBe(2); + expect(await exists(archiveLink)).toBe(true); + expect(await exists(quarantineLink)).toBe(true); + expect(await exists(path.join(outside, "keep.txt"))).toBe(true); + } finally { + await fs.rm(outside, { recursive: true, force: true }); + } + }); + + it("skips symlinked evidence folders without following them", async () => { + const session = await seedSession({ issueStatus: "in_progress" }); + const outside = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-evidence-outside-")); + try { + const stampedAt = now.getTime() - 10 * DAY_MS; + const inside = path.join(outside, `${stampedAt}-${randomUUID()}`); + await fs.mkdir(inside); + await fs.utimes(inside, new Date(stampedAt), new Date(stampedAt)); + await fs.symlink(outside, path.join(session.root, "continuity-breaks")); + await fs.symlink(outside, path.join(stateBase, "quarantine")); + + const result = await evidenceService().tick(); + + expect(result).toMatchObject({ evidenceCandidates: 0, evidenceRemoved: 0 }); + expect(result.skipped.unsafe_path).toBe(2); + expect(await exists(inside)).toBe(true); + } finally { + await fs.rm(outside, { recursive: true, force: true }); + } + }); + + it("removes quarantine entries older than the retention window and keeps recent ones", async () => { + const scope = await emptyStateBase(); + const old = await seedQuarantine(scope, { stampedDaysAgo: 9 }); + const recent = await seedQuarantine(scope, { stampedDaysAgo: 2 }); + + const result = await evidenceService().tick(); + + expect(result).toMatchObject({ evidenceCandidates: 1, evidenceRemoved: 1, failed: 0 }); + expect(result.skipped.recent_evidence).toBe(1); + expect(await exists(old)).toBe(false); + expect(await exists(recent)).toBe(true); + expect(await fs.readdir(path.join(stateBase, "quarantine"))).toEqual([path.basename(recent)]); + }); + + it("keeps cleanup source archives in quarantine", async () => { + const scope = await emptyStateBase(); + const entry = await seedQuarantine(scope, { name: `${scope}.identity_indeterminate.cleanup.${randomUUID()}` }); + const old = new Date(now.getTime() - 30 * DAY_MS); + await fs.utimes(entry, old, old); + + const result = await evidenceService().tick(); + + expect(result.evidenceCandidates).toBe(0); + expect(result.skipped.cleanup_archive).toBe(1); + expect(await exists(entry)).toBe(true); + }); + + it("finishes removing evidence left over from an interrupted removal", async () => { + const session = await seedSession({ issueStatus: "in_progress" }); + const archive = await seedArchive(session.root, { stampedDaysAgo: 1 }); + const leftover = path.join(session.root, "continuity-breaks", `.expired-${randomUUID()}`); + await fs.mkdir(path.join(leftover, "codex-home"), { recursive: true }); + const quarantineLeftover = path.join(stateBase, "quarantine", `.expired-${randomUUID()}`); + await fs.mkdir(quarantineLeftover, { recursive: true }); + + await evidenceService().tick(); + + expect(await exists(leftover)).toBe(false); + expect(await exists(quarantineLeftover)).toBe(false); + expect(await exists(archive)).toBe(true); + }); + + it.each([false, true])("pages evidence removals across ticks (dry run %s)", async (dryRun) => { + const session = await seedSession({ issueStatus: "in_progress" }); + const archives = [await seedArchive(session.root), await seedArchive(session.root), await seedArchive(session.root)]; + const quarantine = await seedQuarantine(session.scope); + const retention = evidenceService({ dryRun, maxRemovals: 2 }); + + const results = []; + for (let i = 0; i < 4; i++) { + const result = await retention.tick(); + results.push(result); + if (!result.truncated) break; + } + + expect(results.map((result) => result.evidenceCandidates)).toEqual([2, 2]); + expect(results.map((result) => result.truncated)).toEqual([true, false]); + for (const archive of archives) expect(await exists(archive)).toBe(dryRun); + expect(await exists(quarantine)).toBe(dryRun); + }); + + it("does not recount a session's backup when its archives resume on the next tick", async () => { + const session = await seedSession(); + await seedArchive(session.root); + await seedArchive(session.root); + const retention = evidenceService({ dryRun: true, maxRemovals: 2 }); + + const first = await retention.tick(); + const second = await retention.tick(); + + expect(first).toMatchObject({ candidates: 1, evidenceCandidates: 1, truncated: true }); + expect(second).toMatchObject({ candidates: 0, evidenceCandidates: 1, truncated: false }); + }); + it("removes old quarantine entries even when their session's issue is still open", async () => { + const session = await seedSession({ issueStatus: "in_progress", backupAgeDays: 1 }); + const entry = await seedQuarantine(session.scope); + await fs.cp(path.join(session.root, "control-plane"), path.join(entry, "control-plane"), { recursive: true }); + + expect(await evidenceService().tick()).toMatchObject({ evidenceRemoved: 1 }); + expect(await exists(entry)).toBe(false); + }); + + it("stays quiet until retained evidence is due and wakes when new evidence is written", async () => { + const session = await seedSession({ issueStatus: "in_progress", backupAgeDays: 1 }); + const recent = await seedArchive(session.root, { stampedDaysAgo: 2 }); + const retention = evidenceService(); + const at = (days: number) => ({ now: new Date(now.getTime() + days * DAY_MS) }); + + expect((await retention.tick()).skipped.recent_evidence).toBe(1); + expect((await retention.tick(at(4))).skipped.recent_evidence).toBeUndefined(); + expect(await retention.tick(at(6))).toMatchObject({ evidenceRemoved: 1 }); + expect(await exists(recent)).toBe(false); + + const written = await seedArchive(session.root, { stampedDaysAgo: 0 }); + expect(await retention.tick(at(8))).toMatchObject({ evidenceCandidates: 0 }); + retention.noteEvidence(now.getTime()); + expect(await retention.tick(at(8))).toMatchObject({ evidenceRemoved: 1 }); + expect(await exists(written)).toBe(false); + }); + + it("retries evidence of a busy session on the next tick", async () => { + const session = await seedSession({ issueStatus: "in_progress", backupAgeDays: 1 }); + const archive = await seedArchive(session.root); + let busy = true; + const retention = evidenceService({ isSessionBusy: () => busy }); + + expect(await retention.tick()).toMatchObject({ evidenceRemoved: 0 }); + busy = false; + expect(await retention.tick()).toMatchObject({ evidenceRemoved: 1 }); + expect(await exists(archive)).toBe(false); + }); + + it("reports dry-run evidence once until new evidence is written", async () => { + const session = await seedSession({ issueStatus: "in_progress", backupAgeDays: 1 }); + await seedArchive(session.root); + const retention = evidenceService({ dryRun: true }); + + expect(await retention.tick()).toMatchObject({ evidenceCandidates: 1 }); + expect(await retention.tick()).toMatchObject({ evidenceCandidates: 0 }); + retention.noteEvidence(now.getTime()); + expect(await retention.tick({ now: new Date(now.getTime() + 7 * DAY_MS) })).toMatchObject({ evidenceCandidates: 1 }); + }); + + it("counts inspected archives and leftovers against the entry limit", async () => { + const session = await seedSession({ issueStatus: "in_progress", backupAgeDays: 1 }); + const archives = [ + await seedArchive(session.root, { stampedDaysAgo: 1 }), + await seedArchive(session.root, { stampedDaysAgo: 2 }), + await seedArchive(session.root, { stampedDaysAgo: 3 }), + ]; + const leftovers = [randomUUID(), randomUUID()].map((id) => path.join(session.root, "continuity-breaks", `.expired-${id}`)); + for (const leftover of leftovers) await fs.mkdir(leftover); + const retention = evidenceService({ maxEntries: 2 }); + + const first = await retention.tick(); + expect(first).toMatchObject({ checked: 2, truncated: true }); + expect(first.skipped.recent_evidence).toBeUndefined(); + expect((await fs.readdir(path.join(session.root, "continuity-breaks"))).filter((name) => name.startsWith(".expired-"))).toHaveLength(1); + + const results = [first]; + for (let i = 0; i < 6 && results.at(-1)!.truncated; i++) results.push(await retention.tick()); + expect(results.at(-1)!.truncated).toBe(false); + expect(results.every((result) => result.checked <= 2)).toBe(true); + expect(results.every((result) => (result.skipped.recent_evidence ?? 0) <= 2)).toBe(true); + expect(results.reduce((sum, result) => sum + (result.skipped.recent_evidence ?? 0), 0)).toBe(3); + for (const leftover of leftovers) expect(await exists(leftover)).toBe(false); + for (const archive of archives) expect(await exists(archive)).toBe(true); + }); + + it("stops removing leftovers once the sweep must stop", async () => { + const session = await seedSession({ issueStatus: "in_progress", backupAgeDays: 1 }); + await fs.mkdir(path.join(session.root, "continuity-breaks")); + const leftover = path.join(session.root, "continuity-breaks", `.expired-${randomUUID()}`); + await fs.mkdir(leftover); + let calls = 0; + + const retention = evidenceService({ shouldContinue: () => ++calls !== 2 }); + + await retention.tick(); + expect(await exists(leftover)).toBe(true); + await retention.tick(); + expect(await exists(leftover)).toBe(false); + }); + + it("keeps a due evidence pass pending when drain stops it before any session", async () => { + const session = await seedSession({ issueStatus: "in_progress", backupAgeDays: 1 }); + const archive = await seedArchive(session.root); + let draining = true; + const retention = evidenceService({ shouldContinue: () => !draining }); + + expect(await retention.tick()).toMatchObject({ checked: 0, truncated: true }); + draining = false; + expect(await retention.tick()).toMatchObject({ evidenceRemoved: 1 }); + expect(await exists(archive)).toBe(false); + }); + + it("finishes one-entry batches without recounting a resumed session", async () => { + const session = await seedSession({ issueStatus: "in_progress", backupAgeDays: 1 }); + const archives = [await seedArchive(session.root), await seedArchive(session.root)]; + const quarantine = await seedQuarantine(session.scope); + const retention = evidenceService({ maxEntries: 1 }); + + const results = []; + for (let i = 0; i < 8; i++) { + results.push(await retention.tick()); + if (!results.at(-1)!.truncated) break; + } + + expect(results.at(-1)!.truncated).toBe(false); + for (const archive of archives) expect(await exists(archive)).toBe(false); + expect(await exists(quarantine)).toBe(false); + }); }); diff --git a/server/src/config.ts b/server/src/config.ts index 74e80c77ee1..dac9dba2142 100644 --- a/server/src/config.ts +++ b/server/src/config.ts @@ -95,6 +95,7 @@ export interface Config { nativeHarnessBackupExpirationEnabled: boolean; nativeHarnessBackupExpirationDryRun: boolean; nativeHarnessBackupExpirationDays: number; + nativeRunnerEvidenceRetentionDays: number; nativeWorkspaceSyncRetentionEnabled: boolean; nativeWorkspaceSyncRetentionDryRun: boolean; nativeWorkspaceSyncRetentionDays: number; @@ -351,6 +352,7 @@ export function loadConfig(): Config { const skillVersionRetentionKeepNewest = nonNegativeIntegerEnv("PAPERCLIP_SKILL_VERSION_RETENTION_KEEP", 0); const skillVersionRetentionGraceMinutes = nonNegativeIntegerEnv("PAPERCLIP_SKILL_VERSION_RETENTION_GRACE_MINUTES", 60); const nativeHarnessBackupExpirationDays = Math.max(1, nonNegativeIntegerEnv("PAPERCLIP_NATIVE_HARNESS_BACKUP_EXPIRATION_DAYS", 7)); + const nativeRunnerEvidenceRetentionDays = Math.max(1, nonNegativeIntegerEnv("PAPERCLIP_NATIVE_RUNNER_EVIDENCE_RETENTION_DAYS", 7)); const nativeWorkspaceSyncRetentionDays = Math.max(1, nonNegativeIntegerEnv("PAPERCLIP_NATIVE_WORKSPACE_SYNC_RETENTION_DAYS", 7)); const gitRestorePointRetentionDays = Math.max(1, nonNegativeIntegerEnv("PAPERCLIP_GIT_RESTORE_POINT_RETENTION_DAYS", 90)); const gitRestorePointTerminalDelayDays = nonNegativeIntegerEnv("PAPERCLIP_GIT_RESTORE_POINT_TERMINAL_DELAY_DAYS", 3); @@ -417,6 +419,7 @@ export function loadConfig(): Config { nativeHarnessBackupExpirationEnabled: process.env.PAPERCLIP_NATIVE_HARNESS_BACKUP_EXPIRATION_ENABLED !== "false", nativeHarnessBackupExpirationDryRun: process.env.PAPERCLIP_NATIVE_HARNESS_BACKUP_EXPIRATION_DRY_RUN === "true", nativeHarnessBackupExpirationDays, + nativeRunnerEvidenceRetentionDays, nativeWorkspaceSyncRetentionEnabled: process.env.PAPERCLIP_NATIVE_WORKSPACE_SYNC_RETENTION_ENABLED !== "false", nativeWorkspaceSyncRetentionDryRun: process.env.PAPERCLIP_NATIVE_WORKSPACE_SYNC_RETENTION_DRY_RUN === "true", nativeWorkspaceSyncRetentionDays, diff --git a/server/src/index.ts b/server/src/index.ts index 207f342a2ae..4212387dd04 100644 --- a/server/src/index.ts +++ b/server/src/index.ts @@ -13,6 +13,7 @@ import { NATIVE_HARNESS_BACKUP_EXPIRATION_STARTUP_DELAY_MS, nativeHarnessBackupExpirationService, } from "./services/native-runtime/native-harness-backup-expiration.js"; +import { onNativeRunnerEvidence } from "./services/native-runtime/native-runner-evidence-signal.js"; import { gitRestorePointRetentionService, registerGitRestorePointWork } from "./services/git-restore-point-ledger.js"; import { nativeWorkspaceSyncRetentionService, @@ -1269,8 +1270,10 @@ async function startServerWithDatabaseTeardown( const nativeHarnessBackupExpiration = nativeHarnessBackupExpirationService(db as any, { dryRun: config.nativeHarnessBackupExpirationDryRun, closedForDays: config.nativeHarnessBackupExpirationDays, + evidenceRetentionDays: config.nativeRunnerEvidenceRetentionDays, shouldContinue: () => !heartbeatSchedulerStopped && !isIdleTaskDrainActive() && !isWarmStandby(), }); + const unsubscribeNativeRunnerEvidence = onNativeRunnerEvidence(nativeHarnessBackupExpiration.noteEvidence); let nativeHarnessBackupExpirationInFlight = false; let nativeHarnessBackupExpirationContinuation: ReturnType | undefined; const sweepNativeHarnessBackups = () => { @@ -1278,7 +1281,7 @@ async function startServerWithDatabaseTeardown( nativeHarnessBackupExpirationInFlight = true; trackHeartbeatSchedulerWork(nativeHarnessBackupExpiration.tick() .then((result) => { - if (result.candidates > 0 || result.failed > 0) { + if (result.candidates > 0 || result.evidenceCandidates > 0 || result.failed > 0) { logger.info({ ...result, dryRun: config.nativeHarnessBackupExpirationDryRun }, "native harness backup expiration"); } if (result.truncated && !heartbeatSchedulerStopped) { @@ -2095,6 +2098,7 @@ async function startServerWithDatabaseTeardown( clearInterval(nativeHarnessBackupExpirationInterval); clearTimeout(nativeHarnessBackupExpirationStartup); clearTimeout(nativeHarnessBackupExpirationContinuation); + unsubscribeNativeRunnerEvidence(); await skillVersionRetention.dispose(); await skillSourceSync.stop(); unsubscribeChatCompletions(); diff --git a/server/src/services/native-runtime/native-harness-backup-expiration.ts b/server/src/services/native-runtime/native-harness-backup-expiration.ts index 448997670e1..d4c0975f0b5 100644 --- a/server/src/services/native-runtime/native-harness-backup-expiration.ts +++ b/server/src/services/native-runtime/native-harness-backup-expiration.ts @@ -17,10 +17,15 @@ import { nativeSessionScopeDigestIsBusy } from "./native-session-executor.js"; export const NATIVE_HARNESS_BACKUP_EXPIRATION_INTERVAL_MS = 60 * 60 * 1000; export const NATIVE_HARNESS_BACKUP_EXPIRATION_STARTUP_DELAY_MS = 2 * 60 * 1000; export const NATIVE_HARNESS_BACKUP_EXPIRATION_DEFAULT_DAYS = 7; +export const NATIVE_RUNNER_EVIDENCE_RETENTION_DEFAULT_DAYS = 7; const DAY_MS = 24 * 60 * 60 * 1000; const SCOPE_PATTERN = /^[0-9a-f]{64}$/; const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; +const CONTINUITY_ARCHIVE_PATTERN = /^(\d{1,15})-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; +const QUARANTINE_PATTERN = + /^([0-9a-f]{64})\.(?:identity_indeterminate|identity_mismatch)\.(\d{1,15})\.\d{1,10}\.[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; +const QUARANTINE_CLEANUP_PATTERN = /^[0-9a-f]{64}\.identity_indeterminate\.cleanup\./; const EXPIRED_PREFIX = ".expired-"; const RETIRING_PREFIX = ".retiring-"; const LIVE_RUN_STATUSES = ["queued", "scheduled_retry", "running"]; @@ -31,6 +36,7 @@ const MAX_CONTROL_PLANE_STATE_BYTES = 4 * 1024 * 1024; export type NativeHarnessBackupExpirationOptions = { closedForDays?: number; + evidenceRetentionDays?: number; dryRun?: boolean; maxEntries?: number; maxRemovals?: number; @@ -47,11 +53,25 @@ export type NativeHarnessBackupExpirationResult = { expired: number; reclaimedBytes: number; clearedTaskSessions: number; + evidenceCandidates: number; + evidenceCandidateBytes: number; + evidenceRemoved: number; + evidenceReclaimedBytes: number; failed: number; truncated: boolean; skipped: Record; }; +type EvidenceContext = { + dryRun: boolean; + isSessionBusy: (scopeDigest: string) => boolean; + now: number; + retentionMs: number; + retainedBefore: number; + canInspect: () => boolean; + dueAt: (at: number) => void; +}; + type SessionIdentity = { runId: string; normalizedSessionId: string; @@ -66,6 +86,10 @@ function emptyResult(): NativeHarnessBackupExpirationResult { expired: 0, reclaimedBytes: 0, clearedTaskSessions: 0, + evidenceCandidates: 0, + evidenceCandidateBytes: 0, + evidenceRemoved: 0, + evidenceReclaimedBytes: 0, failed: 0, truncated: false, skipped: {}, @@ -223,6 +247,13 @@ export function nativeHarnessBackupExpirationService( defaults: NativeHarnessBackupExpirationOptions = {}, ) { let cursor: string | null = null; + let resume: { scope: string; archive: string } | null = null; + let quarantineCursor: string | null = null; + let phase: "sessions" | "quarantine" = "sessions"; + let passActive = false; + let evidencePass = false; + let evidenceDueAt = 0; + let passDueAt = Number.POSITIVE_INFINITY; async function settleLeftovers(backupRoot: string) { const current = path.join(backupRoot, "current"); @@ -310,46 +341,247 @@ export function nativeHarnessBackupExpirationService( result.reclaimedBytes += bytes; } + async function removeExpiredLeftovers(parent: string, context: EvidenceContext, result: NativeHarnessBackupExpirationResult) { + for (const name of await fs.readdir(parent).catch(() => [] as string[])) { + if (!name.startsWith(EXPIRED_PREFIX) || !UUID_PATTERN.test(name.slice(EXPIRED_PREFIX.length))) continue; + if (!context.canInspect()) { + context.dueAt(context.now); + return; + } + result.checked++; + await removeBackupTree(path.join(parent, name)); + } + } + + async function retireEvidence( + parent: string, + name: string, + scopeDigest: string, + stampedAt: number, + context: EvidenceContext, + result: NativeHarnessBackupExpirationResult, + ) { + const skip = (reason: string) => { + result.skipped[reason] = (result.skipped[reason] ?? 0) + 1; + }; + const target = path.join(parent, name); + const stat = await fs.lstat(target).catch(() => null); + if (path.dirname(target) !== parent || !stat?.isDirectory()) { + return skip("unsafe_path"); + } + const createdAt = stampedAt > 0 && stampedAt <= context.now ? stampedAt : stat.mtimeMs; + if (createdAt >= context.retainedBefore) { + context.dueAt(createdAt + context.retentionMs); + return skip("recent_evidence"); + } + if (context.isSessionBusy(scopeDigest)) { + context.dueAt(context.now); + return skip("session_active"); + } + const bytes = await allocatedBytes(target); + result.evidenceCandidates++; + result.evidenceCandidateBytes += bytes; + if (context.dryRun) return; + if (context.isSessionBusy(scopeDigest)) { + context.dueAt(context.now); + return skip("session_active"); + } + const trash = path.join(parent, `${EXPIRED_PREFIX}${randomUUID()}`); + await fs.rename(target, trash); + await removeBackupTree(trash); + result.evidenceRemoved++; + result.evidenceReclaimedBytes += bytes; + } + + async function retireContinuityBreaks( + root: string, + scopeDigest: string, + resumeAfter: string | null, + context: EvidenceContext, + result: NativeHarnessBackupExpirationResult, + ): Promise { + const parent = path.join(root, "continuity-breaks"); + const stat = await fs.lstat(parent).catch(() => null); + if (!stat) return null; + if (!stat.isDirectory()) { + result.skipped.unsafe_path = (result.skipped.unsafe_path ?? 0) + 1; + return null; + } + if (!context.dryRun) await removeExpiredLeftovers(parent, context, result); + let last = resumeAfter ?? ""; + const names = (await fs.readdir(parent)).filter((name) => name > last).sort(); + for (const name of names) { + const match = CONTINUITY_ARCHIVE_PATTERN.exec(name); + if (!match) continue; + if (!context.canInspect()) return last; + result.checked++; + last = name; + try { + await retireEvidence(parent, name, scopeDigest, Number(match[1]), context, result); + } catch (err) { + result.failed++; + context.dueAt(context.now); + logger.warn({ err, scope: scopeDigest }, "native runner evidence retention skipped a continuity archive"); + } + } + if (!context.dryRun) await fs.rmdir(parent).catch(() => undefined); + return null; + } + + async function retireQuarantine( + base: string, + context: EvidenceContext, + result: NativeHarnessBackupExpirationResult, + ): Promise { + const parent = path.join(base, "quarantine"); + const stat = await fs.lstat(parent).catch(() => null); + if (!stat) return true; + if (!stat.isDirectory()) { + result.skipped.unsafe_path = (result.skipped.unsafe_path ?? 0) + 1; + return true; + } + if (!context.dryRun && quarantineCursor === null) await removeExpiredLeftovers(parent, context, result); + const names = (await fs.readdir(parent)).sort(); + const pending = quarantineCursor ? names.filter((name) => name > quarantineCursor!) : names; + for (const name of pending) { + const match = QUARANTINE_PATTERN.exec(name); + const cleanupArchive = QUARANTINE_CLEANUP_PATTERN.test(name); + if (!match && !cleanupArchive) continue; + if (!context.canInspect()) return false; + result.checked++; + quarantineCursor = name; + if (!match) { + result.skipped.cleanup_archive = (result.skipped.cleanup_archive ?? 0) + 1; + continue; + } + try { + await retireEvidence(parent, name, match[1]!, Number(match[2]), context, result); + } catch (err) { + result.failed++; + context.dueAt(context.now); + logger.warn({ err, scope: match[1] }, "native runner evidence retention skipped a quarantine entry"); + } + } + quarantineCursor = null; + return true; + } + + function noteEvidence(writtenAt: number) { + evidenceDueAt = Math.min(evidenceDueAt, writtenAt + evidenceRetentionMs()); + } + + function evidenceRetentionMs(options: NativeHarnessBackupExpirationOptions = {}) { + return Math.max( + 1, + options.evidenceRetentionDays ?? defaults.evidenceRetentionDays ?? NATIVE_RUNNER_EVIDENCE_RETENTION_DEFAULT_DAYS, + ) * DAY_MS; + } + async function tick(options: NativeHarnessBackupExpirationOptions = {}) { const closedForDays = Math.max( 1, options.closedForDays ?? defaults.closedForDays ?? NATIVE_HARNESS_BACKUP_EXPIRATION_DEFAULT_DAYS, ); + const retentionMs = evidenceRetentionMs(options); const dryRun = options.dryRun ?? defaults.dryRun ?? false; const maxEntries = Math.max(1, options.maxEntries ?? defaults.maxEntries ?? 200); const maxRemovals = Math.max(1, options.maxRemovals ?? defaults.maxRemovals ?? 50); const shouldContinue = options.shouldContinue ?? defaults.shouldContinue ?? (() => true); const isSessionBusy = options.isSessionBusy ?? defaults.isSessionBusy ?? nativeSessionScopeDigestIsBusy; const base = path.resolve(options.stateBase ?? defaults.stateBase ?? nativeHarnessStateBase()); - const closedBefore = new Date((options.now ?? defaults.now ?? new Date()).getTime() - closedForDays * DAY_MS); + const now = (options.now ?? defaults.now ?? new Date()).getTime(); + const closedBefore = new Date(now - closedForDays * DAY_MS); const result = emptyResult(); - - const names = (await fs.readdir(base).catch(() => [] as string[])) - .filter((name) => SCOPE_PATTERN.test(name)) - .sort(); - const pending = cursor ? names.filter((name) => name > cursor!) : names; - for (const name of pending) { - if (!shouldContinue() || result.checked >= maxEntries || result.candidates >= maxRemovals) { - result.truncated = true; - break; - } - result.checked++; - cursor = name; - const root = path.join(base, name); - if (path.dirname(root) !== base || !(await isRealDirectory(root))) { - result.skipped.unsafe_path = (result.skipped.unsafe_path ?? 0) + 1; - continue; - } - try { - await expireSession(root, name, { dryRun, isSessionBusy, closedBefore }, result); - } catch (err) { - result.failed++; - logger.warn({ err, scope: name }, "native harness backup expiration skipped a session"); + const hasBudget = () => shouldContinue() && result.candidates + result.evidenceCandidates < maxRemovals; + if (!passActive) { + passActive = true; + evidencePass = evidenceDueAt <= now; + if (evidencePass) { + evidenceDueAt = Number.POSITIVE_INFINITY; + passDueAt = Number.POSITIVE_INFINITY; } } - if (!result.truncated) cursor = null; + const context: EvidenceContext = { + dryRun, + isSessionBusy, + now, + retentionMs, + retainedBefore: now - retentionMs, + canInspect: () => hasBudget() && result.checked < maxEntries, + dueAt: (at) => { + passDueAt = Math.min(passDueAt, at); + }, + }; + + if (phase === "sessions") { + const names = (await fs.readdir(base).catch(() => [] as string[])) + .filter((name) => SCOPE_PATTERN.test(name)) + .sort(); + const pending = cursor ? names.filter((name) => name > cursor!) : names; + for (const name of pending) { + if (!hasBudget() || result.checked >= maxEntries) { + result.truncated = true; + break; + } + const resumeAfter = resume?.scope === name ? resume.archive : null; + if (resume && name >= resume.scope) resume = null; + if (resumeAfter === null) result.checked++; + const previous = cursor; + cursor = name; + const root = path.join(base, name); + if (path.dirname(root) !== base || !(await isRealDirectory(root))) { + result.skipped.unsafe_path = (result.skipped.unsafe_path ?? 0) + 1; + continue; + } + if (resumeAfter === null) { + try { + await expireSession(root, name, { dryRun, isSessionBusy, closedBefore }, result); + } catch (err) { + result.failed++; + logger.warn({ err, scope: name }, "native harness backup expiration skipped a session"); + } + } + if (!evidencePass) continue; + let stoppedAt: string | null = null; + try { + stoppedAt = await retireContinuityBreaks(root, name, resumeAfter, context, result); + } catch (err) { + result.failed++; + context.dueAt(now); + logger.warn({ err, scope: name }, "native runner evidence retention skipped a session"); + } + if (stoppedAt !== null) { + resume = { scope: name, archive: stoppedAt }; + cursor = previous; + result.truncated = true; + break; + } + } + if (result.truncated) return result; + cursor = null; + if (!evidencePass) { + passActive = false; + return result; + } + phase = "quarantine"; + } + try { + if (!(await retireQuarantine(base, context, result))) { + result.truncated = true; + return result; + } + } catch (err) { + result.failed++; + context.dueAt(now); + quarantineCursor = null; + logger.warn({ err }, "native runner evidence retention skipped quarantine"); + } + phase = "sessions"; + passActive = false; + evidencePass = false; + evidenceDueAt = Math.min(evidenceDueAt, passDueAt); return result; } - return { tick }; + return { tick, noteEvidence }; } diff --git a/server/src/services/native-runtime/native-runner-evidence-signal.ts b/server/src/services/native-runtime/native-runner-evidence-signal.ts new file mode 100644 index 00000000000..39d51bee146 --- /dev/null +++ b/server/src/services/native-runtime/native-runner-evidence-signal.ts @@ -0,0 +1,12 @@ +const listeners = new Set<(writtenAt: number) => void>(); + +export function onNativeRunnerEvidence(listener: (writtenAt: number) => void): () => void { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; +} + +export function noteNativeRunnerEvidence(writtenAt: number): void { + for (const listener of listeners) listener(writtenAt); +} diff --git a/server/src/services/native-runtime/native-session-executor.test.ts b/server/src/services/native-runtime/native-session-executor.test.ts index 5c8c3e211f7..39862333f8c 100644 --- a/server/src/services/native-runtime/native-session-executor.test.ts +++ b/server/src/services/native-runtime/native-session-executor.test.ts @@ -394,6 +394,7 @@ import { verifyNativeHarnessBackup, shouldRestoreNativeHarnessBackupIntoSandbox, } from "./native-session-executor.js"; +import { onNativeRunnerEvidence } from "./native-runner-evidence-signal.js"; beforeEach(() => { usageRecorder.capture.mockReset().mockImplementation(async receipt => receipt); @@ -12442,6 +12443,8 @@ describe("runnerd provider runtime wiring", () => { await writeRunnerAuthority(legacyRoot, identity, "ready"); state.createBackend.mockClear(); state.createTransport.mockClear(); + const evidence: number[] = []; + const stopEvidence = onNativeRunnerEvidence((writtenAt) => evidence.push(writtenAt)); await expect( createRunnerdBackend({ @@ -12449,11 +12452,12 @@ describe("runnerd provider runtime wiring", () => { execution: currentExecution, runnerInstanceId: "runner-after-legacy-terminal-unsuspended", }), - ).rejects.toThrow("runner_state_identity_mismatch"); + ).rejects.toThrow("runner_state_identity_mismatch").finally(stopEvidence); await expect(access(legacyRoot)).rejects.toThrow(); const quarantineEntries = await readdir(join(stateBase, "quarantine")); expect(quarantineEntries).toHaveLength(1); expect(quarantineEntries[0]).toContain(".identity_indeterminate."); + expect(evidence).toEqual([Number(quarantineEntries[0]!.split(".")[2])]); expect(state.createBackend).not.toHaveBeenCalled(); expect(state.createTransport).not.toHaveBeenCalled(); }); diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index 7f67a8aa2fc..234f673e664 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -209,6 +209,7 @@ import { type NativeRunTrace, } from "./native-run-trace.js"; import { createNativeHarnessBackupStamp } from "./native-harness-backup-stamp.js"; +import { noteNativeRunnerEvidence } from "./native-runner-evidence-signal.js"; import { removeNativeHarnessBackup } from "./native-harness-backup-cleanup.js"; import { registerLiveRunnerGoalController } from "../runner-goal-control-broker.js"; import { applyRunnerGoalPrpEvent } from "../runner-goals.js"; @@ -1952,11 +1953,13 @@ function quarantineRunnerdStateRoot( if (!isSafeNativeStateDirectory(quarantineRoot)) { throw new Error("runner_state_directory_unsafe"); } + const quarantinedAt = Date.now(); const destination = resolve( quarantineRoot, - `${stateKey}.${reason}.${Date.now()}.${process.pid}.${randomUUID()}`, + `${stateKey}.${reason}.${quarantinedAt}.${process.pid}.${randomUUID()}`, ); renameSync(resolvedRoot, destination); + noteNativeRunnerEvidence(quarantinedAt); return destination; } @@ -13276,9 +13279,11 @@ async function createRunnerdBackendWithinSessionClaim( if (hasRetainedWarmTransitionEvidence(root)) { throw new Error("native_runner_warm_transition_recovery_unproven"); } - const archiveToken = `${Date.now()}-${randomUUID()}`; + const archivedAt = Date.now(); + const archiveToken = `${archivedAt}-${randomUUID()}`; const archiveRoot = resolve(root, "continuity-breaks", archiveToken); mkdirSync(archiveRoot, { recursive: true, mode: 0o700 }); + noteNativeRunnerEvidence(archivedAt); for (const name of [ "control-plane", "runner", From e302f2098ff1f5868a3b3537e635cc380329cdb0 Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Sun, 25 Oct 2026 09:40:28 -0700 Subject: [PATCH 068/110] perf(wake-queue): omit unused native launch context from release reads (#17619) Read native wake-release control context without saved launch payloads. Keep stored input, full legacy context, cancellation evidence, and release decisions. PostgreSQL response-budget regression, 785 lifecycle tests, typecheck, build, and all 55 CI checks pass. Apex reviewed the exact head at 5/5 with no findings. Co-Authored-By: Paperclip --- doc/DATABASE.md | 12 +++-- .../wake-queue/adapters/postgres.test.ts | 7 ++- .../adapters/release-run-read.test.ts | 49 +++++++++++++++++++ .../wake-queue/adapters/release-run-read.ts | 7 +++ 4 files changed, 69 insertions(+), 6 deletions(-) diff --git a/doc/DATABASE.md b/doc/DATABASE.md index e5478530c02..4d6622bc784 100644 --- a/doc/DATABASE.md +++ b/doc/DATABASE.md @@ -50,10 +50,14 @@ and leaves all existing cases passive. Source identities are not grants. ### Task query performance The issue-lock adapter's release read omits `result_json.stdout` and -`result_json.stderr` before transferring a run to the controller. Every other result key, context field, and -stop, retry, lease, and workspace-recovery check stays intact. Full output remains -stored for execution history and detail reads. Terminal telemetry loads only its -run identity, timestamps, usage, and typed task identifier. +`result_json.stderr` before transferring a run to the controller. Native context +also omits saved launch text, execution-continuation bodies, workspace and +environment payloads, and the launch wake envelope. Task identity, retry and +continuation controls, interaction and comment references, execution policy, unknown context fields, and every other +result key stay intact. Legacy reads retain full context. Stop, retry, lease, +and workspace-recovery checks do not change. Full inputs and output remain stored +for execution history and detail reads. Terminal telemetry loads only its run +identity, timestamps, usage, and typed task identifier. Recovery's latest-run queries return the context fields used by recovery decisions. Prompts, execution continuation bodies, and workspace setup payloads diff --git a/server/src/modules/wake-queue/adapters/postgres.test.ts b/server/src/modules/wake-queue/adapters/postgres.test.ts index 6a8c360e22d..83d5bb6ee44 100644 --- a/server/src/modules/wake-queue/adapters/postgres.test.ts +++ b/server/src/modules/wake-queue/adapters/postgres.test.ts @@ -219,7 +219,8 @@ describeEmbeddedPostgres("wake-queue postgres adapter", () => { executionCancellation: { state: "acknowledged" }, executionRecovery: { kind: "interrupted", providerStopped: true }, configurationIncomplete: { reason: "workspace_unavailable" }, unknownFutureReceipt: { retained: true } }; await db.update(heartbeatRuns).set({ runtimeMode, - ...(runtimeMode === "native" ? { runnerProfileJson: { savedInput: payload }, stdoutExcerpt: payload, stderrExcerpt: payload } : {}), + ...(runtimeMode === "native" ? { runnerProfileJson: { savedInput: payload }, stdoutExcerpt: payload, stderrExcerpt: payload, + contextSnapshot: { issueId, paperclipWake: { savedTask: payload }, paperclipTaskMarkdown: payload } } : {}), resultJson: { ...evidence, stdout: payload.repeat(3), stderr: payload } }).where(eq(heartbeatRuns.id, runId)); await db.update(issues).set({ executionRunId: runId, checkoutRunId: runId }).where(eq(issues.id, issueId)); const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)); @@ -233,7 +234,9 @@ describeEmbeddedPostgres("wake-queue postgres adapter", () => { expect(result.outcome.kind).toBe("released"); expect(rows).toHaveLength(1); expect(rows[0]).toEqual([{ ...run, resultJson: evidence, - ...(runtimeMode === "native" ? { runnerProfileJson: null, stdoutExcerpt: null, stderrExcerpt: null } : {}) }]); + ...(runtimeMode === "native" ? { runnerProfileJson: null, stdoutExcerpt: null, stderrExcerpt: null, + contextSnapshot: { issueId } } : {}) }]); + expect(result.run.contextSnapshot).toEqual({ issueId }); expect(Buffer.byteLength(JSON.stringify(rows))).toBeLessThan(8 * 1024); expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)))[0]).toEqual(run); expect((await db.select().from(issues).where(eq(issues.id, issueId)))[0]).toEqual(issue); diff --git a/server/src/modules/wake-queue/adapters/release-run-read.test.ts b/server/src/modules/wake-queue/adapters/release-run-read.test.ts index e4129e6c692..6a669edf617 100644 --- a/server/src/modules/wake-queue/adapters/release-run-read.test.ts +++ b/server/src/modules/wake-queue/adapters/release-run-read.test.ts @@ -71,4 +71,53 @@ describe.skipIf(!support.supported)("wake release run reads", () => { expect((await readReleaseRun(db, { companyId, runId: run.id })).run?.resultJson).toEqual(result); }, ); + + it("keeps launch text in storage while releasing native runs with their control context", async () => { + const bulk = randomBytes(128 * 1024).toString("base64"); + const context = { + issueId: randomUUID(), taskId: randomUUID(), taskKey: "saved-task", + retryReason: "execution_review_participant_recovery", wakeReason: "issue_commented", + explicitUserContinuation: true, + interactionId: randomUUID(), interactionKind: "review", interactionStatus: "resolved", + wakeCommentIds: [randomUUID()], queuedCommentSourceWakeIds: [randomUUID()], + chatConversationId: randomUUID(), executionPolicy: { requireApproval: true }, + opaqueFutureContext: { retained: [null, false, "input"] }, + }; + const launch = { + executionContinuation: { instruction: bulk, state: "saved" }, + paperclipWake: { savedTask: bulk }, paperclipWakeComment: bulk, paperclipTaskMarkdown: bulk, + paperclipTaskMarkdownCompact: bulk, paperclipTaskMarkdownAssignment: bulk, + paperclipTaskMarkdownAssignmentCompact: bulk, paperclipWorkspace: { files: bulk }, + paperclipEnvironment: { input: bulk }, paperclipContinuationSummary: bulk, + }; + const evidence = { nativeCancellation: { schema: "paperclip.native-cancellation.v1", dispatched: true }, + executionCancellation: { state: "acknowledged" }, workspaceRestoreRecovery: { leaseIds: [randomUUID()] }, + configurationIncomplete: { reason: "secret_binding_missing" }, unknownFutureReceipt: { retained: true } }; + const [before] = await db.insert(heartbeatRuns).values({ companyId, agentId, runtimeMode: "native", + contextSnapshot: { ...context, ...launch }, resultJson: evidence }).returning(); + const events: Array> = []; + const now = Date.now(); + const capture = createDatabaseResponseCapture({ start: now - 100, end: now + 59_000 }, event => events.push(event)); + installDatabaseResponseCapture(db, { heartbeatRuns }, capture); + let selected: Awaited>; + try { selected = await db.transaction(tx => readReleaseRun(tx as unknown as typeof db, { companyId, runId: before.id })); } + finally { capture.flush(); } + const summary = events.find(event => event.event === "paperclip.db_response_capture.summary.v1")!; + expect(summary.completedQueries).toBe(1); + expect(summary.responseValueBytes).toBeLessThan(8192); + expect(selected!.run?.contextSnapshot).toEqual(context); + expect(selected!.run?.resultJson).toEqual(evidence); + expect(JSON.stringify(events)).not.toContain(bulk.slice(0, 64)); + expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, before.id)))[0]).toEqual(before); + await db.update(heartbeatRuns).set({ runtimeMode: "legacy" }).where(eq(heartbeatRuns.id, before.id)); + expect((await readReleaseRun(db, { companyId, runId: before.id })).run?.contextSnapshot).toEqual(before.contextSnapshot); + }); + + it.each([null, ["paperclipWake", { savedInput: "keep" }], "scalar", 42].map(context => ({ context })))( + "preserves non-object native context $context", async ({ context }) => { + const [run] = await db.insert(heartbeatRuns).values({ companyId, agentId, runtimeMode: "native", + contextSnapshot: context as Record | null }).returning(); + expect((await readReleaseRun(db, { companyId, runId: run.id })).run?.contextSnapshot).toEqual(context); + }, + ); }); diff --git a/server/src/modules/wake-queue/adapters/release-run-read.ts b/server/src/modules/wake-queue/adapters/release-run-read.ts index cc8bcf80388..3fa7371bc1a 100644 --- a/server/src/modules/wake-queue/adapters/release-run-read.ts +++ b/server/src/modules/wake-queue/adapters/release-run-read.ts @@ -7,6 +7,13 @@ export type ReleaseRun = Omit`case when ${heartbeatRuns.runtimeMode} = 'native' + and jsonb_typeof(${heartbeatRuns.contextSnapshot}) = 'object' + then ${heartbeatRuns.contextSnapshot} - array['executionContinuation', 'paperclipWake', 'paperclipWakeComment', + 'paperclipTaskMarkdown', 'paperclipTaskMarkdownCompact', 'paperclipTaskMarkdownAssignment', + 'paperclipTaskMarkdownAssignmentCompact', 'paperclipWorkspace', 'paperclipEnvironment', + 'paperclipContinuationSummary'] + else ${heartbeatRuns.contextSnapshot} end`, runnerProfileJson: sql`case when ${heartbeatRuns.runtimeMode} = 'native' then null else ${heartbeatRuns.runnerProfileJson} end`, stdoutExcerpt: sql`case when ${heartbeatRuns.runtimeMode} = 'native' From b65897f9bf05121290895b48e4794c301790ef67 Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Sun, 25 Oct 2026 09:53:27 -0700 Subject: [PATCH 069/110] perf(recovery): read workspace contract without native launch prompts (#17621) Project native input to the complete schema, binding, provider, and workspace evidence used by execution-blocker checks. Preserve absent and malformed fields and retain all saved inputs and recovery holds. 149 focused tests and 123 workspace-recovery tests pass. Server typecheck, build, all 55 CI checks, and exact-head Apex 5/5 pass. Co-Authored-By: Paperclip --- doc/DATABASE.md | 9 +++-- .../services/execution-blocker-read.test.ts | 37 ++++++++++++++++++- server/src/services/execution-blocker.ts | 5 +++ 3 files changed, 47 insertions(+), 4 deletions(-) diff --git a/doc/DATABASE.md b/doc/DATABASE.md index 4d6622bc784..043493acd8f 100644 --- a/doc/DATABASE.md +++ b/doc/DATABASE.md @@ -68,9 +68,12 @@ update, including an edit outside the projection, defers repair to a fresh sweep Execution-blocker reads select process, lifecycle, and task-binding fields rather than full execution rows. Context retains typed task and pre-dispatch evidence; -Runner profiles retain the adapter type and complete native execution input and -workspace-sync receipts. Full result evidence stays available to the existing -retry and workspace checks. Stored context, profiles, and output are unchanged. +Runner profiles retain the adapter type, native input schema, binding, provider, +workspace-access evidence, and complete workspace-sync receipts. Native task and +runtime prompt payloads are not needed for these checks. Missing fields and +malformed input values retain their original shape. Full result evidence stays +available to the existing retry and workspace checks. Stored context, profiles, +and output are unchanged. Committed native finalization reads run identity and ownership state before it claims the coordinator. It loads complete saved input only when finalization diff --git a/server/src/services/execution-blocker-read.test.ts b/server/src/services/execution-blocker-read.test.ts index 309385a25cb..5b16c521af1 100644 --- a/server/src/services/execution-blocker-read.test.ts +++ b/server/src/services/execution-blocker-read.test.ts @@ -100,7 +100,9 @@ describe.skipIf(!support.supported)("execution blocker PostgreSQL read projectio }); const input = { schema: "paperclip.native-execution-input.v6", binding: { runId: f.run.id, companyId: f.companyId, agentId: f.agentId, issueId: f.issueId }, - provider: { kind: "grok_bot" }, workspace: { access: "none", ...(hasCwd ? { cwd: null } : {}) } }; + provider: { kind: "grok_bot" }, workspace: { access: "none", ...(hasCwd ? { cwd: null } : {}) }, + task: { description: randomBytes(128 * 1024).toString("base64") }, + runtimeContext: { instructions: randomBytes(128 * 1024).toString("base64") } }; await db.update(heartbeatRuns).set({ nativeIssueId: f.issueId, runnerProfileJson: { ...f.run.runnerProfileJson, nativeExecutionInput: input } }).where(eq(heartbeatRuns.id, f.run.id)); expect(await compare(f)).toMatchObject({ workspaceRepairRequired: !hasCwd, canRetry: false }); @@ -108,6 +110,39 @@ describe.skipIf(!support.supported)("execution blocker PostgreSQL read projectio expect(stored.runnerProfileJson?.nativeExecutionInput).toEqual(input); }); + it.each(["run", "company", "agent", "issue", "provider", "schema", "access", "workspace", "binding", "missing_binding", + "null_input", "array_input", "scalar_input", "number_input"])( + "does not relax native workspace recovery for invalid input (%s)", async kind => { + const f = await fixture({ runtimeMode: "native", driverKind: "grok_bot_mcp" }, { + workspaceRestoreFailure: "restore_unsafe_archive", + workspaceRestoreRecovery: { schema: "paperclip.workspace-restore-recovery.v1", leaseIds: [] }, + }); + const input: Record = { + schema: "paperclip.native-execution-input.v6", + binding: { runId: f.run.id, companyId: f.companyId, agentId: f.agentId, issueId: f.issueId }, + provider: { kind: "grok_bot" }, workspace: { access: "none", cwd: null }, + task: { description: randomBytes(128 * 1024).toString("base64") }, + }; + const binding = input.binding as Record; + if (kind === "run") binding.runId = randomUUID(); + if (kind === "company") binding.companyId = randomUUID(); + if (kind === "agent") binding.agentId = randomUUID(); + if (kind === "issue") binding.issueId = randomUUID(); + if (kind === "provider") input.provider = { kind: "codex" }; + if (kind === "schema") input.schema = "unsupported"; + if (kind === "access") input.workspace = { cwd: null }; + if (kind === "workspace") input.workspace = "none"; + if (kind === "binding") input.binding = []; + if (kind === "missing_binding") delete input.binding; + const selectedInput = kind === "null_input" ? null : kind === "array_input" ? [] + : kind === "scalar_input" ? "input" : kind === "number_input" ? 42 : input; + await db.update(heartbeatRuns).set({ nativeIssueId: f.issueId, + runnerProfileJson: { ...f.run.runnerProfileJson, nativeExecutionInput: selectedInput } }).where(eq(heartbeatRuns.id, f.run.id)); + expect(await compare(f)).toMatchObject({ workspaceRepairRequired: true, canRetry: false }); + expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.run.id)))[0].runnerProfileJson?.nativeExecutionInput).toEqual(selectedInput); + }, + ); + it.each([null, [], "scalar", 42, { issueId: 42, taskId: false }].map(context => ({ context })))("preserves decisions for malformed context $context", async ({ context }) => { const f = await fixture({ contextSnapshot: context as Record | null }); expect(await compare(f)).toMatchObject({ canRetry: true }); diff --git a/server/src/services/execution-blocker.ts b/server/src/services/execution-blocker.ts index 4777d5947b3..3ee94aedb72 100644 --- a/server/src/services/execution-blocker.ts +++ b/server/src/services/execution-blocker.ts @@ -28,6 +28,11 @@ const blockerProfileColumn = sql | null>`case when ${heartbeatRuns.runnerProfileJson} is null then null else ( select coalesce(jsonb_object_agg(field.key, case field.key when 'adapterDispatch' then jsonb_build_object('adapterType', field.value->'adapterType') + when 'nativeExecutionInput' then case when jsonb_typeof(field.value) = 'object' then ( + select coalesce(jsonb_object_agg(input_field.key, input_field.value), '{}'::jsonb) + from jsonb_each(field.value) as input_field(key, value) + where input_field.key in ('schema', 'binding', 'provider', 'workspace') + ) else field.value end else field.value end), '{}'::jsonb) from jsonb_each(case when jsonb_typeof(${heartbeatRuns.runnerProfileJson}) = 'object' then ${heartbeatRuns.runnerProfileJson} else '{}'::jsonb end) as field(key, value) From 19ec787e5bdd8684720068e7e39f02996afe7d8c Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Sun, 25 Oct 2026 10:06:27 -0700 Subject: [PATCH 070/110] perf(recovery): release native process identity without saved payload reads (#17622) Keep locked process and terminal-state evidence plus JavaScript-compatible checkpoint presence. Preserve every host, provider, lease, coordinator and stop-receipt check without transferring saved prompts or checkpoint bodies. 53 focused tests, server typecheck, build, all 55 CI checks, and exact-head Apex 5/5 pass. Co-Authored-By: Paperclip --- doc/DATABASE.md | 6 +++ .../native-settled-process-release.test.ts | 37 ++++++++++++++++++- .../src/services/native-local-process-stop.ts | 13 +++++-- 3 files changed, 51 insertions(+), 5 deletions(-) diff --git a/doc/DATABASE.md b/doc/DATABASE.md index 043493acd8f..51f565e8bed 100644 --- a/doc/DATABASE.md +++ b/doc/DATABASE.md @@ -84,6 +84,12 @@ Stop settlement still load complete run evidence. Workspace settlement reads the saved sync descriptor, export retry, and first-heartbeat flag. These projections leave stored prompts, logs, results, and recovery state unchanged. +Settled native process release locks run identity, terminal state, process +identity, and checkpoint presence without loading the checkpoint or execution +payloads. It retains current coordinator checks, provider evidence, local-host +identity checks, and every lease's termination receipt. The stop receipt and +process-field update remain in the same transaction. + Conversation ownership checks select process identity and full recovery result evidence without execution prompts or profiles. Committed native reply repair selects its persisted result and identity bindings plus typed presentation flags. diff --git a/server/src/__tests__/native-settled-process-release.test.ts b/server/src/__tests__/native-settled-process-release.test.ts index be5c00a4516..d2a60b89ccb 100644 --- a/server/src/__tests__/native-settled-process-release.test.ts +++ b/server/src/__tests__/native-settled-process-release.test.ts @@ -1,5 +1,6 @@ import { EMBEDDED_POSTGRES_TEST_TIMEOUT_MS } from "@paperclipai/db"; -import { randomUUID } from "node:crypto"; +import { randomBytes, randomUUID } from "node:crypto"; +import { createDatabaseResponseCapture, installDatabaseResponseCapture } from "@paperclipai/db/response-capture"; import { spawn } from "node:child_process"; import os from "node:os"; import { and, eq } from "drizzle-orm"; @@ -207,6 +208,40 @@ suite("settled native run process identity", () => { expect((await readRun(runId)).processPid).toBeNull(); }); + it("releases the stopped identity without reading saved execution payloads", async () => { + const { runId } = await seed(); + const bulk = randomBytes(128 * 1024).toString("base64"); + const before = await readRun(runId); + await db.update(heartbeatRuns).set({ contextSnapshot: { ...before.contextSnapshot, savedTask: bulk }, + runnerProfileJson: { ...before.runnerProfileJson, sessionCheckpoint: { providerSessionId: "thread", savedState: bulk }, + nativeExecutionInput: { task: bulk } }, resultJson: { savedResult: bulk }, stdoutExcerpt: bulk, + }).where(eq(heartbeatRuns.id, runId)); + const saved = await readRun(runId); + const events: Array> = []; + const now = Date.now(); + const capture = createDatabaseResponseCapture({ start: now - 100, end: now + 59_000 }, event => events.push(event)); + installDatabaseResponseCapture(db, { heartbeatRuns }, capture); + try { expect(await releaseSettledNativeRunProcess(db, runId)).toBe("released"); } + finally { capture.flush(); } + const summary = events.find(event => event.event === "paperclip.db_response_capture.summary.v1")!; + expect(summary.responseValueBytes).toBeLessThan(8192); + const after = await readRun(runId); + expect(after).toEqual({ ...saved, processPid: null, processGroupId: null, processStartedAt: null, + nextEventSeq: saved.nextEventSeq + 1, updatedAt: after.updatedAt }); + expect(await hasNativeLocalProcessStop(db, companyId, runId)).toBe(true); + expect(JSON.stringify(events)).not.toContain(bulk.slice(0, 64)); + }); + + it.each([null, false, 0, "", {}, []].map(checkpoint => ({ checkpoint })))( + "preserves checkpoint presence semantics when releasing an identity ($checkpoint)", async ({ checkpoint }) => { + const { runId, pid } = await seed({ checkpoint: false }); + await db.update(heartbeatRuns).set({ runnerProfileJson: { sessionCheckpoint: checkpoint } }) + .where(eq(heartbeatRuns.id, runId)); + expect(await releaseSettledNativeRunProcess(db, runId)).toBe(checkpoint === null ? "skipped" : "released"); + expect((await readRun(runId)).processPid).toBe(checkpoint === null ? pid : null); + }, + ); + it("keeps the identity while the process is still alive, then releases it after exit", async () => { const child = startDetached(); children.push(child); diff --git a/server/src/services/native-local-process-stop.ts b/server/src/services/native-local-process-stop.ts index 422d2c24f0f..07ff696ec59 100644 --- a/server/src/services/native-local-process-stop.ts +++ b/server/src/services/native-local-process-stop.ts @@ -1,4 +1,4 @@ -import { and, asc, desc, eq, gt, inArray, isNotNull, isNull, or } from "drizzle-orm"; +import { and, asc, desc, eq, gt, inArray, isNotNull, isNull, or, sql } from "drizzle-orm"; import { environmentLeases, heartbeatRunEvents, heartbeatRuns, nativeRunFinalizations, type Db } from "@paperclipai/db"; import { appendHeartbeatRunEvent } from "./heartbeat-run-events.js"; import { nativeSessionProviderEvidence } from "./native-runtime/native-session-resume.js"; @@ -41,7 +41,8 @@ export async function recordedLocalExecutionStopped(db: Db, run: Pick) { if (run.runtimeMode !== "native" || (!run.processPid && !run.processGroupId)) return false; const leases = await db.select({ provider: environmentLeases.provider }) .from(environmentLeases) @@ -144,13 +145,17 @@ type SettledProcessRelease = "released" | "pending" | "skipped"; export async function releaseSettledNativeRunProcess(db: Db, runId: string): Promise { return db.transaction(async transaction => { const tx = transaction as unknown as Db; - const [run] = await tx.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)).for("update").limit(1); + const [run] = await tx.select({ id: heartbeatRuns.id, companyId: heartbeatRuns.companyId, agentId: heartbeatRuns.agentId, + runtimeMode: heartbeatRuns.runtimeMode, status: heartbeatRuns.status, finishedAt: heartbeatRuns.finishedAt, + processPid: heartbeatRuns.processPid, processGroupId: heartbeatRuns.processGroupId, processStartedAt: heartbeatRuns.processStartedAt, + hasSessionCheckpoint: sql`coalesce(${heartbeatRuns.runnerProfileJson}->'sessionCheckpoint', 'null'::jsonb) <> 'null'::jsonb`, + }).from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)).for("update").limit(1); if (!run || run.runtimeMode !== "native" || !SETTLED_RUN_STATUSES.includes(run.status) || !run.finishedAt || (run.processPid === null && run.processGroupId === null && run.processStartedAt === null)) return "skipped"; const [coordinator] = await tx.select({ phase: nativeRunFinalizations.phase }).from(nativeRunFinalizations) .where(eq(nativeRunFinalizations.runId, run.id)).limit(1); if (coordinator && !SETTLED_COORDINATOR_PHASES.includes(coordinator.phase)) return "skipped"; - if (run.runnerProfileJson?.sessionCheckpoint == null && + if (!run.hasSessionCheckpoint && !(await nativeSessionProviderEvidence(tx, [run.id])).has(run.id)) return "skipped"; const leases = await tx.select().from(environmentLeases).where(and( eq(environmentLeases.companyId, run.companyId), eq(environmentLeases.heartbeatRunId, run.id), From 332e4c5df9199b41e5d4b3ff757cdc4644179f8c Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Sun, 25 Oct 2026 10:47:02 -0700 Subject: [PATCH 071/110] fix(native): settle completed results that retain a valid monitor (#17641) Preserve a valid saved monitor after its successful source releases execution and checkout. Recheck accepted result identity, receipts, ownership and governance under the task lock. Notify the existing scheduler once and preserve accepted live and recovered replies. Apex 5/5 after fixing its reply-presentation finding. All CI checks, 191 focused tests, 293 broader native tests, workspace typecheck and server build pass. Hosted effects require staging verification. Co-Authored-By: Paperclip --- doc/architecture/native-status-arbitration.md | 24 ++ .../__tests__/heartbeat-run-summary.test.ts | 4 +- server/src/services/heartbeat-run-summary.ts | 2 +- .../native-runtime/native-monitor-delivery.ts | 38 ++- .../native-preserved-monitor-wait.test.ts | 217 ++++++++++++++++++ .../native-runtime/native-run-finalizer.ts | 13 +- .../native-runtime/status-arbiter.test.ts | 2 +- .../services/native-runtime/status-arbiter.ts | 10 +- .../status-decision-committer.ts | 15 +- 9 files changed, 315 insertions(+), 10 deletions(-) create mode 100644 server/src/services/native-runtime/native-preserved-monitor-wait.test.ts diff --git a/doc/architecture/native-status-arbitration.md b/doc/architecture/native-status-arbitration.md index f56014fa5b0..7fa6d5782ed 100644 --- a/doc/architecture/native-status-arbitration.md +++ b/doc/architecture/native-status-arbitration.md @@ -374,3 +374,27 @@ and records a recovery action for the reviewer without an automatic retry loop. Both Codex and ACPX providers wait for server completion feedback before their terminal tool call succeeds. A rejected completion report stays correctable in the same provider turn. The runner does not latch it as an accepted result. + +## Completed runs with saved monitors + +A successful accepted result can report a monitor wait after the run has +already released execution and checkout. Finalization can preserve that wait +when the same agent still owns a valid ordinary task monitor and the completed +run has a server-recorded `set_task_monitor` receipt for the task. The current +monitor can have a later deadline; finalization does not restore an older timer. + +The server rechecks the accepted source, current monitor, empty execution and +checkout slots, and governance under the coordinator and task locks. The +`scheduled_monitor_preserved` decision keeps task status and has no task effects. +It records the completed result without dispatching another provider turn. +The existing monitor scheduler receives a transaction-aware notification when +this finalization blocker clears. Replaying the committed decision sends no +second notification. +Live response selection and committed response repair retain the accepted +monitor explanation under the existing reply and publication authorization rules. + +Missing receipts, changed ownership, cancellation intents, cleared or quota +monitors, and unfinished workspace finalization retain their recovery paths. +Due and exhausted monitors still belong to the scheduler. This does not change +their deadlines or attempts, clear unrelated recovery holds, or relax the +Cloud sleep and wake contract. diff --git a/server/src/__tests__/heartbeat-run-summary.test.ts b/server/src/__tests__/heartbeat-run-summary.test.ts index 33b03986b83..c0ed3d6b113 100644 --- a/server/src/__tests__/heartbeat-run-summary.test.ts +++ b/server/src/__tests__/heartbeat-run-summary.test.ts @@ -25,10 +25,10 @@ describe("model-facing run errors", () => { }); }); -describe("scheduled continuation presentation", () => { +describe.each(["scheduled_monitor_waiting", "scheduled_monitor_dispatched", "scheduled_monitor_preserved"])("scheduled continuation presentation (%s)", finalizationReasonCode => { const resultJson = { finalizationPhase: "committed", - finalizationReasonCode: "scheduled_monitor_waiting", + finalizationReasonCode, nativeResult: { schema: "paperclip.run_result.v1", reportedWorkDisposition: "yielded", diff --git a/server/src/services/heartbeat-run-summary.ts b/server/src/services/heartbeat-run-summary.ts index 25e0de11276..97368cb1da6 100644 --- a/server/src/services/heartbeat-run-summary.ts +++ b/server/src/services/heartbeat-run-summary.ts @@ -298,7 +298,7 @@ export function readAcceptedTaskContinuationSummary( const result = record(resultJson); if (result.finalizationPhase !== "committed") return null; const kind = result.finalizationReasonCode === "live_continuation_registered" ? "same_agent" - : ["scheduled_monitor_waiting", "scheduled_monitor_dispatched"].includes(String(result.finalizationReasonCode)) ? "monitor" : null; + : ["scheduled_monitor_waiting", "scheduled_monitor_dispatched", "scheduled_monitor_preserved"].includes(String(result.finalizationReasonCode)) ? "monitor" : null; if (!kind) return null; for (const candidate of semanticResultCandidates(result)) { const continuation = record(candidate.continuation); diff --git a/server/src/services/native-runtime/native-monitor-delivery.ts b/server/src/services/native-runtime/native-monitor-delivery.ts index d38e41d8bc1..b2af0e80605 100644 --- a/server/src/services/native-runtime/native-monitor-delivery.ts +++ b/server/src/services/native-runtime/native-monitor-delivery.ts @@ -1,7 +1,8 @@ -import { agentWakeupRequests, heartbeatRuns, type Db } from "@paperclipai/db"; -import { and, desc, eq, inArray, ne, sql } from "drizzle-orm"; +import { agentWakeupRequests, heartbeatRuns, nativeRunFinalizations, nativeRunResults, type Db, type issues } from "@paperclipai/db"; +import { and, desc, eq, inArray, isNotNull, ne, sql } from "drizzle-orm"; import { alias } from "drizzle-orm/pg-core"; import { boundRunIssueIdSql } from "../run-task-binding.js"; +import { scheduledIssueMonitorWait } from "../issue-monitors.js"; function record(value: unknown): Record { return value !== null && typeof value === "object" && !Array.isArray(value) @@ -9,6 +10,39 @@ function record(value: unknown): Record { } export type NativeMonitorDelivery = { wakeId: string; successorRunId: string }; +export type NativePreservedMonitorWait = { agentId: string; nextCheckAt: string; resultId: string }; + +export async function readNativePreservedMonitorWait( + db: Db, + binding: { companyId: string; issueId: string; runId: string; agentId: string }, + issue: typeof issues.$inferSelect, +): Promise { + if (issue.companyId !== binding.companyId || issue.id !== binding.issueId || issue.workMode !== "standard" || + issue.executionRunId !== null || issue.checkoutRunId !== null) return null; + const nextCheckAt = scheduledIssueMonitorWait(issue, binding.agentId); + if (!nextCheckAt) return null; + const [source] = await db.select({ resultId: nativeRunResults.id, hasReceipt: sql`exists ( + select 1 from jsonb_each(case when jsonb_typeof(${heartbeatRuns.resultJson}->'semanticToolReceipts') = 'object' + then ${heartbeatRuns.resultJson}->'semanticToolReceipts' else '{}'::jsonb end) receipt + where receipt.value->>'operationId' = 'set_task_monitor' + and receipt.value->'result'->>'taskId' = ${binding.issueId} + and receipt.value->'result'->'monitor'->>'status' = 'scheduled' + and jsonb_typeof(receipt.value->'result'->'monitor'->'nextCheckAt') = 'string' + )` }).from(heartbeatRuns).innerJoin(nativeRunFinalizations, and( + eq(nativeRunFinalizations.companyId, binding.companyId), eq(nativeRunFinalizations.issueId, binding.issueId), + eq(nativeRunFinalizations.runId, heartbeatRuns.id), + )).innerJoin(nativeRunResults, and( + eq(nativeRunResults.id, nativeRunFinalizations.resultId), eq(nativeRunResults.companyId, binding.companyId), + eq(nativeRunResults.issueId, binding.issueId), eq(nativeRunResults.runId, heartbeatRuns.id), + eq(nativeRunResults.schemaStatus, "accepted"), + )).where(and(eq(heartbeatRuns.id, binding.runId), eq(heartbeatRuns.companyId, binding.companyId), + eq(heartbeatRuns.agentId, binding.agentId), eq(heartbeatRuns.nativeIssueId, binding.issueId), + eq(heartbeatRuns.runtimeMode, "native"), eq(heartbeatRuns.status, "succeeded"), isNotNull(heartbeatRuns.finishedAt), + ...["cancellation", "nativeCancellation", "executionCancellation", "startupCancellation"].map(key => + sql`coalesce(${heartbeatRuns.resultJson}->${key}, 'null'::jsonb) = 'null'::jsonb`), + )).limit(1); + return source?.hasReceipt ? { agentId: binding.agentId, nextCheckAt, resultId: source.resultId } : null; +} export async function readNativeMonitorSource( db: Pick, diff --git a/server/src/services/native-runtime/native-preserved-monitor-wait.test.ts b/server/src/services/native-runtime/native-preserved-monitor-wait.test.ts new file mode 100644 index 00000000000..ad269c7467c --- /dev/null +++ b/server/src/services/native-runtime/native-preserved-monitor-wait.test.ts @@ -0,0 +1,217 @@ +import { randomUUID } from "node:crypto"; +import { and, eq } from "drizzle-orm"; +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; +import { agents, agentWakeupRequests, companies, completionContracts, createDb, heartbeatRuns, + issueComments, issueRecoveryActions, issues, nativeRunFinalizations, nativeRunResults, statusDecisions, subscribeDatabaseWork } from "@paperclipai/db"; +import { PROVIDER_QUOTA_MONITOR_SERVICE_NAME } from "@paperclipai/shared"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embedded-postgres.js"; +import { PaperclipRunnerToolAuthority } from "./paperclip-runner-tool-authority.js"; +import { finalizeNativeRun, repairCommittedNativeChatResponse } from "./native-run-finalizer.js"; +import { nativeSha256 } from "./canonical.js"; +import * as monitorDelivery from "./native-monitor-delivery.js"; +import { DELIVERY_QUEUES } from "../delivery-work-notifications.js"; +import { hasPendingRunCleanup } from "../execution-blocker.js"; + +const support = await getEmbeddedPostgresTestSupport(); +describe.skipIf(!support.supported)("released native monitor results", () => { + let temporary: Awaited>; + let db: ReturnType; + beforeAll(async () => { + temporary = await startEmbeddedPostgresTestDatabase("native-preserved-monitor-"); + db = createDb(temporary.connectionString); + }); + afterAll(async () => { await db?.$client.end(); await temporary?.cleanup(); }); + + async function fixture() { + const companyId = randomUUID(), agentId = randomUUID(), issueId = randomUUID(), runId = randomUUID(); + const contractId = randomUUID(), resultId = randomUUID(); + await db.insert(companies).values({ id: companyId, name: "Saved monitor", issuePrefix: `P${companyId.slice(0, 7)}` }); + await db.insert(agents).values({ id: agentId, companyId, name: "Worker", adapterType: "paperclip_runner", status: "active" }); + await db.insert(issues).values({ id: issueId, companyId, title: "Saved follow-up", status: "in_progress", assigneeAgentId: agentId }); + await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, nativeIssueId: issueId, + runtimeMode: "native", status: "running", contextSnapshot: { issueId } }); + await db.update(issues).set({ executionRunId: runId }).where(eq(issues.id, issueId)); + const nextCheckAt = new Date(Date.now() + 3_600_000).toISOString(); + const authority = new PaperclipRunnerToolAuthority(db, { companyId, agentId, issueId, runId }); + await authority.execute({ tool: "set_task_monitor", callId: randomUUID(), arguments: { + idempotencyKey: "saved-monitor", monitor: { nextCheckAt, notes: "Check the saved result." }, + } }); + await db.insert(completionContracts).values({ id: contractId, companyId, issueId, revision: 1, + schemaVersion: "paperclip.completion-contract.v1", policyVersion: "test", risk: "standard", + completionAuthority: "server_arbiter", incompleteCriteriaPolicy: "preserve_non_terminal", + contractJson: { revision: "test", criteria: [] }, canonicalSha256: randomUUID(), + createdByActorType: "system", createdByActorId: "test" }); + const result = { result: { schema: "paperclip.run_result.v1", reportedWorkDisposition: "yielded", + summary: "Wait for the saved check.", completionClaim: { contractRevision: "test", objectiveSatisfied: false, + criteria: [], remainingWork: [{ description: "Check again", blocksCompletion: true }] }, + continuation: { kind: "monitor", summary: "Wait for the check", idempotencyKey: "provider-selected" }, + evidence: [], verification: [], attentionRequests: [], artifacts: [] }, + terminal: { schema: "paperclip.prp.terminal.v1", runTerminalState: "succeeded", turnTerminalState: "completed", reportedWorkDisposition: "yielded" } }; + const finishedAt = new Date("2020-01-01T00:00:00Z"); + await db.update(heartbeatRuns).set({ status: "succeeded", finishedAt, completionContractId: contractId }).where(eq(heartbeatRuns.id, runId)); + await db.insert(nativeRunResults).values({ id: resultId, companyId, issueId, runId, completionContractId: contractId, + serverFingerprint: randomUUID(), canonicalSha256: randomUUID(), schemaStatus: "accepted", resultJson: result }); + await db.insert(nativeRunFinalizations).values({ companyId, issueId, runId, phase: "retryable_failure", resultId }); + await db.update(issues).set({ executionRunId: null, checkoutRunId: null }).where(eq(issues.id, issueId)); + const readIssue = async () => (await db.select().from(issues).where(eq(issues.id, issueId)))[0]!; + const finalize = (workspaceFinalizeStatus: "succeeded" | "failed" = "succeeded") => finalizeNativeRun({ + db, runId, workspaceFinalizeStatus, projectRunStatus: true, + }); + return { companyId, agentId, issueId, runId, resultId, result, finishedAt, nextCheckAt, readIssue, finalize }; + } + + it.each(["original", "rescheduled", "past_due"])("keeps the saved monitor and settles a released successful result (%s)", async state => { + const f = await fixture(); + if (state !== "original") { + const issue = await f.readIssue(); + const nextCheckAt = state === "past_due" ? "2020-01-01T01:00:00Z" : new Date(Date.now() + 7_200_000).toISOString(); + await db.update(issues).set({ monitorNextCheckAt: new Date(nextCheckAt), executionPolicy: { + ...issue.executionPolicy, monitor: { ...(issue.executionPolicy?.monitor as Record), nextCheckAt }, + } }).where(eq(issues.id, f.issueId)); + } + const issueBefore = await f.readIssue(); + const [hold] = await db.insert(issueRecoveryActions).values({ companyId: f.companyId, sourceIssueId: f.issueId, + kind: "active_run_watchdog", cause: "legacy_execution_requires_reconciliation", fingerprint: randomUUID(), + status: "active", ownerType: "board", nextAction: "Preserve independent recovery.", evidence: { runId: randomUUID() }, + }).returning(); + await f.finalize(); + const [coordinator] = await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, f.runId)); + expect(coordinator.phase).toBe("committed"); + const decisions = await db.select().from(statusDecisions).where(eq(statusDecisions.runId, f.runId)); + expect(decisions.at(-1)).toMatchObject({ reasonCode: "scheduled_monitor_preserved", toStatus: issueBefore.status }); + expect(decisions.at(-1)?.decisionJson).toMatchObject({ effects: [] }); + expect(await f.readIssue()).toMatchObject({ status: issueBefore.status, executionPolicy: issueBefore.executionPolicy, + monitorNextCheckAt: issueBefore.monitorNextCheckAt, monitorAttemptCount: issueBefore.monitorAttemptCount, + executionRunId: null, checkoutRunId: null }); + expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId)))[0].finishedAt).toEqual(f.finishedAt); + expect((await db.select().from(nativeRunResults).where(eq(nativeRunResults.id, f.resultId)))[0].resultJson).toEqual(f.result); + expect(await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.id, hold!.id))).toEqual([hold]); + expect(await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.companyId, f.companyId))).toEqual([]); + expect(await db.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(eq(heartbeatRuns.companyId, f.companyId))).toEqual([{ id: f.runId }]); + await f.finalize(); + expect(await db.select().from(statusDecisions).where(eq(statusDecisions.runId, f.runId))).toEqual(decisions); + }); + + it.each(["cleared", "owner", "checkout", "other_agent", "no_receipt", "foreign_receipt", "unfinished", "failed_source", "quota", "workspace_failed", + "cancellation", "nativeCancellation", "executionCancellation", "startupCancellation"])( + "does not settle a released monitor without current proof (%s)", async state => { + const f = await fixture(); + const issue = await f.readIssue(); + if (state === "cleared") await db.update(issues).set({ monitorNextCheckAt: null, executionPolicy: {} }).where(eq(issues.id, f.issueId)); + if (state === "quota") await db.update(issues).set({ executionPolicy: { ...issue.executionPolicy, + monitor: { ...(issue.executionPolicy?.monitor as Record), serviceName: PROVIDER_QUOTA_MONITOR_SERVICE_NAME }, + } }).where(eq(issues.id, f.issueId)); + if (state === "other_agent") await db.update(issues).set({ assigneeAgentId: null }).where(eq(issues.id, f.issueId)); + if (state === "owner" || state === "checkout") { + const [owner] = await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, status: "running" }).returning(); + await db.update(issues).set(state === "owner" ? { executionRunId: owner!.id } : { checkoutRunId: owner!.id }).where(eq(issues.id, f.issueId)); + } + if (state === "unfinished") await db.update(heartbeatRuns).set({ finishedAt: null }).where(eq(heartbeatRuns.id, f.runId)); + if (state === "failed_source") await db.update(heartbeatRuns).set({ status: "failed" }).where(eq(heartbeatRuns.id, f.runId)); + if (state === "no_receipt") await db.update(heartbeatRuns).set({ resultJson: {} }).where(eq(heartbeatRuns.id, f.runId)); + if (["cancellation", "nativeCancellation", "executionCancellation", "startupCancellation"].includes(state)) { + const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId)); + await db.update(heartbeatRuns).set({ resultJson: { ...run.resultJson, [state]: { state: "pending" } } }).where(eq(heartbeatRuns.id, f.runId)); + } + if (state === "foreign_receipt") await db.update(heartbeatRuns).set({ resultJson: { semanticToolReceipts: { + invalid: { operationId: "set_task_monitor", result: { taskId: randomUUID(), monitor: { status: "scheduled", nextCheckAt: f.nextCheckAt } } }, + } } }).where(eq(heartbeatRuns.id, f.runId)); + const before = await f.readIssue(); + await f.finalize(state === "workspace_failed" ? "failed" : "succeeded"); + const [coordinator] = await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, f.runId)); + expect(coordinator.phase).toBe("retryable_failure"); + expect(await f.readIssue()).toMatchObject({ executionPolicy: before.executionPolicy, monitorNextCheckAt: before.monitorNextCheckAt, + executionRunId: before.executionRunId, checkoutRunId: before.checkoutRunId, assigneeAgentId: before.assigneeAgentId }); + expect(await db.select().from(statusDecisions).where(and(eq(statusDecisions.runId, f.runId), eq(statusDecisions.reasonCode, "scheduled_monitor_preserved")))).toEqual([]); + }, + ); + + it("supersedes an earlier authority error without replaying the accepted result", async () => { + const f = await fixture(), scheduled = await f.readIssue(); + await db.update(issues).set({ executionPolicy: {}, monitorNextCheckAt: null }).where(eq(issues.id, f.issueId)); + await f.finalize(); + const old = await db.select().from(statusDecisions).where(eq(statusDecisions.runId, f.runId)); + expect(old.some(decision => decision.reasonCode === "monitor_wait_authority_lost")).toBe(true); + await db.update(issues).set({ executionPolicy: scheduled.executionPolicy, monitorNextCheckAt: scheduled.monitorNextCheckAt }) + .where(eq(issues.id, f.issueId)); + await f.finalize(); + expect((await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, f.runId)))[0].phase).toBe("committed"); + const after = await db.select().from(statusDecisions).where(eq(statusDecisions.runId, f.runId)); + for (const before of old) expect(after.find(decision => decision.id === before.id)).toEqual(before); + expect(after.some(decision => decision.reasonCode === "scheduled_monitor_preserved")).toBe(true); + expect((await db.select().from(nativeRunResults).where(eq(nativeRunResults.id, f.resultId)))[0].resultJson).toEqual(f.result); + expect(await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.companyId, f.companyId))).toEqual([]); + }); + + it("notifies the existing monitor scheduler once when finalization stops blocking it", async () => { + const f = await fixture(), events: string[] = []; + expect(await hasPendingRunCleanup(db, f.companyId, f.runId)).toBe(true); + const unsubscribe = subscribeDatabaseWork(db, DELIVERY_QUEUES.issueMonitors, event => { events.push(event); }); + try { + await f.finalize(); + expect(events).toEqual(["intent", "settled"]); + expect(await hasPendingRunCleanup(db, f.companyId, f.runId)).toBe(false); + expect((await f.readIssue()).monitorNextCheckAt?.toISOString()).toBe(f.nextCheckAt); + await f.finalize(); + expect(events).toEqual(["intent", "settled"]); + } finally { unsubscribe(); } + }); + + it.each(["live", "recovered"])("publishes the accepted monitor explanation once (%s)", async mode => { + const f = await fixture(), before = await f.readIssue(); + const completionContractSha256 = `sha256:${nativeSha256({ revision: "test", criteria: [] })}`; + const canonicalSha256 = `sha256:${nativeSha256({ ...f.result, turnId: null })}`; + const serverFingerprint = `sha256:${nativeSha256({ runId: f.runId, completionContractSha256, canonicalSha256 })}`; + await db.update(nativeRunResults).set({ canonicalSha256, serverFingerprint }).where(eq(nativeRunResults.id, f.resultId)); + await db.update(heartbeatRuns).set({ completionContractSha256, + contextSnapshot: { issueId: f.issueId, ...(mode === "recovered" ? { skipIssueComment: true } : {}) }, + }).where(eq(heartbeatRuns.id, f.runId)); + const comments = () => db.select({ id: issueComments.id, body: issueComments.body }).from(issueComments) + .where(and(eq(issueComments.companyId, f.companyId), eq(issueComments.createdByRunId, f.runId))); + const repair = () => repairCommittedNativeChatResponse(db, { companyId: f.companyId, issueId: f.issueId, runId: f.runId }); + await f.finalize(); + if (mode === "recovered") { + expect(await comments()).toEqual([]); + await db.update(heartbeatRuns).set({ contextSnapshot: { issueId: f.issueId } }).where(eq(heartbeatRuns.id, f.runId)); + expect(await repair()).toBe(true); + } + const published = await comments(); + expect(published).toEqual([{ id: expect.any(String), body: f.result.result.summary }]); + expect(await repair()).toBe(false); + await f.finalize(); + expect(await comments()).toEqual(published); + expect((await f.readIssue()).monitorNextCheckAt).toEqual(before.monitorNextCheckAt); + expect((await db.select().from(nativeRunResults).where(eq(nativeRunResults.id, f.resultId)))[0].resultJson).toEqual(f.result); + expect(await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.companyId, f.companyId))).toEqual([]); + }); + + it.each(["cleared", "owner", "receipt", "rescheduled"])("rechecks monitor proof under the task lock (%s)", async state => { + const f = await fixture(), scheduled = await f.readIssue(); + const [owner] = await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, status: "running" }).returning(); + const nextCheckAt = new Date(Date.now() + 7_200_000).toISOString(); + const original = monitorDelivery.readNativePreservedMonitorWait; + const events: string[] = []; + const unsubscribe = subscribeDatabaseWork(db, DELIVERY_QUEUES.issueMonitors, event => { events.push(event); }); + const race = vi.spyOn(monitorDelivery, "readNativePreservedMonitorWait").mockImplementationOnce(async (...args) => { + const proof = await original(...args); + expect(proof).not.toBeNull(); + if (state === "cleared") await db.update(issues).set({ executionPolicy: {}, monitorNextCheckAt: null }).where(eq(issues.id, f.issueId)); + if (state === "owner") await db.update(issues).set({ executionRunId: owner!.id }).where(eq(issues.id, f.issueId)); + if (state === "receipt") await db.update(heartbeatRuns).set({ resultJson: {} }).where(eq(heartbeatRuns.id, f.runId)); + if (state === "rescheduled") await db.update(issues).set({ monitorNextCheckAt: new Date(nextCheckAt), executionPolicy: { + ...scheduled.executionPolicy, monitor: { ...(scheduled.executionPolicy?.monitor as Record), nextCheckAt }, + } }).where(eq(issues.id, f.issueId)); + return proof; + }); + try { await f.finalize(); } finally { race.mockRestore(); unsubscribe(); } + const [coordinator] = await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, f.runId)); + expect(coordinator.phase).toBe(state === "rescheduled" ? "committed" : "retryable_failure"); + expect(events).toEqual(state === "rescheduled" ? ["intent", "settled"] : []); + const task = await f.readIssue(); + expect(task.executionRunId).toBe(state === "owner" ? owner!.id : null); + expect(task.monitorNextCheckAt?.toISOString() ?? null).toBe(state === "cleared" ? null : state === "rescheduled" ? nextCheckAt : f.nextCheckAt); + expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, owner!.id)))[0].status).toBe("running"); + expect((await db.select().from(nativeRunResults).where(eq(nativeRunResults.id, f.resultId)))[0].resultJson).toEqual(f.result); + expect(await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.companyId, f.companyId))).toEqual([]); + }); +}); diff --git a/server/src/services/native-runtime/native-run-finalizer.ts b/server/src/services/native-runtime/native-run-finalizer.ts index 805fd623d18..1f8b830ff03 100644 --- a/server/src/services/native-runtime/native-run-finalizer.ts +++ b/server/src/services/native-runtime/native-run-finalizer.ts @@ -4,7 +4,7 @@ import { reconcileMuseNativeTerminalRun } from "./muse-terminal-reconciliation.j import { assertNativeCaseHandoffResult } from "./native-case-handoff.js"; import { scheduledIssueMonitorWait } from "../issue-monitors.js"; import { hasPublishedGitHubReview } from "../chat-channels/github/review-wait.js"; -import { readNativeMonitorDelivery } from "./native-monitor-delivery.js"; +import { readNativeMonitorDelivery, readNativePreservedMonitorWait } from "./native-monitor-delivery.js"; import { isNativePlanWaitResult, readNativePlanWait } from "./native-plan-wait.js"; import { hasPendingNativeChildCompletion } from "./native-child-completion-delivery.js"; import { settleExternalConversation } from "../slack-conversation-lifecycle.js"; @@ -1331,10 +1331,16 @@ export async function finalizeNativeRun(input: { }) : "not_applicable"; const monitorWaitAt = scheduledIssueMonitorWait(authoritativeIssue, run.agentId); + const preservedMonitorWait = terminalState === "succeeded" && input.workspaceFinalizeStatus === "succeeded" && + assessment.reportedDisposition === "yielded" && assessment.continuation?.kind === "monitor" + ? await readNativePreservedMonitorWait(input.db, { + companyId: run.companyId, issueId: authoritativeIssue.id, runId: run.id, agentId: run.agentId, + }, authoritativeIssue) : null; + if (preservedMonitorWait && preservedMonitorWait.resultId !== resultRow.id) throw new NativeStatusRaceError(); const supersededReviews = terminalState === "succeeded" && input.workspaceFinalizeStatus === "succeeded" && assessment.attentionRequests.length === 0 && (assessment.reportedDisposition === "done" || (assessment.reportedDisposition === "yielded" && (externalChatResponseWaitAuthorization === "authorized" || - (assessment.continuation?.kind === "monitor" && monitorWaitAt !== null)))) + (assessment.continuation?.kind === "monitor" && monitorWaitAt !== null && !preservedMonitorWait)))) ? await findSupersededExternalReviewRequests(input.db, { companyId: run.companyId, issueId: authoritativeIssue.id, runId: run.id, agentId: run.agentId, }) : []; @@ -1419,6 +1425,7 @@ export async function finalizeNativeRun(input: { const proposedDecision = resolveNativeFinalizerStatus({ caseHandoffAuthorized: Boolean(await assertNativeCaseHandoffResult(input.db, run.id, authoritativeIssue.id, result)), monitorWaitDispatched: monitorDelivery !== null, + monitorWaitPreserved: preservedMonitorWait !== null, monitorWaitAuthorized: authoritativeIssue.workMode === "standard" && authoritativeIssue.executionRunId === run.id && monitorWaitAt !== null, planWaitAuthorized: planWait !== null, hasPendingChildCompletion, @@ -1522,6 +1529,8 @@ export async function finalizeNativeRun(input: { ? { agentId: run.agentId, nextCheckAt: monitorWaitAt } : undefined, requireMonitorDelivery: decision.reasonCode === "scheduled_monitor_dispatched" ? monitorDelivery ?? undefined : undefined, + requirePreservedMonitorWait: decision.reasonCode === "scheduled_monitor_preserved" + ? preservedMonitorWait ?? undefined : undefined, requirePlanWaitSource: decision.reasonCode === "native_plan_accepted_waiting_for_continuation" ? planWait?.source : undefined, diff --git a/server/src/services/native-runtime/status-arbiter.test.ts b/server/src/services/native-runtime/status-arbiter.test.ts index 6262e01adaf..9a3609f9a2c 100644 --- a/server/src/services/native-runtime/status-arbiter.test.ts +++ b/server/src/services/native-runtime/status-arbiter.test.ts @@ -560,7 +560,7 @@ describe("native status authority", () => { expect.objectContaining({ statusAction: "blocked", toStatus: "blocked", - policyVersion: "phase6-v12", + policyVersion: "phase6-v13", reasonCode: "current_track_blocker_waiting", unblockDescriptor: { owner: "board", diff --git a/server/src/services/native-runtime/status-arbiter.ts b/server/src/services/native-runtime/status-arbiter.ts index 5c6e4679e12..4fdc5496cc1 100644 --- a/server/src/services/native-runtime/status-arbiter.ts +++ b/server/src/services/native-runtime/status-arbiter.ts @@ -1,7 +1,7 @@ import type { NativeEvidenceAssessment } from "./evidence-classifier.js"; import { NATIVE_MODEL_REJECTION_MESSAGE, NATIVE_PROVIDER_CAPACITY_MAX_RETRIES, NATIVE_PROVIDER_OVERLOADED_CODE, NATIVE_PROVIDER_OVERLOADED_MESSAGE } from "./native-provider-failure.js"; -export const NATIVE_STATUS_ARBITER_POLICY_VERSION = "phase6-v12"; +export const NATIVE_STATUS_ARBITER_POLICY_VERSION = "phase6-v13"; export type NativeAuthoritativeIssueStatus = | "backlog" @@ -118,6 +118,7 @@ export function arbitrateNativeStatus(input: { caseHandoffAuthorized?: boolean; /** The saved timer already admitted another run and this run no longer owns checkout. */ monitorWaitDispatched?: boolean; + monitorWaitPreserved?: boolean; boardResponseWaitAuthorized?: boolean; boardResponseWaitOrigin?: boolean; isConversation?: boolean; @@ -483,6 +484,13 @@ export function arbitrateNativeStatus(input: { effects: [], }; } + if (input.monitorWaitPreserved) { + return { + policyVersion: NATIVE_STATUS_ARBITER_POLICY_VERSION, + statusAction: "preserve", toStatus: input.priorIssueStatus, + reasonCode: "scheduled_monitor_preserved", unblockDescriptor: null, effects: [], + }; + } if (input.monitorWaitAuthorized) { return { policyVersion: NATIVE_STATUS_ARBITER_POLICY_VERSION, diff --git a/server/src/services/native-runtime/status-decision-committer.ts b/server/src/services/native-runtime/status-decision-committer.ts index eafd64245c9..c7684448cbf 100644 --- a/server/src/services/native-runtime/status-decision-committer.ts +++ b/server/src/services/native-runtime/status-decision-committer.ts @@ -3,7 +3,7 @@ import { hasPublishedGitHubReview } from "../chat-channels/github/review-wait.js import { pendingNativeGovernance } from "./native-governance.js"; import { findSupersededExternalReviewRequests, supersedeExternalReviewRequestsInTransaction } from "./superseded-external-review-requests.js"; import { normalizePrpResultSignals, type PrpStructuredRunResult } from "../../vendor/paperclip-runner/index.js"; -import { readNativeMonitorDelivery, type NativeMonitorDelivery } from "./native-monitor-delivery.js"; +import { readNativeMonitorDelivery, readNativePreservedMonitorWait, type NativeMonitorDelivery, type NativePreservedMonitorWait } from "./native-monitor-delivery.js"; import { readNativePlanWait, type NativePlanWaitSource } from "./native-plan-wait.js"; import { activeIssueInteractionCondition } from "../issue-question-context.js"; import { isConversation } from "../agent-conversations.js"; @@ -1565,6 +1565,7 @@ export async function commitNativeStatusDecision(input: { requirePlanWaitSource?: NativePlanWaitSource; requireMonitorWait?: { agentId: string; nextCheckAt: string }; requireMonitorDelivery?: NativeMonitorDelivery; + requirePreservedMonitorWait?: NativePreservedMonitorWait; requireNoPendingChildCompletion?: NativeChildCompletionRecipient; requireModelRejectionOwner?: { agentId: string; reviewContext: NativeReviewAssignmentContext | null }; requireProviderFailureOwner?: { agentId: string; reviewContext: NativeReviewAssignmentContext | null }; @@ -1675,6 +1676,18 @@ export async function commitNativeStatusDecision(input: { input.decision.statusAction !== "preserve" || input.decision.toStatus !== issue.status || input.decision.effects.length !== 0) throw new NativeStatusRaceError(); } + if (reasonCode === "scheduled_monitor_preserved") { + const expected = input.requirePreservedMonitorWait; + const actual = expected ? await readNativePreservedMonitorWait(tx as unknown as Db, { + companyId: input.companyId, issueId: input.issueId, runId: input.runId, agentId: expected.agentId, + }, issue) : null; + if (!expected || !actual || actual.nextCheckAt !== expected.nextCheckAt || actual.resultId !== expected.resultId || + input.decision.statusAction !== "preserve" || input.decision.toStatus !== issue.status || + input.decision.effects.length !== 0 || await pendingNativeGovernance({ db: tx as unknown as Db, + companyId: input.companyId, issueId: input.issueId, runId: input.runId, executionState: record(issue.executionState), + })) throw new NativeStatusRaceError(); + await notifyDeliveryWork(tx, DELIVERY_QUEUES.issueMonitors); + } // Recheck under the parent status lock: a child can finish between the // finalizer's read and this commit. Re-arbitrate instead of discarding its wake. if (input.requireNoPendingChildCompletion && await hasPendingNativeChildCompletion( From 82c998233c10ca23f88e0b4ed7dbceb74feb2684 Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Sun, 25 Oct 2026 11:06:22 -0700 Subject: [PATCH 072/110] perf(recovery): omit unused launch payloads from reconciliation reads (#17645) Project unused launch context and native execution input out of two preliminary recovery reads. Preserve full results, unknown controls, complete legacy profiles, current filters, native rejection and full locked terminalization. Apex 5/5 with no unresolved comments and all CI checks green. Ten combined local suites pass (370 tests), plus workspace typecheck and server build. Hosted traffic effects require staging verification. Co-Authored-By: Paperclip --- doc/DATABASE.md | 6 + .../src/services/legacy-execution-recovery.ts | 20 +++- .../recovery/reconciliation-run-read.test.ts | 107 ++++++++++++++++++ server/src/services/recovery/service.ts | 5 +- 4 files changed, 135 insertions(+), 3 deletions(-) create mode 100644 server/src/services/recovery/reconciliation-run-read.test.ts diff --git a/doc/DATABASE.md b/doc/DATABASE.md index 51f565e8bed..961d532aef9 100644 --- a/doc/DATABASE.md +++ b/doc/DATABASE.md @@ -66,6 +66,12 @@ the PostgreSQL row version. Native blocked-wait repair compares that version against a fresh full source read before applying changes. Any intervening row update, including an edit outside the projection, defers repair to a fresh sweep. +The two preliminary reconciliation reads omit named launch renderings and +preparation payloads. Native profiles omit unused native execution input. +They retain all other context, full results, legacy profiles, task identity, +retry accounting, and unknown controls. Native runs still reach their native +recovery guard. Terminalization keeps its full locked source and stored input. + Execution-blocker reads select process, lifecycle, and task-binding fields rather than full execution rows. Context retains typed task and pre-dispatch evidence; Runner profiles retain the adapter type, native input schema, binding, provider, diff --git a/server/src/services/legacy-execution-recovery.ts b/server/src/services/legacy-execution-recovery.ts index 5bbea0e61a5..3561bff8768 100644 --- a/server/src/services/legacy-execution-recovery.ts +++ b/server/src/services/legacy-execution-recovery.ts @@ -8,7 +8,7 @@ import { normalizeMaxTurnStopReason } from "./heartbeat-stop-metadata.js"; import { claimedAdapterType, hasConversationContinuationPolicy } from "./conversation-continuation.js"; import { canonicalExecutionUuid } from "./execution-identity.js"; import { randomUUID } from "node:crypto"; -import { and, desc, eq, inArray, isNull, or, sql, type SQL } from "drizzle-orm"; +import { and, desc, eq, getTableColumns, inArray, isNull, or, sql, type SQL } from "drizzle-orm"; import { environmentLeases, heartbeatRuns, issueRecoveryActions, issues, nativeRunFinalizations, type Db } from "@paperclipai/db"; import { issueRecoveryActionService } from "./issue-recovery-actions.js"; import { parseIssueExecutionState } from "./issue-execution-policy.js"; @@ -20,6 +20,24 @@ import { issueService } from "./issues.js"; type Run = typeof heartbeatRuns.$inferSelect; export const LEGACY_RECOVERY_CAUSE = "legacy_execution_requires_reconciliation"; +const unusedReconciliationContextKeys = [ + "executionContinuation", "paperclipWake", "paperclipWakeComment", + "paperclipTaskMarkdown", "paperclipTaskMarkdownCompact", "paperclipTaskAssignment", + "paperclipTaskAssignmentCompact", "paperclipWorkspace", "paperclipEnvironment", "paperclipContinuationSummary", +] as const; + +export const legacyReconciliationRunFields = { + ...getTableColumns(heartbeatRuns), + contextSnapshot: sql`case + when jsonb_typeof(${heartbeatRuns.contextSnapshot}) = 'object' + then ${heartbeatRuns.contextSnapshot} - ARRAY[${sql.join(unusedReconciliationContextKeys.map(key => sql`${key}`), sql`, `)}]::text[] + else ${heartbeatRuns.contextSnapshot} end`, + runnerProfileJson: sql`case + when ${heartbeatRuns.runtimeMode} = 'native' and jsonb_typeof(${heartbeatRuns.runnerProfileJson}) = 'object' + then ${heartbeatRuns.runnerProfileJson} - 'nativeExecutionInput' + else ${heartbeatRuns.runnerProfileJson} end`, +}; + /** Error families describe availability, not whether earlier actions happened. */ export function legacyExecutionNeedsReconciliation( run: Pick & Partial>, diff --git a/server/src/services/recovery/reconciliation-run-read.test.ts b/server/src/services/recovery/reconciliation-run-read.test.ts new file mode 100644 index 00000000000..ff42eb35aac --- /dev/null +++ b/server/src/services/recovery/reconciliation-run-read.test.ts @@ -0,0 +1,107 @@ +import { randomBytes, randomUUID } from "node:crypto"; +import { agents, agentWakeupRequests, companies, createDb, heartbeatRuns, issueRecoveryActions, issues } from "@paperclipai/db"; +import { and, eq } from "drizzle-orm"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embedded-postgres.js"; +import { executionFailureRetryCount } from "../execution-recovery-attempt.js"; +import { legacyExecutionNeedsReconciliationWithEvidence, legacyReconciliationRunFields, terminalizeLegacyExecution } from "../legacy-execution-recovery.js"; + +const support = await getEmbeddedPostgresTestSupport(); +describe.skipIf(!support.supported)("reconciliation source PostgreSQL reads", () => { + let temporary: Awaited>; + let db: ReturnType; + let companyId: string, agentId: string; + const launchKeys = ["executionContinuation", "paperclipWake", "paperclipWakeComment", "paperclipTaskMarkdown", + "paperclipTaskMarkdownCompact", "paperclipTaskAssignment", "paperclipTaskAssignmentCompact", "paperclipWorkspace", + "paperclipEnvironment", "paperclipContinuationSummary"]; + beforeAll(async () => { + temporary = await startEmbeddedPostgresTestDatabase("reconciliation-source-"); + db = createDb(temporary.connectionString); + companyId = randomUUID(); agentId = randomUUID(); + await db.insert(companies).values({ id: companyId, name: "Recovery reads", issuePrefix: "RCR" }); + await db.insert(agents).values({ id: agentId, companyId, name: "Recovery worker", adapterType: "process", status: "active" }); + }); + afterAll(async () => { await db?.$client.end(); await temporary?.cleanup(); }); + + async function fixture(patch: Partial = {}) { + const payload = randomBytes(64 * 1024).toString("base64"); + const contextSnapshot = { ...Object.fromEntries(launchKeys.map(key => [key, { prompt: payload }])), + issueId: randomUUID(), taskId: randomUUID(), executionWorkspaceId: randomUUID(), + executionRetryAccounting: { version: 1, failureRetries: 2, maxTurnContinuations: 3 }, + failureRetriesBeforeAiConnectionWait: 1, failureRetriesBeforeWorkspaceWait: 1, + conversationSessionGeneration: 7, connectionIntentResolution: "existing_connection", source: "connection_intent.resolved", + interactionKind: "connection_intent", interactionStatus: "expired", mutation: "interaction", interactionId: randomUUID(), + futureControl: { nonce: "retained", nested: null }, cancellation: { state: "pending" }, + }; + const [full] = await db.insert(heartbeatRuns).values({ companyId, agentId, status: "failed", runtimeMode: "legacy", + errorCode: "process_lost", contextSnapshot, resultJson: { futureOutput: { retained: true } }, + runnerProfileJson: { adapterDispatch: { adapterType: "process" }, futureControl: { retained: true } }, + ...patch, + }).returning(); + const [selected] = await db.select(legacyReconciliationRunFields).from(heartbeatRuns) + .where(and(eq(heartbeatRuns.companyId, companyId), eq(heartbeatRuns.id, full!.id))); + return { full: full!, selected: selected! }; + } + + it.each(["native", "legacy"])("omits unused launch text and preserves current control fields (%s)", async runtimeMode => { + const profile = { nativeExecutionInput: { prompt: randomBytes(128 * 1024).toString("base64") }, futureControl: { retained: true } }; + const f = await fixture({ runtimeMode, ...(runtimeMode === "native" ? { runnerProfileJson: profile } : {}) }); + const expected = { ...f.full.contextSnapshot }; + for (const key of launchKeys) delete expected[key]; + expect(f.selected).toEqual({ ...f.full, contextSnapshot: expected, + runnerProfileJson: runtimeMode === "native" ? { futureControl: profile.futureControl } : f.full.runnerProfileJson }); + expect(Buffer.byteLength(JSON.stringify(f.full))).toBeGreaterThan(800_000); + expect(Buffer.byteLength(JSON.stringify(f.selected))).toBeLessThan(8192); + expect(executionFailureRetryCount(f.selected)).toBe(executionFailureRetryCount(f.full)); + expect(await legacyExecutionNeedsReconciliationWithEvidence(db, f.selected)) + .toBe(await legacyExecutionNeedsReconciliationWithEvidence(db, f.full)); + expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.full.id)))[0]).toEqual(f.full); + }); + + it.each([null, [], ["unexpected"], "scalar", 42].map(value => ({ value })))("preserves non-object JSON $value", async ({ value }) => { + for (const runtimeMode of ["native", "legacy"]) { + const f = await fixture({ runtimeMode, + contextSnapshot: value as typeof heartbeatRuns.$inferInsert.contextSnapshot, + runnerProfileJson: value as typeof heartbeatRuns.$inferInsert.runnerProfileJson, + }); + expect(f.selected).toEqual(f.full); + } + }); + + it.each([ + { status: "failed", errorCode: "setup_failed", resultJson: { executionRecovery: { kind: "bootstrap", providerWorkStarted: false } } }, + { status: "cancelled", errorCode: "cancelled", resultJson: { executionCancellation: { state: "acknowledged" }, + executionRecovery: { kind: "interrupted", providerStopped: true, sessionPreserved: true, actionOutcomes: "settled" } } }, + { status: "cancelled", errorCode: "cancelled", resultJson: { executionCancellation: { state: "requested" }, + executionRecovery: { kind: "interrupted", providerStopped: false, sessionPreserved: true, actionOutcomes: "unknown" } } }, + { status: "cancelled", errorCode: "ai_connection_busy", resultJson: { executionRecovery: { kind: "ai_connection_wait", providerWorkStarted: false } } }, + { status: "cancelled", errorCode: "workspace_busy", resultJson: { executionRecovery: { kind: "workspace_wait", providerWorkStarted: false } } }, + { status: "failed", errorCode: "workspace_restore_failed", resultJson: { workspaceRestoreFailure: "restore_unsafe_archive" } }, + { status: "failed", errorCode: "process_lost", resultJson: { conversationContinuation: "continue_conversation_v1" } }, + { status: "cancelled", errorCode: "issue_waiting_for_response", resultJson: { stopReason: "issue_waiting_for_response", timeoutSource: "stale_queued_run_gate" } }, + ])("keeps reconciliation, cancellation, and retry decisions ($errorCode)", async patch => { + const f = await fixture(patch); + expect(f.selected.resultJson).toEqual(f.full.resultJson); + expect(executionFailureRetryCount(f.selected)).toBe(executionFailureRetryCount(f.full)); + expect(await legacyExecutionNeedsReconciliationWithEvidence(db, f.selected)) + .toBe(await legacyExecutionNeedsReconciliationWithEvidence(db, f.full)); + }); + + it("keeps full stored input and newer ownership when the projected source is terminalized", async () => { + const issueId = randomUUID(); + await db.insert(issues).values({ id: issueId, companyId, title: "Recover the stopped source", status: "in_progress", assigneeAgentId: agentId }); + const f = await fixture({ issueId, contextSnapshot: { issueId, paperclipTaskMarkdown: randomBytes(128 * 1024).toString("base64"), + executionRetryAccounting: { version: 1, failureRetries: 2, maxTurnContinuations: 0 } } }); + const [successor] = await db.insert(heartbeatRuns).values({ companyId, agentId, issueId, status: "running" }).returning(); + await db.update(issues).set({ executionRunId: successor!.id, checkoutRunId: successor!.id }).where(eq(issues.id, issueId)); + await terminalizeLegacyExecution({ db, run: f.selected, status: "failed", fromStatuses: ["failed"] }); + const [stored] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.full.id)); + expect(stored).toMatchObject({ contextSnapshot: f.full.contextSnapshot, runnerProfileJson: f.full.runnerProfileJson, resultJson: f.full.resultJson }); + expect((await db.select().from(issues).where(eq(issues.id, issueId)))[0]) + .toMatchObject({ executionRunId: successor!.id, checkoutRunId: successor!.id }); + expect(await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, issueId))) + .toEqual([expect.objectContaining({ cause: "legacy_execution_requires_reconciliation", ownerType: "board", + evidence: expect.objectContaining({ runId: f.full.id, attempt: 3 }) })]); + expect(await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.companyId, companyId))).toEqual([]); + }); +}); diff --git a/server/src/services/recovery/service.ts b/server/src/services/recovery/service.ts index 5701571e864..488ef813306 100644 --- a/server/src/services/recovery/service.ts +++ b/server/src/services/recovery/service.ts @@ -106,6 +106,7 @@ import { issueRecoveryActionService } from "../issue-recovery-actions.js"; import { hasUnverifiedNativeWorkspaceFinalizationOwner } from "../native-runtime/native-workspace-finalization-recovery-state.js"; import { legacyExecutionNeedsReconciliationWithEvidence, + legacyReconciliationRunFields, terminalizeLegacyExecution, } from "../legacy-execution-recovery.js"; import { issueTreeControlService } from "../issue-tree-control.js"; @@ -2010,7 +2011,7 @@ export function recoveryService( }) { if (input.retryOfRunId) { const [predecessor] = await db - .select() + .select(legacyReconciliationRunFields) .from(heartbeatRuns) .where( and( @@ -4809,7 +4810,7 @@ export function recoveryService( ) ) { const [source] = await db - .select() + .select(legacyReconciliationRunFields) .from(heartbeatRuns) .where( and( From 1949e726f8515127a04314e3793c427ccfc33c1e Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Sun, 25 Oct 2026 11:46:29 -0700 Subject: [PATCH 073/110] perf(recovery): read only legacy terminal control fields under lock (#17646) Select only runtime mode, status, complete result evidence and the delivery token from the locked legacy terminal-state read. Keep filters, row lock, guards, writes, full returned rows, source retention and recovery holds. The synthetic regression reduces a 699,454-byte read to under 4 KB while preserving full stored and returned data. All CI checks, 236 combined tests, workspace typecheck and server build pass. Apex 5/5 after correcting a documentation contradiction, with no unresolved comments. Co-Authored-By: Paperclip --- doc/DATABASE.md | 8 ++++- .../legacy-workspace-restore-recovery.test.ts | 29 ++++++++++++++++++- .../src/services/legacy-execution-recovery.ts | 4 ++- 3 files changed, 38 insertions(+), 3 deletions(-) diff --git a/doc/DATABASE.md b/doc/DATABASE.md index 961d532aef9..c7b525877fc 100644 --- a/doc/DATABASE.md +++ b/doc/DATABASE.md @@ -70,7 +70,8 @@ The two preliminary reconciliation reads omit named launch renderings and preparation payloads. Native profiles omit unused native execution input. They retain all other context, full results, legacy profiles, task identity, retry accounting, and unknown controls. Native runs still reach their native -recovery guard. Terminalization keeps its full locked source and stored input. +recovery guard. Terminalization locks its current control state and returns +full rows from its writes. Stored input remains intact. Execution-blocker reads select process, lifecycle, and task-binding fields rather than full execution rows. Context retains typed task and pre-dispatch evidence; @@ -96,6 +97,11 @@ payloads. It retains current coordinator checks, provider evidence, local-host identity checks, and every lease's termination receipt. The stop receipt and process-field update remain in the same transaction. +Legacy terminalization locks runtime mode, status, full result evidence, and the +status-delivery token without loading unused input, profile, or log bodies. +It keeps the existing lock, writes, full returned run, workspace-retention +receipts, and source-bound recovery holds. Stored payloads remain unchanged. + Conversation ownership checks select process identity and full recovery result evidence without execution prompts or profiles. Committed native reply repair selects its persisted result and identity bindings plus typed presentation flags. diff --git a/server/src/__tests__/legacy-workspace-restore-recovery.test.ts b/server/src/__tests__/legacy-workspace-restore-recovery.test.ts index 4629092e10e..84da47b84b7 100644 --- a/server/src/__tests__/legacy-workspace-restore-recovery.test.ts +++ b/server/src/__tests__/legacy-workspace-restore-recovery.test.ts @@ -1,4 +1,5 @@ -import { randomUUID } from "node:crypto"; +import { randomBytes, randomUUID } from "node:crypto"; +import { createDatabaseResponseCapture, installDatabaseResponseCapture } from "@paperclipai/db/response-capture"; import { and, eq, sql } from "drizzle-orm"; import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; import { agents, companies, createDb, environmentLeases, environments, executionWorkspaces, heartbeatRuns, issueRecoveryActions, issues, projects } from "@paperclipai/db"; @@ -46,6 +47,32 @@ const support = externalTestDatabaseUrl ? { supported: true } : await getEmbedde } }; const readLease = async (id: string) => (await db.select().from(environmentLeases).where(eq(environmentLeases.id, id)))[0]; + it("locks only terminal control state while returning and retaining the complete run", async () => { + const f = await seed(); + const bulk = randomBytes(128 * 1024).toString("base64"); + const [saved] = await db.update(heartbeatRuns).set({ contextSnapshot: { ...f.run.contextSnapshot, savedInput: bulk }, + runnerProfileJson: { savedProfile: bulk }, stdoutExcerpt: bulk, stderrExcerpt: bulk, + }).where(eq(heartbeatRuns.id, f.runId)).returning(); + const events: Array> = [], now = Date.now(); + const capture = createDatabaseResponseCapture({ start: now - 100, end: now + 59_000 }, event => events.push(event)); + installDatabaseResponseCapture(db, { heartbeatRuns }, capture); + let returned: Awaited>; + try { returned = await terminalizeLegacyExecution({ db, run: saved!, status: "failed", patch }); } + finally { capture.flush(); } + const groups = events.filter(event => event.event === "paperclip.db_response_capture.entry.v1"); + const reads = groups.filter(group => group.table === "heartbeat_runs" && group.operation === "select"); + expect(reads.reduce((sum, group) => sum + Number(group.calls), 0)).toBe(1); + expect(reads.reduce((sum, group) => sum + Number(group.responseValueBytes), 0)).toBeLessThan(4096); + expect(returned).toMatchObject({ id: f.runId, status: "failed", contextSnapshot: saved!.contextSnapshot, + runnerProfileJson: saved!.runnerProfileJson, stdoutExcerpt: bulk, stderrExcerpt: bulk }); + expect(hasRequiredWorkspaceRecovery(returned!.resultJson)).toBe(true); + expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId)))[0]).toEqual(returned); + expect(await readLease(f.lease.id)).toMatchObject({ status: "pending_cleanup", leasePolicy: "retain_on_failure" }); + expect(await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, f.issueId))) + .toEqual([expect.objectContaining({ evidence: expect.objectContaining({ runId: f.runId }), ownerType: "board" })]); + expect(JSON.stringify(events)).not.toContain(bulk.slice(0, 64)); + }); + it("preserves pending and acknowledged status delivery on unpatched legacy recovery retries", async () => { await deliverExecutionStatuses(db, { publish: vi.fn() }); const f = await seed(); diff --git a/server/src/services/legacy-execution-recovery.ts b/server/src/services/legacy-execution-recovery.ts index 3561bff8768..5d5fe783b3f 100644 --- a/server/src/services/legacy-execution-recovery.ts +++ b/server/src/services/legacy-execution-recovery.ts @@ -118,7 +118,9 @@ export async function terminalizeLegacyExecution(input: { ) .for("update") : []; - const [current] = await tx.select().from(heartbeatRuns).where(and( + const [current] = await tx.select({ runtimeMode: heartbeatRuns.runtimeMode, status: heartbeatRuns.status, + resultJson: heartbeatRuns.resultJson, executionStatusDeliveryId: heartbeatRuns.executionStatusDeliveryId, + }).from(heartbeatRuns).where(and( eq(heartbeatRuns.id, run.id), eq(heartbeatRuns.companyId, run.companyId), )).for("update"); if (!current || (current.runtimeMode !== "legacy" && !(input.recordRestoreFailureOnly && current.runtimeMode === "native")) || From 67aa87a93bb1bbc4559105497863f541f9fb4e9b Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Sun, 25 Oct 2026 12:58:50 -0700 Subject: [PATCH 074/110] perf(recovery): skip unchanged retained workspace evidence writes (#17650) Guard the retained-evidence update with its existing JSONB comparison. Reuse the full first result when evidence is unchanged, while preserving new evidence delivery, source-bound retention, cleanup, and recovery holds. Verified with 199 recovery and retention tests, full workspace typechecking, the server build, green CI, and exact-head Apex5/5. Co-Authored-By: Paperclip --- doc/DATABASE.md | 5 ++- .../legacy-workspace-restore-recovery.test.ts | 35 +++++++++++++++++++ .../src/services/legacy-execution-recovery.ts | 9 ++--- 3 files changed, 44 insertions(+), 5 deletions(-) diff --git a/doc/DATABASE.md b/doc/DATABASE.md index c7b525877fc..137b7fe1810 100644 --- a/doc/DATABASE.md +++ b/doc/DATABASE.md @@ -99,7 +99,7 @@ process-field update remain in the same transaction. Legacy terminalization locks runtime mode, status, full result evidence, and the status-delivery token without loading unused input, profile, or log bodies. -It keeps the existing lock, writes, full returned run, workspace-retention +It keeps the existing lock, full returned run, workspace-retention receipts, and source-bound recovery holds. Stored payloads remain unchanged. Conversation ownership checks select process identity and full recovery result @@ -281,6 +281,9 @@ Legacy recovery also retains the pending delivery when status is unchanged and no patch was supplied. Explicit patches, new terminal statuses, and newly retained workspace evidence still create a delivery. File retention, ownership checks, failed write conditions, lock cleanup, and recovery holds still apply. +The retention-evidence write returns another full run only when that evidence +changes. An unchanged retry keeps the full run returned by the first write and +still processes retained leases and recovery holds. Agent lists read the complete company roster once and use that same snapshot for termination filtering and organization-chain normalization. Detail and plugin runtime reads diff --git a/server/src/__tests__/legacy-workspace-restore-recovery.test.ts b/server/src/__tests__/legacy-workspace-restore-recovery.test.ts index 84da47b84b7..65e0e0cc147 100644 --- a/server/src/__tests__/legacy-workspace-restore-recovery.test.ts +++ b/server/src/__tests__/legacy-workspace-restore-recovery.test.ts @@ -73,6 +73,41 @@ const support = externalTestDatabaseUrl ? { supported: true } : await getEmbedde expect(JSON.stringify(events)).not.toContain(bulk.slice(0, 64)); }); + it.each(["legacy", "native"])("returns one complete run when retained workspace evidence is unchanged for %s", async (runtimeMode) => { + const f = await seed(); + const bulk = randomBytes(128 * 1024).toString("base64"); + const [saved] = await db.update(heartbeatRuns).set({ runtimeMode, status: "failed", finishedAt: new Date(), + contextSnapshot: { ...f.run.contextSnapshot, savedInput: bulk }, runnerProfileJson: { savedProfile: bulk }, + stdoutExcerpt: bulk, stderrExcerpt: bulk, + }).where(eq(heartbeatRuns.id, f.runId)).returning(); + const recordRestoreFailureOnly = runtimeMode === "native"; + const failed = (await terminalizeLegacyExecution({ db, run: saved!, status: "failed", recordRestoreFailureOnly, + workspaceRestoreSource: f.lease, + patch: { resultJson: { workspaceRestoreFailure: "restore_failed", futureResult: bulk } }, + }))!; + const events: Array> = [], now = Date.now(); + const capture = createDatabaseResponseCapture({ start: now - 100, end: now + 59_000 }, event => events.push(event)); + installDatabaseResponseCapture(db, { heartbeatRuns }, capture); + let returned: Awaited>; + try { returned = await terminalizeLegacyExecution({ db, run: failed, status: "failed", recordRestoreFailureOnly, + workspaceRestoreSource: f.lease, + ...(recordRestoreFailureOnly ? { patch: { resultJson: failed.resultJson } } : {}), + }); } + finally { capture.flush(); } + const writes = events.filter(event => event.event === "paperclip.db_response_capture.entry.v1" + && event.table === "heartbeat_runs" && event.operation === "update"); + expect(writes.reduce((sum, group) => sum + Number(group.rows), 0)).toBe(1); + expect(returned).toMatchObject({ id: f.runId, status: "failed", finishedAt: failed.finishedAt, + contextSnapshot: failed.contextSnapshot, runnerProfileJson: failed.runnerProfileJson, resultJson: failed.resultJson, + stdoutExcerpt: bulk, stderrExcerpt: bulk }); + if (!recordRestoreFailureOnly) expect(returned!.executionStatusDeliveryId).toBe(failed.executionStatusDeliveryId); + expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId)))[0]).toEqual(returned); + expect(await readLease(f.lease.id)).toMatchObject({ status: "pending_cleanup", leasePolicy: "retain_on_failure" }); + expect(await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, f.issueId))) + .toEqual([expect.objectContaining({ evidence: expect.objectContaining({ runId: f.runId }), ownerType: "board" })]); + expect(JSON.stringify(events)).not.toContain(bulk.slice(0, 64)); + }); + it("preserves pending and acknowledged status delivery on unpatched legacy recovery retries", async () => { await deliverExecutionStatuses(db, { publish: vi.fn() }); const f = await seed(); diff --git a/server/src/services/legacy-execution-recovery.ts b/server/src/services/legacy-execution-recovery.ts index 5d5fe783b3f..9a3041c88d8 100644 --- a/server/src/services/legacy-execution-recovery.ts +++ b/server/src/services/legacy-execution-recovery.ts @@ -156,11 +156,12 @@ export async function terminalizeLegacyExecution(input: { ...updated.resultJson, workspaceRestoreRecovery: { schema: LEGACY_WORKSPACE_RECOVERY_SCHEMA, leaseIds: [...retainedLeaseIds].sort() }, }; - [updated] = await tx.update(heartbeatRuns).set({ + const [retained] = await tx.update(heartbeatRuns).set({ resultJson: retainedResult, - executionStatusDeliveryId: sql`case when ${heartbeatRuns.resultJson} is distinct from ${JSON.stringify(retainedResult)}::jsonb - then ${randomUUID()}::uuid else ${heartbeatRuns.executionStatusDeliveryId} end`, - }).where(and(eq(heartbeatRuns.id, updated.id), eq(heartbeatRuns.companyId, updated.companyId))).returning(); + executionStatusDeliveryId: randomUUID(), + }).where(and(eq(heartbeatRuns.id, updated.id), eq(heartbeatRuns.companyId, updated.companyId), + sql`${heartbeatRuns.resultJson} is distinct from ${JSON.stringify(retainedResult)}::jsonb`)).returning(); + if (retained) updated = retained; } const needsRecovery = input.recordRestoreFailureOnly ? retainedLeaseIds.length > 0 || hasRequiredWorkspaceRecovery(updated.resultJson) From f0b597172b9ba434e7a490ba4778f63ddc8f1fb7 Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Sun, 25 Oct 2026 13:37:11 -0700 Subject: [PATCH 075/110] perf(skills): verify bundled releases with current inventory digests (#17652) Use current scoped database inventory fingerprints and the current on-disk expectation before reusing bounded snapshot verification. Preserve full validation, seeding and access checks when content, expectation or row existence changes. Verified177 skill and authorization tests, workspace typechecking, server build, all green CI and exact-head Apex5/5. Prior staging release measured and saved Legacy data fingerprints preserved. Co-Authored-By: Paperclip --- doc/DATABASE.md | 7 ++ .../__tests__/company-skills-service.test.ts | 68 ++++++++++++ .../bundled-skill-release-validation.test.ts | 103 ++++++++++++++++++ .../bundled-skill-release-validation.ts | 45 ++++++++ server/src/services/company-skills.ts | 41 +++---- 5 files changed, 240 insertions(+), 24 deletions(-) create mode 100644 server/src/services/bundled-skill-release-validation.test.ts create mode 100644 server/src/services/bundled-skill-release-validation.ts diff --git a/doc/DATABASE.md b/doc/DATABASE.md index 137b7fe1810..966595b7536 100644 --- a/doc/DATABASE.md +++ b/doc/DATABASE.md @@ -185,6 +185,13 @@ queries after any older request. Follow-up reads belong to the current mounted scope and stop when it changes or unmounts. The first open and reconnect still reconcile missed events. +Bundled skill release checks read the current stored version ID and a SHA-256 +fingerprint of its file inventory. A per-database memo keeps at most 64 verified +snapshots. It reuses a verification only when the current database fingerprint +and current on-disk inventory hash both match. A changed or missing snapshot +still follows full validation or seeding. Company access and local source +reconciliation still run for each request; authorization is not cached. + Connection-assignment checks select profile bindings for the current company or agent and read rules that can match the selected connection's catalog rows. All five selector kinds, null application matching, exclusions, and profile diff --git a/server/src/__tests__/company-skills-service.test.ts b/server/src/__tests__/company-skills-service.test.ts index 7217eb4f2be..c1c9a448232 100644 --- a/server/src/__tests__/company-skills-service.test.ts +++ b/server/src/__tests__/company-skills-service.test.ts @@ -16,6 +16,7 @@ import { projectWorkspaces, } from "@paperclipai/db"; import { parseFrontmatterMarkdown } from "@paperclipai/shared"; +import { createDatabaseResponseCapture, installDatabaseResponseCapture } from "@paperclipai/db/response-capture"; import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase, @@ -722,6 +723,73 @@ describeEmbeddedPostgres("companySkillService.list", () => { expect(refreshed.filter((skill) => skill.key === key)).toHaveLength(1); }); + it("validates warm bundled releases without returning their stored file bodies", async () => { + const companyId = randomUUID(); + await db.insert(companies).values({ id: companyId, name: "Release read checks", issuePrefix: "RRC" }); + await svc.list(companyId); + const expected = await svc.list(companyId); + const before = await db.select().from(companySkillVersions).where(eq(companySkillVersions.companyId, companyId)) + .orderBy(companySkillVersions.id); + expect(before.length).toBeGreaterThan(0); + const events: Array> = [], now = Date.now(); + const capture = createDatabaseResponseCapture({ start: now - 100, end: now + 59_000 }, event => events.push(event)); + installDatabaseResponseCapture(db, { companySkillVersions }, capture); + try { expect(await companySkillService(db).list(companyId)).toEqual(expected); } + finally { capture.flush(); } + const reads = events.filter(event => event.event === "paperclip.db_response_capture.entry.v1" + && event.table === "company_skill_versions" && event.operation === "select"); + expect(reads.reduce((sum, event) => sum + Number(event.calls), 0)).toBeGreaterThan(0); + expect(reads.reduce((sum, event) => sum + Number(event.responseValueBytes), 0)).toBeLessThan(4096); + expect(await db.select().from(companySkillVersions).where(eq(companySkillVersions.companyId, companyId)) + .orderBy(companySkillVersions.id)).toEqual(before); + }); + + it.each(["agent", "board"] as const)("checks %s company access before using a warm release validation", async type => { + const companyId = randomUUID(), otherCompanyId = randomUUID(); + await db.insert(companies).values({ id: companyId, name: "Release access checks", issuePrefix: "RAC" }); + await svc.list(companyId); + await svc.list(companyId); + const actor = type === "agent" + ? { type, companyId: otherCompanyId, agentId: randomUUID() } + : { type, companyIds: [otherCompanyId] }; + const events: Array> = [], now = Date.now(); + const capture = createDatabaseResponseCapture({ start: now - 100, end: now + 59_000 }, event => events.push(event)); + installDatabaseResponseCapture(db, { companySkillVersions }, capture); + try { expect(await companySkillService(db, { actor }).list(companyId)).toEqual([]); } + finally { capture.flush(); } + expect(events.find(event => event.event === "paperclip.db_response_capture.summary.v1")?.completedQueries).toBe(0); + }); + + it("restores a deleted release after warm validation", async () => { + const companyId = randomUUID(); + await db.insert(companies).values({ id: companyId, name: "Release deletion checks", issuePrefix: "RDC" }); + await svc.list(companyId); + await svc.list(companyId); + const before = await db.select().from(companySkillVersions).where(eq(companySkillVersions.companyId, companyId)); + const original = before[0]!; + await db.delete(companySkillVersions).where(eq(companySkillVersions.id, original.id)); + await companySkillService(db).list(companyId); + const after = await db.select().from(companySkillVersions).where(eq(companySkillVersions.companyId, companyId)); + expect(after).toHaveLength(before.length); + expect(after.find(version => version.releaseId === original.releaseId)).toMatchObject({ + companyId, companySkillId: original.companySkillId, fileInventory: original.fileInventory, + }); + expect(after.some(version => version.id === original.id)).toBe(false); + }); + + it("rejects a changed bundled snapshot after warm validation without overwriting it", async () => { + const companyId = randomUUID(); + await db.insert(companies).values({ id: companyId, name: "Release integrity checks", issuePrefix: "RIC" }); + await svc.list(companyId); + await svc.list(companyId); + const [version] = await db.select().from(companySkillVersions).where(eq(companySkillVersions.companyId, companyId)); + const changed = [{ path: "SKILL.md", kind: "skill" as const, content: "Changed stored snapshot" }]; + await db.update(companySkillVersions).set({ fileInventory: changed }).where(eq(companySkillVersions.id, version!.id)); + await expect(companySkillService(db).list(companyId)).rejects.toThrow("does not match its seeded snapshot"); + expect((await db.select().from(companySkillVersions).where(eq(companySkillVersions.id, version!.id)))[0]!.fileInventory) + .toEqual(changed); + }); + it("seeds bundled skill releases idempotently and materializes the frozen champion snapshot", async () => { const companyId = randomUUID(); await db.insert(companies).values({ diff --git a/server/src/services/bundled-skill-release-validation.test.ts b/server/src/services/bundled-skill-release-validation.test.ts new file mode 100644 index 00000000000..4c4c1c42857 --- /dev/null +++ b/server/src/services/bundled-skill-release-validation.test.ts @@ -0,0 +1,103 @@ +import { createHash, randomUUID } from "node:crypto"; +import { and, eq } from "drizzle-orm"; +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; +import { companies, companySkills, companySkillVersions, createDb } from "@paperclipai/db"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../__tests__/helpers/embedded-postgres.js"; +import { verifyExistingBundledSkillRelease } from "./bundled-skill-release-validation.js"; + +const support = await getEmbeddedPostgresTestSupport(); +const hashInventory = (files: Array<{ path: string; content: string }>) => createHash("sha256") + .update(JSON.stringify(files.map(file => [file.path, file.content]))).digest("hex"); + +(support.supported ? describe : describe.skip)("bundled release validation with current database fingerprints", () => { + let db: ReturnType; + let temporary: Awaited>; + beforeAll(async () => { + temporary = await startEmbeddedPostgresTestDatabase("bundled-release-validation-"); + db = createDb(temporary.connectionString); + }, 30_000); + afterAll(async () => { await db?.$client.end(); await temporary?.cleanup(); }); + + async function seed(content = "saved release content") { + const companyId = randomUUID(), skillId = randomUUID(); + await db.insert(companies).values({ id: companyId, name: "Release validation", issuePrefix: companyId.slice(0, 8) }); + await db.insert(companySkills).values({ id: skillId, companyId, key: "fixture/release", slug: "release", + name: "Release", markdown: "# Release", sourceType: "local_path" }); + const files = [{ path: "SKILL.md", kind: "skill" as const, content }]; + const [version] = await db.insert(companySkillVersions).values({ companyId, companySkillId: skillId, + revisionNumber: 1, releaseId: "release-1", fileInventory: files }).returning(); + const expectedInventoryHash = hashInventory(files); + const validateInventory = vi.fn((row: typeof companySkillVersions.$inferSelect) => { + if (hashInventory(row.fileInventory) !== expectedInventoryHash) throw new Error("snapshot mismatch"); + }); + return { version: version!, input: { db, companyId, skillId, releaseId: "release-1", expectedInventoryHash, validateInventory } }; + } + + it("reuses proof only within current company, skill and release bindings", async () => { + const f = await seed(); + expect(await verifyExistingBundledSkillRelease(f.input)).toBe(true); + expect(await verifyExistingBundledSkillRelease(f.input)).toBe(true); + expect(f.input.validateInventory).toHaveBeenCalledTimes(1); + expect(await verifyExistingBundledSkillRelease({ ...f.input, companyId: randomUUID() })).toBe(false); + expect(await verifyExistingBundledSkillRelease({ ...f.input, skillId: randomUUID() })).toBe(false); + expect(await verifyExistingBundledSkillRelease({ ...f.input, releaseId: "other-release" })).toBe(false); + expect(f.input.validateInventory).toHaveBeenCalledTimes(1); + expect(await verifyExistingBundledSkillRelease(f.input)).toBe(true); + }); + + it("revalidates when the expected on-disk inventory changes without poisoning valid proof", async () => { + const f = await seed(); + await verifyExistingBundledSkillRelease(f.input); + const changedHash = hashInventory([{ path: "SKILL.md", content: "new on-disk content" }]); + const validateChanged = vi.fn((row: typeof companySkillVersions.$inferSelect) => { + if (hashInventory(row.fileInventory) !== changedHash) throw new Error("snapshot mismatch"); + }); + await expect(verifyExistingBundledSkillRelease({ ...f.input, expectedInventoryHash: changedHash, + validateInventory: validateChanged })).rejects.toThrow("snapshot mismatch"); + expect(validateChanged).toHaveBeenCalledOnce(); + expect(await verifyExistingBundledSkillRelease(f.input)).toBe(true); + expect(f.input.validateInventory).toHaveBeenCalledOnce(); + }); + + it("rechecks current content after a change overlaps an earlier validation", async () => { + const f = await seed(); + let entered!: () => void, release!: () => void; + const validating = new Promise(resolve => { entered = resolve; }); + const held = new Promise(resolve => { release = resolve; }); + const first = verifyExistingBundledSkillRelease({ ...f.input, validateInventory: async row => { + f.input.validateInventory(row); + entered(); + await held; + } }); + await validating; + try { + await db.update(companySkillVersions).set({ fileInventory: [{ path: "SKILL.md", kind: "skill", content: "changed" }] }) + .where(and(eq(companySkillVersions.companyId, f.input.companyId), eq(companySkillVersions.id, f.version.id))); + } finally { release(); } + expect(await first).toBe(true); + await expect(verifyExistingBundledSkillRelease(f.input)).rejects.toThrow("snapshot mismatch"); + expect(f.input.validateInventory).toHaveBeenCalledTimes(2); + }); + + it("does not accept a deleted row from earlier proof", async () => { + const f = await seed(); + await verifyExistingBundledSkillRelease(f.input); + await db.delete(companySkillVersions).where(eq(companySkillVersions.id, f.version.id)); + expect(await verifyExistingBundledSkillRelease(f.input)).toBe(false); + expect(f.input.validateInventory).toHaveBeenCalledOnce(); + }); + + it("bounds retained proof and safely revalidates an evicted release", async () => { + const f = await seed(); + await verifyExistingBundledSkillRelease(f.input); + for (let revisionNumber = 2; revisionNumber <= 66; revisionNumber++) { + const releaseId = `release-${revisionNumber}`; + await db.insert(companySkillVersions).values({ companyId: f.input.companyId, companySkillId: f.input.skillId, + revisionNumber, releaseId, fileInventory: f.version.fileInventory }); + expect(await verifyExistingBundledSkillRelease({ ...f.input, releaseId })).toBe(true); + } + const before = f.input.validateInventory.mock.calls.length; + expect(await verifyExistingBundledSkillRelease(f.input)).toBe(true); + expect(f.input.validateInventory).toHaveBeenCalledTimes(before + 1); + }); +}); diff --git a/server/src/services/bundled-skill-release-validation.ts b/server/src/services/bundled-skill-release-validation.ts new file mode 100644 index 00000000000..b29f8ee28a6 --- /dev/null +++ b/server/src/services/bundled-skill-release-validation.ts @@ -0,0 +1,45 @@ +import { companySkillVersions, type Db } from "@paperclipai/db"; +import { and, eq, getTableColumns, sql } from "drizzle-orm"; + +type Version = typeof companySkillVersions.$inferSelect; +type Verification = { inventorySha256: string; expectedInventoryHash: string }; +const verifiedInventories = new WeakMap>(); +const inventorySha256 = sql`encode(sha256(convert_to(${companySkillVersions.fileInventory}::text, 'UTF8')), 'hex')`; + +export async function verifyExistingBundledSkillRelease(input: { + db: Db; + companyId: string; + skillId: string; + releaseId: string; + expectedInventoryHash: string; + validateInventory: (version: Version) => void | Promise; +}): Promise { + const scope = and(eq(companySkillVersions.companyId, input.companyId), + eq(companySkillVersions.companySkillId, input.skillId), eq(companySkillVersions.releaseId, input.releaseId)); + const [current] = await input.db.select({ id: companySkillVersions.id, inventorySha256 }) + .from(companySkillVersions).where(scope).limit(1); + if (!current) return false; + let verified = verifiedInventories.get(input.db); + if (!verified) { + verified = new Map(); + verifiedInventories.set(input.db, verified); + } + const previous = verified.get(current.id); + if (previous?.inventorySha256 === current.inventorySha256 + && previous.expectedInventoryHash === input.expectedInventoryHash) { + verified.delete(current.id); + verified.set(current.id, previous); + return true; + } + const [version] = await input.db.select({ ...getTableColumns(companySkillVersions), inventorySha256 }) + .from(companySkillVersions).where(scope).limit(1); + if (!version) return false; + await input.validateInventory(version); + verified.delete(version.id); + verified.set(version.id, { inventorySha256: version.inventorySha256, expectedInventoryHash: input.expectedInventoryHash }); + while (verified.size > 64) { + const oldest = verified.keys().next().value; + if (oldest !== undefined) verified.delete(oldest); + } + return true; +} diff --git a/server/src/services/company-skills.ts b/server/src/services/company-skills.ts index ac114ee692f..f29f4ece222 100644 --- a/server/src/services/company-skills.ts +++ b/server/src/services/company-skills.ts @@ -1,4 +1,5 @@ import { ensureSkillCacheDirectory, touchSkillVersionCache, withSkillVersionCacheLock } from "./skill-version-cache.js"; +import { verifyExistingBundledSkillRelease } from "./bundled-skill-release-validation.js"; import { retainProjectSkillAccess, skillAccessService } from "./skill-access.js"; import type { AuthorizationActor } from "./authorization.js"; import { updateAgentConfigurationInTransaction } from "./agent-configuration-transaction.js"; @@ -3094,30 +3095,22 @@ export function companySkillService(db: Db, options: { actor?: AuthorizationActo const fileInventory = serializeVersionFileInventory( await collectVersionFileInventoryFromDirectory(release.releaseDir), ); - const existing = await db - .select() - .from(companySkillVersions) - .where(and( - eq(companySkillVersions.companyId, companyId), - eq(companySkillVersions.companySkillId, paperclipSkill.id), - eq(companySkillVersions.releaseId, release.id), - )) - .then((rows) => rows[0] ?? null); - if (existing) { - const existingInventory = toCompanySkillVersion(existing).fileInventory; - const existingHash = buildInventoryContentHash(existingInventory.map((entry) => ({ - path: entry.path, - sha256: sha256Buffer(entry.content), - }))); - const registryHash = buildInventoryContentHash(fileInventory.map((entry) => ({ - path: entry.path, - sha256: sha256Buffer(entry.content), - }))); - if (existingHash !== registryHash) { - throw new Error(`Bundled skill release ${release.id} does not match its seeded snapshot.`); - } - continue; - } + const registryHash = buildInventoryContentHash(fileInventory.map((entry) => ({ + path: entry.path, + sha256: sha256Buffer(entry.content), + }))); + if (await verifyExistingBundledSkillRelease({ db, companyId, skillId: paperclipSkill.id, releaseId: release.id, + expectedInventoryHash: registryHash, validateInventory: existing => { + const existingInventory = toCompanySkillVersion(existing).fileInventory; + const existingHash = buildInventoryContentHash(existingInventory.map((entry) => ({ + path: entry.path, + sha256: sha256Buffer(entry.content), + }))); + if (existingHash !== registryHash) { + throw new Error(`Bundled skill release ${release.id} does not match its seeded snapshot.`); + } + }, + })) continue; const releasedAt = new Date(release.releasedAt); if (Number.isNaN(releasedAt.getTime())) { throw new Error(`Invalid bundled skill release date: ${release.releasedAt}`); From 2a45fd95df352b1e9d20ab366181bc715a06fe35 Mon Sep 17 00:00:00 2001 From: Naeem Akhtar <32741588+naeemakhtar110@users.noreply.github.com> Date: Mon, 26 Oct 2026 00:15:03 +0300 Subject: [PATCH 076/110] Reduce newer-run history reads for attention (#15697) Replace broad newer-run responses with bounded company-scoped existence probes. Read keyless history once per unique agent and preserve existing matching and millisecond rules. Keep all stored run data. Verify with 31 real PostgreSQL attention tests, workspace typecheck, server build, response-budget counterfactuals, full green CI, and Apex 5/5 review. Co-Authored-By: Paperclip --- doc/DATABASE.md | 9 + .../src/__tests__/attention-service.test.ts | 174 +++++++++++++++++- server/src/services/attention.ts | 102 ++++++---- 3 files changed, 249 insertions(+), 36 deletions(-) diff --git a/doc/DATABASE.md b/doc/DATABASE.md index 966595b7536..ed99988523b 100644 --- a/doc/DATABASE.md +++ b/doc/DATABASE.md @@ -49,6 +49,15 @@ and leaves all existing cases passive. Source identities are not grants. ### Task query performance +The attention feed checks for newer runs with company-scoped existence probes. +The probes match the failed run's agent and issue or task context. They preserve +the existing millisecond comparison and empty-context rules. Each batch holds +at most 1,000 failed runs. Retained run history stays in the database; this check +returns only the identifiers of failures that have a newer matching run. +For failures without a task key, it reads the latest keyless timestamp once per +agent. Unique agents are batched separately, so repeated failures do not repeat +the same history scan. Both paths retain the current millisecond comparison. + The issue-lock adapter's release read omits `result_json.stdout` and `result_json.stderr` before transferring a run to the controller. Native context also omits saved launch text, execution-continuation bodies, workspace and diff --git a/server/src/__tests__/attention-service.test.ts b/server/src/__tests__/attention-service.test.ts index 26934470fbd..bf4879957cd 100644 --- a/server/src/__tests__/attention-service.test.ts +++ b/server/src/__tests__/attention-service.test.ts @@ -2,7 +2,8 @@ import { createAgentLifecycle } from "../services/agent-lifecycle.js"; import { randomUUID } from "node:crypto"; import express from "express"; import request from "supertest"; -import { eq } from "drizzle-orm"; +import { eq, sql } from "drizzle-orm"; +import { createDatabaseResponseCapture, installDatabaseResponseCapture } from "@paperclipai/db/response-capture"; import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest"; import { activityLog, @@ -1034,6 +1035,177 @@ describeEmbeddedPostgres("attention service", () => { expect(feed.items.filter((item) => item.sourceKind === "failed_run")).toEqual([]); }); + it("hides a failed run only after a newer run of the same agent on the same issue or task", async () => { + const { companyId, workerId, reviewerId } = await seedCompany("ATK"); + const taskIssueId = await insertIssue({ companyId, identifier: "ATK-1", title: "Task-keyed", status: "in_progress" }); + const issueKeyedId = await insertIssue({ companyId, identifier: "ATK-2", title: "Issue-keyed", status: "in_progress" }); + const otherIssueId = await insertIssue({ companyId, identifier: "ATK-3", title: "Other work", status: "in_progress" }); + const failedAt = new Date("2026-07-09T12:00:00.000Z"); + const laterAt = new Date("2026-07-09T12:01:00.000Z"); + const taskKeyedFailureId = randomUUID(); + const issueKeyedFailureId = randomUUID(); + const unkeyedHiddenFailureId = randomUUID(); + const unkeyedKeptFailureId = randomUUID(); + const failureIds = [taskKeyedFailureId, issueKeyedFailureId, unkeyedHiddenFailureId, unkeyedKeptFailureId]; + const sameMillisecondRunId = randomUUID(); + const run = (id: string, agentId: string, status: string, contextSnapshot: Record, at: Date) => ({ + id, companyId, agentId, invocationSource: "automation", status, contextSnapshot, + createdAt: at, updatedAt: at, finishedAt: at, ...(status === "failed" ? { error: "adapter failed" } : {}), + }); + + await db.insert(heartbeatRuns).values([ + run(taskKeyedFailureId, workerId, "failed", { taskId: taskIssueId }, failedAt), + run(issueKeyedFailureId, workerId, "failed", { issueId: issueKeyedId }, failedAt), + run(unkeyedHiddenFailureId, workerId, "failed", {}, failedAt), + run(unkeyedKeptFailureId, reviewerId, "failed", {}, failedAt), + run(randomUUID(), workerId, "succeeded", { taskId: taskIssueId }, laterAt), + run(randomUUID(), workerId, "succeeded", { wakeReason: "timer" }, laterAt), + run(randomUUID(), reviewerId, "succeeded", { issueId: issueKeyedId }, laterAt), + run(randomUUID(), reviewerId, "succeeded", { issueId: otherIssueId }, laterAt), + run(randomUUID(), workerId, "succeeded", { issueId: otherIssueId }, laterAt), + run(randomUUID(), workerId, "succeeded", { issueId: otherIssueId, taskId: issueKeyedId }, laterAt), + run(randomUUID(), workerId, "succeeded", { issueId: "", taskId: issueKeyedId }, laterAt), + run(sameMillisecondRunId, workerId, "succeeded", { issueId: issueKeyedId }, failedAt), + run(randomUUID(), workerId, "succeeded", { issueId: issueKeyedId }, new Date("2026-07-09T11:59:00.000Z")), + ]); + await db.execute(sql`update heartbeat_runs set created_at = created_at + interval '400 microseconds' + where id in (${sql.join(failureIds.map((id) => sql`${id}::uuid`), sql`, `)})`); + await db.execute(sql`update heartbeat_runs set created_at = created_at + interval '600 microseconds' + where id = ${sameMillisecondRunId}::uuid`); + await db.insert(heartbeatRunEvents).values( + failureIds.map((runId) => ({ + companyId, + runId, + agentId: runId === unkeyedKeptFailureId ? reviewerId : workerId, + seq: 1, + eventType: "lifecycle", + message: "Bounded retry exhausted after 4 scheduled attempts; no further automatic retry will be queued", + createdAt: new Date("2026-07-09T12:00:01.000Z"), + })), + ); + + const feed = await attentionService(db).list(companyId, { userId: "board-user" }); + + expect(feed.items.filter((item) => item.sourceKind === "failed_run").map((item) => item.subject.id).sort()) + .toEqual([issueKeyedFailureId, unkeyedKeptFailureId].sort()); + }); + + it("keeps newer-run response size bounded despite unrelated retained history", async () => { + const { companyId, workerId } = await seedCompany("ATW"); + const issueId = await insertIssue({ companyId, identifier: "ATW-1", title: "Exhausted task", status: "in_progress" }); + const otherIssueId = await insertIssue({ companyId, identifier: "ATW-2", title: "Other task", status: "done" }); + const failedId = randomUUID(), failedAt = new Date("2026-07-09T12:00:00.000Z"); + await db.insert(heartbeatRuns).values({ + id: failedId, companyId, agentId: workerId, status: "failed", contextSnapshot: { issueId }, + createdAt: failedAt, updatedAt: failedAt, finishedAt: failedAt, + }); + await db.insert(heartbeatRunEvents).values({ + companyId, agentId: workerId, runId: failedId, seq: 1, eventType: "lifecycle", + message: "Bounded retry exhausted after scheduled attempts", + }); + for (let batch = 0; batch < 4; batch += 1) { + await db.insert(heartbeatRuns).values(Array.from({ length: 500 }, (_, index) => ({ + id: randomUUID(), companyId, agentId: workerId, status: "succeeded", + contextSnapshot: { issueId: otherIssueId, prompt: "x".repeat(8_000) }, + createdAt: new Date(failedAt.getTime() + batch * 500 + index + 1), + updatedAt: failedAt, finishedAt: failedAt, + }))); + } + const events: Array> = [], now = Date.now(); + const capture = createDatabaseResponseCapture({ start: now - 100, end: now + 59_000 }, event => events.push(event)); + installDatabaseResponseCapture(db, { heartbeatRuns }, capture); + try { + const feed = await attentionService(db).list(companyId, { userId: "board-user" }); + expect(feed.items.filter(item => item.sourceKind === "failed_run").map(item => item.subject.id)).toEqual([failedId]); + } finally { capture.flush(); } + const reads = events.filter(event => event.event === "paperclip.db_response_capture.entry.v1" + && event.table === "heartbeat_runs" && (event.operation === "select" || event.operation === "execute")); + expect(reads.reduce((sum, event) => sum + Number(event.calls), 0)).toBeGreaterThan(0); + expect(reads.reduce((sum, event) => sum + Number(event.rows), 0)).toBeLessThan(64); + expect(reads.reduce((sum, event) => sum + Number(event.responseValueBytes), 0)).toBeLessThan(4096); + expect(reads.filter(event => event.operation === "execute") + .reduce((sum, event) => sum + Number(event.calls), 0)).toBeGreaterThan(0); + const [remaining] = await db.select({ count: sql`count(*)::int` }).from(heartbeatRuns) + .where(eq(heartbeatRuns.companyId, companyId)); + expect(remaining?.count).toBe(2001); + }); + + it("reads keyless history once per agent despite thousands of failures", async () => { + const { companyId, workerId, reviewerId } = await seedCompany("ATB"); + const failedAt = new Date("2026-07-09T12:00:00.000Z"); + const laterAt = new Date("2026-07-09T12:01:00.000Z"); + const hiddenIds = Array.from({ length: 16_390 }, () => randomUUID()); + const keptIds = Array.from({ length: 10 }, () => randomUUID()); + const failure = (id: string, agentId: string) => ({ + id, companyId, agentId, invocationSource: "automation", status: "failed", error: "adapter failed", + contextSnapshot: {}, createdAt: failedAt, updatedAt: failedAt, finishedAt: failedAt, + }); + const failures = hiddenIds.map((id) => failure(id, workerId)); + keptIds.forEach((id, index) => failures.splice(index * 1_700, 0, failure(id, reviewerId))); + for (let start = 0; start < failures.length; start += 1_000) { + const chunk = failures.slice(start, start + 1_000); + await db.insert(heartbeatRuns).values(chunk); + await db.insert(heartbeatRunEvents).values(chunk.map((run) => ({ + companyId, runId: run.id, agentId: run.agentId, seq: 1, eventType: "lifecycle", + message: "Bounded retry exhausted after 4 scheduled attempts; no further automatic retry will be queued", + createdAt: new Date("2026-07-09T12:00:01.000Z"), + }))); + } + await db.insert(heartbeatRuns).values({ + id: randomUUID(), companyId, agentId: workerId, invocationSource: "automation", status: "succeeded", + contextSnapshot: { wakeReason: "timer" }, createdAt: laterAt, updatedAt: laterAt, finishedAt: laterAt, + }); + + const events: Array> = [], now = Date.now(); + const capture = createDatabaseResponseCapture({ start: now - 100, end: now + 59_000 }, event => events.push(event)); + installDatabaseResponseCapture(db, { heartbeatRuns }, capture); + try { + const feed = await attentionService(db).list(companyId, { + includeDismissed: true, all: true, allowUnscopedAll: true, + }); + expect(feed.items.filter((item) => item.sourceKind === "failed_run").map((item) => item.subject.id).sort()) + .toEqual([...keptIds].sort()); + } finally { capture.flush(); } + const reads = events.filter(event => event.event === "paperclip.db_response_capture.entry.v1" + && event.table === "heartbeat_runs" && (event.operation === "select" || event.operation === "execute")); + expect(reads.reduce((sum, event) => sum + Number(event.calls), 0)).toBeGreaterThan(0); + expect(reads.reduce((sum, event) => sum + Number(event.calls), 0)).toBeLessThan(4); + }, 180_000); + + it("checks more failed runs for a newer run than one statement can bind", async () => { + const { companyId, workerId, reviewerId } = await seedCompany("ATQ"); + const issueId = await insertIssue({ companyId, identifier: "ATQ-1", title: "Keyed retained failures", status: "in_progress" }); + const failedAt = new Date("2026-07-09T12:00:00.000Z"); + const laterAt = new Date("2026-07-09T12:01:00.000Z"); + const hiddenIds = Array.from({ length: 16_390 }, () => randomUUID()); + const keptIds = Array.from({ length: 10 }, () => randomUUID()); + const failure = (id: string, agentId: string) => ({ + id, companyId, agentId, invocationSource: "automation", status: "failed", error: "adapter failed", + contextSnapshot: { issueId }, createdAt: failedAt, updatedAt: failedAt, finishedAt: failedAt, + }); + const failures = hiddenIds.map((id) => failure(id, workerId)); + keptIds.forEach((id, index) => failures.splice(index * 1_700, 0, failure(id, reviewerId))); + for (let start = 0; start < failures.length; start += 1_000) { + const chunk = failures.slice(start, start + 1_000); + await db.insert(heartbeatRuns).values(chunk); + await db.insert(heartbeatRunEvents).values(chunk.map((run) => ({ + companyId, runId: run.id, agentId: run.agentId, seq: 1, eventType: "lifecycle", + message: "Bounded retry exhausted after 4 scheduled attempts; no further automatic retry will be queued", + createdAt: new Date("2026-07-09T12:00:01.000Z"), + }))); + } + await db.insert(heartbeatRuns).values({ + id: randomUUID(), companyId, agentId: workerId, invocationSource: "automation", status: "succeeded", + contextSnapshot: { issueId }, createdAt: laterAt, updatedAt: laterAt, finishedAt: laterAt, + }); + + const feed = await attentionService(db).list(companyId, { + includeDismissed: true, all: true, allowUnscopedAll: true, + }); + expect(feed.items.filter(item => item.sourceKind === "failed_run").map(item => item.subject.id).sort()) + .toEqual([...keptIds].sort()); + }, 180_000); + it("enriches interaction details with project, workspace, plan metadata, and images", async () => { const { companyId, workerId } = await seedCompany("ATE"); const projectId = randomUUID(); diff --git a/server/src/services/attention.ts b/server/src/services/attention.ts index dd46de7d91e..90ed24f135e 100644 --- a/server/src/services/attention.ts +++ b/server/src/services/attention.ts @@ -1099,6 +1099,65 @@ function readRunIssueId(contextSnapshot: Record | null) { return typeof issueId === "string" && issueId.length > 0 ? issueId : null; } +type FailedRunProbe = { id: string; agentId: string; issueId: string | null; createdAt: Date }; + +const FAILED_RUN_PROBE_BATCH_SIZE = 1000; + +async function listFailedRunsWithNewerRun(db: Db, companyId: string, failedRuns: FailedRunProbe[]) { + const withNewerRun = new Set(); + const keyed = failedRuns.filter(run => run.issueId !== null); + for (let start = 0; start < keyed.length; start += FAILED_RUN_PROBE_BATCH_SIZE) { + const batch = keyed.slice(start, start + FAILED_RUN_PROBE_BATCH_SIZE); + for (const id of await listFailedRunBatchWithNewerRun(db, companyId, batch)) withNewerRun.add(id); + } + const unkeyed = failedRuns.filter(run => run.issueId === null); + if (unkeyed.length === 0) return withNewerRun; + const agentIds = [...new Set(unkeyed.map(run => run.agentId))]; + const oldestCreatedAt = unkeyed.reduce((oldest, run) => run.createdAt < oldest ? run.createdAt : oldest, + unkeyed[0]!.createdAt); + const latestByAgent = new Map(); + for (let start = 0; start < agentIds.length; start += FAILED_RUN_PROBE_BATCH_SIZE) { + const rows = await db.select({ + agentId: heartbeatRuns.agentId, + createdAt: sql`max(${heartbeatRuns.createdAt})`.mapWith(heartbeatRuns.createdAt), + }).from(heartbeatRuns).where(and( + eq(heartbeatRuns.companyId, companyId), + inArray(heartbeatRuns.agentId, agentIds.slice(start, start + FAILED_RUN_PROBE_BATCH_SIZE)), + gt(heartbeatRuns.createdAt, oldestCreatedAt), + sql`coalesce(${heartbeatRuns.contextSnapshot} ->> 'issueId', ${heartbeatRuns.contextSnapshot} ->> 'taskId', '') = ''`, + )).groupBy(heartbeatRuns.agentId); + for (const row of rows) latestByAgent.set(row.agentId, row.createdAt); + } + for (const run of unkeyed) { + if ((latestByAgent.get(run.agentId)?.getTime() ?? 0) > run.createdAt.getTime()) withNewerRun.add(run.id); + } + return withNewerRun; +} + +async function listFailedRunBatchWithNewerRun(db: Db, companyId: string, failedRuns: FailedRunProbe[]) { + if (failedRuns.length === 0) return []; + const failed = sql.join( + failedRuns.map((run) => sql`(${run.id}::uuid, ${run.agentId}::uuid, ${run.issueId}::text, ${new Date(run.createdAt.getTime() + 1).toISOString()}::timestamptz)`), + sql`, `, + ); + const runIssueId = sql`(${heartbeatRuns.contextSnapshot} ->> 'issueId')`; + const runTaskId = sql`(${heartbeatRuns.contextSnapshot} ->> 'taskId')`; + const newerRunExists = (match: SQL) => sql`exists ( + select 1 from ${heartbeatRuns} + where ${heartbeatRuns.companyId} = ${companyId} + and ${heartbeatRuns.agentId} = failed.agent_id + and ${heartbeatRuns.createdAt} >= failed.newer_from + and ${match} + )`; + const rows = await db.execute(sql` + select failed.id + from (values ${failed}) as failed (id, agent_id, issue_id, newer_from) + where ${newerRunExists(sql`${runIssueId} = failed.issue_id`)} + or ${newerRunExists(sql`${runTaskId} = failed.issue_id and ${runIssueId} is null`)} + `) as unknown as Array<{ id: string }>; + return rows.map((row) => row.id); +} + export function attentionService(db: Db, serviceOptions: AttentionServiceOptions = {}) { const openDecisionLimit = Math.min( Math.max(Math.trunc(serviceOptions.openDecisionLimit ?? OPEN_DECISION_DEFAULT_LIMIT), 1), @@ -1717,12 +1776,7 @@ export function attentionService(db: Db, serviceOptions: AttentionServiceOptions const failedRows = await listAttentionExhaustedRuns(db, companyId); const failedIssueIds = failedRows.map((row) => readRunIssueId(row.contextSnapshot)); - const failedAgentIds = [...new Set(failedRows.map((row) => row.agentId))]; - const oldestFailedRunCreatedAt = failedRows.reduce((oldest, row) => { - if (!oldest || row.createdAt < oldest) return row.createdAt; - return oldest; - }, null); - const [failedIssueMap, failedImageMap, newerRuns] = await Promise.all([ + const [failedIssueMap, failedImageMap, failedRunsWithNewerRun] = await Promise.all([ issueSummaryMap( db, companyId, @@ -1730,38 +1784,16 @@ export function attentionService(db: Db, serviceOptions: AttentionServiceOptions readCondition, ), issueImageMap(db, companyId, failedIssueIds, readCondition), - oldestFailedRunCreatedAt && failedAgentIds.length > 0 - ? db - .select({ - agentId: heartbeatRuns.agentId, - createdAt: heartbeatRuns.createdAt, - // Project just the ids readRunIssueId needs; pulling the whole - // context_snapshot detoasts megabytes per feed build. - runIssueId: sql`${heartbeatRuns.contextSnapshot} ->> 'issueId'`, - runTaskId: sql`${heartbeatRuns.contextSnapshot} ->> 'taskId'`, - }) - .from(heartbeatRuns) - .where(and( - eq(heartbeatRuns.companyId, companyId), - inArray(heartbeatRuns.agentId, failedAgentIds), - gt(heartbeatRuns.createdAt, oldestFailedRunCreatedAt), - )) - : Promise.resolve([]), + listFailedRunsWithNewerRun(db, companyId, failedRows.map((row, index) => ({ + id: row.id, + agentId: row.agentId, + issueId: failedIssueIds[index], + createdAt: row.createdAt, + }))), ]); - const latestRunCreatedAtByKey = new Map(); - for (const newerRun of newerRuns) { - const newerRunIssueId = readRunIssueId({ issueId: newerRun.runIssueId, taskId: newerRun.runTaskId }); - const newerRunKey = `${newerRun.agentId}:${newerRunIssueId ?? ""}`; - const latestCreatedAt = latestRunCreatedAtByKey.get(newerRunKey); - if (!latestCreatedAt || newerRun.createdAt > latestCreatedAt) { - latestRunCreatedAtByKey.set(newerRunKey, newerRun.createdAt); - } - } for (const run of failedRows) { const issueId = readRunIssueId(run.contextSnapshot); - const runKey = `${run.agentId}:${issueId ?? ""}`; - const hasNewerRun = (latestRunCreatedAtByKey.get(runKey)?.getTime() ?? 0) > run.createdAt.getTime(); - if (hasNewerRun) continue; + if (failedRunsWithNewerRun.has(run.id)) continue; const issue = issueId ? failedIssueMap.get(issueId) ?? null : null; if (issueId && !issue) continue; From f9581e533e899ce6c67ad7b74ee1f38321a348e5 Mon Sep 17 00:00:00 2001 From: Naeem Akhtar <32741588+naeemakhtar110@users.noreply.github.com> Date: Mon, 26 Oct 2026 01:35:36 +0300 Subject: [PATCH 077/110] perf(server): find the native event cursor through the source seq index (#16140) Find the contiguous native cursor in PostgreSQL while preserving gaps, late arrivals, source isolation, and event replay. Verify a long-history response budget against current master. Co-Authored-By: Paperclip --- doc/DATABASE.md | 6 ++ .../heartbeat-run-event-sequencing.test.ts | 101 +++++++++++++++++- server/src/services/heartbeat-run-events.ts | 42 +++++--- 3 files changed, 136 insertions(+), 13 deletions(-) diff --git a/doc/DATABASE.md b/doc/DATABASE.md index ed99988523b..e35cf130381 100644 --- a/doc/DATABASE.md +++ b/doc/DATABASE.md @@ -49,6 +49,12 @@ and leaves all existing cases passive. Source identities are not grants. ### Task query performance +Native event acknowledgements read a count and maximum through the existing +source-sequence index. A stream with gaps uses indexed lookups for its first +missing successor. The acknowledgement keeps its contiguous-prefix rule without +returning every historical sequence number. All events stay stored. Counting the +index entries still grows with the stream length. + The attention feed checks for newer runs with company-scoped existence probes. The probes match the failed run's agent and issue or task context. They preserve the existing millisecond comparison and empty-context rules. Each batch holds diff --git a/server/src/__tests__/heartbeat-run-event-sequencing.test.ts b/server/src/__tests__/heartbeat-run-event-sequencing.test.ts index 28c2dd00d24..d8e7bd0b9cb 100644 --- a/server/src/__tests__/heartbeat-run-event-sequencing.test.ts +++ b/server/src/__tests__/heartbeat-run-event-sequencing.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from "vitest"; -import { eq } from "drizzle-orm"; +import { eq, sql } from "drizzle-orm"; +import { createDatabaseResponseCapture, installDatabaseResponseCapture } from "@paperclipai/db/response-capture"; import { agents, companies, @@ -15,6 +16,62 @@ import { import { startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; describe("P6-11..13 / P6-17 canonical event allocator", () => { + it("keeps native cursor responses bounded with long histories and a late gap fill", async () => { + const temporary = await startEmbeddedPostgresTestDatabase("paperclip-native-cursor-budget-"); + const db = createDb(temporary.connectionString); + const companyId = "20000000-0000-4000-8000-000000000001"; + const agentId = "20000000-0000-4000-8000-000000000002"; + const runId = "20000000-0000-4000-8000-000000000003"; + const otherRunId = "20000000-0000-4000-8000-000000000004"; + try { + await db.insert(companies).values({ id: companyId, name: "Cursor budget", issuePrefix: "CBG" }); + await db.insert(agents).values({ id: agentId, companyId, name: "Cursor agent" }); + await db.insert(heartbeatRuns).values([ + { id: runId, companyId, agentId, status: "running", nextEventSeq: 5005 }, + { id: otherRunId, companyId, agentId, status: "running" }, + ]); + for (let batch = 0; batch < 10; batch += 1) { + await db.insert(heartbeatRunEvents).values(Array.from({ length: 500 }, (_, index) => { + const seq = batch * 500 + index + 1; + return { companyId, agentId, runId, seq, eventType: "item.delta", sourceInstanceId: "runner-a", + sourceSeq: seq, sourceEventId: `seed:${seq}` }; + })); + } + await db.insert(heartbeatRunEvents).values([ + ...[-1, 0, null].map((sourceSeq, index) => ({ + companyId, agentId, runId, seq: 5001 + index, eventType: "item.delta", + sourceInstanceId: "runner-a", sourceSeq, sourceEventId: `legacy:${index}`, + })), + { companyId, agentId, runId, seq: 5004, eventType: "item.delta", sourceInstanceId: "runner-b", + sourceSeq: 5001, sourceEventId: "other-source:5001" }, + { companyId, agentId, runId: otherRunId, seq: 1, eventType: "item.delta", sourceInstanceId: "runner-a", + sourceSeq: 5001, sourceEventId: "other-run:5001" }, + ]); + const append = (sourceSeq: number) => appendHeartbeatRunEvent(db, { + companyId, agentId, runId, eventType: "item.delta", payload: { sourceSeq }, + nativeSource: { sourceInstanceId: "runner-a", sourceSeq, sourceEventId: `runner-a:${sourceSeq}`, + protocolSchemaVersion: 1, canonicalPayload: { sourceSeq } }, + }); + const events: Array> = [], now = Date.now(); + const capture = createDatabaseResponseCapture({ start: now - 100, end: now + 59_000 }, event => events.push(event)); + installDatabaseResponseCapture(db, { heartbeatRunEvents }, capture); + try { expect((await append(5002)).highestContiguousSourceSeq).toBe(5000); } + finally { capture.flush(); } + const reads = events.filter(event => event.event === "paperclip.db_response_capture.entry.v1" + && event.table === "heartbeat_run_events" && (event.operation === "select" || event.operation === "execute")); + expect(reads.reduce((sum, event) => sum + Number(event.calls), 0)).toBeGreaterThan(0); + expect(reads.reduce((sum, event) => sum + Number(event.rows), 0)).toBeLessThan(16); + expect(reads.reduce((sum, event) => sum + Number(event.responseValueBytes), 0)).toBeLessThan(2048); + expect((await append(5001)).highestContiguousSourceSeq).toBe(5002); + const replay = await append(5002); + expect(replay.disposition).toBe("duplicate"); + expect(replay.highestContiguousSourceSeq).toBe(5002); + const [remaining] = await db.select({ count: sql`count(*)::int` }).from(heartbeatRunEvents) + .where(eq(heartbeatRunEvents.runId, runId)); + expect(remaining?.count).toBe(5006); + } finally { await temporary.cleanup(); } + }, 60_000); + it.each([false, true])("deduplicates concurrent retry exhaustion (historical receipt: %s)", async (historical) => { const temporary = await startEmbeddedPostgresTestDatabase("paperclip-exhaustion-events-"); const db = createDb(temporary.connectionString); @@ -165,4 +222,46 @@ describe("P6-11..13 / P6-17 canonical event allocator", () => { await temporary.cleanup(); } }, 60_000); + + it("reports the highest contiguous source seq per source instance across gaps and late arrivals", async () => { + const temporary = await startEmbeddedPostgresTestDatabase("paperclip-native-cursor-"); + const db = createDb(temporary.connectionString); + const companyId = "20000000-0000-4000-8000-000000000001"; + const agentId = "20000000-0000-4000-8000-000000000002"; + const runId = "20000000-0000-4000-8000-000000000003"; + try { + await db.insert(companies).values({ id: companyId, name: "Cursor fixture", issuePrefix: "CUR" }); + await db.insert(agents).values({ id: agentId, companyId, name: "Cursor agent" }); + await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, status: "running" }); + const append = async (sourceInstanceId: string, sourceSeq: number) => (await appendHeartbeatRunEvent(db, { + companyId, + runId, + agentId, + eventType: "item.delta", + payload: { sourceInstanceId, sourceSeq }, + nativeSource: { + sourceInstanceId, + sourceEventId: `${sourceInstanceId}:${sourceSeq}`, + sourceSeq, + protocolSchemaVersion: 1, + canonicalPayload: { sourceInstanceId, sourceSeq }, + }, + })).highestContiguousSourceSeq; + + expect(await append("runner-a", 2)).toBe(0); + expect(await append("runner-a", 1)).toBe(2); + expect(await append("runner-a", 3)).toBe(3); + expect(await append("runner-a", 5)).toBe(3); + expect(await append("runner-a", 6)).toBe(3); + expect(await append("runner-b", 1)).toBe(1); + expect(await append("runner-a", 4)).toBe(6); + for (let sourceSeq = 7; sourceSeq <= 200; sourceSeq += 1) { + expect(await append("runner-a", sourceSeq)).toBe(sourceSeq); + } + expect(await append("runner-b", 3)).toBe(1); + expect(await append("runner-b", 2)).toBe(3); + } finally { + await temporary.cleanup(); + } + }, 60_000); }); diff --git a/server/src/services/heartbeat-run-events.ts b/server/src/services/heartbeat-run-events.ts index ecb7ff5864a..efefbc63b3c 100644 --- a/server/src/services/heartbeat-run-events.ts +++ b/server/src/services/heartbeat-run-events.ts @@ -202,18 +202,36 @@ export async function appendHeartbeatRunEvent( } async function contiguousCursor(db: Db, runId: string, sourceInstanceId: string): Promise { - const rows = await db + const scope = and( + eq(heartbeatRunEvents.runId, runId), + eq(heartbeatRunEvents.sourceInstanceId, sourceInstanceId), + sql`${heartbeatRunEvents.sourceSeq} >= 1`, + ); + const [range] = await db + .select({ + count: sql`count(*)`.mapWith(Number), + max: sql`max(${heartbeatRunEvents.sourceSeq})`.mapWith(Number), + }) + .from(heartbeatRunEvents) + .where(scope); + if (!range || !range.count) return 0; + if (range.max === range.count) return range.count; + const [first] = await db .select({ sourceSeq: heartbeatRunEvents.sourceSeq }) .from(heartbeatRunEvents) - .where(and( - eq(heartbeatRunEvents.runId, runId), - eq(heartbeatRunEvents.sourceInstanceId, sourceInstanceId), - )) - .orderBy(asc(heartbeatRunEvents.sourceSeq)); - let cursor = 0; - for (const row of rows) { - if (row.sourceSeq === cursor + 1) cursor += 1; - else if (row.sourceSeq !== null && row.sourceSeq > cursor + 1) break; - } - return cursor; + .where(and(scope, eq(heartbeatRunEvents.sourceSeq, 1))) + .limit(1); + if (!first) return 0; + const [last] = await db + .select({ sourceSeq: heartbeatRunEvents.sourceSeq }) + .from(heartbeatRunEvents) + .where(and(scope, sql`not exists ( + select 1 from heartbeat_run_events next_event + where next_event.run_id = heartbeat_run_events.run_id + and next_event.source_instance_id = heartbeat_run_events.source_instance_id + and next_event.source_seq = heartbeat_run_events.source_seq + 1 + )`)) + .orderBy(asc(heartbeatRunEvents.sourceSeq)) + .limit(1); + return last?.sourceSeq ?? 0; } From 9f3a5456acda24cab7040daa67cefb321dd73f15 Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Sun, 25 Oct 2026 15:53:18 -0700 Subject: [PATCH 078/110] perf(server): bound run reads in authentication and conversation recovery (#17663) Read compact run identity during authentication and compact turn state during conversation recovery. Preserve fresh checks, durable steering and reply evidence, locking, and complete stored payloads. Validate 184 targeted PostgreSQL and lifecycle tests, workspace typecheck, server build, full CI, and Apex 5/5. Co-Authored-By: Paperclip --- doc/DATABASE.md | 12 ++ .../agent-auth-identity-transfer.test.ts | 102 +++++++++++++++++ .../conversation-settlement-transfer.test.ts | 105 ++++++++++++++++++ server/src/__tests__/run-identity.test.ts | 22 ++-- server/src/middleware/auth.ts | 3 +- server/src/services/agent-conversations.ts | 31 +++++- server/src/services/recovery/service.ts | 4 +- server/src/services/run-identity.ts | 4 +- 8 files changed, 265 insertions(+), 18 deletions(-) create mode 100644 server/src/__tests__/agent-auth-identity-transfer.test.ts create mode 100644 server/src/__tests__/conversation-settlement-transfer.test.ts diff --git a/doc/DATABASE.md b/doc/DATABASE.md index e35cf130381..d5f970ac23d 100644 --- a/doc/DATABASE.md +++ b/doc/DATABASE.md @@ -49,12 +49,24 @@ and leaves all existing cases passive. Source identities are not grants. ### Task query performance +Agent request authentication uses a compact run-identity read. It omits saved +execution payloads, results, and log excerpts from the query response. The read +still locks the task before the run and reconciles pending steering from durable +acknowledgements on every request. Default identity reads retain the full run. +Stored payloads and separate native tool authorization checks remain unchanged. + Native event acknowledgements read a count and maximum through the existing source-sequence index. A stream with gaps uses indexed lookups for its first missing successor. The acknowledgement keeps its contiguous-prefix rule without returning every historical sequence number. All events stay stored. Counting the index entries still grows with the stream length. +Conversation recovery reads only the saved run fields used to settle a turn. +Settlement locks and reads current conversation state without loading the task +description or comment bodies. It still checks the durable reply or pending +interaction, session generation, owning run, and newer user messages. Saved +execution payloads, task text, and comments remain stored in full. + The attention feed checks for newer runs with company-scoped existence probes. The probes match the failed run's agent and issue or task context. They preserve the existing millisecond comparison and empty-context rules. Each batch holds diff --git a/server/src/__tests__/agent-auth-identity-transfer.test.ts b/server/src/__tests__/agent-auth-identity-transfer.test.ts new file mode 100644 index 00000000000..819b23dc64a --- /dev/null +++ b/server/src/__tests__/agent-auth-identity-transfer.test.ts @@ -0,0 +1,102 @@ +import { randomUUID } from "node:crypto"; +import express from "express"; +import request from "supertest"; +import { eq } from "drizzle-orm"; +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; +import { agents, companies, createDb, heartbeatRunEvents, heartbeatRuns, issueComments, issues } from "@paperclipai/db"; +import { createDatabaseResponseCapture, installDatabaseResponseCapture } from "@paperclipai/db/response-capture"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; +import { createLocalAgentJwt } from "../agent-auth-jwt.js"; +import { actorMiddleware } from "../middleware/auth.js"; +import { errorHandler } from "../middleware/error-handler.js"; +import { captureRunIdentity, initializeRunIdentity, reserveSteeredIdentity } from "../services/run-identity.js"; + +const support = await getEmbeddedPostgresTestSupport(); +(support.supported ? describe : describe.skip)("agent authentication identity transfer", () => { + let database: Awaited>; + let db: ReturnType; + beforeAll(async () => { + vi.stubEnv("PAPERCLIP_AGENT_JWT_SECRET", "identity-transfer-test-secret"); + vi.stubEnv("PAPERCLIP_INSTANCE_ID", "default"); + database = await startEmbeddedPostgresTestDatabase("paperclip-auth-identity-transfer-"); + db = createDb(database.connectionString); + }, 30_000); + afterAll(async () => { + vi.unstubAllEnvs(); + await db?.$client.end({ timeout: 5 }); + await database?.cleanup(); + }, 60_000); + + async function seed() { + const companyId = randomUUID(), agentId = randomUUID(), issueId = randomUUID(), runId = randomUUID(); + await db.insert(companies).values({ id: companyId, name: "Authentication transfer", issuePrefix: companyId.slice(0, 8) }); + await db.insert(agents).values({ id: agentId, companyId, name: "Reader", role: "engineer", adapterType: "codex_local", status: "idle" }); + await db.insert(issues).values({ id: issueId, companyId, title: "Authentication task", responsibleUserId: "owner" }); + const padding = "retained input ".repeat(32_768); + const payloads = { + contextSnapshot: { issueId, launchInput: padding }, + runnerProfileJson: { nativeExecutionInput: { savedInput: padding } }, + resultJson: { savedResult: padding }, stdoutExcerpt: padding, stderrExcerpt: padding, + }; + await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, status: "running", ...payloads }); + const identity = await initializeRunIdentity(db, { companyId, runId, issueId, messageIds: [], responsibleUserId: "owner", cause: "instruction" }); + const app = express(); + app.use(actorMiddleware(db, { deploymentMode: "authenticated", resolveSession: async () => null })); + app.get("/actor", (req, res) => res.json(req.actor)); + app.patch("/actor", (req, res) => res.json(req.actor)); + app.use(errorHandler); + const token = createLocalAgentJwt(agentId, companyId, "codex_local", runId, "stale-user"); + expect(token).not.toBeNull(); + return { companyId, agentId, issueId, runId, app, token: token!, identity, payloads }; + } + + it("bounds actual middleware responses and preserves the complete stored run", async () => { + const fixture = await seed(); + const events: Array> = [], now = Date.now(); + const capture = createDatabaseResponseCapture({ start: now - 100, end: now + 59_000 }, event => events.push(event)); + installDatabaseResponseCapture(db, { heartbeatRuns }, capture); + try { + const response = await request(fixture.app).get("/actor").set("Authorization", `Bearer ${fixture.token}`); + expect(response.status).toBe(200); + expect(response.body).toMatchObject({ type: "agent", runId: fixture.runId, + identityContextId: fixture.identity.id, onBehalfOfUserId: "owner" }); + } finally { capture.flush(); } + const reads = events.filter(event => event.event === "paperclip.db_response_capture.entry.v1" + && event.table === "heartbeat_runs" && (event.operation === "select" || event.operation === "execute")); + expect(reads.reduce((sum, event) => sum + Number(event.calls), 0)).toBeGreaterThanOrEqual(3); + expect(reads.reduce((sum, event) => sum + Number(event.responseValueBytes), 0)).toBeLessThan(16_384); + expect((await captureRunIdentity(db, fixture)).run).toMatchObject(fixture.payloads); + }); + + it("blocks uncertain steering, accepts its durable acknowledgement, and rechecks cancellation", async () => { + const fixture = await seed(), messageId = randomUUID(); + await db.insert(issueComments).values({ id: messageId, companyId: fixture.companyId, issueId: fixture.issueId, + authorUserId: "next-user", body: "Next instruction" }); + const pending = await reserveSteeredIdentity(db, { ...fixture, messageId }); + expect(pending).not.toBeNull(); + const blocked = await request(fixture.app).get("/actor").set("Authorization", `Bearer ${fixture.token}`); + expect(blocked.status).toBe(409); + await db.insert(heartbeatRunEvents).values({ companyId: fixture.companyId, agentId: fixture.agentId, runId: fixture.runId, + seq: 1, eventType: "item.completed", sourceEventId: randomUUID(), + payload: { prpEvent: { turnId: "auth-turn", itemId: `auth-turn:steer:${messageId}`, + payload: { kind: "steering_acknowledgement" } } } }); + const accepted = await request(fixture.app).get("/actor").set("Authorization", `Bearer ${fixture.token}`); + expect(accepted.status).toBe(200); + expect(accepted.body).toMatchObject({ identityContextId: pending!.id, onBehalfOfUserId: "next-user" }); + await db.update(heartbeatRuns).set({ status: "cancelled" }).where(eq(heartbeatRuns.id, fixture.runId)); + const revoked = await request(fixture.app).patch("/actor").set("Authorization", `Bearer ${fixture.token}`); + expect(revoked.status).toBe(403); + expect(revoked.body.code).toBe("agent_run_cancelled"); + const [stored] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, fixture.runId)); + expect(stored).toMatchObject(fixture.payloads); + }); + + it.each(["company", "agent", "missing", "finished"] as const)("rejects %s run identity for the compact scope", async (fault) => { + const fixture = await seed(); + if (fault === "finished") await db.update(heartbeatRuns).set({ status: "succeeded" }).where(eq(heartbeatRuns.id, fixture.runId)); + const input = { companyId: fault === "company" ? randomUUID() : fixture.companyId, + agentId: fault === "agent" ? randomUUID() : fixture.agentId, + runId: fault === "missing" ? randomUUID() : fixture.runId }; + await expect(captureRunIdentity(db, input, { readScope: "request_authentication" })).rejects.toThrow(/active run/); + }); +}); diff --git a/server/src/__tests__/conversation-settlement-transfer.test.ts b/server/src/__tests__/conversation-settlement-transfer.test.ts new file mode 100644 index 00000000000..6a128b00e95 --- /dev/null +++ b/server/src/__tests__/conversation-settlement-transfer.test.ts @@ -0,0 +1,105 @@ +import { randomUUID } from "node:crypto"; +import { and, eq, sql } from "drizzle-orm"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { agents, companies, createDb, heartbeatRuns, issueComments, issueThreadInteractions, issues } from "@paperclipai/db"; +import { createDatabaseResponseCapture, installDatabaseResponseCapture } from "@paperclipai/db/response-capture"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; +import { settleConversationTurnForRun } from "../services/agent-conversations.js"; + +const support = await getEmbeddedPostgresTestSupport(); +(support.supported ? describe : describe.skip)("conversation settlement transfer", () => { + let database: Awaited>; + let db: ReturnType; + beforeAll(async () => { + database = await startEmbeddedPostgresTestDatabase("paperclip-conversation-settlement-"); + db = createDb(database.connectionString); + }, 30_000); + afterAll(async () => { await db?.$client.end({ timeout: 5 }); await database?.cleanup(); }, 60_000); + + async function seed(reply: "response" | "interaction" | "reset" | "none" = "response") { + const companyId = randomUUID(), agentId = randomUUID(), issueId = randomUUID(), runId = randomUUID(), wakeId = randomUUID(); + const padding = "saved conversation ".repeat(32_768); + await db.insert(companies).values({ id: companyId, name: "Settlement transfer", issuePrefix: companyId.slice(0, 8) }); + await db.insert(agents).values({ id: agentId, companyId, name: "Conversation agent", role: "engineer" }); + await db.insert(issues).values({ id: issueId, companyId, title: "Conversation", description: padding, + status: "in_progress", conversationState: "active", conversationUserId: "conversation-owner", + conversationAgentId: agentId, assigneeAgentId: agentId, conversationSessionGeneration: 3 }); + await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, status: "succeeded", + contextSnapshot: { issueId, conversationSessionGeneration: 3, wakeCommentId: wakeId, + conversationReset: reply === "reset", savedInput: padding }, + runnerProfileJson: { savedProfile: padding }, resultJson: { savedResult: padding }, + stdoutExcerpt: padding, stderrExcerpt: padding }); + await db.update(issues).set({ executionRunId: runId }).where(eq(issues.id, issueId)); + const wakeTime = new Date(Date.now() - 10_000); + await db.insert(issueComments).values({ id: wakeId, companyId, issueId, authorUserId: "conversation-owner", + body: padding, createdAt: wakeTime }); + if (reply === "response") await db.insert(issueComments).values({ companyId, issueId, + createdByRunId: runId, authorAgentId: agentId, origin: "comment", body: padding }); + if (reply === "interaction") await db.insert(issueThreadInteractions).values({ companyId, issueId, + sourceRunId: runId, createdByAgentId: agentId, status: "pending", kind: "request_confirmation", payload: { version: 1 } }); + return { companyId, agentId, issueId, runId, wakeId, wakeTime }; + } + + async function sourceDigests(input: Awaited>) { + return db.execute(sql`select + (select encode(sha256(convert_to(jsonb_build_array(context_snapshot,runner_profile_json,result_json,stdout_excerpt,stderr_excerpt)::text,'UTF8')),'hex') + from heartbeat_runs where id=${input.runId}::uuid) as run_digest, + (select encode(sha256(convert_to(description,'UTF8')),'hex') from issues where id=${input.issueId}::uuid) as description_digest, + (select encode(sha256(convert_to(jsonb_agg(jsonb_build_array(id,body) order by id)::text,'UTF8')),'hex') + from issue_comments where issue_id=${input.issueId}::uuid) as comments_digest`); + } + + it.each(["response", "interaction", "reset"] as const)("bounds %s settlement reads and retains all saved text and run payloads", async reply => { + const input = await seed(reply), before = await sourceDigests(input); + const events: Array> = [], now = Date.now(); + const capture = createDatabaseResponseCapture({ start: now - 100, end: now + 59_000 }, event => events.push(event)); + installDatabaseResponseCapture(db, { heartbeatRuns, issues, issueComments }, capture); + try { expect(await settleConversationTurnForRun(db, input.companyId, input.runId)).toBe(true); } + finally { capture.flush(); } + const reads = events.filter(event => event.event === "paperclip.db_response_capture.entry.v1" + && ["heartbeat_runs", "issues", "issue_comments"].includes(String(event.table)) + && (event.operation === "select" || event.operation === "execute")); + expect(reads.reduce((sum, event) => sum + Number(event.calls), 0)).toBeGreaterThanOrEqual(4); + expect(reads.reduce((sum, event) => sum + Number(event.responseValueBytes), 0)).toBeLessThan(16_384); + const [issue] = await db.select({ status: issues.status, state: issues.conversationState }).from(issues).where(eq(issues.id, input.issueId)); + expect(issue).toEqual({ status: "in_review", state: "waiting" }); + expect(await sourceDigests(input)).toEqual(before); + }); + + it.each(["conversationReplyBoundaryCommentId", "wakeCommentId", "commentId"] as const)("keeps later user messages active through %s", async key => { + const input = await seed(); + await db.update(heartbeatRuns).set({ contextSnapshot: { issueId: input.issueId, + conversationSessionGeneration: 3, [key]: input.wakeId } }).where(eq(heartbeatRuns.id, input.runId)); + await db.insert(issueComments).values({ companyId: input.companyId, issueId: input.issueId, + authorUserId: "conversation-owner", body: "A new instruction", createdAt: new Date(input.wakeTime.getTime() + 1000) }); + expect(await settleConversationTurnForRun(db, input.companyId, input.runId)).toBe(true); + const [issue] = await db.select({ status: issues.status, state: issues.conversationState }).from(issues).where(eq(issues.id, input.issueId)); + expect(issue).toEqual({ status: "in_progress", state: "active" }); + }); + + it.each(["missing", "company", "issue-company", "generation", "owner", "failed", "no-reply"] as const)("refuses to settle a %s mismatch", async fault => { + const input = await seed(fault === "no-reply" ? "none" : "response"); + if (fault === "generation") await db.update(heartbeatRuns).set({ contextSnapshot: { issueId: input.issueId, + conversationSessionGeneration: 2, wakeCommentId: input.wakeId } }).where(eq(heartbeatRuns.id, input.runId)); + if (fault === "owner") { + const otherRun = randomUUID(); + await db.insert(heartbeatRuns).values({ id: otherRun, companyId: input.companyId, agentId: input.agentId }); + await db.update(issues).set({ executionRunId: otherRun }).where(eq(issues.id, input.issueId)); + } + if (fault === "failed") await db.update(heartbeatRuns).set({ status: "failed" }).where(eq(heartbeatRuns.id, input.runId)); + if (fault === "issue-company") { + const otherCompany = randomUUID(), otherIssue = randomUUID(), otherAgent = randomUUID(); + await db.insert(companies).values({ id: otherCompany, name: "Other company", issuePrefix: otherCompany.slice(0, 8) }); + await db.insert(agents).values({ id: otherAgent, companyId: otherCompany, name: "Other agent" }); + await db.insert(issues).values({ id: otherIssue, companyId: otherCompany, title: "Other conversation", + conversationUserId: "other-owner", conversationAgentId: otherAgent, assigneeAgentId: otherAgent, + conversationState: "active", conversationSessionGeneration: 3 }); + await db.update(heartbeatRuns).set({ contextSnapshot: { issueId: otherIssue, conversationSessionGeneration: 3, + conversationReset: true } }).where(eq(heartbeatRuns.id, input.runId)); + } + expect(await settleConversationTurnForRun(db, fault === "company" ? randomUUID() : input.companyId, + fault === "missing" ? randomUUID() : input.runId)).toBe(false); + const [issue] = await db.select({ status: issues.status }).from(issues).where(and(eq(issues.id, input.issueId), eq(issues.companyId, input.companyId))); + expect(issue.status).toBe("in_progress"); + }); +}); diff --git a/server/src/__tests__/run-identity.test.ts b/server/src/__tests__/run-identity.test.ts index b371c59f043..069139a8123 100644 --- a/server/src/__tests__/run-identity.test.ts +++ b/server/src/__tests__/run-identity.test.ts @@ -29,14 +29,14 @@ const support = await getEmbeddedPostgresTestSupport(); } return { companyId, agentId, issueId, runId, messageIds }; } - it("retains typed GitHub trust bindings and keeps other identity reads complete", async () => { + it.each(["github_credentials", "request_authentication"] as const)("retains typed trust bindings for %s and keeps other identity reads complete", async (readScope) => { const input = await seed(); await initializeRunIdentity(db, { ...input, responsibleUserId: "owner", cause: "queued" }); for (const value of [null, true, 42, " padded ", [], {}, { future: { opaque: true } }]) { const contextSnapshot = { issueId: input.issueId, projectId: value, executionPolicy: value, savedInput: { retained: true } }; const runnerProfileJson = { nativeExecutionInput: { opaque: value }, savedInput: "retained" }; await db.update(heartbeatRuns).set({ contextSnapshot, runnerProfileJson }).where(eq(heartbeatRuns.id, input.runId)); - const narrow = await captureRunIdentity(db, input, { readScope: "github_credentials" }); + const narrow = await captureRunIdentity(db, input, { readScope }); expect(narrow.run.contextSnapshot).toEqual({ issueId: input.issueId, taskId: null, projectId: value, executionPolicy: value }); expect(narrow.run.runnerProfileJson).toBeNull(); const full = await captureRunIdentity(db, input); @@ -123,24 +123,25 @@ const support = await getEmbeddedPostgresTestSupport(); }, ); - it("holds acquisition during uncertain steering, preserves snapshots, and never rewinds on replay", async () => { + it.each([undefined, "github_credentials", "request_authentication"] as const)("holds acquisition during uncertain steering and never rewinds on replay with %s", async (readScope) => { + const options = readScope ? { readScope } : undefined; const input = await seed(); await initializeRunIdentity(db, { ...input, messageIds: [input.messageIds[0]], responsibleUserId: "A", cause: "instruction" }); - const startedUnderA = await captureRunIdentity(db, input); + const startedUnderA = await captureRunIdentity(db, input, options); const b = await reserveSteeredIdentity(db, { ...input, messageId: input.messageIds[1] }); expect(b).not.toBeNull(); - await expect(captureRunIdentity(db, input)).rejects.toThrow(/reconciled/); + await expect(captureRunIdentity(db, input, options)).rejects.toThrow(/reconciled/); await expect(reserveSteeredIdentity(db, { ...input, messageId: input.messageIds[2] })).rejects.toThrow(/reconciled/); await db.transaction(async tx => { await tx.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, input.runId)).for("update"); await acceptSteeredIdentity(tx, b!); }); - expect((await captureRunIdentity(db, input)).context?.responsibleUserId).toBe("B"); + expect((await captureRunIdentity(db, input, options)).context?.responsibleUserId).toBe("B"); expect(startedUnderA.context?.responsibleUserId).toBe("A"); const a = await reserveSteeredIdentity(db, { ...input, messageId: input.messageIds[2] }); await acceptSteeredIdentity(db, a!); await acceptSteeredIdentity(db, b!); - expect((await captureRunIdentity(db, input)).context?.responsibleUserId).toBe("A"); + expect((await captureRunIdentity(db, input, options)).context?.responsibleUserId).toBe("A"); }); it("keeps rejected steering unchanged and preserves the originating identity on retry", async () => { const input = await seed(); @@ -175,16 +176,17 @@ const support = await getEmbeddedPostgresTestSupport(); expect(captured.run.responsibleUserId).toBeNull(); expect(captured.context?.parentContextId).toBe(origin.id); }); - it("recovers an uncertain acknowledgement from the authenticated native event journal", async () => { + it.each([undefined, "github_credentials", "request_authentication"] as const)("recovers an uncertain native acknowledgement with %s", async (readScope) => { + const options = readScope ? { readScope } : undefined; const input = await seed(); await initializeRunIdentity(db, { ...input, messageIds: [], responsibleUserId: "A", cause: "instruction" }); const pending = await reserveSteeredIdentity(db, { ...input, messageId: input.messageIds[1] }); - await expect(captureRunIdentity(db, input)).rejects.toThrow(/reconciled/); + await expect(captureRunIdentity(db, input, options)).rejects.toThrow(/reconciled/); await db.insert(heartbeatRunEvents).values({ companyId: input.companyId, runId: input.runId, agentId: input.agentId, seq: 1, eventType: "item.completed", sourceEventId: randomUUID(), payload: { prpEvent: { turnId: "turn-1", itemId: `turn-1:steer:${pending!.messageId}`, payload: {kind: "steering_acknowledgement"} } }, }); - expect((await captureRunIdentity(db, input)).context?.responsibleUserId).toBe("B"); + expect((await captureRunIdentity(db, input, options)).context?.responsibleUserId).toBe("B"); await db.update(heartbeatRuns).set({status: "succeeded"}).where(eq(heartbeatRuns.id, input.runId)); expect((await reserveSteeredIdentity(db, { ...input, messageId: input.messageIds[1] }))?.status).toBe("accepted"); }); diff --git a/server/src/middleware/auth.ts b/server/src/middleware/auth.ts index 8504fc3c853..86347bb40d5 100644 --- a/server/src/middleware/auth.ts +++ b/server/src/middleware/auth.ts @@ -429,7 +429,8 @@ export function actorMiddleware(db: Db, opts: ActorMiddlewareOptions): RequestHa return; } if (identityRun?.activeIdentityContextId && identityRun.status === "running") { - const captured = await captureRunIdentity(db, { companyId: claims.company_id, agentId: claims.sub, runId: claims.run_id }); + const captured = await captureRunIdentity(db, { companyId: claims.company_id, agentId: claims.sub, runId: claims.run_id }, + { readScope: "request_authentication" }); identityRun.activeIdentityContextId = captured.context?.id ?? null; identityRun.responsibleUserId = captured.context?.responsibleUserId ?? null; } diff --git a/server/src/services/agent-conversations.ts b/server/src/services/agent-conversations.ts index a2ec8f74b01..b6cfd1a7337 100644 --- a/server/src/services/agent-conversations.ts +++ b/server/src/services/agent-conversations.ts @@ -282,7 +282,7 @@ export async function prepareConversationTurn( /** Finalizers only park a turn with a durable response, interaction, or processed /new. */ export async function settleConversationTurn( db: Db, - run: typeof heartbeatRuns.$inferSelect, + run: Pick, ) { if (run.status !== "succeeded") return false; const context = run.contextSnapshot ?? {}; @@ -291,7 +291,12 @@ export async function settleConversationTurn( let publication: ActivityPublication | null = null; const settled = await db.transaction(async (tx) => { const [issue] = await tx - .select() + .select({ + id: issues.id, companyId: issues.companyId, status: issues.status, + conversationAgentId: issues.conversationAgentId, conversationUserId: issues.conversationUserId, + conversationState: issues.conversationState, conversationSessionGeneration: issues.conversationSessionGeneration, + executionRunId: issues.executionRunId, + }) .from(issues) .where(and(eq(issues.id, issueId), eq(issues.companyId, run.companyId))) .for("update"); @@ -344,7 +349,7 @@ export async function settleConversationTurn( const [wake] = typeof wakeId === "string" ? await tx - .select() + .select({ id: issueComments.id }) .from(issueComments) .where(eq(issueComments.id, wakeId)) : []; @@ -407,6 +412,26 @@ export async function settleConversationTurn( return settled; } +export async function settleConversationTurnForRun( + db: Db, + companyId: string, + runId: string, +) { + const [run] = await db.select({ + id: heartbeatRuns.id, companyId: heartbeatRuns.companyId, status: heartbeatRuns.status, + contextSnapshot: sql | null>`case when jsonb_typeof(${heartbeatRuns.contextSnapshot}) = 'object' + then jsonb_build_object( + 'issueId', ${heartbeatRuns.contextSnapshot}->'issueId', + 'conversationReset', ${heartbeatRuns.contextSnapshot}->'conversationReset', + 'conversationSessionGeneration', ${heartbeatRuns.contextSnapshot}->'conversationSessionGeneration', + 'conversationReplyBoundaryCommentId', ${heartbeatRuns.contextSnapshot}->'conversationReplyBoundaryCommentId', + 'wakeCommentId', ${heartbeatRuns.contextSnapshot}->'wakeCommentId', + 'commentId', ${heartbeatRuns.contextSnapshot}->'commentId' + ) else null end`, + }).from(heartbeatRuns).where(and(eq(heartbeatRuns.id, runId), eq(heartbeatRuns.companyId, companyId))); + return run ? settleConversationTurn(db, run) : false; +} + /** Fresh provider context uses only messages in this session, up to this turn. */ export async function conversationReplay( db: Db, diff --git a/server/src/services/recovery/service.ts b/server/src/services/recovery/service.ts index 488ef813306..3bbf40ab0d2 100644 --- a/server/src/services/recovery/service.ts +++ b/server/src/services/recovery/service.ts @@ -21,7 +21,7 @@ import { import { CONTROLLER_LEASE_LOST_FAILURE_CODE, hasLiveLegacyController } from "../legacy-controller-lease.js"; import { isCompletedOnboardingHandoffWake } from "../chat-completion-delivery.js"; import { instanceSettingsService } from "../instance-settings.js"; -import { isWaitingConversation, settleConversationTurn, deliverConversationComments } from "../agent-conversations.js"; +import { isWaitingConversation, settleConversationTurnForRun, deliverConversationComments } from "../agent-conversations.js"; import { and, asc, @@ -4582,7 +4582,7 @@ export function recoveryService( if (issue.conversationAgentId) { const lastRun = await getLatestIssueRun(issue.companyId, issue.id); if (lastRun?.status === "succeeded") { - if (await settleConversationTurn(db, (await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, lastRun.id)))[0]!)) { + if (await settleConversationTurnForRun(db, issue.companyId, lastRun.id)) { const [current] = await db.select().from(issues).where(eq(issues.id, issue.id)); if (current) Object.assign(issue, current); } diff --git a/server/src/services/run-identity.ts b/server/src/services/run-identity.ts index b1e27d1ae72..2f1e9e97d65 100644 --- a/server/src/services/run-identity.ts +++ b/server/src/services/run-identity.ts @@ -434,13 +434,13 @@ export async function acceptSteeredIdentity( export async function captureRunIdentity( db: Db, input: { companyId: string; runId: string; agentId: string }, - options?: { readScope: "github_credentials" }, + options?: { readScope: "github_credentials" | "request_authentication" }, ) { // Lock acquisition serializes with steering delivery and its durable acknowledgement. return db.transaction(async (tx) => { await lockIdentityTask(tx, input.companyId, input.runId); const [run] = await tx - .select(options?.readScope === "github_credentials" ? { + .select(options?.readScope === "github_credentials" || options?.readScope === "request_authentication" ? { ...getTableColumns(heartbeatRuns), contextSnapshot: sql | null>`case when jsonb_typeof(${heartbeatRuns.contextSnapshot}) = 'object' then jsonb_build_object('issueId', ${heartbeatRuns.contextSnapshot}->'issueId', From 5a28f7acf8a8c86536c4f5c5369bfeb49a46c41a Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Sun, 25 Oct 2026 16:06:36 -0700 Subject: [PATCH 079/110] fix(server): include restored monitor proof in assessment identity (#17665) Include validated preserved monitor proof in the immutable assessment input so restored receipts or completion times can produce a new status decision at the same deadline. Preserve accepted results, earlier decisions, provider attempts, monitor deadlines, and idempotent replay. Validate two baseline regressions, 201 targeted tests on current master, workspace typecheck, server build, full CI, and Apex 5/5. Co-Authored-By: Paperclip --- doc/DATABASE.md | 5 ++++ .../native-preserved-monitor-wait.test.ts | 25 ++++++++++++++++--- .../native-runtime/native-run-finalizer.ts | 1 + .../native-runtime/work-assessments.ts | 4 ++- 4 files changed, 30 insertions(+), 5 deletions(-) diff --git a/doc/DATABASE.md b/doc/DATABASE.md index d5f970ac23d..cb341f8ea79 100644 --- a/doc/DATABASE.md +++ b/doc/DATABASE.md @@ -175,6 +175,11 @@ launch context does not travel with each policy or parent-report check. JSON types, task-key precedence, and company and agent identity checks are preserved. Each decision still reads current data; this is not an authorization cache. +Restoring a saved monitor's receipt or completion proof creates a new native +assessment identity even when its scheduled deadline is unchanged. The saved +proof is part of the assessment input. Prior decisions and accepted results stay +intact, and an unchanged replay reuses the same assessment and decision. + Native tool authority lookups select current run identity, status, invocation, responsible user, context, and receipt data. Saved profiles and output excerpts stay in storage and are omitted from that read. Task and agent binding, current diff --git a/server/src/services/native-runtime/native-preserved-monitor-wait.test.ts b/server/src/services/native-runtime/native-preserved-monitor-wait.test.ts index ad269c7467c..1cedcb28be8 100644 --- a/server/src/services/native-runtime/native-preserved-monitor-wait.test.ts +++ b/server/src/services/native-runtime/native-preserved-monitor-wait.test.ts @@ -126,21 +126,38 @@ describe.skipIf(!support.supported)("released native monitor results", () => { }, ); - it("supersedes an earlier authority error without replaying the accepted result", async () => { + it.each(["schedule", "receipt", "finished_time"] as const)("supersedes an earlier authority error after restoring %s without replaying the result", async state => { const f = await fixture(), scheduled = await f.readIssue(); - await db.update(issues).set({ executionPolicy: {}, monitorNextCheckAt: null }).where(eq(issues.id, f.issueId)); + const [source] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId)); + await db.update(nativeRunFinalizations).set({ controllerBootId: randomUUID(), attempt: 1 }) + .where(eq(nativeRunFinalizations.runId, f.runId)); + if (state === "schedule") await db.update(issues).set({ executionPolicy: {}, monitorNextCheckAt: null }).where(eq(issues.id, f.issueId)); + if (state === "receipt") await db.update(heartbeatRuns).set({ resultJson: {} }).where(eq(heartbeatRuns.id, f.runId)); + if (state === "finished_time") await db.update(heartbeatRuns).set({ finishedAt: null }).where(eq(heartbeatRuns.id, f.runId)); await f.finalize(); const old = await db.select().from(statusDecisions).where(eq(statusDecisions.runId, f.runId)); expect(old.some(decision => decision.reasonCode === "monitor_wait_authority_lost")).toBe(true); - await db.update(issues).set({ executionPolicy: scheduled.executionPolicy, monitorNextCheckAt: scheduled.monitorNextCheckAt }) + if (state === "schedule") await db.update(issues).set({ executionPolicy: scheduled.executionPolicy, monitorNextCheckAt: scheduled.monitorNextCheckAt }) .where(eq(issues.id, f.issueId)); + if (state === "receipt") { + const [current] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId)); + await db.update(heartbeatRuns).set({ resultJson: { ...current.resultJson, + semanticToolReceipts: source.resultJson?.semanticToolReceipts } }).where(eq(heartbeatRuns.id, f.runId)); + } + if (state === "finished_time") await db.update(heartbeatRuns).set({ finishedAt: f.finishedAt }).where(eq(heartbeatRuns.id, f.runId)); await f.finalize(); - expect((await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, f.runId)))[0].phase).toBe("committed"); + const [settled] = await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, f.runId)); + expect(settled).toMatchObject({ phase: "committed", nextAttemptAt: null, attempt: 1 }); const after = await db.select().from(statusDecisions).where(eq(statusDecisions.runId, f.runId)); for (const before of old) expect(after.find(decision => decision.id === before.id)).toEqual(before); expect(after.some(decision => decision.reasonCode === "scheduled_monitor_preserved")).toBe(true); expect((await db.select().from(nativeRunResults).where(eq(nativeRunResults.id, f.resultId)))[0].resultJson).toEqual(f.result); expect(await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.companyId, f.companyId))).toEqual([]); + expect(await f.readIssue()).toMatchObject({ monitorNextCheckAt: scheduled.monitorNextCheckAt, + executionRunId: null, checkoutRunId: null }); + await f.finalize(); + expect(await db.select().from(statusDecisions).where(eq(statusDecisions.runId, f.runId))).toEqual(after); + expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId)))[0].finishedAt).toEqual(f.finishedAt); }); it("notifies the existing monitor scheduler once when finalization stops blocking it", async () => { diff --git a/server/src/services/native-runtime/native-run-finalizer.ts b/server/src/services/native-runtime/native-run-finalizer.ts index 1f8b830ff03..5931662d7db 100644 --- a/server/src/services/native-runtime/native-run-finalizer.ts +++ b/server/src/services/native-runtime/native-run-finalizer.ts @@ -1488,6 +1488,7 @@ export async function finalizeNativeRun(input: { workspaceFinalizeStatus: input.workspaceFinalizeStatus, monitorDelivery, monitorWaitAt: assessment.continuation?.kind === "monitor" ? monitorWaitAt : null, + preservedMonitorWait, }); await input.db .update(nativeRunFinalizations) diff --git a/server/src/services/native-runtime/work-assessments.ts b/server/src/services/native-runtime/work-assessments.ts index 829b497040b..58975d83b6d 100644 --- a/server/src/services/native-runtime/work-assessments.ts +++ b/server/src/services/native-runtime/work-assessments.ts @@ -3,7 +3,7 @@ import type { Db } from "@paperclipai/db"; import { workAssessments } from "@paperclipai/db"; import type { NativeEvidenceAssessment } from "./evidence-classifier.js"; import { nativeSha256 } from "./canonical.js"; -import type { NativeMonitorDelivery } from "./native-monitor-delivery.js"; +import type { NativeMonitorDelivery, NativePreservedMonitorWait } from "./native-monitor-delivery.js"; export async function recordNativeWorkAssessment(input: { db: Db; @@ -26,12 +26,14 @@ export async function recordNativeWorkAssessment(input: { monitorDelivery?: NativeMonitorDelivery | null; /** A persisted schedule can regain settlement authority after a policy repair. */ monitorWaitAt?: string | null; + preservedMonitorWait?: NativePreservedMonitorWait | null; supersedesAssessmentId?: string | null; }) { const assessmentJson = { ...input.assessment, ...(input.monitorDelivery ? { monitorDelivery: input.monitorDelivery } : {}), ...(input.monitorWaitAt ? { monitorWaitAt: input.monitorWaitAt } : {}), + ...(input.preservedMonitorWait ? { preservedMonitorWait: input.preservedMonitorWait } : {}), } as unknown as Record; const inputDigest = nativeSha256({ contractId: input.contractId, From a8e63f0e2a9a5af43a2731a52601971307d4da94 Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Sun, 25 Oct 2026 17:42:54 -0700 Subject: [PATCH 080/110] perf(server): avoid repeated delivery scans in GitHub review repair (#17669) Resolve the exact delivery through its primary key before looking up stale-head cancellations. Backport the predicate from #17664 while preserving the current worker lifecycle and receipt checks. Verified 372 selected tests, workspace typechecking, the server build, green CI, and an Apex 5/5 review. Co-Authored-By: Paperclip --- server/src/services/chat-github-checks.ts | 21 +- .../chat-github-review-repair.test.ts | 183 ++++++++++++++++++ 2 files changed, 196 insertions(+), 8 deletions(-) create mode 100644 server/src/services/chat-github-review-repair.test.ts diff --git a/server/src/services/chat-github-checks.ts b/server/src/services/chat-github-checks.ts index dceb5ae3df5..a47cf3b1021 100644 --- a/server/src/services/chat-github-checks.ts +++ b/server/src/services/chat-github-checks.ts @@ -427,19 +427,24 @@ export function githubReviewCheckService(db: Db, fetchImpl = fetch) { and( inArray(chatGitHubReviews.state, ["queued", "running"]), isNull(chatGitHubReviews.assessment), - sql`exists ( - select 1 from ${chatActions} action - join ${chatDeliveries} delivery - on delivery.id::text = ${chatGitHubReviews.deliveryId} + sql`${chatGitHubReviews.deliveryId} ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$'`, + sql`( + select action.id from ${chatActions} action where action.company_id = ${chatGitHubReviews.companyId} and action.endpoint_id = ${chatGitHubReviews.endpointId} - and delivery.endpoint_id = action.endpoint_id and action.kind = 'github_review_check' and action.status = 'cancelled' and action.result->>'code' = 'stale_head' - and action.payload->'event'->>'deliveryId' = - delivery.normalized_event->'githubAutomatic'->'context'->>'deliveryId' - )`, + and action.payload->'event'->>'deliveryId' = ( + select delivery.normalized_event->'githubAutomatic'->'context'->>'deliveryId' + from ${chatDeliveries} delivery + where delivery.id = case + when ${chatGitHubReviews.deliveryId} ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + then ${chatGitHubReviews.deliveryId}::uuid end + and delivery.endpoint_id = ${chatGitHubReviews.endpointId} + ) + limit 1 + ) is not null`, ), ); const rows = await db diff --git a/server/src/services/chat-github-review-repair.test.ts b/server/src/services/chat-github-review-repair.test.ts new file mode 100644 index 00000000000..01d3649aa2c --- /dev/null +++ b/server/src/services/chat-github-review-repair.test.ts @@ -0,0 +1,183 @@ +import { randomUUID } from "node:crypto"; +import { sql } from "drizzle-orm"; +import { createDb, getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase, type Db } from "@paperclipai/db"; +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; +import { githubReviewCheckService } from "./chat-github-checks.js"; + +type QueryParameters = NonNullable[1]>; +type CapturedQuery = { text: string; parameters: QueryParameters }; +type Plan = { "Node Type"?: string; "Relation Name"?: string; "Index Name"?: string; "Actual Loops"?: number; Plans?: Plan[] }; +const support = await getEmbeddedPostgresTestSupport(); + +describe.skipIf(!support.supported)("GitHub stale review repair PostgreSQL behavior", () => { + let temporary: Awaited>; + let db: Db; + let queries: CapturedQuery[]; + const noProviderCall = vi.fn(async () => { throw new Error("Repair must not contact a provider"); }); + + beforeAll(async () => { + temporary = await startEmbeddedPostgresTestDatabase("github-review-repair-"); + const setup = createDb(temporary.connectionString, { maxConnections: 1 }); + try { + await setup.execute(sql`create schema github_review_repair_fixture`); + await setup.execute(sql`set search_path=github_review_repair_fixture`); + await setup.execute(sql`create table chat_github_reviews (id uuid primary key, company_id uuid not null, + endpoint_id uuid not null, delivery_id text not null, state text not null, assessment jsonb, + updated_at timestamptz not null default now())`); + await setup.execute(sql`create table chat_deliveries (id uuid primary key, endpoint_id uuid not null, normalized_event jsonb)`); + await setup.execute(sql`create table chat_actions (id uuid primary key, company_id uuid not null, + endpoint_id uuid not null, provider_action_id text, kind text not null, status text not null, + payload jsonb not null, result jsonb, updated_at timestamptz not null default now())`); + await setup.execute(sql`create unique index chat_actions_provider_action_uq + on chat_actions(company_id, endpoint_id, provider_action_id)`); + } finally { + await setup.$client.end(); + } + }, 90_000); + + beforeEach(async () => { + queries = []; + db = createDb(temporary.connectionString, { maxConnections: 1 }); + db.$client.options.debug = (_connection: number, text: string, parameters: QueryParameters) => { + if (/^update "chat_github_reviews"/i.test(text)) queries.push({ text, parameters: [...parameters] }); + }; + await db.execute(sql`set search_path=github_review_repair_fixture`); + await db.execute(sql`truncate chat_github_reviews, chat_deliveries, chat_actions`); + noProviderCall.mockClear(); + }); + afterEach(async () => { await db?.$client.end(); }); + afterAll(async () => { await temporary?.cleanup(); }); + + async function seed(overrides: Record = {}) { + const companyId = randomUUID(), endpointId = randomUUID(); + const deliveryId = "a" + randomUUID().slice(1), reviewId = randomUUID(), actionId = randomUUID(); + const providerDeliveryId = "provider-" + randomUUID(); + const values = { companyId, endpointId, deliveryId, reviewId, actionId, providerDeliveryId, + actionCompanyId: companyId, actionEndpointId: endpointId, deliveryEndpointId: endpointId, + actionDeliveryId: providerDeliveryId, reviewDeliveryId: deliveryId, state: "queued", assessment: null, + kind: "github_review_check", status: "cancelled", code: "stale_head", ...overrides }; + await db.execute(sql`insert into chat_deliveries(id, endpoint_id, normalized_event) + values (${deliveryId}::uuid, ${values.deliveryEndpointId}::uuid, + ${JSON.stringify({ githubAutomatic: { context: { deliveryId: providerDeliveryId } } })}::jsonb)`); + await db.execute(sql`insert into chat_actions(id, company_id, endpoint_id, kind, status, payload, result) + values (${actionId}::uuid, ${values.actionCompanyId}::uuid, ${values.actionEndpointId}::uuid, + ${values.kind}, ${values.status}, ${JSON.stringify({ event: { deliveryId: values.actionDeliveryId } })}::jsonb, + ${JSON.stringify({ code: values.code })}::jsonb)`); + await db.execute(sql`insert into chat_github_reviews(id, company_id, endpoint_id, delivery_id, state, assessment, updated_at) + values (${reviewId}::uuid, ${companyId}::uuid, ${endpointId}::uuid, ${values.reviewDeliveryId}, + ${values.state}, ${values.assessment === null ? null : JSON.stringify(values.assessment)}::jsonb, '2000-01-01T00:00:00Z')`); + return values; + } + + async function retainedRows() { + return { + reviews: await db.$client.unsafe("select * from chat_github_reviews order by id"), + deliveries: await db.$client.unsafe("select * from chat_deliveries order by id"), + actions: await db.$client.unsafe("select * from chat_actions order by id"), + }; + } + + it.each(["queued", "running"])("supersedes only the exact %s unassessed review", async state => { + const fixture = await seed({ state }); + const before = await retainedRows(); + const service = githubReviewCheckService(db, noProviderCall); + await service.processPending(); + const after = await retainedRows(); + expect(after.reviews).toHaveLength(1); + expect(after.reviews[0]).toMatchObject({ id: fixture.reviewId, state: "superseded", assessment: null }); + expect(after.deliveries).toEqual(before.deliveries); + expect(after.actions).toEqual(before.actions); + await service.processPending(); + expect(await retainedRows()).toEqual(after); + expect(noProviderCall).not.toHaveBeenCalled(); + }); + + it.each([ + ["another action company", { actionCompanyId: randomUUID() }], + ["another action endpoint", { actionEndpointId: randomUUID() }], + ["another delivery endpoint", { deliveryEndpointId: randomUUID() }], + ["another provider delivery", { actionDeliveryId: "another-delivery" }], + ["another cancellation reason", { code: "another_reason" }], + ["another action kind", { kind: "another_kind" }], + ["a processed action", { status: "processed" }], + ["an assessed review", { assessment: { retained: true } }], + ["a completed review", { state: "completed" }], + ])("preserves rows for %s", async (_name, overrides) => { + await seed(overrides as Record); + const before = await retainedRows(); + await githubReviewCheckService(db, noProviderCall).processPending(); + expect(await retainedRows()).toEqual(before); + expect(noProviderCall).not.toHaveBeenCalled(); + }); + + it.each(["malformed", "uppercase", "whitespace", "braces", "unhyphenated"])("preserves %s delivery references without cast errors", async kind => { + const fixture = await seed(); + const reference = kind === "malformed" ? "not-a-uuid" : kind === "uppercase" ? fixture.deliveryId.toUpperCase() + : kind === "whitespace" ? ` ${fixture.deliveryId} ` : kind === "braces" ? `{${fixture.deliveryId}}` + : fixture.deliveryId.replaceAll("-", ""); + await db.execute(sql`update chat_github_reviews set delivery_id=${reference} where id=${fixture.reviewId}::uuid`); + const before = await retainedRows(); + await githubReviewCheckService(db, noProviderCall).processPending(); + expect(await retainedRows()).toEqual(before); + expect(noProviderCall).not.toHaveBeenCalled(); + }); + + it.each(["missing delivery", "missing provider identity"])("preserves a review with %s", async kind => { + const fixture = await seed(); + if (kind === "missing delivery") { + await db.execute(sql`delete from chat_deliveries where id=${fixture.deliveryId}::uuid`); + } else { + await db.execute(sql`update chat_deliveries set normalized_event='{}'::jsonb where id=${fixture.deliveryId}::uuid`); + } + const before = await retainedRows(); + await githubReviewCheckService(db, noProviderCall).processPending(); + expect(await retainedRows()).toEqual(before); + expect(noProviderCall).not.toHaveBeenCalled(); + }); + + it("repairs a late review from the retained cancellation without replaying provider work", async () => { + const fixture = await seed(); + await db.execute(sql`delete from chat_github_reviews where id=${fixture.reviewId}::uuid`); + const service = githubReviewCheckService(db, noProviderCall); + await service.processPending(); + await db.execute(sql`insert into chat_github_reviews(id, company_id, endpoint_id, delivery_id, state) + values (${fixture.reviewId}::uuid, ${fixture.companyId}::uuid, ${fixture.endpointId}::uuid, ${fixture.deliveryId}, 'queued')`); + await service.processPending(); + const rows = await db.$client.unsafe("select state from chat_github_reviews"); + expect(rows).toEqual([{ state: "superseded" }]); + expect(noProviderCall).not.toHaveBeenCalled(); + }); + + it("resolves each candidate delivery once through its primary key with retained history", async () => { + const companyId = randomUUID(), endpointId = randomUUID(); + const candidates = 200; + await db.execute(sql`insert into chat_deliveries(id, endpoint_id, normalized_event) + select gen_random_uuid(), ${endpointId}::uuid, + jsonb_build_object('githubAutomatic', jsonb_build_object('context', jsonb_build_object('deliveryId', 'delivery-' || n))) + from generate_series(1,8000) n`); + await db.execute(sql`insert into chat_github_reviews(id, company_id, endpoint_id, delivery_id, state) + select gen_random_uuid(), ${companyId}::uuid, ${endpointId}::uuid, id::text, 'queued' + from chat_deliveries order by id limit ${candidates}`); + await db.execute(sql`insert into chat_actions(id, company_id, endpoint_id, provider_action_id, kind, status, payload, result) + select gen_random_uuid(), ${companyId}::uuid, ${endpointId}::uuid, 'action-' || n, + case when n<=100 then 'github_review_check' else 'another_kind' end, 'cancelled', + jsonb_build_object('event', jsonb_build_object('deliveryId', 'unmatched-' || n)), + jsonb_build_object('code', 'stale_head') from generate_series(1,1100) n`); + await db.execute(sql`analyze chat_deliveries`); + await db.execute(sql`analyze chat_actions`); + await db.execute(sql`analyze chat_github_reviews`); + await db.execute(sql`set statement_timeout='5s'`); + await githubReviewCheckService(db, noProviderCall).processPending(); + expect(queries).toHaveLength(1); + const query = queries[0]; + const explained = await db.$client.unsafe(`explain (analyze,buffers,format json) ${query.text}`, query.parameters); + const root = (explained[0]["QUERY PLAN"] as Array<{ Plan: Plan }>)[0].Plan; + function flatten(plan: Plan): Plan[] { return [plan, ...(plan.Plans ?? []).flatMap(flatten)]; } + const deliveries = flatten(root).filter(node => node["Relation Name"] === "chat_deliveries"); + expect(deliveries).toHaveLength(1); + expect(deliveries[0]["Index Name"]).toBe("chat_deliveries_pkey"); + expect(deliveries[0]["Actual Loops"]).toBeLessThanOrEqual(candidates); + expect((await db.$client.unsafe("select count(*)::int as count from chat_github_reviews where state='queued'"))[0].count).toBe(candidates); + expect(noProviderCall).not.toHaveBeenCalled(); + }, 30_000); +}); From 1a3f604097d81fb653b271af4c7c3614d2b032a7 Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Sun, 25 Oct 2026 18:17:43 -0700 Subject: [PATCH 081/110] fix(db): honor the prepared-statement opt-in for ORM queries (#17673) Drizzle calls Postgres.js unsafe queries, which disable preparation unless per-query options enable it. The existing client-level opt-in therefore does not prepare ORM queries. Honor explicit true across root and child clients. Preserve defaults, per-query options, lazy execution, and driver error handling. Document the pooler capability requirement. Test with 92 selected database and connection checks, workspace typechecks, server and database builds, and a read-only hosted ORM protocol probe. Co-Authored-By: Paperclip --- doc/DATABASE.md | 12 +- docs/deploy/database.md | 11 +- packages/db/src/client.ts | 9 +- .../db/src/prepared-queries-postgres.test.ts | 175 ++++++++++++++++++ packages/db/src/prepared-queries.ts | 47 +++++ .../db/src/response-capture-postgres.test.ts | 20 +- 6 files changed, 259 insertions(+), 15 deletions(-) create mode 100644 packages/db/src/prepared-queries-postgres.test.ts create mode 100644 packages/db/src/prepared-queries.ts diff --git a/doc/DATABASE.md b/doc/DATABASE.md index cb341f8ea79..2032268da2d 100644 --- a/doc/DATABASE.md +++ b/doc/DATABASE.md @@ -458,14 +458,14 @@ DATABASE_URL=postgres://postgres.[PROJECT-REF]:[PASSWORD]@aws-0-[REGION].pooler. DATABASE_MIGRATION_URL=postgres://postgres.[PROJECT-REF]:[PASSWORD]@aws-0-[REGION].pooler.supabase.com:5432/postgres ``` -If your hosted database requires transaction-pooling-only connections (pgbouncer transaction mode, Supavisor port 6543, Neon `-pooler` endpoints), set `DATABASE_PREPARED_STATEMENTS=false` so the client does not rely on session-scoped prepared statements, and keep `DATABASE_MIGRATION_URL` on a direct connection. Do not edit database client source files as part of deployment setup. +If your transaction-mode pooler does not support protocol-level named prepared statements, set `DATABASE_PREPARED_STATEMENTS=false`. If your pooler supports them, you can opt in with `DATABASE_PREPARED_STATEMENTS=true`. Check your provider's pooler configuration before you enable this setting. Keep `DATABASE_MIGRATION_URL` on a direct connection. Do not edit database client source files as part of deployment setup. ### Client tuning (optional) All of these are optional; when unset, the driver defaults apply and behavior is unchanged — typical self-hosted setups need none of them: ```sh -DATABASE_PREPARED_STATEMENTS=false # required for transaction-mode poolers; default: enabled +DATABASE_PREPARED_STATEMENTS=false # use false when the pooler does not support named prepared statements DATABASE_POOL_MAX=25 # connection pool size; default: 10 DATABASE_IDLE_TIMEOUT_SECONDS=60 # close idle pooled connections; default: 60 (0 = keep open) DATABASE_CONNECT_TIMEOUT_SECONDS=10 # default: 30 @@ -473,6 +473,14 @@ DATABASE_MAX_LIFETIME_SECONDS=1800 # recycle a pooled connection after this lo DATABASE_APPLICATION_NAME=paperclip # application_name in pg_stat_activity; default: paperclip ``` +An explicit `DATABASE_PREPARED_STATEMENTS=true` enables named prepared statements +for parameterized ORM queries, transactions, reserved connections, and dedicated +clients. Postgres.js manages the statement cache. This does not cache query +results. Bound values and returned data stay fresh. Explicit per-query options +still apply, including `prepare: false` and simple-protocol execution. With the +setting unset, ORM queries keep their existing unprepared behavior and tagged +SQL uses the driver default. With `false`, preparation stays disabled. + ### Bounded response diagnostics `PAPERCLIP_DB_RESPONSE_CAPTURE_WINDOW=/` enables one explicit UTC diff --git a/docs/deploy/database.md b/docs/deploy/database.md index 4f72b70c097..6e85cebce7e 100644 --- a/docs/deploy/database.md +++ b/docs/deploy/database.md @@ -56,12 +56,19 @@ For production, use a hosted provider like [Supabase](https://supabase.com/). Use the **direct connection** (port 5432) for migrations and the **pooled connection** (port 6543) for the application. -If using connection pooling (transaction mode), disable prepared statements via the environment — no source edits needed: +If your transaction-mode pooler does not support protocol-level named prepared statements, disable them via the environment: ```sh DATABASE_PREPARED_STATEMENTS=false ``` +For a direct connection or a pooler that supports named prepared statements, +`DATABASE_PREPARED_STATEMENTS=true` also prepares parameterized ORM queries and +queries inside transactions and reserved or dedicated connections. Check the +provider's configuration before you enable it. Preparation caches statement +metadata, not query results. Unset preserves the existing ORM behavior and the +driver default for tagged SQL. Explicit per-query options still apply. + Related optional client tuning: `DATABASE_POOL_MAX`, `DATABASE_IDLE_TIMEOUT_SECONDS`, `DATABASE_CONNECT_TIMEOUT_SECONDS`, `DATABASE_MAX_LIFETIME_SECONDS`, `DATABASE_APPLICATION_NAME`. Driver defaults apply when unset, except that idle pooled connections close after 60 seconds (`DATABASE_IDLE_TIMEOUT_SECONDS=0` keeps them open) and the pool reports `application_name=paperclip`. See [Connection pool settings](#connection-pool-settings). ## Connection Pool Settings @@ -75,7 +82,7 @@ The server opens one postgres.js pool for its own queries (and a second one when | `DATABASE_CONNECT_TIMEOUT_SECONDS` | `30` (driver) | Give up on a connection attempt after this long. | | `DATABASE_MAX_LIFETIME_SECONDS` | 30–60 min, randomized (driver) | Recycle a pooled connection once it is this old. | | `DATABASE_APPLICATION_NAME` | `paperclip` | Value of `application_name` in `pg_stat_activity`, so you can find Paperclip's backends: `SELECT * FROM pg_stat_activity WHERE application_name = 'paperclip';` | -| `DATABASE_PREPARED_STATEMENTS` | `true` (driver) | Set `false` behind a transaction-mode pooler (see above). | +| `DATABASE_PREPARED_STATEMENTS` | Unset | `true` opts parameterized ORM queries into preparation. `false` disables preparation. Use `false` when the pooler does not support named statements. Unset preserves existing behavior. | The server ends its pools during shutdown (SIGINT/SIGTERM) and when startup fails after the pool was opened, so a restarting server does not leave idle backends behind. Size `max_connections` on the PostgreSQL side for at least `DATABASE_POOL_MAX` per server process plus your other clients. Each server process also opens up to 2 connections (`application_name=paperclip-controller-lease`) for agent-run lease renewals, so they never queue behind slow application queries; count those too. diff --git a/packages/db/src/client.ts b/packages/db/src/client.ts index f1b8079db45..7f067cbfc1c 100644 --- a/packages/db/src/client.ts +++ b/packages/db/src/client.ts @@ -5,6 +5,7 @@ import { fileURLToPath } from "node:url"; import postgres from "postgres"; import { installDatabaseWorkSignals } from "./work-signals.js"; import { installDatabaseResponseCapture } from "./response-capture.js"; +import { installPreparedQueries } from "./prepared-queries.js"; import * as schema from "./schema/index.js"; const MIGRATIONS_FOLDER = fileURLToPath(new URL("./migrations", import.meta.url)); @@ -129,13 +130,6 @@ export type MigrationState = }; export interface DatabaseClientOptions { - /** - * postgres.js `prepare`. Set false when connecting through a - * transaction-mode pooler (pgbouncer / Neon `-pooler` endpoints / - * Supabase Supavisor transaction ports) so the client does not rely on - * session-scoped prepared statements. Defaults to the driver default - * (enabled), preserving existing behavior on direct connections. - */ prepare?: boolean; /** postgres.js `max` — connection pool size (driver default: 10). */ maxConnections?: number; @@ -301,6 +295,7 @@ export function createDb(url: string, options?: DatabaseClientOptions) { function createDbClient(url: string, resolved: DatabaseClientOptions, owner?: object) { const sql = postgres(url, postgresJsOptions(resolved)); + if (resolved.prepare === true) installPreparedQueries(sql); const key = hostPortKeyOrNull(url); if (key) registerClient(key, sql); // A disconnect can lose the response after a statement has committed. diff --git a/packages/db/src/prepared-queries-postgres.test.ts b/packages/db/src/prepared-queries-postgres.test.ts new file mode 100644 index 00000000000..edef6dc060e --- /dev/null +++ b/packages/db/src/prepared-queries-postgres.test.ts @@ -0,0 +1,175 @@ +import { eq, sql } from "drizzle-orm"; +import { integer, jsonb, pgTable, text } from "drizzle-orm/pg-core"; +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest"; +import { closeLivenessDb, createDb, databaseClientOptionsFromEnv, livenessDb, withDedicatedDbConnection, type DatabaseClientOptions, type Db } from "./client.js"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./test-embedded-postgres.js"; +import { runEventPayload } from "./run-event-payload.js"; + +const records = pgTable("prepared_query_fixture", { id: text("id").primaryKey(), companyId: text("company_id").notNull(), value: integer("value").notNull(), payload: jsonb("payload") }); +const encoded = pgTable("prepared_encoded_fixture", { id: text("id").primaryKey(), payload: runEventPayload("payload") }); +const support = await getEmbeddedPostgresTestSupport(); + +describe.skipIf(!support.supported)("explicit ORM prepared statements on PostgreSQL", () => { + let temporary: Awaited>; + let setup: Db; + const clients: Db[] = []; + beforeAll(async () => { + temporary = await startEmbeddedPostgresTestDatabase("prepared-orm-"); + setup = createDb(temporary.connectionString, { prepare: false, maxConnections: 1 }); + await setup.execute(sql`create table prepared_query_fixture(id text primary key, company_id text not null, value integer not null, payload jsonb)`); + await setup.execute(sql`create table prepared_encoded_fixture(id text primary key, payload jsonb)`); + await setup.execute(sql`create table prepared_schema_change_fixture(id text primary key)`); + await setup.execute(sql`insert into prepared_schema_change_fixture(id) values ('retained')`); + }, 90_000); + beforeEach(async () => { + await setup.execute(sql`truncate prepared_query_fixture, prepared_encoded_fixture`); + await setup.insert(records).values([ + { id: "a", companyId: "company-a", value: 1, payload: { owner: "a" } }, + { id: "b", companyId: "company-b", value: 2, payload: { owner: "b" } }, + ]); + }); + afterEach(async () => { + for (const db of clients.splice(0)) { + await closeLivenessDb(db, 2); + await db.$client.end(); + } + }); + afterAll(async () => { await setup?.$client.end(); await temporary?.cleanup(); }); + function fixture(options: DatabaseClientOptions = {}) { + const db = createDb(temporary.connectionString, { ...options, maxConnections: 1 }); + clients.push(db); return db; + } + async function statements(db: Db, pattern = '%"prepared_query_fixture"%') { + return db.$client.unsafe("select name,statement from pg_prepared_statements where statement like $1", [pattern]); + } + + it.each([undefined, false])("keeps the existing ORM mode when prepare is %s", async prepare => { + const db = fixture({ prepare }); + expect(await db.select().from(records).where(eq(records.companyId, "company-a"))).toEqual([ + { id: "a", companyId: "company-a", value: 1, payload: { owner: "a" } }, + ]); + expect(await statements(db)).toHaveLength(0); + }); + + it("honors the explicit environment opt-in for ORM queries with fresh company bindings", async () => { + const db = fixture(databaseClientOptionsFromEnv({ DATABASE_PREPARED_STATEMENTS: "true" })); + for (let i = 0; i < 12; i++) { + const companyId = i % 2 ? "company-b" : "company-a"; + const rows = await db.select().from(records).where(eq(records.companyId, companyId)); + expect(rows).toEqual([{ id: i % 2 ? "b" : "a", companyId, value: i % 2 ? 2 : 1, payload: { owner: i % 2 ? "b" : "a" } }]); + } + expect(await statements(db)).toHaveLength(1); + }); + + it("preserves explicit per-query opt-out", async () => { + const db = fixture({ prepare: true }); + expect((await db.$client.unsafe("select $1::integer as explicit_opt_out_marker", [7], { prepare: false }))[0].explicit_opt_out_marker).toBe(7); + expect(await statements(db, "%explicit_opt_out_marker%")).toHaveLength(0); + }); + + it("preserves simple queries and the two-argument options overload", async () => { + const db = fixture({ prepare: true }); + const simpleOptions = { prepare: true, simple: true }; + const simple = await db.$client.unsafe("select 1 as first; select 2 as second", [], simpleOptions); + expect(simple).toEqual([[{ first: 1 }], [{ second: 2 }]]); + const unsafe = db.$client.unsafe as unknown as (query: string, options: { simple: boolean }) => Promise; + expect(await unsafe("select 3 as third; select 4 as fourth", { simple: true })) + .toEqual([[{ third: 3 }], [{ fourth: 4 }]]); + }); + + it("does not replay a rejected prepared write", async () => { + const db = fixture({ prepare: true }); + await expect(db.insert(records).values({ id: "a", companyId: "company-b", value: 9 })) + .rejects.toMatchObject({ cause: { code: "23505" } }); + expect(await db.select({ companyId: records.companyId, value: records.value }).from(records).where(eq(records.id, "a"))) + .toEqual([{ companyId: "company-a", value: 1 }]); + }); + + it("keeps write queries lazy and repeated awaits from repeating writes", async () => { + const db = fixture({ prepare: true }); + const pending = db.$client.unsafe("insert into prepared_query_fixture(id,company_id,value) values ($1,$2,$3) returning id", ["lazy", "company-a", 3]); + expect(typeof pending.values).toBe("function"); + expect(await setup.select().from(records).where(eq(records.id, "lazy"))).toEqual([]); + expect(await pending).toEqual([{ id: "lazy" }]); + expect(await pending).toEqual([{ id: "lazy" }]); + expect(await setup.select({ id: records.id }).from(records).where(eq(records.id, "lazy"))).toEqual([{ id: "lazy" }]); + expect(await statements(db, "%insert into prepared_query_fixture%")).toHaveLength(1); + }); + + it("preserves transaction commits, nested savepoint rollback, and scoped reads", async () => { + const db = fixture({ prepare: true }); + await db.transaction(async tx => { + expect(await tx.select({ value: records.value }).from(records).where(eq(records.companyId, "company-a"))).toEqual([{ value: 1 }]); + await expect(tx.transaction(async nested => { + await nested.update(records).set({ value: 99 }).where(eq(records.companyId, "company-a")); + throw new Error("rollback savepoint"); + })).rejects.toThrow("rollback savepoint"); + expect(await tx.select({ value: records.value }).from(records).where(eq(records.companyId, "company-a"))).toEqual([{ value: 1 }]); + await tx.insert(records).values({ id: "committed", companyId: "company-b", value: 3 }); + const names = await tx.execute(sql`select statement from pg_prepared_statements`); + expect(names.some(row => String(row.statement).includes('"prepared_query_fixture"'))).toBe(true); + }, { isolationLevel: "serializable" }); + expect(await db.select({ value: records.value }).from(records).where(eq(records.id, "committed"))).toEqual([{ value: 3 }]); + }); + + it("rolls back failed outer transactions without replay", async () => { + const db = fixture({ prepare: true }); + await expect(db.transaction(async tx => { + await tx.update(records).set({ value: 42 }).where(eq(records.id, "a")); + throw new Error("rollback outer transaction"); + })).rejects.toThrow("rollback outer transaction"); + expect(await db.select({ value: records.value }).from(records).where(eq(records.id, "a"))).toEqual([{ value: 1 }]); + }); + + it("prepares reserved-client queries and keeps their bound values fresh", async () => { + const db = fixture({ prepare: true }); + const reserved = await db.$client.reserve(); + try { + for (const marker of [1, 2, 3]) { + expect((await reserved.unsafe("select $1::integer as reserved_prepared_marker", [marker]))[0].reserved_prepared_marker).toBe(marker); + } + const names = await reserved.unsafe("select statement from pg_prepared_statements where statement like $1", ["%reserved_prepared_marker%"]); + expect(names).toHaveLength(1); + } finally { reserved.release(); } + }); + + it("preserves object and array results for the same prepared shape", async () => { + const db = fixture({ prepare: true }); + expect(await db.$client.unsafe("select $1::integer as result_mode_marker", [41]).values()).toEqual([[41]]); + expect(await db.$client.unsafe("select $1::integer as result_mode_marker", [42])).toEqual([{ result_mode_marker: 42 }]); + }); + + it("keeps custom stored-payload decoding fresh", async () => { + const db = fixture({ prepare: true }); + const first = { text: "encoded first payload🙂".repeat(2048) }; + const second = { text: "encoded second payload🙂".repeat(2048) }; + await setup.insert(encoded).values({ id: "encoded", payload: first }); + expect((await db.select().from(encoded).where(eq(encoded.id, "encoded")))[0].payload).toEqual(first); + await setup.update(encoded).set({ payload: second }).where(eq(encoded.id, "encoded")); + expect((await db.select().from(encoded).where(eq(encoded.id, "encoded")))[0].payload).toEqual(second); + expect(await statements(db, '%"prepared_encoded_fixture"%')).toHaveLength(1); + }); + + it("inherits the opt-in in dedicated and liveness clients", async () => { + const db = fixture({ prepare: true }); + await withDedicatedDbConnection(db, async dedicated => { + expect(await dedicated.select({ value: records.value }).from(records).where(eq(records.companyId, "company-b"))).toEqual([{ value: 2 }]); + expect(await statements(dedicated)).toHaveLength(1); + }); + const live = livenessDb(db); + expect(await live.select({ value: records.value }).from(records).where(eq(records.companyId, "company-a"))).toEqual([{ value: 1 }]); + expect(await statements(live)).toHaveLength(1); + }); + + it("refreshes prepared result metadata after a schema change", async () => { + const db = fixture({ prepare: true }); + const query = "select * from prepared_schema_change_fixture where id=$1"; + expect(await db.$client.unsafe(query, ["retained"])).toEqual([{ id: "retained" }]); + try { + await setup.execute(sql`alter table prepared_schema_change_fixture add column extra text`); + expect(await db.$client.unsafe(query, ["retained"])).toEqual([{ id: "retained", extra: null }]); + } finally { + await setup.execute(sql`alter table prepared_schema_change_fixture drop column if exists extra`); + } + }); +}); diff --git a/packages/db/src/prepared-queries.ts b/packages/db/src/prepared-queries.ts new file mode 100644 index 00000000000..7622722027a --- /dev/null +++ b/packages/db/src/prepared-queries.ts @@ -0,0 +1,47 @@ +type Method = (this: unknown, ...args: unknown[]) => unknown; + +export function installPreparedQueries(client: unknown): void { + const visited = new WeakSet(); + + function visit(value: unknown): void { + if ((typeof value !== "object" || value === null) && typeof value !== "function") return; + if (visited.has(value)) return; + visited.add(value); + const target = value as Record; + const unsafe = target.unsafe; + if (typeof unsafe === "function") { + target.unsafe = function (this: unknown, ...args: unknown[]) { + const index = args.length === 2 && !Array.isArray(args[1]) ? 1 : 2; + const options = args[index]; + if (options !== undefined && (options === null || typeof options !== "object")) { + return Reflect.apply(unsafe, this, args); + } + if (index === 2 && args.length < 2) args[1] = []; + args[index] = { prepare: true, ...options }; + return Reflect.apply(unsafe, this, args); + }; + } + for (const method of ["begin", "savepoint"]) { + const original = target[method]; + if (typeof original !== "function") continue; + target[method] = function (this: unknown, ...args: unknown[]) { + const wrapped = args.map(arg => typeof arg !== "function" ? arg : function (this: unknown, ...inner: unknown[]) { + visit(inner[0]); + return Reflect.apply(arg, this, inner); + }); + return Reflect.apply(original, this, wrapped); + } satisfies Method; + } + const reserve = target.reserve; + if (typeof reserve === "function") { + target.reserve = function (this: unknown, ...args: unknown[]) { + return Promise.resolve(Reflect.apply(reserve, this, args)).then(reserved => { + visit(reserved); + return reserved; + }); + } satisfies Method; + } + } + + visit(client); +} diff --git a/packages/db/src/response-capture-postgres.test.ts b/packages/db/src/response-capture-postgres.test.ts index 96de91ff913..42d5d805a0c 100644 --- a/packages/db/src/response-capture-postgres.test.ts +++ b/packages/db/src/response-capture-postgres.test.ts @@ -31,11 +31,11 @@ describe.skipIf(!support.supported)("database response capture PostgreSQL behavi vi.restoreAllMocks(); vi.unstubAllEnvs(); }); afterAll(async () => { await temporary?.cleanup(); }); - function fixture() { + function fixture(prepare?: boolean) { const events: Array> = []; const now = Date.now(); const capture = createDatabaseResponseCapture({ start: now - 100, end: now + 59_000 }, event => events.push(event)); - const db = createDb(temporary.connectionString); + const db = createDb(temporary.connectionString, { prepare }); clients.push(db); captures.push(capture); expect(installDatabaseResponseCapture(db, { table, encodedTable }, capture)).toBe(db); expect(installDatabaseResponseCapture(db, { table, encodedTable }, capture)).toBe(db); @@ -43,6 +43,18 @@ describe.skipIf(!support.supported)("database response capture PostgreSQL behavi } function summary(events: Array>) { return events.find(event => event.event === "paperclip.db_response_capture.summary.v1")!; } + it("retains capture counts when ORM preparation is enabled", async () => { + const f = fixture(true), id = randomUUID(), payload = "prepared-capture-value"; + await f.db.insert(table).values({ id, payload }); + await f.db.transaction(async tx => { + expect(await tx.select().from(table).where(eq(table.id, id))).toEqual([{ id, payload }]); + }); + f.capture.flush(); + expect(summary(f.events)).toMatchObject({ startedQueries: 2, completedQueries: 2 }); + expect(JSON.stringify(f.events)).not.toContain(payload); + expect(JSON.stringify(f.events)).not.toContain(id); + }); + it("keeps rows and builder identity through lazy select and write returning", async () => { const f = fixture(), id = randomUUID(), payload = "sentinel-result-and-parameter-value🙂\n\""; const insert = f.db.insert(table).values({ id, payload }); @@ -173,11 +185,11 @@ describe.skipIf(!support.supported)("database response capture PostgreSQL behavi f.capture.flush(); expect(summary(f.events).completedQueries).toBeGreaterThan(4); }); - it("covers automatically created dedicated pools and retains owner identity", async () => { + it.each([undefined, true])("covers automatically created dedicated pools with prepare %s and retains owner identity", async prepare => { const logs: string[] = [], now = Date.now(); vi.spyOn(console, "info").mockImplementation(value => logs.push(String(value))); vi.stubEnv("PAPERCLIP_DB_RESPONSE_CAPTURE_WINDOW", `${new Date(now - 100).toISOString()}/${new Date(now + 59_000).toISOString()}`); - const db = createDb(temporary.connectionString); clients.push(db); + const db = createDb(temporary.connectionString, { prepare }); clients.push(db); const capture = databaseResponseCaptureFromEnv()!; captures.push(capture); expect(await withDedicatedDbConnection(db, async dedicated => dedicated.execute(sql`select ${"dedicated-value"}::text as value`))) .toEqual([{ value: "dedicated-value" }]); From 5cea9c7c0eb176dd8d053f4606230fea165f9d64 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sun, 25 Oct 2026 21:49:52 -0500 Subject: [PATCH 082/110] fix(ui): show eligible wake targets when resuming tasks (#17521) ## Thinking Path > - Paperclip manages agents and their assigned tasks. > - A task pause controls execution without changing task status. > - Resume can remove that pause and request work from eligible assignees. > - The preview counted blocked tasks and former executors as wake targets. > - The release route correctly skipped those targets, so the dialog promised work that did not start. > - Resume also trusted stale pause snapshots after tasks were reopened. > - This PR aligns preview with execution eligibility and rechecks current task state when releasing a pause. ## Linked Issues or Issue Description **What happened?** Pause an assigned blocked task, then open Resume. The dialog says that one task will resume and offers to wake one agent. Applying it only removes the pause. The route skips blocked and backlog tasks. A former executor can also inflate the wake count after reassignment. **Expected behavior** The dialog must distinguish removing a pause from starting work. Its wake count must use the current assignees and statuses accepted by the release route. Blocked work must stay blocked. **Steps to reproduce** 1. Open an assigned blocked task. 2. Choose Pause work, then Resume task. 3. Inspect the wake count and apply Resume work. Related runtime recovery work is tracked separately in #17097 and #17439. This PR does not change remote execution recovery. ## What Changed - Share the resume status list between preview and release. Count only current assignees on todo, in-progress, and in-review tasks for resume wakes. - Explain that Resume removes the pause. Show the existing preview warnings, including tasks that remain idle. - Disable and uncheck the wake option when no agents qualify. Send the same choice to the server. - Reevaluate previously skipped pause members after reopening or releasing another hold. Retain active-pause and unsafe-execution guards. - Add real PostgreSQL and HTTP-route regressions plus browser coverage for both task interfaces. Keep draft, ancestor-pause, and Stop/reconciliation coverage. - Update the task coordination maps. Add an opt-in dedicated test database URL for hosts where embedded PostgreSQL cannot start. ## Verification - Final head `9548eb16736f632cc111a5c13a9a994ec1d95a13`: all 55 completed checks pass, with two optional Storybook checks skipped. [CI 40188094904](https://github.com/paperclipai/paperclip/actions/runs/40188094904) passes, including typecheck, build, all general/serialized suites, and all eight E2E shards. Greptile is 5/5 on this commit; the reopened-task finding is fixed and resolved. - Red: the real PostgreSQL regression receives three agents instead of the one eligible current assignee on the original code. - Green: all 27 tree-control service, route, and unit tests pass. They cover current assignees, blocked/backlog exclusions, reopened tasks, company boundaries, remaining pause holds, and execution blockers. - The reopened-task route regression fails on the previous implementation: skipped members never reach preflight/wake, and an unsafe replay releases the hold instead of returning 409. All cases pass with the fix. - Browser: all five applicable cases pass together (90 seconds): blocked-work resume in both interfaces, draft/ancestor-pause cases in both interfaces, and the process Stop/pause/reconciliation/restart/cancel lifecycle. The optional native-runner fixture is skipped locally because its fixture binary is not configured. - All 157 task-page component tests pass on the prior commit; subsequent changes affect the server route and Stop fixture only. - `pnpm -r typecheck` and `pnpm build` pass before rebase, and CI typecheck/build passed on the previous PR commit. Server typecheck passes again after the route fix. The final-head CI run also passes these full checks. - `node scripts/check-maps.mjs`, `node scripts/check-token-gates.mjs`, and `git diff --check` pass. - Full `pnpm test:run` was attempted but did not complete: this host cannot initialize embedded PostgreSQL, and unrelated workspace-runtime tests timed out. The focused database tests and E2E suite use disposable PostgreSQL 18 instead. All general-test and serialized-test CI shards passed on the previous PR commit; the final-head CI run also passes every test shard. - The first CI run caught the existing Stop test trying to check a disabled wake option for blocked legacy work. It now asserts zero wake targets and retains the no-execution-before-reconciliation checks. - Earlier E2E attempts exposed fixture problems: assignment started the fixture before it was paused, and the classic interface had two matching editor nodes. The fixture now enables dispatch after the hold exists and scopes the final assertion to the task composer. No product assertion was removed. ## Risks Resume preview is a snapshot. The release route still checks current status, assignment, and execution blockers. It does not bypass approval, budget, or recovery gates. Pause, cancel, and restore keep their existing affected-agent semantics. The test database override only accepts a dedicated database name ending in `_test`; it runs migrations before the suite and closes its clients afterward. ## Model Used OpenAI GPT-6 through Codex, with reasoning, repository tools, browser control, and code execution. The runtime does not expose a more specific model ID or 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 `#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 --- maps/agent-access-map/task-coordination.md | 6 +- maps/feature-map/task-coordination.md | 7 ++ .../issue-tree-control-routes.test.ts | 36 ++++++++++- .../issue-tree-control-service.test.ts | 64 ++++++++++++++++++- server/src/routes/issue-tree-control.ts | 14 ++-- server/src/services/issue-tree-control.ts | 26 +++++++- tests/e2e/composer-stop.spec.ts | 11 +++- tests/e2e/paused-composer.spec.ts | 50 ++++++++++++++- ui/src/components/TaskTreeControls.tsx | 11 +++- ui/src/pages/IssueDetail.tsx | 3 +- 10 files changed, 209 insertions(+), 19 deletions(-) diff --git a/maps/agent-access-map/task-coordination.md b/maps/agent-access-map/task-coordination.md index a9bd1ddcc56..dda7994a89a 100644 --- a/maps/agent-access-map/task-coordination.md +++ b/maps/agent-access-map/task-coordination.md @@ -27,7 +27,11 @@ API: `present` — representative operation IDs: Agent access: `available` — Native create_task/reassign_task; REST / CLI / MCP. Policy: Task visibility/mutation, task-assignment and ownership policy; review audience -independent; tree controls board-only. +independent; tree controls board-only. Resume preview counts only current agent +assignees on todo, in-progress, and in-review tasks as wake targets. Release keeps +blocked and backlog statuses intact; existing execution gates still apply. +Reopened tasks use current eligibility rather than the pause snapshot's skipped +flag. Other active pause holds and execution reconciliation gates remain effective. Evidence: `source-only` — [implementation](../../server/src/routes/issue-tree-control.ts#L95) at the reviewed diff --git a/maps/feature-map/task-coordination.md b/maps/feature-map/task-coordination.md index 86a60dc5611..67f58c06244 100644 --- a/maps/feature-map/task-coordination.md +++ b/maps/feature-map/task-coordination.md @@ -49,6 +49,13 @@ Automated: [execution policy](../../server/src/__tests__/issue-execution-policy. Manual: Complete implementation under a review-required policy and confirm it waits for the required review outcome. Exercise rejection and later approval. Pause the parent while child work is pending, then verify resumption respects budget and ownership gates. +Resume removes the pause without changing task status. Its wake count includes only +current agent assignees on todo, in-progress, or in-review tasks. The dialog explains +that blocked, backlog, and unassigned tasks remain idle. Verify this in both task +interfaces with [the paused composer browser suite](../../tests/e2e/paused-composer.spec.ts). +Release rechecks tasks reopened after the pause; another active pause still prevents +their execution, and uncertain prior executions must be reconciled before waking. + ## Gotchas - Review completion and task completion are different events under some policies. diff --git a/server/src/__tests__/issue-tree-control-routes.test.ts b/server/src/__tests__/issue-tree-control-routes.test.ts index 7931bb768ec..682650b7c5d 100644 --- a/server/src/__tests__/issue-tree-control-routes.test.ts +++ b/server/src/__tests__/issue-tree-control-routes.test.ts @@ -14,6 +14,7 @@ const mockTreeControlService = vi.hoisted(() => ({ cancelIssueStatusesForHold: vi.fn(), restoreIssueStatusesForHold: vi.fn(), getHold: vi.fn(), + getActivePauseHoldGate: vi.fn(), releaseHold: vi.fn(), cancelUnclaimedWakeupsForTree: vi.fn(), })); @@ -72,6 +73,7 @@ describe("issue tree control routes", () => { mockReplayBlocks.mockResolvedValue([]); mockExecutionBlocker.mockResolvedValue(null); mockTreeControlService.getHold.mockResolvedValue(null); + mockTreeControlService.getActivePauseHoldGate.mockResolvedValue(null); mockIssueService.getById.mockResolvedValue({ id: "11111111-1111-4111-8111-111111111111", companyId: "company-2", @@ -213,6 +215,36 @@ describe("issue tree control routes", () => { }, ); + it.each([ + { skipReason: "terminal_status", stillPaused: false }, + { skipReason: "already_held", stillPaused: false }, + { skipReason: "already_held", stillPaused: true }, + ])("rechecks skipped pause members with $skipReason and remaining pause=$stillPaused", async ({ skipReason, stillPaused }) => { + const rootId = "11111111-1111-4111-8111-111111111111"; + const holdId = "33333333-3333-4333-8333-333333333333"; + const childId = "44444444-4444-4444-8444-444444444444"; + const root = { id: rootId, companyId: "company-2", status: "todo", assigneeAgentId: null }; + const child = { id: childId, companyId: "company-2", status: "todo", assigneeAgentId: "current-agent" }; + mockIssueService.getById.mockImplementation(async (id: string) => id === rootId ? root : child); + const hold = { id: holdId, rootIssueId: rootId, mode: "pause", members: [ + { issueId: childId, skipped: true, skipReason, issueStatus: "done" }, + ] }; + mockTreeControlService.getHold.mockResolvedValue(hold); + mockTreeControlService.releaseHold.mockResolvedValue({ ...hold, status: "released" }); + mockTreeControlService.getActivePauseHoldGate.mockResolvedValue(stillPaused ? { holdId: "remaining-hold" } : null); + mockReplayBlocks.mockResolvedValue([{ id: childId, identifier: "TEST-2" }]); + const app = await createApp({ type: "board", userId: "user-1", companyIds: ["company-2"], source: "session" }); + const response = await request(app) + .post(`/api/issues/${rootId}/tree-holds/${holdId}/release`) + .send({ metadata: { wakeAgents: true } }); + expect(response.status).toBe(200); + expect(mockExecutionBlocker).toHaveBeenCalledWith(expect.anything(), "company-2", childId); + expect(mockHeartbeatService.wakeup).toHaveBeenCalledTimes(stillPaused ? 0 : 1); + if (!stillPaused) expect(mockHeartbeatService.wakeup).toHaveBeenCalledWith("current-agent", expect.objectContaining({ + payload: expect.objectContaining({ issueId: childId }), + })); + }); + it("resumes sandbox-backed work through the shared plugin worker manager", async () => { const rootId = "11111111-1111-4111-8111-111111111111"; const holdId = "33333333-3333-4333-8333-333333333333"; @@ -284,14 +316,14 @@ describe("issue tree control routes", () => { ).toEqual([rootId, "child"]); }); - it("keeps the hold active when resume requests an unsafe execution replay", async () => { + it.each([false, true])("keeps the hold active when resume requests an unsafe execution replay (previously skipped=%s)", async (skipped) => { const rootId = "11111111-1111-4111-8111-111111111111"; const holdId = "33333333-3333-4333-8333-333333333333"; mockTreeControlService.getHold.mockResolvedValue({ id: holdId, rootIssueId: rootId, mode: "pause", - members: [{ issueId: rootId }], + members: [{ issueId: rootId, skipped, skipReason: skipped ? "terminal_status" : null }], }); mockReplayBlocks.mockResolvedValue([{ id: rootId, identifier: "TEST-1" }]); mockExecutionBlocker.mockResolvedValue({ nextAction: "Resume without waking agents until the previous execution stops.", diff --git a/server/src/__tests__/issue-tree-control-service.test.ts b/server/src/__tests__/issue-tree-control-service.test.ts index 43c620053a5..923f399d3bd 100644 --- a/server/src/__tests__/issue-tree-control-service.test.ts +++ b/server/src/__tests__/issue-tree-control-service.test.ts @@ -6,6 +6,8 @@ import { agents, agentWakeupRequests, companies, + applyPendingMigrations, + closeRegisteredClients, createDb, heartbeatRuns, issueComments, @@ -20,8 +22,10 @@ import { } from "./helpers/embedded-postgres.js"; import { issueTreeControlService } from "../services/issue-tree-control.js"; import { issueService } from "../services/issues.js"; +import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js"; -const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport(); +const externalUrl = resolveExternalTestDatabaseUrl("PAPERCLIP_ISSUE_TREE_TEST_DATABASE_URL"); +const embeddedPostgresSupport = externalUrl ? { supported: true } : await getEmbeddedPostgresTestSupport(); const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip; if (!embeddedPostgresSupport.supported) { @@ -35,6 +39,11 @@ describeEmbeddedPostgres("issueTreeControlService", () => { let tempDb: Awaited> | null = null; beforeAll(async () => { + if (externalUrl) { + await applyPendingMigrations(externalUrl); + db = createDb(externalUrl); + return; + } tempDb = await startEmbeddedPostgresTestDatabase("paperclip-issue-tree-control-"); db = createDb(tempDb.connectionString); }, 20_000); @@ -53,6 +62,7 @@ describeEmbeddedPostgres("issueTreeControlService", () => { }); afterAll(async () => { + if (externalUrl) await closeRegisteredClients(externalUrl); await tempDb?.cleanup(); }); @@ -623,6 +633,58 @@ describeEmbeddedPostgres("issueTreeControlService", () => { expect(checkedOutLegacyFullPauseRoot.checkoutRunId).toBe(rootRunId); }); + it("previews only executable current assignees as resume wake targets", async () => { + const companyId = randomUUID(); + const rootId = randomUUID(); + const readyAgentId = randomUUID(); + const parkedAgentId = randomUUID(); + const previousAgentId = randomUUID(); + const runId = randomUUID(); + await db.insert(companies).values({ + id: companyId, name: "Resume preview", issuePrefix: "RESUME", + }); + await db.insert(agents).values([readyAgentId, parkedAgentId, previousAgentId].map((id) => ({ + id, companyId, name: id, role: "engineer", status: "idle", adapterType: "process", + }))); + const children = ["todo", "in_progress", "in_review", "blocked", "backlog", "done"].map((status) => ({ + id: randomUUID(), companyId, parentId: rootId, title: status, status, + assigneeAgentId: status === "blocked" || status === "backlog" ? parkedAgentId : readyAgentId, + })); + await db.insert(issues).values([ + { id: rootId, companyId, title: "Unassigned root", status: "todo" }, + ...children, + ]); + const svc = issueTreeControlService(db); + const pause = await svc.createHold(companyId, rootId, { + mode: "pause", + actor: { actorType: "user", actorId: "board-user", userId: "board-user" }, + }); + expect(pause.hold.members?.find((member) => member.issueId === children[5].id)).toMatchObject({ + skipped: true, skipReason: "terminal_status", + }); + await db.update(issues).set({ status: "todo" }).where(eq(issues.id, children[5].id)); + // A previous executor is observable while stopping, but is not the current assignee to wake. + await db.insert(heartbeatRuns).values({ + id: runId, companyId, agentId: previousAgentId, invocationSource: "assignment", + status: "running", contextSnapshot: { issueId: children[0].id }, + }); + await db.update(issues).set({ executionRunId: runId }).where(eq(issues.id, children[0].id)); + + const preview = await svc.preview(companyId, rootId, { mode: "resume" }); + expect(preview.totals.affectedIssues).toBe(7); + expect(preview.affectedAgents).toEqual([{ agentId: readyAgentId, issueCount: 4, activeRunCount: 0 }]); + expect(preview.totals.affectedAgents).toBe(1); + expect(preview.warnings).toContainEqual({ + code: "resume_tasks_remain_idle", + message: "Blocked, backlog, and unassigned tasks will be unpaused but will not start.", + issueIds: [rootId, children[3].id, children[4].id].sort(), + }); + const rows = await db.select().from(issues).where(eq(issues.companyId, companyId)); + expect(rows.find((row) => row.id === children[3].id)?.status).toBe("blocked"); + expect(rows.find((row) => row.id === children[4].id)?.status).toBe("backlog"); + expect((await svc.getHold(companyId, pause.hold.id))?.status).toBe("active"); + }); + it("resumes subtree pauses by releasing matching pause holds", async () => { const companyId = randomUUID(); const rootIssueId = randomUUID(); diff --git a/server/src/routes/issue-tree-control.ts b/server/src/routes/issue-tree-control.ts index c9a00491ba3..05c208756e9 100644 --- a/server/src/routes/issue-tree-control.ts +++ b/server/src/routes/issue-tree-control.ts @@ -6,6 +6,7 @@ import { } from "@paperclipai/db"; import { and, eq, inArray, isNotNull } from "drizzle-orm"; import { getExecutionBlocker } from "../services/execution-blocker.js"; +import { ISSUE_TREE_RESUME_EXECUTABLE_STATUSES } from "../services/issue-tree-control.js"; import { conflict } from "../errors.js"; import { createIssueTreeHoldSchema, @@ -26,7 +27,6 @@ import { assertBoard, getAccessibleResource, getActorInfo } from "./authz.js"; import type { PluginWorkerManager } from "../services/plugin-worker-manager.js"; const TREE_RUN_CANCELLATION_RESPONSE_WAIT_MS = 1_000; -const RESUME_EXECUTABLE_STATUSES = ["todo", "in_progress", "in_review"]; function errorToMessage(error: unknown) { return error instanceof Error ? error.message : String(error); @@ -436,15 +436,13 @@ export function issueTreeControlRoutes( const activeHold = await treeControlSvc.getHold(root.companyId, holdId); const issueIds = activeHold?.mode === "pause" && activeHold.rootIssueId === root.id - ? (activeHold.members ?? []) - .filter((member) => !member.skipped) - .map((member) => member.issueId) + ? (activeHold.members ?? []).map((member) => member.issueId) : []; if (issueIds.length > 0) { const candidates = await db.select({ id: issueRows.id, identifier: issueRows.identifier }) .from(issueRows).where(and( eq(issueRows.companyId, root.companyId), inArray(issueRows.id, issueIds), - inArray(issueRows.status, RESUME_EXECUTABLE_STATUSES), isNotNull(issueRows.assigneeAgentId), + inArray(issueRows.status, ISSUE_TREE_RESUME_EXECUTABLE_STATUSES), isNotNull(issueRows.assigneeAgentId), )); for (const task of candidates) { const blocked = await getExecutionBlocker(db, root.companyId, task.id); @@ -489,16 +487,18 @@ export function issueTreeControlRoutes( const wakeFailures: Array<{ issueId: string; message: string }> = []; if (hold.mode === "pause" && req.body.metadata?.wakeAgents === true) { for (const member of hold.members ?? []) { - if (member.skipped) continue; try { const issue = await issuesSvc.getById(member.issueId); if ( !issue || issue.companyId !== root.companyId || !issue.assigneeAgentId || - !RESUME_EXECUTABLE_STATUSES.includes(issue.status) + !ISSUE_TREE_RESUME_EXECUTABLE_STATUSES.includes(issue.status) ) continue; + // The snapshot may predate reopening a task or releasing another + // pause. Current task state and remaining holds govern execution. + if (await treeControlSvc.getActivePauseHoldGate(root.companyId, issue.id)) continue; await heartbeat.wakeup(issue.assigneeAgentId, { source: "assignment", triggerDetail: "system", diff --git a/server/src/services/issue-tree-control.ts b/server/src/services/issue-tree-control.ts index ecf8a07c6fd..1d8af92fd5b 100644 --- a/server/src/services/issue-tree-control.ts +++ b/server/src/services/issue-tree-control.ts @@ -71,6 +71,7 @@ type RestoreTreeStatusResult = TreeStatusUpdateResult & { }; const TERMINAL_ISSUE_STATUSES = new Set(["done", "cancelled"]); +export const ISSUE_TREE_RESUME_EXECUTABLE_STATUSES = ["todo", "in_progress", "in_review"]; const ACTIVE_RUN_STATUSES = ["queued", "running"] as const; const DEFAULT_RELEASE_POLICY: IssueTreeHoldReleasePolicy = { strategy: "manual" }; const MAX_PAUSE_HOLD_ANCESTOR_DEPTH = 100; @@ -325,13 +326,21 @@ function issueSkipReason(input: { return null; } -function buildAffectedAgents(issuesToPreview: IssueTreePreviewIssue[]): IssueTreePreviewAgent[] { +function canWakeOnResume(issue: IssueTreePreviewIssue): boolean { + return !!issue.assigneeAgentId && ISSUE_TREE_RESUME_EXECUTABLE_STATUSES.includes(issue.status); +} + +function buildAffectedAgents( + issuesToPreview: IssueTreePreviewIssue[], + mode: IssueTreeControlMode, +): IssueTreePreviewAgent[] { const byAgentId = new Map(); for (const issue of issuesToPreview) { if (issue.skipped) continue; + if (mode === "resume" && !canWakeOnResume(issue)) continue; const agentIds = new Set(); if (issue.assigneeAgentId) agentIds.add(issue.assigneeAgentId); - if (issue.activeRun) agentIds.add(issue.activeRun.agentId); + if (mode !== "resume" && issue.activeRun) agentIds.add(issue.activeRun.agentId); for (const agentId of agentIds) { const current = byAgentId.get(agentId) ?? { agentId, issueCount: 0, activeRunCount: 0 }; current.issueCount += 1; @@ -388,6 +397,17 @@ function buildWarnings(input: { }); } + if (input.mode === "resume") { + const idleIssueIds = affectedIssues.filter((issue) => !canWakeOnResume(issue)).map((issue) => issue.id); + if (idleIssueIds.length > 0) { + warnings.push({ + code: "resume_tasks_remain_idle", + message: "Blocked, backlog, and unassigned tasks will be unpaused but will not start.", + issueIds: idleIssueIds.sort(), + }); + } + } + if (input.mode === "restore") { const changedIssueIds = input.issuesToPreview .filter((issue) => issue.skipReason === "changed_after_cancel") @@ -676,7 +696,7 @@ export function issueTreeControlService(db: Db) { const activeRuns = activeRunRows .map(toPreviewRun) .sort((a, b) => a.issueId.localeCompare(b.issueId) || a.id.localeCompare(b.id)); - const affectedAgents = buildAffectedAgents(issuesToPreview); + const affectedAgents = buildAffectedAgents(issuesToPreview, input.mode); return { companyId, diff --git a/tests/e2e/composer-stop.spec.ts b/tests/e2e/composer-stop.spec.ts index a9c747f9bf5..30c31a33a8b 100644 --- a/tests/e2e/composer-stop.spec.ts +++ b/tests/e2e/composer-stop.spec.ts @@ -380,7 +380,16 @@ for (const adapter of ["process", "paperclip_runner"] as const) { ).toEqual([]); } await menu(page, "Resume subtree"); - await page.getByRole("dialog").getByRole("checkbox").check(); + const resumeWake = page.getByRole("dialog").getByRole("checkbox"); + if (adapter === "process") { + // Stopped legacy work is blocked pending reconciliation. Removing the + // pause must not promise or request a wake through that recovery gate. + await expect(resumeWake).toHaveAccessibleName("Wake affected agents (0)"); + await expect(resumeWake).toBeDisabled(); + await expect(resumeWake).not.toBeChecked(); + } else { + await resumeWake.check(); + } await page .getByRole("dialog") .getByRole("button", { name: "Resume subtree", exact: true }) diff --git a/tests/e2e/paused-composer.spec.ts b/tests/e2e/paused-composer.spec.ts index c01d083632a..f3c41525648 100644 --- a/tests/e2e/paused-composer.spec.ts +++ b/tests/e2e/paused-composer.spec.ts @@ -7,6 +7,51 @@ async function json(response: APIResponse) { } for (const classic of [false, true]) { + test(`resume preview: ${classic ? "classic" : "task chat"} does not promise to wake blocked work`, async ({ page, request }) => { + test.setTimeout(120_000); + const company = await json(await request.post("/api/companies", { data: { name: `Resume preview ${Date.now()}` } })); + const settings = await json(await request.get("/api/instance/settings/experimental")); + try { + await json(await request.patch("/api/instance/settings/experimental", { data: { enableClassicTaskInterface: classic } })); + const agent = await json(await request.post(`/api/companies/${company.id}/agents`, { data: { + name: "Resume preview fixture", role: "engineer", adapterType: "process", + adapterConfig: { command: "/usr/bin/true" }, + runtimeConfig: { heartbeat: { enabled: false, wakeOnDemand: false } }, + } })); + const task = await json(await request.post(`/api/companies/${company.id}/issues`, { data: { + title: "Blocked work stays blocked", status: "blocked", assigneeAgentId: agent.id, + } })); + await page.goto(`/${company.issuePrefix}/issues/${task.identifier}`); + await page.getByRole("button", { name: "More task actions", exact: true }).click(); + await page.getByRole("button", { name: "Pause work", exact: true }).click(); + const takeover = page.getByTestId("paused-composer-takeover"); + await expect(takeover).toBeVisible(); + // Enable dispatch only after the hold exists; assignment itself otherwise starts a run. + expect((await json(await request.get(`/api/issues/${task.id}`))).status).toBe("blocked"); + await json(await request.patch(`/api/agents/${agent.id}`, { data: { + runtimeConfig: { heartbeat: { enabled: false, wakeOnDemand: true } }, + } })); + await takeover.getByRole("button", { name: "Resume task" }).click(); + const dialog = page.getByRole("dialog"); + await expect(dialog).toContainText("The pause will be removed from 1 task."); + const wake = dialog.getByRole("checkbox", { name: "Wake affected agents (0)" }); + await expect(wake).toBeDisabled(); + await expect(wake).not.toBeChecked(); + await expect(dialog).toContainText("Blocked, backlog, and unassigned tasks will be unpaused but will not start."); + await dialog.getByRole("button", { name: "Resume work", exact: true }).click(); + await expect(dialog).toHaveCount(0); + await expect(takeover).toHaveCount(0); + await page.reload(); + const editor = (classic ? page.getByTestId("issue-chat-composer") : page).getByRole("textbox", { name: "editable markdown" }); + await expect(editor).toBeVisible(); + expect((await json(await request.get(`/api/issues/${task.id}`))).status).toBe("blocked"); + expect(await json(await request.get(`/api/companies/${company.id}/heartbeat-runs?agentId=${agent.id}`))).toEqual([]); + } finally { + await request.patch(`/api/companies/${company.id}`, { data: { status: "archived" } }); + await request.patch("/api/instance/settings/experimental", { data: { enableClassicTaskInterface: settings.enableClassicTaskInterface } }); + } + }); + test(`paused composer: ${classic ? "classic" : "task chat"} preserves drafts and requires resume`, async ({ page, request }) => { test.setTimeout(120_000); const company = await json(await request.post("/api/companies", { data: { name: `Paused composer ${Date.now()}` } })); @@ -63,8 +108,11 @@ for (const classic of [false, true]) { await takeover.getByRole("link", { name: "Resume subtree" }).click(); await expect(page).toHaveURL(new RegExp(task.identifier)); await takeover.getByRole("button", { name: "Resume subtree" }).click(); - await page.getByRole("dialog").getByRole("checkbox").uncheck(); + const subtreeWake = page.getByRole("dialog").getByRole("checkbox"); + if (await subtreeWake.isEnabled()) await subtreeWake.uncheck(); + else await expect(subtreeWake).not.toBeChecked(); await page.getByRole("dialog").getByRole("button", { name: "Resume subtree", exact: true }).click(); + await expect(page.getByRole("dialog")).toHaveCount(0); await page.goto(`/${company.issuePrefix}/issues/${child.identifier}`); await expect(takeover).toHaveCount(0); await expect(editor).toBeVisible(); diff --git a/ui/src/components/TaskTreeControls.tsx b/ui/src/components/TaskTreeControls.tsx index d2fd9137547..dfd0d1aaf1f 100644 --- a/ui/src/components/TaskTreeControls.tsx +++ b/ui/src/components/TaskTreeControls.tsx @@ -78,6 +78,7 @@ export function TaskTreeControlDialog({ scope, affectedCount, affectedAgentCount, + warnings = [], loading, error, pending, @@ -93,6 +94,7 @@ export function TaskTreeControlDialog({ scope: "leaf" | "subtree"; affectedCount: number; affectedAgentCount: number; + warnings?: string[]; loading: boolean; error?: string | null; pending: boolean; @@ -129,7 +131,9 @@ export function TaskTreeControlDialog({ ? "Loading…" : cancel ? `${tasks} will be cancelled.` - : `${tasks} will ${mode === "restore" ? "be restored" : "resume"}.`} + : mode === "restore" + ? `${tasks} will be restored.` + : `The pause will be removed from ${tasks}.`} {error ? ( @@ -151,13 +155,16 @@ export function TaskTreeControlDialog({ ) : null} + {!loading ? warnings.map((warning) => ( +

{warning}

+ )) : null}