From b1330c98e8fe528bb3a4b24299cd3b4cd67c6941 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Thu, 12 Nov 2026 06:05:19 -0600 Subject: [PATCH 1/7] fix(evals): grade full cohort 6 false failures on saved state and keep failed-run evidence (#21089) 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 > - The chat catalog evals check that a chat agent does real product work, and they grade saved state, not reply wording > - Full cohort 6 (OpenCode with DeepSeek V4.1 Flash on master b7693e2076) had five false failures where the product behaviour was correct > - Three more failures kept no run logs or ledger, and one was labelled as transient infrastructure when the product had cancelled the run > - A false failure hides real product defects, and missing evidence stops diagnosis > - This pull request corrects the five graders on saved state and fixes the evidence gaps > - The benefit is that the cohort result shows real product behaviour, and each failure keeps the evidence to explain it ## Linked Issues or Issue Description **What happened?** Five chat eval cases failed although saved state showed correct behaviour. Three run-bound failures and one early Playwright exit saved no run logs or run ledger. A reassignment cancellation was classified as `transient_infrastructure`. **Expected behavior** Each grader accepts the valid behaviour and still rejects the broken product. Every failed attempt keeps its run ledger and the logs it can read. **Steps to reproduce** Run the cohort 6 cases on master. Read the failed checks and the missing `chat-catalog-runs.json` files. ## What Changed - `budgets-costs.spend-breakdown` (oracle v5). Old check: only unranged cost reports, the task cost summary, or the single run record counted. The lead read the run through `GET /api/companies/{companyId}/heartbeat-runs` filtered to Morgan with `limit: 200` (saved input digest `36e47c51…`). New check: a run-list read counts when its saved input digest names a full list that reaches the original run (unfiltered or filtered to its agent, with a limit past the runs ahead of it at read time). Still fails: no accounting read, a list that cannot reach the run, another agent's list, a summary list, a denied read, a read in another run. - `status-cards.explain-card` (oracle v6). Old check: only `GET /api/issues/{id}` counted as a live read. The lead read COM-1 through `search_tasks`, and the saved result showed the task as done. New check: a dedicated task tool result that holds the source task id with its live status counts. Still fails: an empty search, another task, a different status, a `call_api` result, an error result, a result with no paired tool use. - `secrets.personal-secret` (oracle v20). Old check: `JSON.parse` of the whole bash output. The worker appended `EXIT_CODE=0`. New check: the one JSON object in the output that carries `receiptId`, which must still equal the fixture endpoint's authorised call receipt. Still fails: a wrong receipt, a failed check, two different receipts, no JSON object, key=value text. - `skills.fork-read-only` (oracle `integrator.skill-fork.v2`). Old check: a wording list (`unchanged|read-only|protected|not changed`) rejected "untouched". New check: the reply names the saved fork or links its Studio page. Saved state already proves the upstream is unchanged and the fork exists. Still fails: no fork, a reply without the fork name or link, a link to another skill, an edited upstream. - `steering.discard-queued-message` (oracle v6). Old check: the label string must not appear anywhere in the final plan. The revised plan kept a "superseded" note with the label. New check: the person asked for a section labelled with the attempt nonce (a setup literal). A heading with that label must exist in the plan before the consuming run or in that run's saves, and the final saved revision must have no heading with it. Body mentions are allowed. The base plan is the revision before the consuming run first saved the label, so repeated saves by that run do not matter. Still fails: the labelled heading kept, renamed but still labelled, or never saved. - Failure evidence: the failure path saves `chat-catalog-failure-run-ledger.json` before retirement, continues when retirement fails, and reads a failed run's log and events independently with a separate `logError` / `eventsError` when one run has no log. Before, one cancelled never-started run (log 404) dropped the logs of every run (`cases.cases-disabled`, `defer-and-reopen`, `approve-tool-once`, `assignment-conflict`). - Interruption act: the click and its `waitForResponse` are awaited together. Before, the response promise could reject while the click waited, and the unhandled rejection stopped the worker with no evidence (`interrupt-with-direction`). - A product-cancelled run is reported as `Observed run was cancelled by ()` and classifies as `candidate_failure`. Failed and timed-out runs keep `Observed provider run failed`. ## Verification - Calibration tests for each grader: the retained cohort 6 shape, a reworded valid shape, and broken shapes. - Regrade of retained cohort 6 evidence: spend-breakdown and fork-read-only observations pass; the explain-card initial run reads the source live; the discard plan revisions pass and the unrevised plan fails. - `npx vitest run` on the changed and related runner-e2e domain tests: 283 passed, 4 skipped. All 148 identity, integrator, runtime and personal-secret domain test files pass. - `pnpm test:e2e:runner:typecheck` passes. - `node tests/runner-e2e/source-sdk-public-inputs.mjs --check`: `changed: false`. - Paid run: see the PR comment. ## Risks - Low. Only eval graders and harness evidence change. The run-list rule depends on the list order (newest first) and the default and maximum limits from `packages/shared`. - A product-cancelled run no longer retries automatically as transient infrastructure. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, with tool use and code execution in Claude Code. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- .../runner-e2e/chat-catalog-descriptors.json | 10 ++--- .../external-personal-secret-receipt.test.ts | 11 +++++ .../external-personal-secret.test.ts | 2 +- .../external-personal-secret.ts | 24 ++++++++--- .../identity-accounting.test.ts | 30 +++++++++++++- .../identity-accounting.ts | 37 +++++++++++++++-- .../integrator-skill-imports.test.ts | 11 ++++- .../integrator-skill-imports.ts | 8 ++-- .../integrator-status-cards.test.ts | 14 +++++++ .../integrator-status-cards.ts | 26 ++++++++++-- .../runtime-discard.test.ts | 27 +++++++++++- .../chat-catalog-domains/runtime-discard.ts | 17 ++++++-- .../runtime-interruption.ts | 11 ++--- .../runner-e2e/chat-catalog-ended-run.test.ts | 16 ++++++++ .../chat-catalog-failure-retirement.test.ts | 33 +++++++++++++-- tests/runner-e2e/chat-catalog-flow.ts | 41 ++++++++++++++++--- 16 files changed, 275 insertions(+), 43 deletions(-) create mode 100644 tests/runner-e2e/chat-catalog-ended-run.test.ts diff --git a/tests/runner-e2e/chat-catalog-descriptors.json b/tests/runner-e2e/chat-catalog-descriptors.json index 6c796464629..c1aff01ccca 100644 --- a/tests/runner-e2e/chat-catalog-descriptors.json +++ b/tests/runner-e2e/chat-catalog-descriptors.json @@ -1258,7 +1258,7 @@ "chat-catalog-domains/api-read-receipts.ts", "run-observations.ts" ], - "oracleVersion": "paperclip.chat-catalog.spend-breakdown.structural.v4", + "oracleVersion": "paperclip.chat-catalog.spend-breakdown.structural.v5", "expectedRunCount": 2, "turnTimeoutMs": 120000, "attemptTimeoutMs": 600000, @@ -5079,7 +5079,7 @@ "../../ui/src/pages/secrets/SetMyUserSecretDialog.tsx", "chat-scenarios/secrets.yaml" ], - "oracleVersion": "paperclip.chat-catalog.personal-secret.v19", + "oracleVersion": "paperclip.chat-catalog.personal-secret.v20", "expectedRunCount": 3, "expectedHumanMessageCount": 2, "minimumRunCount": 3, @@ -5275,7 +5275,7 @@ "chat-catalog-domains/internal-support.ts", "chat-scenarios/skills.yaml" ], - "oracleVersion": "paperclip.chat-catalog.integrator.v1", + "oracleVersion": "paperclip.chat-catalog.integrator.skill-fork.v2", "expectedRunCount": 1, "expectedHumanMessageCount": 1, "turnTimeoutMs": 120000, @@ -5394,7 +5394,7 @@ "run-observations.ts", "chat-scenarios/status-cards.yaml" ], - "oracleVersion": "paperclip.chat-catalog.status-card.explain.v5", + "oracleVersion": "paperclip.chat-catalog.status-card.explain.v6", "expectedRunCount": 5, "minimumRunCount": 3, "expectedHumanMessageCount": 2, @@ -5493,7 +5493,7 @@ "chat-catalog-domains/identity-support.ts", "chat-scenarios/steering.yaml" ], - "oracleVersion": "paperclip.chat-catalog.runtime-discard.v4", + "oracleVersion": "paperclip.chat-catalog.runtime-discard.v6", "coverageGaps": [], "expectedRunCount": 5, "expectedHumanMessageCount": 2, diff --git a/tests/runner-e2e/chat-catalog-domains/external-personal-secret-receipt.test.ts b/tests/runner-e2e/chat-catalog-domains/external-personal-secret-receipt.test.ts index 02ba333dad6..70a6226023e 100644 --- a/tests/runner-e2e/chat-catalog-domains/external-personal-secret-receipt.test.ts +++ b/tests/runner-e2e/chat-catalog-domains/external-personal-secret-receipt.test.ts @@ -86,3 +86,14 @@ it("does not enable the personal receipt option for other credential cases", asy const ctx = await context(); ctx.scenario.id = "secrets.least-scope-delivery"; await expect(secretTestEndpoint(ctx, "morgan", "synthetic-personal-value", "PUBLISHING_API_KEY", undefined, { personalWorkerReceipt: true })).rejects.toThrow("dedicated personal-secret endpoint"); }); +it("reads the receipt object out of output that carries other text, still requiring the endpoint's receipt", () => { + const receipt = JSON.stringify({ ok: true, status: 200, check: "publishing endpoint", receiptId: "a".repeat(48) }); + const withOutput = (output: string) => { const f = delivery(); f.evidence.events[0]!.payload.prpEvent.payload.output = output; return personalSecretWorkerReceipt(f.run, f.evidence, f.expected); }; + expect(withOutput(`${receipt}EXIT_CODE=0\n`)).toMatchObject({ receiptId: "a".repeat(48) }); + expect(withOutput(`checking publishing endpoint...\n${JSON.stringify(JSON.parse(receipt), null, 2)}\nexit: 0 {done}\n`)).toMatchObject({ receiptId: "a".repeat(48) }); + expect(withOutput(`${receipt.replace("a".repeat(48), "b".repeat(48))}EXIT_CODE=0\n`)).toBeUndefined(); + expect(withOutput(`${JSON.stringify({ ok: false, status: 403, check: "publishing endpoint", receiptId: "a".repeat(48) })}EXIT_CODE=1\n`)).toBeUndefined(); + expect(withOutput(`${receipt}\n${receipt.replace("a".repeat(48), "b".repeat(48))}`)).toBeUndefined(); + expect(withOutput("EXIT_CODE=0\n")).toBeUndefined(); + expect(withOutput(`receiptId=${"a".repeat(48)} ok=true status=200`)).toBeUndefined(); +}); diff --git a/tests/runner-e2e/chat-catalog-domains/external-personal-secret.test.ts b/tests/runner-e2e/chat-catalog-domains/external-personal-secret.test.ts index cd1db18e3e1..47d9469c950 100644 --- a/tests/runner-e2e/chat-catalog-domains/external-personal-secret.test.ts +++ b/tests/runner-e2e/chat-catalog-domains/external-personal-secret.test.ts @@ -338,7 +338,7 @@ it("keeps a confirmation dependent on actual worker delivery",()=>{ }); it("declares the prospective personal acknowledgment calibration without changing its bounds", () => { - expect(personalSecretExternalCases[0]).toMatchObject({ oracleVersion: "paperclip.chat-catalog.personal-secret.v19", + expect(personalSecretExternalCases[0]).toMatchObject({ oracleVersion: "paperclip.chat-catalog.personal-secret.v20", expectedRunCount: 3, minimumRunCount: 3, expectedHumanMessageCount: 2, attemptTimeoutMs: 660000 }); }); // Full cohort 3: the recorded guidance linked My secrets and excluded chat; a variant that also asks diff --git a/tests/runner-e2e/chat-catalog-domains/external-personal-secret.ts b/tests/runner-e2e/chat-catalog-domains/external-personal-secret.ts index ee37909a501..56351ccbbe7 100644 --- a/tests/runner-e2e/chat-catalog-domains/external-personal-secret.ts +++ b/tests/runner-e2e/chat-catalog-domains/external-personal-secret.ts @@ -194,6 +194,22 @@ export interface PersonalSecretWorkerEvidence { calls: Awaited>["calls"]; events: PersonalSecretWorkerEvent[]; } +export function jsonObjectsIn(text: string): Record[] { + const objects: Record[] = []; + let start = -1, depth = 0, inString = false, escaped = false; + for (let index = 0; index < text.length; index++) { + const char = text[index]; + if (start < 0) { if (char === "{") { start = index; depth = 1; inString = false; escaped = false; } continue; } + if (inString) { if (escaped) escaped = false; else if (char === "\\") escaped = true; else if (char === '"') inString = false; continue; } + if (char === '"') inString = true; + else if (char === "{") depth++; + else if (char === "}" && --depth === 0) { + try { const parsed = JSON.parse(text.slice(start, index + 1)); if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) objects.push(parsed); } catch { index = start; } + start = -1; + } + } + return objects; +} export function personalSecretWorkerReceipt(run: PersonalSecretWorkerRun | undefined, evidence: PersonalSecretWorkerEvidence | undefined, expected: { companyId: string; agentId: string; taskId: string; userId: string }) { const task = evidence?.task; @@ -214,10 +230,8 @@ export function personalSecretWorkerReceipt(run: PersonalSecretWorkerRun | undef if (prp?.runId !== run.id || prp.eventType !== event.eventType || tool?.name !== "bash" || tool.status !== "completed" || tool.exitCode !== 0 || tool.outputTruncated !== false || typeof tool.output !== "string" || !Number.isFinite(observed) || observed < requested || observed > finished) return false; - try { - const output = JSON.parse(tool.output) as { ok?: boolean; status?: number; check?: string; receiptId?: string } | null; - return output?.ok === true && output.status === 200 && output.check === "publishing endpoint" && output.receiptId === call.receiptId; - } catch { return false; } + const receipts = jsonObjectsIn(tool.output).filter(output => "receiptId" in output) as Array<{ ok?: unknown; status?: unknown; check?: unknown; receiptId?: unknown }>; + return receipts.length === 1 && receipts[0]!.ok === true && receipts[0]!.status === 200 && receipts[0]!.check === "publishing endpoint" && receipts[0]!.receiptId === call.receiptId; }); if (!matching.length) return; return { receiptId: call.receiptId!, runId: run.id, agentId: run.agentId, event: matching[0]! }; @@ -475,7 +489,7 @@ export const personalSecretExternalCases = [ if (!o.state.initialQuestionId) return; return { interactionId: String(o.state.initialQuestionId), sourceRunId: String(o.state.initialRunId), userId: String(o.state.currentPersonId) }; }, - oracleVersion: "paperclip.chat-catalog.personal-secret.v19", + oracleVersion: "paperclip.chat-catalog.personal-secret.v20", setupPolicy: { readiness: "preserve-scenario", invariantCheckIds: ["current-owner-missing-required-personal-value"] }, expectedRunCount: 3, minimumRunCount: 3, diff --git a/tests/runner-e2e/chat-catalog-domains/identity-accounting.test.ts b/tests/runner-e2e/chat-catalog-domains/identity-accounting.test.ts index 4154de4a806..6ab2773ae87 100644 --- a/tests/runner-e2e/chat-catalog-domains/identity-accounting.test.ts +++ b/tests/runner-e2e/chat-catalog-domains/identity-accounting.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { accountingIdentityCases, leadApiCalls, nativeAccountingPrerequisite, readSavedAccounting, citedRunReads, isCostsPagePath, type LeadApiCall } from "./identity-accounting.js"; +import { accountingIdentityCases, leadApiCalls, nativeAccountingPrerequisite, readSavedAccounting, citedRunReads, isCostsPagePath, runListPosition, type LeadApiCall } from "./identity-accounting.js"; import { callApiInputDigest } from "./api-read-receipts.js"; import type { IdentityObservation } from "./identity-support.js"; const costRead = (runId: string, operationId: string, status = 200, digest = "d"): LeadApiCall => ({ runId, operationId, digest, ok: status < 300, status }); @@ -173,3 +173,31 @@ it("the browser check opens the same Costs links the grader accepts", () => { for (const path of ["/ACO/activity/costs", "/ACO/costs"]) expect(isCostsPagePath(path)).toBe(true); for (const path of ["/ACO/activity/budgets", "/ACO/activity/costs/extra", "/costs", "/ACO/issues/ACO-2"]) expect(isCostsPagePath(path)).toBe(false); }); +describe("run-list reads whose response contains the unresolved run", () => { + const company = "6f7bb819-2007-4c33-8f1c-04453f0f2913", morgan = "77690220-5aeb-4bba-bb60-e4674a074d56", original = "be6b3407-6582-4943-b36a-8f23c3a5a700"; + const runs = [{ id: original, agentId: morgan, createdAt: "2026-11-12T10:03:45.598Z" }, { id: "lead", agentId: "ceo", createdAt: "2026-11-12T10:04:12.795Z", finishedAt: "2026-11-12T10:05:34.548Z" }]; + const position = runListPosition(runs, original, runs[1]!)!; + const list = (input: Record, status = 200) => costRead("lead", "GET /api/companies/{companyId}/heartbeat-runs", status, callApiInputDigest({ operationId: "GET /api/companies/{companyId}/heartbeat-runs", ...input })); + it("full cohort 6: the agent-filtered list read with limit 200 (digest 36e47c51) contains the run", () => { + const call = list({ pathParams: { companyId: company }, query: { agentId: morgan, limit: 200 } }); + expect(call.digest.startsWith("36e47c51")).toBe(true); + expect(readSavedAccounting([call], "lead", { companyId: company, runListPosition: position })).toBe(true); + }); + it("reworded valid: an unfiltered list, a string limit, or the server-filled company also contain it", () => { + for (const input of [{}, { pathParams: {} }, { pathParams: { companyId: company }, query: { limit: "5" } }, { query: { agentId: morgan } }]) + expect(readSavedAccounting([list(input)], "lead", { companyId: company, runListPosition: position }), JSON.stringify(input)).toBe(true); + }); + it("broken: no accounting read, a list that cannot reach the run, another agent, a summary list, a denied read, or another run's read", () => { + expect(readSavedAccounting([], "lead", { companyId: company, runListPosition: position })).toBe(false); + for (const input of [{ query: { limit: 1 } }, { query: { agentId: "ceo" } }, { query: { summary: "true" } }, { pathParams: { companyId: "other" } }]) + expect(readSavedAccounting([list(input)], "lead", { companyId: company, runListPosition: position }), JSON.stringify(input)).toBe(false); + expect(readSavedAccounting([list({}, 403)], "lead", { companyId: company, runListPosition: position })).toBe(false); + expect(readSavedAccounting([{ ...list({}), runId: "other" }], "lead", { companyId: company, runListPosition: position })).toBe(false); + expect(readSavedAccounting([list({})], "lead", { companyId: company })).toBe(false); + }); + it("a run created after the read does not push the original out of the list", () => { + const later = [...runs, { id: "later", agentId: morgan, createdAt: "2026-11-12T10:06:00.000Z" }]; + expect(runListPosition(later, original, runs[1]!)).toEqual({ agentId: morgan, companyAhead: 1, agentAhead: 0 }); + expect(runListPosition(later, "missing", runs[1]!)).toBeUndefined(); + }); +}); diff --git a/tests/runner-e2e/chat-catalog-domains/identity-accounting.ts b/tests/runner-e2e/chat-catalog-domains/identity-accounting.ts index 2f1d213aa17..af460992149 100644 --- a/tests/runner-e2e/chat-catalog-domains/identity-accounting.ts +++ b/tests/runner-e2e/chat-catalog-domains/identity-accounting.ts @@ -8,7 +8,8 @@ import { sendChatMessage } from "../chat-flow.js"; import { pollUntil } from "../api.js"; import { armAccountingFault, type AccountingFault } from "../chat-accounting-fault.js"; import { collectRunEvents } from "../run-observations.js"; -import { apiReadDigests, recordParams } from "./api-read-receipts.js"; +import { HEARTBEAT_RUN_LIST_DEFAULT_LIMIT, HEARTBEAT_RUN_LIST_MAX_LIMIT } from "../../../packages/shared/src/constants.js"; +import { apiReadDigests, callApiInputDigest, recordParams } from "./api-read-receipts.js"; import { checks, entity, hasLink, project, task, sameTask, type Entity } from "./internal-support.js"; import { identityDefinition, identityObservation, identityWorker, observeIdentity, openStandingChat, probeAgentPermission } from "./identity-support.js"; @@ -94,7 +95,33 @@ export interface SavedAccountingTarget { companyId?: string; task?: Pick`. */ citedRunReads?: readonly string[]; /** Run records this reading run saved with `saveResponse`, read back from the product's saved asset. */ - savedRunRecords?: readonly SavedRunRecord[] } + savedRunRecords?: readonly SavedRunRecord[]; + runListPosition?: RunListPosition } +export interface RunListPosition { agentId: string; companyAhead: number; agentAhead: number } +const RUN_LIST_OPERATION = "GET /api/companies/{companyId}/heartbeat-runs"; +const runListCache = new Map>(); +export function runListDigests(companyId: string, position: RunListPosition): ReadonlySet { + const key = JSON.stringify([companyId, position]); + const cached = runListCache.get(key); if (cached) return cached; + const queries: Array | undefined> = []; + for (const [filter, ahead] of [[{}, position.companyAhead], [{ agentId: position.agentId }, position.agentAhead]] as const) { + if (ahead < HEARTBEAT_RUN_LIST_DEFAULT_LIMIT) queries.push(filter); + for (let limit = ahead + 1; limit <= HEARTBEAT_RUN_LIST_MAX_LIMIT; limit++) queries.push({ ...filter, limit }, { ...filter, limit: String(limit) }); + } + if (position.companyAhead < HEARTBEAT_RUN_LIST_DEFAULT_LIMIT) queries.push(undefined); + const digests = new Set(); + for (const pathParams of [{ companyId }, {}, undefined]) for (const query of queries) + digests.add(callApiInputDigest({ operationId: RUN_LIST_OPERATION, ...(pathParams ? { pathParams } : {}), ...(query ? { query } : {}) })); + runListCache.set(key, digests); + return digests; +} +export function runListPosition(runs: ReadonlyArray<{ id: string; agentId: string }>, originalRunId: string, readingRun: object): RunListPosition | undefined { + const createdAt = (run: object) => Date.parse(String((run as { createdAt?: unknown }).createdAt)); + const original = runs.find(run => run.id === originalRunId), created = original ? createdAt(original) : NaN, readAt = Date.parse(String((readingRun as { finishedAt?: unknown }).finishedAt)); + if (!original || !Number.isFinite(created) || !Number.isFinite(readAt)) return; + const ahead = runs.filter(run => run.id !== original.id && createdAt(run) >= created && createdAt(run) <= readAt); + return { agentId: original.agentId, companyAhead: ahead.length, agentAhead: ahead.filter(run => run.agentId === original.agentId).length }; +} /** A `call_api` read saved with `saveResponse` becomes a company asset that the product logs as * `asset.created` by the reading run. Its saved content names the record actually read. */ export interface SavedRunRecord { runId: string; assetId: string; recordId: string; companyId: string } @@ -112,8 +139,10 @@ export function readSavedAccounting(calls: readonly LeadApiCall[], runId: string // unlisted digest. A response the run saved is bound by its content instead: the saved run record is the original run. const originalRunSaved = !!originalRunId && (target.savedRunRecords ?? []).some(saved => saved.runId === runId && saved.recordId === originalRunId && (!companyId || saved.companyId === companyId)); + const listDigests = companyId && target.runListPosition ? runListDigests(companyId, target.runListPosition) : new Set(); return calls.some(call => call.runId === runId && call.ok && call.status >= 200 && call.status < 300 && (companyDigests.has(call.digest) || taskDigests.has(call.digest) + || call.operationId === RUN_LIST_OPERATION && listDigests.has(call.digest) || call.operationId === "GET /api/heartbeat-runs/{runId}" && (runDigests.has(call.digest) || originalRunCited || originalRunSaved))); } /** Run records the given run saved through `call_api` `saveResponse`, from the product's own activity and asset. */ @@ -190,7 +219,7 @@ export function gradeAccounting(value: unknown) { const savedRunRecords = Array.isArray(o.state.savedRunRecords) ? o.state.savedRunRecords as SavedRunRecord[] : []; c.add("unresolved-record-read-from-saved-accounting", !!calls && o.runs.some(run => run.agentId === o.leadId && run.status === "succeeded" && readSavedAccounting(calls, run.id, { companyId: o.companyId, task: o.state.preflightTask as Entity | undefined, originalRunId: String(o.state.originalRunId ?? ""), - citedRunReads: citedRunReads(run), savedRunRecords })), + citedRunReads: citedRunReads(run), savedRunRecords, runListPosition: runListPosition(o.runs, String(o.state.originalRunId ?? ""), run) })), "A chat run read the unresolved record's saved accounting through a product cost projection instead of inferring or inventing its cost."); } else if (o.scenarioId === "budgets-costs.repair-cost-recording") { c.add("real-human-saved-cost-retry", quality?.runs.some(row => row.runId === before?.id && row.reason === "retryable") === true && o.state.agentRetryStatus === 403 @@ -293,7 +322,7 @@ export const accountingIdentityCases: readonly ChatCatalogCase[] = [ } await ctx.input.api.patch(`/api/issues/${ctx.issue()!.id}`, { description: `The requested reporting week is ${weekFrom} through ${weekTo} (UTC). Launch contains imported synthetic metered-API receipt tasks ${morganReceiptTask.identifier} (Morgan) and ${rileyReceiptTask.identifier} (Riley), plus actual completed native run ${state.originalRunId} with unresolved saved usage. Imported fixture receipts are not live provider/campaign billing. Other-project and earlier-week charges must be excluded; native subscription usage/fees are separate.` }); return { ...state, riley, morganReceiptTask, rileyReceiptTask, weekFrom, weekTo, importedReceiptIds: receipts, receiptOrigin: "public-imported-synthetic-fixture" }; - }, gradeAccounting, { authentication: "human-session", oracleVersion: "paperclip.chat-catalog.spend-breakdown.structural.v4", sourceFiles: [...sources, "chat-catalog-domains/api-read-receipts.ts", "run-observations.ts"], expectedRunCount: 2, attemptTimeoutMs: 600_000, observe: observeAccounting, verifyResult: verifyAccountingLink, verifySetup: verifyUnresolvedSetup, + }, gradeAccounting, { authentication: "human-session", oracleVersion: "paperclip.chat-catalog.spend-breakdown.structural.v5", sourceFiles: [...sources, "chat-catalog-domains/api-read-receipts.ts", "run-observations.ts"], expectedRunCount: 2, attemptTimeoutMs: 600_000, observe: observeAccounting, verifyResult: verifyAccountingLink, verifySetup: verifyUnresolvedSetup, setupPolicy: { funding: "standard", readiness: "all-ready", invariantCheckIds: ["genuine-unresolved-saved-native-usage"] } }), identityDefinition("budgets-costs.repair-cost-recording", async ctx => { try { diff --git a/tests/runner-e2e/chat-catalog-domains/integrator-skill-imports.test.ts b/tests/runner-e2e/chat-catalog-domains/integrator-skill-imports.test.ts index f68fbc0d10d..7334477e13f 100644 --- a/tests/runner-e2e/chat-catalog-domains/integrator-skill-imports.test.ts +++ b/tests/runner-e2e/chat-catalog-domains/integrator-skill-imports.test.ts @@ -49,8 +49,17 @@ describe("owned vetted source and editable fork controls", () => { expect(gradeIntegratorSkillImports(lostNotes).passed).toBe(false); const wrongTouch = structuredClone(o); wrongTouch.skills[1]!.markdown = wrongTouch.skills[1]!.markdown.replace("44 by 44", "24 by 24"); expect(gradeIntegratorSkillImports(wrongTouch).passed).toBe(false); - expect(gradeIntegratorSkillImports({ ...o, reply: "I edited the upstream. Use Accessibility local notes; the original is unchanged." }).passed).toBe(false); + expect(gradeIntegratorSkillImports({ ...o, reply: "Done. Your mobile checks are saved and ready to use." }).passed).toBe(false); + expect(gradeIntegratorSkillImports({ ...o, reply: "Open your copy: /skills/studio/another-skill", links: ["/skills/studio/another-skill"] }).passed).toBe(false); expect(preservesMobileChecks("Check touch targets at least 44x44 pixels.\nCheck both portrait and landscape orientation.\nReview mobile Safari checkout.")).toBe(true); expect(preservesMobileChecks("Ignore touch targets at least 44x44 pixels.\nCheck both portrait and landscape orientation.\nReview mobile Safari checkout.")).toBe(false); }); }); +it("names or links the saved fork; the upstream's protection is graded from saved state, not wording", () => { + const o = valid("skills.fork-read-only"); + expect(gradeIntegratorSkillImports({ ...o, reply: "I added the mobile checks to **Accessibility local notes**, an editable fork. The upstream accessibility-review package is untouched." }).passed).toBe(true); + expect(gradeIntegratorSkillImports({ ...o, reply: "Use [your editable copy](/ACME/skills/studio/local) from now on.", links: ["/ACME/skills/studio/local"] }).passed).toBe(true); + expect(gradeIntegratorSkillImports({ ...o, reply: "The upstream accessibility-review package is untouched." }).passed).toBe(false); + const noFork = structuredClone(o); noFork.skills = [noFork.skills[0]!]; + expect(gradeIntegratorSkillImports({ ...noFork, reply: "I added the mobile checks to Accessibility local notes." }).passed).toBe(false); +}); diff --git a/tests/runner-e2e/chat-catalog-domains/integrator-skill-imports.ts b/tests/runner-e2e/chat-catalog-domains/integrator-skill-imports.ts index c42f5ab0bcf..d79139a61d7 100644 --- a/tests/runner-e2e/chat-catalog-domains/integrator-skill-imports.ts +++ b/tests/runner-e2e/chat-catalog-domains/integrator-skill-imports.ts @@ -4,7 +4,7 @@ import { factualContextQueryAttachment } from "../chat-query-attachments.js"; import type { CompanySkillDetail, CompanySkillFileDetail, CompanySkillListItem, CompanySkillVersion } from "../../../packages/shared/src/types/company-skill.js"; import type { ChatCatalogContext } from "../chat-catalog-contract.js"; import { checks, observation, project, type InternalObservation } from "./internal-support.js"; -import { groundedStatement, integratorDefinition, inspectResult, resultHref, observeInternal } from "./integrator-support.js"; +import { integratorDefinition, inspectResult, resultHref, observeInternal } from "./integrator-support.js"; import { sourceSkillMarkdown, mobileChecks, openVettedSkillSource, skillSourceRequests, recordVettedSourceImport, closeVettedSkillSource, importReadOnlySkill, editableLocalNotes } from "./integrator-skill-source.js"; interface ImportObservation extends InternalObservation { skills: CompanySkillDetail[]; skillVersions: Record; @@ -66,8 +66,8 @@ export function gradeIntegratorSkillImports(value: unknown) { const localBefore = o.state.localFork as CompanySkillDetail | undefined; const localNow = o.skills.find(row => row.id === localBefore?.id); c.add("unrelated-local-notes-preserved", !!localBefore && !!localNow && localNow.markdown.includes("ORCHID customer escalation notes unchanged") && (localNow.id === fork?.id || localNow.currentVersionId === localBefore.currentVersionId && localNow.markdown === localBefore.markdown), "Existing local notes survive whether the agent edits the existing copy or selects a separate fork."); - c.add("correct-copy-explained", !!fork && o.reply.includes(fork.name) && groundedStatement(o.reply, /\b(?:upstream|original|source)\b/i, /\b(?:unchanged|read.only|protected|not (?:changed|modified|edited))\b/i, - /\b(?:edited|updated|modified|changed)\s+(?:the )?(?:upstream|original source)\b/i), "Chat distinguishes the editable copy for future use from the unmodified upstream."); + c.add("correct-copy-explained", !!fork && (o.reply.includes(fork.name) || !!resultHref(o, fork.id, "studio")), + "Chat points the person at the saved editable copy by its saved name or a link to its page; the saved upstream and fork state above prove which copy changed."); } else c.add("owned-import-oracle", false, "No independent import/fork oracle exists for this scenario."); return c.result(); } @@ -93,7 +93,7 @@ function define(id: "skills.find-and-install" | "skills.fork-read-only") { const o = importObservation(value); const skill = o && (id === "skills.find-and-install" ? o.skills.find(row => row.sourceLocator === o.state.sourceURL) : changedFork(o)); if (!o || !skill) throw new Error("No actual saved skill copy for browser inspection"); await inspectResult(ctx, `/${ctx.input.fixtures.company.issuePrefix}/skills/studio/${skill.id}`, skill.name, resultHref(o, skill.id, "studio")); - }, { ...(id === "skills.find-and-install" ? { oracleVersion: "paperclip.chat-catalog.integrator.skill-import.v2" } : {}), authentication: "human-session", queryAttachments: factualContextQueryAttachment("skill-context.md"), sourceFiles: ["chat-catalog-domains/integrator-skill-versions.ts", "chat-catalog-domains/integrator-skill-imports.ts", "chat-catalog-domains/integrator-skill-source.ts", "chat-catalog-domains/integrator-skills.ts", "chat-catalog-domains/integrator-support.ts", "chat-catalog-domains/internal-support.ts", "chat-scenarios/skills.yaml"], + }, { oracleVersion: id === "skills.find-and-install" ? "paperclip.chat-catalog.integrator.skill-import.v2" : "paperclip.chat-catalog.integrator.skill-fork.v2", authentication: "human-session", queryAttachments: factualContextQueryAttachment("skill-context.md"), sourceFiles: ["chat-catalog-domains/integrator-skill-versions.ts", "chat-catalog-domains/integrator-skill-imports.ts", "chat-catalog-domains/integrator-skill-source.ts", "chat-catalog-domains/integrator-skills.ts", "chat-catalog-domains/integrator-support.ts", "chat-catalog-domains/internal-support.ts", "chat-scenarios/skills.yaml"], async cleanup(ctx) { await closeVettedSkillSource(ctx); } }); } export const integratorSkillImportCases = [define("skills.find-and-install"), define("skills.fork-read-only")]; diff --git a/tests/runner-e2e/chat-catalog-domains/integrator-status-cards.test.ts b/tests/runner-e2e/chat-catalog-domains/integrator-status-cards.test.ts index 08e99054780..f110bc5fc4c 100644 --- a/tests/runner-e2e/chat-catalog-domains/integrator-status-cards.test.ts +++ b/tests/runner-e2e/chat-catalog-domains/integrator-status-cards.test.ts @@ -278,3 +278,17 @@ it("declares factual human attachments only for the two actual missing selected // The refresh query already names Launch and the retained run selected it correctly. expect(integratorStatusCardsCases.find(row => row.scenarioId === "status-cards.refresh-card")!.queryAttachments).toBeUndefined(); }); +it("counts a dedicated task tool result that holds the source task with its live status", () => { + const item = (runId: string, value: Record) => ({ runId, payload: { prpEvent: { runId, payload: { item: value } } } }); + const pair = (name: string, result: unknown, runId = "lead") => [item(runId, { id: "2", type: "tool_use", name, input: { query: "Payment approval blocks launch" } }), item(runId, { id: "2", type: "tool_result", tool_use_id: "2", result })]; + const cohort6 = pair("search_tasks", { limit: 10, tasks: [{ id: "source", identifier: "COM-1", title: "Payment approval blocks launch", status: "done" }], hasMore: false }); + expect(sourceTaskReads(cohort6, "source", "COM-1", "done")).toEqual({ live: true, unavailable: false }); + expect(sourceTaskReads(pair("mcp__paperclip__paperclip_list_tasks", { task: { id: "source", status: "done" } }), "source", "COM-1", "done").live).toBe(true); + expect(sourceTaskReads(pair("search_tasks", { limit: 10, tasks: [], hasMore: false }), "source", "COM-1", "done").live).toBe(false); + expect(sourceTaskReads(pair("search_tasks", { tasks: [{ id: "other", status: "done" }] }), "source", "COM-1", "done").live).toBe(false); + expect(sourceTaskReads(pair("search_tasks", { tasks: [{ id: "source", status: "blocked" }] }), "source", "COM-1", "done").live).toBe(false); + expect(sourceTaskReads(pair("search_tasks", { tasks: [{ id: "source" }] }), "source", "COM-1").live).toBe(false); + expect(sourceTaskReads(pair("call_api", { tasks: [{ id: "source", status: "done" }] }), "source", "COM-1", "done").live).toBe(false); + expect(sourceTaskReads(pair("search_tasks", { ok: false, tasks: [{ id: "source", status: "done" }] }), "source", "COM-1", "done").live).toBe(false); + expect(sourceTaskReads([cohort6[1]!], "source", "COM-1", "done").live).toBe(false); +}); diff --git a/tests/runner-e2e/chat-catalog-domains/integrator-status-cards.ts b/tests/runner-e2e/chat-catalog-domains/integrator-status-cards.ts index adf10046bff..af095691c32 100644 --- a/tests/runner-e2e/chat-catalog-domains/integrator-status-cards.ts +++ b/tests/runner-e2e/chat-catalog-domains/integrator-status-cards.ts @@ -33,14 +33,32 @@ export function statusCardOperations(events: readonly Record[], ]); return apiReadStatuses(events, digests).filter(read => read.ok && read.status >= 200 && read.status < 300).map(read => read.operationId); } +function resultHasTask(value: unknown, sourceId: string, status: string | undefined, depth = 0): boolean { + if (depth > 3 || !value || typeof value !== "object") return false; + if (Array.isArray(value)) return value.some(row => resultHasTask(row, sourceId, status, depth + 1)); + const record = value as Record; + if (record.id === sourceId && typeof record.status === "string" && (status === undefined || record.status === status)) return true; + return Object.values(record).some(row => resultHasTask(row, sourceId, status, depth + 1)); +} +function dedicatedToolTaskRead(events: readonly Record[], sourceId: string, status: string | undefined) { + const tools = new Map(); + return events.some(row => { + const envelope = objectRecord(objectRecord(row.payload).prpEvent), item = objectRecord(objectRecord(envelope.payload).item); + const key = `${String(row.runId ?? envelope.runId ?? "")}:${String(item.type === "tool_use" ? item.id : item.tool_use_id)}`; + if (item.type === "tool_use" && typeof item.name === "string") { tools.set(key, item.name); return false; } + if (item.type !== "tool_result" || !item.result || typeof item.result !== "object") return false; + const tool = tools.get(key), result = objectRecord(item.result); + return !!tool && tool !== "call_api" && result.apiPayloadRedacted !== true && result.ok !== false && resultHasTask(result, sourceId, status); + }); +} /** * Classifies this run's reads of the source task. call_api reads are bound to the source by their saved * input digest: a successful result is a live read and a 404 is an unavailable one. An unredacted * dedicated-tool output naming the source also counts as live. */ -export function sourceTaskReads(events: readonly Record[], sourceId: string, identifier?: string | null) { +export function sourceTaskReads(events: readonly Record[], sourceId: string, identifier?: string | null, liveStatus?: string) { const reads = apiReadStatuses(events, apiReadDigests([{ operationId: "GET /api/issues/{id}", pathParams: recordParams("id", sourceId, identifier) }])); - let live = reads.some(read => read.ok && read.status >= 200 && read.status < 300), unavailable = reads.some(read => read.status === 404); + let live = reads.some(read => read.ok && read.status >= 200 && read.status < 300) || dedicatedToolTaskRead(events, sourceId, liveStatus), unavailable = reads.some(read => read.status === 404); for (const row of events) { const envelope = objectRecord(objectRecord(row.payload).prpEvent), payload = objectRecord(envelope.payload); const output = typeof payload.output === "string" ? payload.output : ""; @@ -82,7 +100,7 @@ async function observeSourceReads(ctx: ChatCatalogContext, base: InternalObserva const reads: SourceReads = { initialLive: false, laterUnavailable: false, laterLive: false }; for (const run of base.runs.filter(row => row.agentId === base.leadId)) { const events = await collectRunEvents>(afterSeq => ctx.input.api.get(`/api/heartbeat-runs/${run.id}/events?afterSeq=${afterSeq}&limit=1000`)); - const found = sourceTaskReads(events, sourceId, source?.identifier); + const found = sourceTaskReads(events, sourceId, source?.identifier, typeof source?.status === "string" ? source.status : undefined); if (initialRuns.has(run.id)) reads.initialLive ||= found.live; else { reads.laterUnavailable ||= found.unavailable; reads.laterLive ||= found.live; } } @@ -339,7 +357,7 @@ export const integratorStatusCardsCases: readonly ChatCatalogCase[] = [ define("status-cards.create-card", "none", { oracleVersion: "paperclip.chat-catalog.status-card.create.v2" }), define("status-cards.archive-card", "ceo", { oracleVersion: "paperclip.chat-catalog.status-card.archive.v3", authentication: "human-session", queryAttachments: factualContextQueryAttachment("selected-status-card.md"), expectedRunCount: 3, attemptTimeoutMs: 720_000 }), define("status-cards.other-authors-card", "morgan", { oracleVersion: "paperclip.chat-catalog.status-card.other-authors.v4", expectedRunCount: 5, minimumRunCount: 2 }), - define("status-cards.explain-card", "ceo", { oracleVersion: "paperclip.chat-catalog.status-card.explain.v5", authentication: "human-session", queryAttachments: factualContextQueryAttachment("selected-status-card.md"), expectedRunCount: 5, minimumRunCount: 3, expectedHumanMessageCount: 2, attemptTimeoutMs: 720_000, + define("status-cards.explain-card", "ceo", { oracleVersion: "paperclip.chat-catalog.status-card.explain.v6", authentication: "human-session", queryAttachments: factualContextQueryAttachment("selected-status-card.md"), expectedRunCount: 5, minimumRunCount: 3, expectedHumanMessageCount: 2, attemptTimeoutMs: 720_000, sourceFiles: ["chat-catalog-domains/integrator-status-cards.ts", "chat-catalog-domains/api-read-receipts.ts", "chat-catalog-domains/identity-support.ts", "chat-catalog-domains/internal-definition.ts", "chat-catalog-domains/internal-support.ts", "chat-catalog-domains/integrator-support.ts", "run-observations.ts", "chat-scenarios/status-cards.yaml"], async act(ctx, state) { // The lead may refresh its own stale card while answering; wait for that generation to settle diff --git a/tests/runner-e2e/chat-catalog-domains/runtime-discard.test.ts b/tests/runner-e2e/chat-catalog-domains/runtime-discard.test.ts index e3255ff1686..63a68cbe290 100644 --- a/tests/runner-e2e/chat-catalog-domains/runtime-discard.test.ts +++ b/tests/runner-e2e/chat-catalog-domains/runtime-discard.test.ts @@ -1,5 +1,5 @@ import { expect, it } from "vitest"; -import { gradeDiscard, promptCarries, replyLinkHrefs } from "./runtime-discard.js"; +import { documentContactRemoved, gradeDiscard, promptCarries, replyLinkHrefs } from "./runtime-discard.js"; function valid() { const neighbour = { position: 0, comment: { id: "font", body: "Use a readable font.", authorUserId: "human", authorAgentId: null } }; return { scenarioId: "steering.discard-queued-message", origin: "http://fixture.invalid", companyId: "company", leadId: "ceo", agents: [], links: [], humanQueries: [], reply: "", @@ -69,3 +69,28 @@ it("rejects an unbound later worker in the grade when its prompt lacks the direc const o = valid(); o.state.cancelDirectionRunBound = promptCarries(`{"body":${JSON.stringify("unrelated")}}`, "Remove the contact section.\nKeep fonts."); expect(gradeDiscard(o).passed).toBe(false); }); +const label = "78f7e3a6c6ec-1"; +const initialPlan = "# Website Plan (Initial)\n\n## Status\n\nInitial plan document created.\n\n## Accessible font guidance (retained)\n\n- Readable base size.\n"; +const consumedPlan = `# Website Plan\n\n## Human direction\n\n- Add a contact section to the saved website plan, labelled \`${label}\`.\n\n## Contact section (label: ${label})\n\n- **Purpose:** give visitors a clear way to reach the site owner.\n\n## Accessible font guidance (retained)\n\n- Readable base size.\n`; +const revs = (finalBody: string, extraSave?: string) => [ + { id: "r1", revisionNumber: 1, createdByRunId: "initial", body: initialPlan }, + { id: "r2", revisionNumber: 2, createdByRunId: "consumer", body: consumedPlan }, + ...(extraSave ? [{ id: "r3", revisionNumber: 3, createdByRunId: "consumer", body: extraSave }] : []), + { id: "final", revisionNumber: 4, createdByRunId: "final", body: finalBody }, +]; +it("full cohort 6: the labelled heading is gone and a superseded note may still name the label", () => { + const final = `# Website Plan\n\n## Human direction\n\n- No contact section is included; the earlier \`${label}\` contact-section request has been superseded.\n\n## Accessible font guidance (retained)\n\n- Readable base size.\n`; + expect(documentContactRemoved(revs(final), "final", "consumer", label)).toBe(true); +}); +it("fails while a heading still carries the label, kept or renamed", () => { + expect(documentContactRemoved(revs(consumedPlan), "final", "consumer", label)).toBe(false); + expect(documentContactRemoved(revs(consumedPlan.replace(`## Contact section (label: ${label})`, `### Reach us (${label})`)), "final", "consumer", label)).toBe(false); +}); +it("compares against the plan from before the consuming run first saved the label, across its repeated saves", () => { + expect(documentContactRemoved(revs(initialPlan, `${consumedPlan}\n## Next steps\n\nConfirm contact details.\n`), "final", "consumer", label)).toBe(true); + expect(documentContactRemoved(revs(consumedPlan, `${consumedPlan}\n## Next steps\n\nConfirm contact details.\n`), "final", "consumer", label)).toBe(false); +}); +it("fails when no labelled section was ever saved, so removal cannot be shown", () => { + const unlabelled = consumedPlan.replace(`## Contact section (label: ${label})`, "## Contact section"); + expect(documentContactRemoved([...revs(initialPlan)].map(row => row.id === "r2" ? { ...row, body: unlabelled } : row), "final", "consumer", label)).toBe(false); +}); diff --git a/tests/runner-e2e/chat-catalog-domains/runtime-discard.ts b/tests/runner-e2e/chat-catalog-domains/runtime-discard.ts index 64e55d0832f..24219b1d364 100644 --- a/tests/runner-e2e/chat-catalog-domains/runtime-discard.ts +++ b/tests/runner-e2e/chat-catalog-domains/runtime-discard.ts @@ -21,6 +21,17 @@ export function promptCarries(prompt: string | undefined, body: string) { export function replyLinkHrefs(reply: string, rendered: readonly string[]) { return [...new Set([...rendered, ...[...reply.matchAll(/\]\(([^)\s]+)\)/g)].map(match => match[1]!)])]; } +const labelledHeading = (body: string, label: string) => body.split(/\r?\n/).some(line => /^#{1,6}\s/.test(line) && line.includes(label)); +export function documentContactRemoved(rows: ReadonlyArray<{ id: string; body?: string | null; createdByRunId?: string | null }>, latestRevisionId: unknown, consumerRunId: string, label: string) { + const number = (row: object) => Number((row as { revisionNumber?: unknown }).revisionNumber); + const revisions = [...rows].sort((a, b) => number(a) - number(b)); + const final = revisions.find(row => row.id === latestRevisionId); + const saves = revisions.filter(row => row.createdByRunId === consumerRunId && (row.body ?? "").includes(label)); + if (!saves.length) return !(final?.body ?? "").includes(label); + const previous = revisions.filter(row => number(row) < number(saves[0]!)).at(-1); + const hadSection = [previous, ...saves].some(row => labelledHeading(row?.body ?? "", label)); + return !!final && hadSection && !labelledHeading(final.body ?? "", label); +} export function gradeDiscard(value: unknown) { const c = checks(), o = runtimeObservation(value); c.add("actual-pending-and-consumed-cancellation-evidence", !!o, "Both actual human discard and separately consumed input with later new direction are required."); if (!o) return c.result(); @@ -49,7 +60,7 @@ export function gradeDiscard(value: unknown) { return c.result(); } export const runtimeDiscardCases = [runtimeDefinition("steering.discard-queued-message", ctx => humanQueuedRuntime(ctx, contactText), gradeDiscard, { - authentication: "human-session", expectedHumanMessageCount: 2, expectedRunCount: 5, attemptTimeoutMs: 1_020_000, oracleVersion: "paperclip.chat-catalog.runtime-discard.v4", + authentication: "human-session", expectedHumanMessageCount: 2, expectedRunCount: 5, attemptTimeoutMs: 1_020_000, oracleVersion: "paperclip.chat-catalog.runtime-discard.v6", sourceFiles: ["chat-catalog-domains/runtime-discard.ts", "chat-catalog-domains/runtime-queue-controls.ts", "chat-catalog-domains/runtime-queue.ts", "chat-catalog-domains/runtime-busy-worker.ts", "chat-catalog-domains/runtime-support.ts", "chat-catalog-domains/identity-support.ts", "chat-scenarios/steering.yaml"], setupPolicy: runtimeQueueCases[0]!.setupPolicy, verifySetup: runtimeQueueCases[0]!.verifySetup, async act(ctx, state) { @@ -122,8 +133,8 @@ export const runtimeDiscardCases = [runtimeDefinition("steering.discard-queued-m state.consumedLabelSaved = o.revisions.some(row => row.createdByRunId === state.consumerRunId && row.createdByAgentId === worker && (row.body ?? "").includes(label)); const latest = o.revisions.filter(row => row.createdByRunId === state.finalWorkerRunId && row.createdByAgentId === worker && o.documents.some(doc => doc.id === row.documentId && doc.latestRevisionId === row.id)); - state.finalPlanWithoutContact = latest.length > 0 && latest.every(row => !(row.body ?? "").includes(label)) - && o.documents.every(doc => !(o.revisions.find(row => row.id === doc.latestRevisionId)?.body ?? "").includes(label)); + state.finalPlanWithoutContact = latest.length > 0 && o.documents.every(doc => documentContactRemoved( + o.revisions.filter(row => row.documentId === doc.id), doc.latestRevisionId, String(state.consumerRunId), label)); return o; }, async cleanup(ctx, state) { try { await cleanupIdentityProbes(ctx); } finally { await releaseRuntimeWorker(state); } }, diff --git a/tests/runner-e2e/chat-catalog-domains/runtime-interruption.ts b/tests/runner-e2e/chat-catalog-domains/runtime-interruption.ts index bf20f60fc77..aef54db560f 100644 --- a/tests/runner-e2e/chat-catalog-domains/runtime-interruption.ts +++ b/tests/runner-e2e/chat-catalog-domains/runtime-interruption.ts @@ -60,9 +60,9 @@ export const runtimeInterruptionCases = [runtimeDefinition("steering.interrupt-w target: { type: "issue_document", issueId: task.id, documentId: plan.id, key: "plan", revisionId: plan.latestRevisionId, revisionNumber: plan.latestRevisionNumber } } })); await ctx.input.page.goto(`/${ctx.input.fixtures.company.issuePrefix}/issues/${task.identifier ?? task.id}`, { waitUntil: "domcontentloaded" }); const acceptPaths = issueApiPaths(task, `/interactions/${confirmation.id}/accept`); - const accept = ctx.input.page.waitForResponse(r => r.request().method() === "POST" && acceptPaths.has(new URL(r.url()).pathname)); - await clickInteractionAction(ctx.input.page, confirmation, "Approve"); - if ((await accept).status() !== 200) throw new Error("Actual human simpler-plan approval did not succeed"); + const [accept] = await Promise.all([ctx.input.page.waitForResponse(r => r.request().method() === "POST" && acceptPaths.has(new URL(r.url()).pathname)), + clickInteractionAction(ctx.input.page, confirmation, "Approve")]); + if (accept.status() !== 200) throw new Error("Actual human simpler-plan approval did not succeed"); const session = await ctx.input.api.get<{ user: { id: string } }>("/api/auth/get-session"); const approved = (await ctx.input.api.get(`/api/issues/${task.id}/interactions`)).find(row => row.id === confirmation.id)!; const queue = await pollUntil({ label: "Real accepted plan response requires a fresh native turn but has not interrupted old work", deadlineAt: Date.now() + 20_000, @@ -94,9 +94,10 @@ export const runtimeInterruptionCases = [runtimeDefinition("steering.interrupt-w await ctx.input.page.waitForURL(url => { const parts = url.pathname.split("/").map(decodeURIComponent), at = parts.indexOf("issues"); return at >= 0 && [task.id, task.identifier].includes(parts[at + 1]); }); state.humanFollowedReplyTaskLink = true; const interruptPaths = issueApiPaths(task, "/queued-comments/interrupt"); - const interrupted = ctx.input.page.waitForResponse(r => r.request().method() === "POST" && interruptPaths.has(new URL(r.url()).pathname)); chatCatalogNativePhaseRemainingBudget(ctx)?.(); - await ctx.input.page.getByTestId(`task-chat-queued-interrupt-${confirmation.id}`).click(); state.humanInterrupted = true; state.interruptStatus = (await interrupted).status(); + const [interrupted] = await Promise.all([ctx.input.page.waitForResponse(r => r.request().method() === "POST" && interruptPaths.has(new URL(r.url()).pathname)), + ctx.input.page.getByTestId(`task-chat-queued-interrupt-${confirmation.id}`).click().then(() => { state.humanInterrupted = true; })]); + state.interruptStatus = interrupted.status(); const stopped = await pollUntil({ label: "Matching native cancellation ACK after actual supported Interrupt", deadlineAt: Date.now() + 90_000, load: () => ctx.input.api.get(`/api/heartbeat-runs/${state.workerRunId}`), accept: run => run.status === "cancelled" && (run.resultJson?.nativeCancellation as { dispatchState?: string } | undefined)?.dispatchState === "acknowledged" }); diff --git a/tests/runner-e2e/chat-catalog-ended-run.test.ts b/tests/runner-e2e/chat-catalog-ended-run.test.ts new file mode 100644 index 00000000000..cd8d7ca4dbe --- /dev/null +++ b/tests/runner-e2e/chat-catalog-ended-run.test.ts @@ -0,0 +1,16 @@ +import { expect, it } from "vitest"; +import { chatCatalogEndedRunRejection } from "./chat-catalog-flow.js"; +import { classifyFailure } from "./failure-classifier.js"; + +const classify = (run: Parameters[0]) => classifyFailure(new Error(`Stopped waiting for tasks.assignment-conflict: ${chatCatalogEndedRunRejection(run)}`)); +it("full cohort 6: a run cancelled for a reassignment is the candidate's outcome, not retryable infrastructure", () => { + const reassigned = { status: "cancelled", errorCode: "issue_reassigned", resultJson: { cancellation: { reason: "Cancelled for task reassignment", source: "control_plane", expected: true } } }; + expect(chatCatalogEndedRunRejection(reassigned)).toBe("Observed run was cancelled by control_plane (issue_reassigned)"); + expect(classify(reassigned)).toBe("candidate_failure"); + expect(classify({ status: "cancelled", errorCode: "cancelled", resultJson: { cancellation: { source: "operator" } } })).toBe("candidate_failure"); + expect(classify({ status: "cancelled", errorCode: null, resultJson: null })).toBe("candidate_failure"); +}); +it("a provider run that failed or timed out keeps its retryable provider classification", () => { + expect(classify({ status: "failed", errorCode: "adapter_failed" })).toBe("transient_infrastructure"); + expect(classify({ status: "timed_out", errorCode: "timeout" })).toBe("transient_infrastructure"); +}); diff --git a/tests/runner-e2e/chat-catalog-failure-retirement.test.ts b/tests/runner-e2e/chat-catalog-failure-retirement.test.ts index a912dff3bd3..b8ccb319f12 100644 --- a/tests/runner-e2e/chat-catalog-failure-retirement.test.ts +++ b/tests/runner-e2e/chat-catalog-failure-retirement.test.ts @@ -2,10 +2,10 @@ import { readFile } from "node:fs/promises"; import { stripTypeScriptTypes } from "node:module"; import { afterEach, beforeEach, expect, it, vi } from "vitest"; const control = vi.hoisted(() => ({ - collectorEntered: Promise.resolve(), collectorRelease: Promise.resolve(), enter: () => {}, release: () => {}, completeQuery: false, stall: true, savedState: { label: "before cleanup" }, + collectorEntered: Promise.resolve(), collectorRelease: Promise.resolve(), enter: () => {}, release: () => {}, completeQuery: false, stall: true, savedState: { label: "before cleanup" }, failingRun: "", })); beforeEach(() => { - control.completeQuery = false; control.stall = true; control.savedState = { label: "before cleanup" }; + control.completeQuery = false; control.stall = true; control.savedState = { label: "before cleanup" }; control.failingRun = ""; control.collectorEntered = new Promise(resolve => { control.enter = resolve; }); control.collectorRelease = new Promise(resolve => { control.release = resolve; }); }); @@ -21,7 +21,8 @@ vi.mock("./chat-query-bindings.js", () => ({ resolveChatCatalogQuery: async () = vi.mock("./chat-rendered-links.js", () => ({ collectConversationLinks: async () => [], collectConversationLinksWithDiagnostics: async () => ({ links: [] }) })); vi.mock("./chat-catalog-run-policy.js", () => ({ gradeChatCatalogRuns: () => ({ checks: [] }), CHAT_CATALOG_MAX_SUPERSEDED_QUEUED_RUNS: 1, chatCatalogProviderRuns: (runs: unknown[]) => runs, chatCatalogSupersededQueuedRuns: () => [], chatCatalogReassignedQueuedRun: () => false })); -vi.mock("./chat-flow.js", () => ({ sendChatMessage: async () => {}, collectChatRunEvidence: async () => { control.enter(); if (control.stall) await control.collectorRelease; return {}; } })); +vi.mock("./chat-flow.js", () => ({ sendChatMessage: async () => {}, collectChatRunEvidence: async (_api: unknown, run: { id: string }) => { control.enter(); if (control.stall) await control.collectorRelease; + if (run.id === control.failingRun) throw new Error("GET /api/heartbeat-runs/never-started/log 404"); return { runId: run.id, log: "log" }; } })); vi.mock("./api.js", () => ({ pollUntil: async ({ load }: { load: () => Promise }) => { await load(); throw new Error("Original attempt failed"); } })); import { runChatCatalogFlow } from "./chat-catalog-flow.js"; it("does not let a stalled failure collector prevent outer retirement of an owned pending native", async () => { @@ -94,3 +95,29 @@ it("executes the real outer failure-capture guard without entering a held duplic expect(reads).toBe(0); expect(source).toContain("if (!(error instanceof SetupHealthAbort)) await captureApiState();"); }); +it("keeps every run's evidence when one never-started run has no log, and saves the ledger before retirement", async () => { + control.stall = false; control.failingRun = "never-started"; + const snapshots: Record = {}, order: string[] = []; + const runs = [{ id: "lead", companyId: "company", status: "succeeded" }, { id: "never-started", companyId: "company", status: "queued" }]; + const context = { scenario: { id: "questions-and-approvals.multi-part-question", query: "Original request" }, + input: { execution: { task: { turnTimeoutMs: 0 } }, fixtures: { company: { id: "company" }, agent: { id: "ceo" } }, + api: { baseURL: "http://127.0.0.1", get: async (route: string) => { if (route.includes("/never-started/log")) throw new Error("Run log not found"); return []; }, + getRunObservation: async (route: string) => route.includes("/never-started/events") && route.includes("afterSeq=0") ? [{ seq: 1, eventType: "lifecycle" }] : [] }, + page: { locator: () => ({ count: async () => 0 }) }, + evidence: async (name: string, value: unknown) => { order.push(name); snapshots[name] = structuredClone(value); }, + retireFailedAttempt: async () => { order.push("retired"); runs[1]!.status = "cancelled"; throw new Error("cancel timed out"); } }, + refreshIssue: async () => {}, issue: () => ({ id: "source", companyId: "company" }), allRuns: async () => runs }; + await expect(runChatCatalogFlow(context as never)).rejects.toThrow("Original attempt failed"); + expect(order.indexOf("chat-catalog-failure-run-ledger.json")).toBeLessThan(order.indexOf("retired")); + expect(snapshots["chat-catalog-failure-run-ledger.json"].runs.map((run: { status: string }) => run.status)).toEqual(["succeeded", "queued"]); + expect(snapshots["chat-catalog-runs.json"]).toEqual([{ runId: "lead", log: "log" }, { runId: "never-started", log: null, events: [{ seq: 1, eventType: "lifecycle" }], logError: "Run log not found" }]); + expect(snapshots["api-state.json"]).toMatchObject({ retirementError: "cancel timed out" }); + expect(snapshots["api-state.json"].incomplete).toBeUndefined(); +}); +it("records a separate error for each piece of a failed run's evidence it cannot read", async () => { + const { failedRunEvidence } = await import("./chat-catalog-flow.js"); + const ok = { get: async () => "log text", getRunObservation: async (route: string) => route.includes("afterSeq=0") ? [{ seq: 1 }] : [] }; + expect(await failedRunEvidence(ok as never, "run")).toEqual({ runId: "run", log: "log text", events: [{ seq: 1 }] }); + const none = { get: async () => { throw new Error("Run log not found"); }, getRunObservation: async () => { throw new Error("events 500"); } }; + expect(await failedRunEvidence(none as never, "run")).toEqual({ runId: "run", log: null, events: [], logError: "Run log not found", eventsError: "events 500" }); +}); diff --git a/tests/runner-e2e/chat-catalog-flow.ts b/tests/runner-e2e/chat-catalog-flow.ts index 54a035f83f1..8a786784c79 100644 --- a/tests/runner-e2e/chat-catalog-flow.ts +++ b/tests/runner-e2e/chat-catalog-flow.ts @@ -9,7 +9,8 @@ import { chatQueryWithAttachments, resolveChatQueryAttachments, verifyChatQueryA import { CHAT_CATALOG_MAX_SUPERSEDED_QUEUED_RUNS, chatCatalogNeverStartedTerminalTaskRun, chatCatalogProviderRuns, chatCatalogReassignedQueuedRun, chatCatalogRunStatusAllowed, chatCatalogSupersededQueuedRuns, gradeChatCatalogRuns, createChatCatalogFinalRunVerifier } from "./chat-catalog-run-policy.js"; import { chatCatalogCaseFingerprint, normalizedChatCatalogExecution } from "./chat-catalog-fingerprint.js"; import { expect, type Page } from "@playwright/test"; -import { pollUntil } from "./api.js"; +import { pollUntil, type RunnerApi } from "./api.js"; +import { collectRunEvents } from "./run-observations.js"; import { collectChatRunEvidence, sendChatMessage } from "./chat-flow.js"; import { prepareNativeStopCanonicalBoundary } from "./chat-native-stop-boundary.js"; import { collectChatCatalogCompanySecretApprovalActivity, verifyChatCatalogCompanySecretBindingApproval, chatCatalogHumanHistoryMatches, chatCatalogAllowsHumanQuestionAnswer, verifyChatCatalogHumanQuestionAnswer, type ChatCatalogHumanQuestionAudit, validateChatCatalogGrade, type ChatCatalogSetupBoundary, type ChatCatalogContext, type ChatCatalogGrade } from "./chat-catalog-contract.js"; @@ -220,9 +221,10 @@ export async function runChatCatalogFlow(context: ChatCatalogContext) { || chatCatalogSupersededQueuedRuns(result.runs, result.issue).length > CHAT_CATALOG_MAX_SUPERSEDED_QUEUED_RUNS) return "Scenario exceeded its declared run bound"; // A queued run retired by reassignment before it started is graded, not rejected: // the run policy admits it only once the new assignee's run exists. - if (result.runs.some(run => ["failed", "cancelled", "timed_out"].includes(run.status) && !chatCatalogNeverStartedTerminalTaskRun(run, result.issue) + const ended = result.runs.find(run => ["failed", "cancelled", "timed_out"].includes(run.status) && !chatCatalogNeverStartedTerminalTaskRun(run, result.issue) && !chatCatalogReassignedQueuedRun(run, result.issue) && !chatCatalogRunStatusAllowed({ implementation, - run, companyId: input.fixtures.company.id, leadId: input.fixtures.agent.id, source: result.issue, observation }))) return "Observed provider run failed"; + run, companyId: input.fixtures.company.id, leadId: input.fixtures.agent.id, source: result.issue, observation })); + if (ended) return chatCatalogEndedRunRejection(ended); if (result.runs.length && result.runs.every(run => !["queued", "running"].includes(run.status)) && result.issue?.conversationState === "waiting") settledAt ??= Date.now(); else settledAt = undefined; // A passing grade is still inside accept()'s stability window; let it finish. @@ -253,13 +255,21 @@ export async function runChatCatalogFlow(context: ChatCatalogContext) { const failureSnapshot: Record = { capturePhase: "failure" }; try { failureSnapshot.observation = observation === undefined ? null : structuredClone(observation); - await input.retireFailedAttempt?.(failure); + let ledgerTimer: ReturnType | undefined; + const ledger = await Promise.race([rawRuns().catch(() => undefined), new Promise(resolve => { ledgerTimer = setTimeout(() => resolve(undefined), 2_000); })]); + if (ledgerTimer) clearTimeout(ledgerTimer); + if (ledger) await input.evidence("chat-catalog-failure-run-ledger.json", { capturePhase: "before_retirement", runs: ledger }).catch(() => {}); + try { await input.retireFailedAttempt?.(failure); } + catch (error) { failureSnapshot.retirementError = error instanceof Error ? error.message : String(error); } + const collected: unknown[] = []; const collection = (async () => { const finalConversation = await conversation(false); Object.assign(failureSnapshot, finalConversation); const interactions = finalConversation.issue ? await input.api.get(`/api/issues/${finalConversation.issue.id}/interactions`) : []; failureSnapshot.interactions = interactions; - const runEvidence = await Promise.all(finalConversation.runs.map(run => collectChatRunEvidence(chatRunEvidenceApi(input), run))); + const runEvidence = await Promise.all(finalConversation.runs.map(run => collectChatRunEvidence(chatRunEvidenceApi(input), run) + .catch(() => failedRunEvidence(chatRunEvidenceApi(input), run.id)) + .then(row => { collected.push(row); return row; }))); return { ...failureSnapshot, runEvidence }; })(); const evidence = await Promise.race([collection, new Promise(resolve => { @@ -269,7 +279,9 @@ export async function runChatCatalogFlow(context: ChatCatalogContext) { await input.evidence("chat-catalog-runs.json", evidence.runEvidence); await input.evidence("api-state.json", evidence); } else { - await input.evidence("api-state.json", structuredClone({ ...failureSnapshot, incomplete: true })); + const partial = structuredClone(collected); + if (partial.length) await input.evidence("chat-catalog-runs.json", partial); + await input.evidence("api-state.json", structuredClone({ ...failureSnapshot, runEvidence: partial, incomplete: true })); await input.evidence("chat-catalog-evidence-error.json", { incomplete: true, scenarioId: scenario.id, reason: "failure_collection_deadline" }); } } catch { @@ -319,3 +331,20 @@ async function reopenConversation(page: Page, url: string) { await page.locator('[data-testid="task-chat-thread"], [data-testid="thread-root"]').first().waitFor({ state: "attached", timeout: 30_000 }); } catch { /* Evidence is still collected; a page that cannot reopen yields an honest empty link read. */ } } + +export async function failedRunEvidence(api: Pick, runId: string) { + const message = (error: unknown) => error instanceof Error ? error.message : String(error); + const [log, events] = await Promise.all([ + api.get(`/api/heartbeat-runs/${runId}/log?limitBytes=1048576`).then(value => ({ value }), (error: unknown) => ({ error: message(error) })), + collectRunEvents((afterSeq, limit) => api.getRunObservation(`/api/heartbeat-runs/${runId}/events?afterSeq=${afterSeq}&limit=${limit}`)) + .then(value => ({ value }), (error: unknown) => ({ error: message(error) })), + ]); + return { runId, log: "value" in log ? log.value : null, events: "value" in events ? events.value : [], + ...("error" in log ? { logError: log.error } : {}), ...("error" in events ? { eventsError: events.error } : {}) }; +} +export function chatCatalogEndedRunRejection(run: { status: string; errorCode?: string | null; resultJson?: Record | null }) { + if (run.status !== "cancelled") return "Observed provider run failed"; + const cancellation = run.resultJson?.cancellation as { source?: unknown } | undefined; + const source = typeof cancellation?.source === "string" ? cancellation.source : "unknown"; + return `Observed run was cancelled by ${source} (${run.errorCode ?? "no code"})`; +} From ca62ca9e2a1ca65abb3629eb19ee432e8fe00af9 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Thu, 12 Nov 2026 06:08:07 -0600 Subject: [PATCH 2/7] fix(release): keep the Runner chaos evals out of the Core image publication gate (#21088) 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 > - A Core image is published only after "Cloud source verified v1" passes for the same commit in `cloud-readiness.yml` > - That job needs `verify`, which is the whole `release-verify.yml` call, and that call included the Runner chaos evals > - The chaos eval job ("Restart, replay, trace, and recovery faults") took 10.2-11.9 min, with a 7-9 min server finalization step. It is one of the two slowest jobs on the gate > - The owner decided on 2026-11-12 that the Runner chaos evals must not be a publication prerequisite > - This pull request runs the chaos evals as a separate job in the same Cloud readiness run. They still run and report, but the source proof does not wait for them > - The benefit is an earlier image publication on every master commit. A chaos failure stays visible as a failed check ## Linked Issues or Issue Description **What happened?** The Core image gate waited for the Runner chaos evals. In master runs 43133035381, 43134251278 and 43145252393 the chaos job took 10.2, 11.9 and 11.0 min. The gate opened at +13.5, +13.2 and +13.9 min. **Proposed change** Owner decision (2026-11-12): keep the chaos evals running on every admitted master commit, but remove them from the set of jobs that the image and Cloud discovery wait for. **Why** Every minute on the gate is a minute on every staging release. ## What Changed - `.github/workflows/release-verify.yml`: new boolean input `runner_chaos_evals`, default `true`. The `runner_chaos_evals` job runs only when it is true. Release callers (`release.yml`, `release-smoke.yml`) do not set it, so they stay gated on the evals. - `.github/workflows/cloud-readiness.yml`: - `verify` passes `runner_chaos_evals: false`. - New job `runner_chaos_evals`, named "Runner chaos evals (not a publication gate)". It needs `admission`, has the same admission condition as `verify`, and calls `runner-chaos-evals.yml` with `ref: github.sha`. It has no `continue-on-error`. - `source_verified` ("Cloud source verified v1") still has `needs: [verify]`. A comment names the owner decision and says not to add the chaos job. - `scripts/cloud-source-verification.mjs`: new `runnerChaosEvalsJob` constant. The fail-fast check ignores jobs named `" / ..."`. A chaos failure therefore does not raise `SourceVerificationFailed`. So `watch-release-source.mjs` no longer cancels the readiness run and the image run when only the chaos evals fail. Every other failed job still fails fast and cancels as before. - Tests: - `scripts/cloud-source-verification.test.mjs`: a chaos failure does not cancel the image or block the proof; a chaos failure while the proof is pending keeps waiting; a required job whose name only resembles the chaos job still fails fast. - `.github/scripts/tests/cloud-readiness.test.mjs`: pins the job set (`admission`, `verify`, `runner_chaos_evals`, `source_verified`), `source_verified` `needs: [verify]` exactly, `verify` passes `runner_chaos_evals: false`, the chaos job calls the eval workflow, and release callers keep the default. Putting the chaos job back into `source_verified`'s `needs` fails this test (checked locally: 2 failures). Publication gate, before: `Cloud source verified v1` waited for typecheck, build, general tests (17 jobs), serialized tests (5), Runner workflow evals, Verify Paperclip Runner (3 lanes), and the Runner chaos evals. After: the same list without the Runner chaos evals. How a chaos failure stays visible: - Its own check fails on the master commit. - The Cloud readiness run concludes `failure`. - The chaos eval bundle is still uploaded (`if: always()`). - Nothing reports the chaos evals as passed. They are just not a prerequisite. Consumers: - `docker.yml` reads the job "Cloud source verified v1" through `scripts/watch-release-source.mjs`. No change to `docker.yml` is needed. - Paperclip Cloud discovery (`src/fleet/cloud-readiness.ts`) runs with `sourceOnly: true` in `cloud-distribution-policy.ts` and `release-resolver.ts`. In that mode it needs the workflow path `.github/workflows/cloud-readiness.yml` and one successful job named "Cloud source verified v1" in the latest attempt. It does not need the run conclusion. Both are unchanged, so Cloud needs no change. - The non-`sourceOnly` mode reads the run conclusion and a job "Cloud deployable v1". That job no longer exists in this workflow. ## Verification - `node --test scripts/cloud-source-verification.test.mjs .github/scripts/tests/cloud-readiness.test.mjs .github/scripts/tests/post-merge-runner-routing.test.mjs`: 395/395 pass. - Red/green: - Before the fail-fast change, the two new chaos tests failed: the watcher cancelled the image. - With the chaos job added back to `needs`, the workflow test failed. - `actionlint .github/workflows/cloud-readiness.yml .github/workflows/release-verify.yml`: clean. - Not run: a real Cloud readiness run of this change. GitHub shows the result after merge. - Expected gate: the slowest remaining gating job sets it. After #21016 that is a general-server shard at about 10.5 min, then chat (8.8-10.5 min) and serialized (9.2-9.5 min). Expected gate open is about +11.5 to +12 min, down from +13.2 to +13.9. ## Risks - A chaos-eval regression no longer blocks the staging image. This is the owner decision. The failure stays visible as a red check and a failed Cloud readiness run. - npm canary publication reuses the same source proof, so it is also no longer gated on the chaos evals. Stable and preview releases (`release.yml`) still run them as a gate. - The non-gating rule depends on the job name prefix. A test pins the name to the constant in `cloud-source-verification.mjs`. > 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`), via Claude Code with tool use (shell, GitHub CLI). Standard reasoning mode. ## 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 Related: #21016 (server shard rebalance), #21013 (image publish time; owns `docker.yml`). 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- .../scripts/tests/cloud-readiness.test.mjs | 30 +++++++++++++++++++ .github/workflows/cloud-readiness.yml | 18 +++++++++++ .github/workflows/release-verify.yml | 9 +++++- .../release-verify-workflow.test.mjs | 5 +++- scripts/cloud-source-verification.mjs | 8 ++++- scripts/cloud-source-verification.test.mjs | 23 +++++++++++++- 6 files changed, 89 insertions(+), 4 deletions(-) diff --git a/.github/scripts/tests/cloud-readiness.test.mjs b/.github/scripts/tests/cloud-readiness.test.mjs index c8137f7dd6d..26c3acb435d 100644 --- a/.github/scripts/tests/cloud-readiness.test.mjs +++ b/.github/scripts/tests/cloud-readiness.test.mjs @@ -18,6 +18,36 @@ test("retirement preserves exact-source verification without issuing legacy depl assert.equal(existsSync(new URL("../../workflows/docker-cloud.yml", import.meta.url)), false); }); +// Owner decision (2026-11-12): the Runner chaos evals run on every admitted +// master commit and report, but are not a prerequisite of the source proof +// that image publication and Cloud discovery wait for. +test("Runner chaos evals still run but stay out of the publication gate", async () => { + const { runnerChaosEvalsJob } = await import("../../../scripts/cloud-source-verification.mjs"); + const jobs = Object.fromEntries([...workflow.split(/^jobs:\n/m)[1].matchAll(/^ ([a-z_]+):\n([\s\S]*?)(?=^ [a-z_]+:\n|(?![\s\S]))/gm)] + .map(([, name, body]) => [name, body])); + assert.deepEqual(Object.keys(jobs), ["admission", "verify", "runner_chaos_evals", "source_verified"]); + + const chaos = jobs.runner_chaos_evals; + assert.match(chaos, new RegExp(`^ name: ${runnerChaosEvalsJob.replace(/[()]/g, "\\$&")}$`, "m")); + assert.match(chaos, /^ needs: admission$/m); + assert.match(chaos, /needs\.admission\.outputs\.admitted == 'true'/); + assert.match(chaos, /uses: \.\/\.github\/workflows\/runner-chaos-evals.yml\s+with:\s+ref: \$\{\{ github.sha \}\}/); + assert.doesNotMatch(chaos, /continue-on-error/); + + // The proof needs exactly the source checks; re-adding chaos must fail here. + assert.deepEqual(jobs.source_verified.match(/^ needs: (.+)$/m)?.[1], "[verify]"); + assert.match(jobs.verify, /runner_chaos_evals: false/); + + // Release callers keep the evals as a gate through the default. + const releaseVerify = readFileSync(new URL("../../workflows/release-verify.yml", import.meta.url), "utf8"); + assert.match(releaseVerify, /runner_chaos_evals:\n\s+description: [^\n]+\n\s+required: false\n\s+default: true\n\s+type: boolean/); + assert.match(releaseVerify, /^ runner_chaos_evals:\n(?: #[^\n]*\n)* if: \$\{\{ !inputs.runner_binaries_only && inputs.runner_chaos_evals \}\}$/m); + for (const file of ["release.yml", "release-smoke.yml"]) { + const caller = readFileSync(new URL(`../../workflows/${file}`, import.meta.url), "utf8"); + assert.doesNotMatch(caller, /runner_chaos_evals:\s*false/, file); + } +}); + test("standard image provenance and independent exact-source migrators remain available", () => { const docker = readFileSync(new URL("../../workflows/docker.yml", import.meta.url), "utf8"); assert.match(docker, /target: production/); diff --git a/.github/workflows/cloud-readiness.yml b/.github/workflows/cloud-readiness.yml index b9ee017ddea..1e9e0a7dcc5 100644 --- a/.github/workflows/cloud-readiness.yml +++ b/.github/workflows/cloud-readiness.yml @@ -45,6 +45,24 @@ jobs: uses: ./.github/workflows/release-verify.yml with: ref: ${{ github.sha }} + runner_chaos_evals: false + + # Owner decision (2026-11-12): the Runner chaos evals are NOT a publication + # prerequisite. They still run on every admitted master commit and still + # fail their own check (and this run) when they fail, but source_verified + # must not need this job, and scripts/cloud-source-verification.mjs must not + # treat its failure as a failed source verification. They took 10-12 min and + # set the image gate. Do not add this job to source_verified's needs. + # .github/scripts/tests/cloud-readiness.test.mjs fails if it is re-added. + runner_chaos_evals: + name: Runner chaos evals (not a publication gate) + needs: admission + if: github.repository == 'paperclipai/paperclip' && github.ref == 'refs/heads/master' && needs.admission.outputs.admitted == 'true' + permissions: + contents: read + uses: ./.github/workflows/runner-chaos-evals.yml + with: + ref: ${{ github.sha }} source_verified: # npm canary publication reuses this exact-source verification proof. diff --git a/.github/workflows/release-verify.yml b/.github/workflows/release-verify.yml index 99c551d0122..e69c8c9b86f 100644 --- a/.github/workflows/release-verify.yml +++ b/.github/workflows/release-verify.yml @@ -12,6 +12,11 @@ on: required: false default: false type: boolean + runner_chaos_evals: + description: Run the Runner chaos evals as part of this verification. Cloud readiness passes false and runs them as a separate, non-gating job. + required: false + default: true + type: boolean outputs: runner_artifact_prefix: value: ${{ jobs.runner_binaries.outputs.artifact_prefix }} @@ -24,8 +29,10 @@ on: # the caller runs on canonical master and verifies that event's exact SHA. # The organization group also restricts these workflow files to master. jobs: + # Release callers keep the default and stay gated on these evals. Cloud + # readiness turns them off here and runs them beside its source proof. runner_chaos_evals: - if: ${{ !inputs.runner_binaries_only }} + if: ${{ !inputs.runner_binaries_only && inputs.runner_chaos_evals }} name: Pre-release Runner chaos evals uses: ./.github/workflows/runner-chaos-evals.yml with: diff --git a/scripts/__tests__/release-verify-workflow.test.mjs b/scripts/__tests__/release-verify-workflow.test.mjs index 4f9c70c647b..396a9b2667a 100644 --- a/scripts/__tests__/release-verify-workflow.test.mjs +++ b/scripts/__tests__/release-verify-workflow.test.mjs @@ -923,9 +923,12 @@ test("release daemon production uses exact-source native hosts and no publisher assert.match(runner.scripts['build:binary'], /cargo build --release --manifest-path runner\/Cargo.toml --locked/); assert.match(runner.scripts['build:binary'], /&& node scripts\/stage-runner-binary.mjs$/); assert.match(producer, /stage-release-runner-binaries.mjs record/); - for (const job of ["runner_chaos_evals", "typecheck", "general_tests", "serialized_tests", "runner_workflow_evals", "verify_paperclip_runner", "build"]) { + for (const job of ["typecheck", "general_tests", "serialized_tests", "runner_workflow_evals", "verify_paperclip_runner", "build"]) { assert.ok(workflow.includes(`${job}:\n if: \${{ !inputs.runner_binaries_only }}`)); } + // Binary-only calls still skip the chaos evals; Cloud readiness also turns + // them off here and runs them as its own non-gating job (2026-11-12). + assert.ok(workflow.includes("runner_chaos_evals:\n if: ${{ !inputs.runner_binaries_only && inputs.runner_chaos_evals }}")); const release = readWorkflow("release.yml"); const source = release.split(" release_runner_source:\n")[1].split(/\n [a-z_]+:\n/)[0]; const binaries = release.split(" release_runner_binaries:\n")[1].split(/\n [a-z_]+:\n/)[0]; diff --git a/scripts/cloud-source-verification.mjs b/scripts/cloud-source-verification.mjs index 09c4687fed1..f2e71314781 100644 --- a/scripts/cloud-source-verification.mjs +++ b/scripts/cloud-source-verification.mjs @@ -6,6 +6,12 @@ import { deferredProducer, requestDeferredProducer, sourceAdmissionJob, createRe const repository = "paperclipai/paperclip"; const workflowPath = ".github/workflows/cloud-readiness.yml"; export const sourceVerificationJob = "Cloud source verified v1"; +// Owner decision (2026-11-12): the Runner chaos evals run in the same Cloud +// readiness run but are not a publication prerequisite. Their reusable-workflow +// jobs are named " / ". Their failure still fails their own +// check and the run; it must not fail or cancel the source proof or the image. +export const runnerChaosEvalsJob = "Runner chaos evals (not a publication gate)"; +const nonGating = job => typeof job.name === "string" && job.name.startsWith(`${runnerChaosEvalsJob} / `); export class SourceVerificationFailed extends Error { constructor(message, run) { super(message); @@ -58,7 +64,7 @@ export async function readSourceVerification(sha, api, { failFast = false, onJob if (matches.length > 1) throw new Error("Cloud source verification job is ambiguous."); await onJobs?.(jobs.filter(job => job.head_sha === sha && job.run_id === run.id && job.run_attempt === run.run_attempt)); if (failFast) { - const failure = jobs.find((job) => job.status === "completed" && + const failure = jobs.find((job) => !nonGating(job) && job.status === "completed" && ["failure", "cancelled", "timed_out", "action_required", "startup_failure", "stale"].includes(job.conclusion) && job.head_sha === sha && job.run_id === run.id && job.run_attempt === run.run_attempt); if (failure) { diff --git a/scripts/cloud-source-verification.test.mjs b/scripts/cloud-source-verification.test.mjs index 35c07a1ed0d..6e1cf174714 100644 --- a/scripts/cloud-source-verification.test.mjs +++ b/scripts/cloud-source-verification.test.mjs @@ -5,7 +5,7 @@ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { fileURLToPath } from "node:url"; -import { createActionsReader, readSourceVerification, sourceVerificationJob, waitForSourceVerification, SourceVerificationDeferred } from "./cloud-source-verification.mjs"; +import { createActionsReader, readSourceVerification, runnerChaosEvalsJob, sourceVerificationJob, waitForSourceVerification, SourceVerificationDeferred } from "./cloud-source-verification.mjs"; import { releaseAdmitted, deferredProducer, requestDeferredProducer, readMigratorPublication, sourceAdmissionJob, migratorAdmissionJob, createReleaseRerunner } from "./cloud-release-admission.mjs"; @@ -378,6 +378,27 @@ describe("image build source monitor", () => { assert.deepEqual(f.cancellations, ["/repos/paperclipai/paperclip/actions/runs/99/cancel", `/repos/paperclipai/paperclip/actions/runs/${runId}/cancel`]); }); + // Owner decision 2026-11-12: Runner chaos evals run and report, but do not + // gate image publication or the exact-source proof. + const chaosJob = { ...proof, id: 112, name: `${runnerChaosEvalsJob} / Restart, replay, trace, and recovery faults` }; + + test("a failed Runner chaos eval neither cancels image work nor blocks the source proof", async () => { + const f = fixture({ jobs: [{ ...chaosJob, conclusion: "failure" }, proof] }); + assert.equal((await watchReleaseSource(f)).jobId, proof.id); + assert.deepEqual(f.cancellations, []); + }); + + test("a failed Runner chaos eval while the proof is pending keeps waiting instead of failing", async () => { + const f = fixture({ jobs: [{ ...chaosJob, conclusion: "failure" }, { ...proof, status: "in_progress", conclusion: null }] }); + assert.equal(await readSourceVerification(sha, f.api, { failFast: true }), undefined); + assert.deepEqual(f.cancellations, []); + }); + + test("a required check that only resembles the chaos job name still fails fast", async () => { + const f = fixture({ jobs: [{ ...proof, name: "Runner chaos evals / Restart", conclusion: "failure" }] }); + await assert.rejects(watchReleaseSource(f), /Runner chaos evals \/ Restart/); + }); + test("a superseded readiness attempt cancels image work with no deployable future", async () => { const f = fixture({ jobs: [], run: { ...sourceRun, status: "completed", conclusion: "cancelled" } }); await assert.rejects(watchReleaseSource(f), /did not pass/); From 67403baaa49e78c6ee6c9bdd8599990fcaa606ba Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Thu, 12 Nov 2026 06:19:21 -0600 Subject: [PATCH 3/7] fix(native): an agent termination Stop with no turn result stays a cancellation (#21093) 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 > - When a person terminates an agent, Paperclip stops the agent's running native turn > - Two paths can record that Stop: the terminate route ("Cancelled because the agent was terminated ...") and the lifecycle worker ("Agent lifecycle stop requested"). Both are system-initiated and expected > - When the stopped turn ends without a semantic result, the native executor keeps the run cancelled only for a person's Stop, a reassignment, or a governance pause. A termination Stop fell through, so the run ended `failed` with `native_session_interrupted` > - Whether the run ended cancelled or failed depended on which path won the race > - This pull request treats an acknowledged termination Stop like a person's Stop in the executor and in the lease-release terminalization > - The benefit is that a terminated agent's interrupted run ends cancelled, whichever path records the Stop first ## Linked Issues or Issue Description Refs #20186 (the same treatment for a governance pause Stop) **What happened?** A person chose Terminate for an agent while its native turn ran. The lifecycle Stop recorded an acknowledged native cancellation (initiator system). The turn ended without a semantic result. The executor then wrote the run as `failed` with `native_finalization_missing: session returned no semantic result`. **Expected behavior** The run ends `cancelled`. A termination is an intentional Stop, not a failure to retry. **Steps to reproduce** Terminate an agent while its native turn runs, so that the Stop interrupts the turn before it records a result. Before this change, the run became `failed` when the lifecycle worker recorded the Stop first. ## What Changed - `governance-pause-stop.ts`: adds `AGENT_TERMINATED_STOP_REASON`, `COMPANY_ARCHIVED_STOP_REASON` and `isAgentLifecycleStopRecord`. The predicate accepts a system-initiated, expected control-plane cancellation whose reason is a lifecycle, termination or company-archive Stop. - `acknowledged-native-stop.ts`: adds `hasAcknowledgedNativeLifecycleStopIntent`, which requires that record and an acknowledged, dispatched native Stop receipt. - `native-session-executor.ts`: the no-semantic-result branch accepts that intent, so it settles the coordinator as `native_retry_cancelled` and raises `NativeCancellationPendingRecoveryError`, as for a person's Stop. - `heartbeat/run-lifecycle.ts`: lease-release terminalization keeps such a run `cancelled`. - The terminate route and the lifecycle driver use the shared reason constants. The reason text does not change. ## Verification - `native-session-executor.test.ts`: a new case for each reason (lifecycle Stop, terminate route, company archive). Each was red before the change and is green now. The earlier control case now uses a system Stop that is neither a pause nor a termination, and it still takes the retry path. Full file: 1414 passed. - `heartbeat-run-lease-release-terminalization.test.ts`: a new case for a lifecycle Stop when teardown wins the finalizer race. It was red before the change (`interrupted`) and is green now. - Product evidence: a paid chat-eval run of `agents.retire-agent` on a branch that combines this change with three related fixes. The result is in a PR comment. ## Risks - A termination or company-archive Stop that interrupts a turn no longer schedules an exact resume of that turn. The agent is leaving service, so no resume can run. - Other system Stops keep their current behavior. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, via Claude Code with tool use (shell, file edits, test execution). Extended reasoning enabled. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 --- ...-run-lease-release-terminalization.test.ts | 18 +++++++++++ server/src/routes/agents.ts | 3 +- .../src/services/acknowledged-native-stop.ts | 5 +++ server/src/services/agent-lifecycle-driver.ts | 3 +- server/src/services/governance-pause-stop.ts | 13 ++++++++ .../src/services/heartbeat/run-lifecycle.ts | 4 ++- .../native-session-executor.test.ts | 32 +++++++++++++++++-- .../native-runtime/native-session-executor.ts | 4 +-- 8 files changed, 74 insertions(+), 8 deletions(-) diff --git a/server/src/__tests__/heartbeat-run-lease-release-terminalization.test.ts b/server/src/__tests__/heartbeat-run-lease-release-terminalization.test.ts index 872da4596e4..422f044097e 100644 --- a/server/src/__tests__/heartbeat-run-lease-release-terminalization.test.ts +++ b/server/src/__tests__/heartbeat-run-lease-release-terminalization.test.ts @@ -167,6 +167,24 @@ describeEmbeddedPostgres("heartbeat terminalizeRunOnLeaseRelease", () => { expect(terminal).toMatchObject({ status: "cancelled", error: null, errorCode: null }); }); + it("preserves an acknowledged agent termination Stop when teardown wins the finalizer race", async () => { + const { companyId, issueId, runId } = await seed({ issueStatus: "in_progress", runStatus: "running" }); + const [run] = await db.update(heartbeatRuns).set({ + nativeIssueId: issueId, + resultJson: { + cancellation: { reason: "Agent lifecycle stop requested", source: "control_plane", expected: true, + initiator: { type: "system" }, recordedAt: new Date().toISOString() }, + nativeCancellation: { + schema: "paperclip.native-cancellation.v1", runId, companyId, issueId, scope: "run", + reasonCode: "cancellation_run_only", dispatched: true, dispatchState: "acknowledged", + intentAuditId: randomUUID(), acknowledgementAuditId: randomUUID(), + }, + }, + }).where(eq(heartbeatRuns.id, runId)).returning(); + const terminal = await heartbeatService(db).terminalizeRunOnLeaseRelease(run!); + expect(terminal).toMatchObject({ status: "cancelled", error: null, errorCode: null }); + }); + it("forces a still-queued run to interrupted when the lease releases before it starts", async () => { // A queued run holds a lease but never reached "running". The teardown // released the lease, so the run must not stay queued and show a phantom diff --git a/server/src/routes/agents.ts b/server/src/routes/agents.ts index ac4b5f90d5d..0775ce81a34 100644 --- a/server/src/routes/agents.ts +++ b/server/src/routes/agents.ts @@ -167,6 +167,7 @@ import { skillVersionSelectionMap } from "../services/runtime-skill-selections.j import { isFixedClaudeOAuthBinding, secretService } from "../services/secrets.js"; import { authorizationDeniedDetails } from "../services/authorization.js"; import { providerTraceStore } from "../services/provider-trace-store.js"; +import { AGENT_TERMINATED_STOP_REASON } from "../services/governance-pause-stop.js"; import { persistReprojectedWorkspaceDiffs, projectCodexWorkspaceDiffsFromTrace, @@ -6053,7 +6054,7 @@ export function agentRoutes( const invalidOrgChainDescendantIds = listInvalidOrgChainDescendantIds(id, companyAgentRows); const cancellation = await heartbeat.cancelInvocationsForAgents( [id, ...invalidOrgChainDescendantIds], - "Cancelled because the agent was terminated or became invalid-org-chain under a terminated manager", + AGENT_TERMINATED_STOP_REASON, ); await logActivity(db, { diff --git a/server/src/services/acknowledged-native-stop.ts b/server/src/services/acknowledged-native-stop.ts index 6ad77cc89f9..25beefee409 100644 --- a/server/src/services/acknowledged-native-stop.ts +++ b/server/src/services/acknowledged-native-stop.ts @@ -7,6 +7,7 @@ import { hasRecoveredCleanupStopReceipt, hasRemoteTerminationReceipt } from "./r import { validatePrpEvent } from "../vendor/paperclip-runner/index.js"; import { nativeSha256 } from "./native-runtime/canonical.js"; import { isConfirmedCursorCloudTerminalObservation } from "./native-runtime/cursor-cloud-runtime.js"; +import { isAgentLifecycleStopRecord } from "./governance-pause-stop.js"; export function hasAcknowledgedNativeRunStopRequest(run: { id: string; companyId: string; status: string; nativeIssueId: string | null; @@ -33,6 +34,10 @@ export function hasAcknowledgedNativeStopIntent(run: Parameters[0]): boolean { + return isAgentLifecycleStopRecord(run.resultJson) && hasAcknowledgedNativeRunStopReceipt(run); +} + /** An intentional handoff retains task state and deferred work for its successor. */ export function hasAcknowledgedNativeReassignmentStopIntent(run: Parameters[0]): boolean { return run.resultJson?.reassignmentStopRequested === true && hasAcknowledgedNativeRunStopReceipt(run); diff --git a/server/src/services/agent-lifecycle-driver.ts b/server/src/services/agent-lifecycle-driver.ts index 00cd438faf6..20fe17f001b 100644 --- a/server/src/services/agent-lifecycle-driver.ts +++ b/server/src/services/agent-lifecycle-driver.ts @@ -10,6 +10,7 @@ import type { PluginWorkerManager } from "./plugin-worker-manager.js"; import type { LifecycleDriver } from "../modules/agent-lifecycle/index.js"; import { agentHarnessVerificationService } from "./agent-harness-verification.js"; import { agentInstanceSecretService } from "./agent-instance-secrets.js"; +import { AGENT_LIFECYCLE_STOP_REASON, COMPANY_ARCHIVED_STOP_REASON } from "./governance-pause-stop.js"; export function createLifecycleDriver(db: Db, manager: PluginWorkerManager): LifecycleDriver { const { verify } = agentHarnessVerificationService(db, manager); @@ -62,7 +63,7 @@ export function createLifecycleDriver(db: Db, manager: PluginWorkerManager): Lif : [agent.id, ...listInvalidOrgChainDescendantIds(agent.id, await db.select().from(agents).where(eq(agents.companyId, agent.companyId)))]; const reason = agent.lifecycleHolds?.includes("company_archived") - ? "Cancelled because the company was archived" : "Agent lifecycle stop requested"; + ? COMPANY_ARCHIVED_STOP_REASON : AGENT_LIFECYCLE_STOP_REASON; // Record what this pause stopped the runs for, so a budget resume // continues only the work its own budget stopped, never a manual pause. if (agent.lifecycleState === "pausing") { diff --git a/server/src/services/governance-pause-stop.ts b/server/src/services/governance-pause-stop.ts index 04a1e5a5616..3c0e00fe29d 100644 --- a/server/src/services/governance-pause-stop.ts +++ b/server/src/services/governance-pause-stop.ts @@ -10,6 +10,9 @@ export const AGENT_LIFECYCLE_STOP_REASON = "Agent lifecycle stop requested"; export const BUDGET_PAUSE_STOP_REASON = "Cancelled due to budget pause"; /** The direct pause route stops the agent's runs with this reason before the lifecycle worker runs. */ export const AGENT_PAUSE_STOP_REASON = "Cancelled due to agent pause"; +export const AGENT_TERMINATED_STOP_REASON = + "Cancelled because the agent was terminated or became invalid-org-chain under a terminated manager"; +export const COMPANY_ARCHIVED_STOP_REASON = "Cancelled because the company was archived"; const GOVERNANCE_PAUSE_STOP_REASONS: ReadonlySet = new Set([ AGENT_LIFECYCLE_STOP_REASON, BUDGET_PAUSE_STOP_REASON, AGENT_PAUSE_STOP_REASON]); @@ -27,3 +30,13 @@ export function isGovernancePauseStop(run: { status: string; resultJson?: Record return cancellation.reason !== AGENT_LIFECYCLE_STOP_REASON || Object.keys(record(run.resultJson?.pauseStop)).length > 0; } + +const AGENT_TERMINATION_STOP_REASONS: ReadonlySet = new Set([ + AGENT_LIFECYCLE_STOP_REASON, AGENT_TERMINATED_STOP_REASON, COMPANY_ARCHIVED_STOP_REASON]); + +export function isAgentLifecycleStopRecord(resultJson: Record | null | undefined): boolean { + const cancellation = record(resultJson?.cancellation); + return record(cancellation.initiator).type === "system" && cancellation.source === "control_plane" + && cancellation.expected === true && typeof cancellation.reason === "string" + && AGENT_TERMINATION_STOP_REASONS.has(cancellation.reason); +} diff --git a/server/src/services/heartbeat/run-lifecycle.ts b/server/src/services/heartbeat/run-lifecycle.ts index da232abd907..f4837170077 100644 --- a/server/src/services/heartbeat/run-lifecycle.ts +++ b/server/src/services/heartbeat/run-lifecycle.ts @@ -48,6 +48,7 @@ import { isWaitingConversation } from "../agent-conversations.js"; import { PROCESS_IDENTITY_RECORDED } from "../native-local-process-stop.js"; import { hasAcknowledgedNativeReassignmentStopIntent, + hasAcknowledgedNativeLifecycleStopIntent, hasAcknowledgedNativeStopIntent, } from "../acknowledged-native-stop.js"; import { connectionIntentService } from "../connection-intents.js"; @@ -1402,7 +1403,8 @@ export function createHeartbeatLifecycle(db: Db, dependencies: HeartbeatLifecycl // Teardown can beat the cancellation finalizer. Preserve the acknowledged // user intent instead of reporting an infrastructure interruption. - if (hasAcknowledgedNativeStopIntent(run) || hasAcknowledgedNativeReassignmentStopIntent(run)) terminalStatus = "cancelled"; + if (hasAcknowledgedNativeStopIntent(run) || hasAcknowledgedNativeReassignmentStopIntent(run) + || hasAcknowledgedNativeLifecycleStopIntent(run)) terminalStatus = "cancelled"; const message = `run terminalized on environment lease release: heartbeat_runs.status was still ${run.status} at teardown`; // Match both "running" and "queued". A queued run has released its lease but 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 32025817354..9e87d7bad89 100644 --- a/server/src/services/native-runtime/native-session-executor.test.ts +++ b/server/src/services/native-runtime/native-session-executor.test.ts @@ -14496,12 +14496,38 @@ describe("native session bounded recovery", () => { } finally { releaseCleanup(); endTurn(); await outcome; } }); - it("still retries a missing result after a system Stop that is not a governance pause", async () => { + it.each([ + "Agent lifecycle stop requested", + "Cancelled because the agent was terminated or became invalid-org-chain under a terminated manager", + "Cancelled because the company was archived", + ])("settles an acknowledged agent termination Stop (%s) with no turn result as a cancellation", async (reason) => { const updates: Array<{ table: unknown; values: Record }> = []; const stop: Record = {}; state.execute.mockReset().mockImplementationOnce(async () => { Object.assign(stop, { - cancellation: { reason: "Agent lifecycle stop requested", source: "control_plane", expected: true, + cancellation: { reason, source: "control_plane", expected: true, initiator: { type: "system" }, + recordedAt: new Date().toISOString() }, + nativeCancellation: { + schema: "paperclip.native-cancellation.v1", ...execution.binding, scope: "run", reasonCode: "cancellation_run_only", + dispatched: true, dispatchState: "acknowledged", intentAuditId: "intent", acknowledgementAuditId: "ack", + } }); + throw new Error("native_finalization_missing: session returned no semantic result"); + }); + state.upsertRecoveryAction.mockClear(); + await expect(executePaperclipNativeSession({ + db: leaseDb(execution, {}, stop, updates), execution, runnerInstanceId: "termination-stop", + })).rejects.toThrow("native_cancellation_pending_recovery"); + expect(updates.some(update => update.table === heartbeatRuns && update.values.status === "failed")).toBe(false); + expect(updates.some(update => update.table === nativeRunFinalizations && update.values.failureCode === "native_retry_cancelled")).toBe(true); + expect(state.upsertRecoveryAction).not.toHaveBeenCalled(); + }); + + it("still retries a missing result after a system Stop that is neither a pause nor a termination", async () => { + const updates: Array<{ table: unknown; values: Record }> = []; + const stop: Record = {}; + state.execute.mockReset().mockImplementationOnce(async () => { + Object.assign(stop, { + cancellation: { reason: "Superseded by a newer execution", source: "control_plane", expected: true, initiator: { type: "system" }, recordedAt: new Date().toISOString() }, nativeCancellation: { schema: "paperclip.native-cancellation.v1", ...execution.binding, scope: "run", reasonCode: "cancellation_run_only", @@ -14513,7 +14539,7 @@ describe("native session bounded recovery", () => { const service = vi.spyOn(issueServiceModule, "issueService").mockReturnValue({ update: vi.fn(async () => null) } as unknown as ReturnType); try { await expect(executePaperclipNativeSession({ - db: leaseDb(execution, {}, stop, updates), execution, runnerInstanceId: "termination-stop", + db: leaseDb(execution, {}, stop, updates), execution, runnerInstanceId: "other-system-stop", })).rejects.not.toThrow("native_cancellation_pending_recovery"); expect(updates.some(update => update.table === nativeRunFinalizations && update.values.failureCode === "native_retry_cancelled")).toBe(false); } finally { service.mockRestore(); } diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index fd67d8f80b9..461462c6b7d 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -119,7 +119,7 @@ import { imageGenerationBindingForRun } from "./generate-image-tool.js"; import { readVerifiedRemoteWorkspaceFile } from "./remote-deliverable-file.js"; import { copyBackCodexAuth } from "@paperclipai/adapter-codex-local/server"; import { nativeCompletionFeedback } from "./native-completion-feedback.js"; -import { hasAcknowledgedNativeReassignmentStopIntent, hasAcknowledgedNativeStopIntent, hasAcknowledgedNativeRunStopReceipt } from "../acknowledged-native-stop.js"; +import { hasAcknowledgedNativeLifecycleStopIntent, hasAcknowledgedNativeReassignmentStopIntent, hasAcknowledgedNativeStopIntent, hasAcknowledgedNativeRunStopReceipt } from "../acknowledged-native-stop.js"; import { stoppedCodexTurnIsTextOnly } from "./stopped-codex-turn.js"; import { prepareVerifiedRemoteProviderPack, useVerifiedPreinstalledRemoteProviderPack, shouldUseBundledAcpxImageAssets } from "./remote-provider-pack.js"; import { uploadVerifiedProviderPack } from "./provider-pack-upload.js"; @@ -12709,7 +12709,7 @@ async function executePaperclipNativeSessionAttempt( const governancePauseStop = !!stoppedRun && hasAcknowledgedNativeRunStopReceipt(stoppedRun) && isGovernancePauseStop({ status: "cancelled", resultJson: stoppedRun.resultJson }); if (stoppedRun && (pendingStartupStop || hasAcknowledgedNativeStopIntent(stoppedRun) || hasAcknowledgedNativeReassignmentStopIntent(stoppedRun) - || governancePauseStop + || governancePauseStop || hasAcknowledgedNativeLifecycleStopIntent(stoppedRun) || (error instanceof NativeCancellationPendingRecoveryError && hasAcknowledgedNativeRunStopReceipt(stoppedRun)))) { const [settled] = await writeExecutionControl(input.db, [DELIVERY_QUEUES.executionFinalization, DELIVERY_QUEUES.accounting], tx => tx.update(nativeRunFinalizations).set({ phase: "terminal_failure", failureCode: "native_retry_cancelled", nextAttemptAt: null, From 2a7fe6c585dfd06d574b134be6ace907390eecd8 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Thu, 12 Nov 2026 06:19:27 -0600 Subject: [PATCH 4/7] fix(server): withhold a queued assignment run once its task moves to backlog (#21095) 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 > - Assigning a ready task to an agent queues an assignment run. Paperclip does not queue one for a backlog task > - An agent created a ready task, which queued an assignment run, and then moved the task to backlog. The agent was busy, so the run stayed queued > - When the run started, the queued-run gate did not check for backlog, and the run checked out and did the backlog task > - This pull request makes the queued-run gate withhold a never-started assignment run whose task is now in backlog > - The benefit is that moving a task to backlog keeps it parked, as when it is created in backlog ## Linked Issues or Issue Description **What happened?** An agent created a task without a status, so it was created ready with a queued assignment run. The agent then moved the task to backlog. The queued assignment run started two minutes later and completed the backlog task. **Expected behavior** A queued assignment run that has not started does not execute a task that has since moved to backlog. The run is cancelled with a clear reason. **Steps to reproduce** Assign a ready task to a busy agent so that its assignment run waits in the queue. Move the task to backlog. Let the agent become free. Before this change, the assignment run started and checked out the task. ## What Changed - `run-dispatch/domain/policy.ts` (`decideQueuedRunStaleness`): a queued run whose wake reason is `issue_assigned` is stale when its task is in `backlog`. The new error code is `issue_in_backlog`, with the reason "Cancelled because the task moved to backlog before its assignment run could start". - `pre-dispatch-review-wait.ts`: lists `issue_in_backlog` as a never-started dispatch cancellation, like the other queued-run gate codes. - `run-dispatch/adapters/postgres.test.ts`: a new test moves the task to backlog after the run is queued and checks that `cancelStaleQueuedRun` cancels it before it starts. A control test checks that a comment wake on a backlog task still starts. ## Verification - The new test failed before the change (`not_stale`) and passes after it. - `pnpm vitest run src/modules/run-dispatch/ src/services/pre-dispatch-review-wait`: 185 passed. - Product evidence: a paid chat-eval run of `questions-and-approvals.accept-one-proposal` on a branch that combines this change with three related fixes. The result is in a PR comment. ## Risks - Low risk. The rule applies only to assignment wakes. Comment, interaction and recovery wakes on a backlog task keep their current behavior. - To start the task, a person or agent moves it out of backlog. That wakes the assignee with `issue_status_changed`, as today. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, via Claude Code with tool use (shell, file edits, test execution). Extended reasoning enabled. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 --- .../run-dispatch/adapters/postgres.test.ts | 27 +++++++++++++++++++ .../src/modules/run-dispatch/domain/policy.ts | 12 ++++++++- .../src/services/pre-dispatch-review-wait.ts | 1 + 3 files changed, 39 insertions(+), 1 deletion(-) diff --git a/server/src/modules/run-dispatch/adapters/postgres.test.ts b/server/src/modules/run-dispatch/adapters/postgres.test.ts index 1529eca1f79..e4b5ca41e92 100644 --- a/server/src/modules/run-dispatch/adapters/postgres.test.ts +++ b/server/src/modules/run-dispatch/adapters/postgres.test.ts @@ -1242,6 +1242,33 @@ describeEmbeddedPostgres("run-dispatch postgres adapter", () => { }); describe("cancelStaleQueuedRun", () => { + it("withholds a never-started assignment run once its task moves to backlog", async () => { + const { companyId, agentId } = await seedCompanyAndAgent(); + const issueId = randomUUID(); + await seedIssue({ companyId, issueId, assigneeAgentId: agentId, status: "todo" }); + const runId = await seedRun({ companyId, agentId, contextSnapshot: { issueId, taskId: issueId, wakeReason: "issue_assigned", source: "assignment" } }); + await db.update(issues).set({ status: "backlog" }).where(eq(issues.id, issueId)); + const adapter = createPostgresRunDispatchAdapter(db); + + expect(await adapter.cancelStaleQueuedRun({ companyId, runId, expectedStatus: "queued", now: new Date() })) + .toMatchObject({ outcome: "cancelled", errorCode: "issue_in_backlog" }); + const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)); + expect(run).toMatchObject({ status: "cancelled", errorCode: "issue_in_backlog", startedAt: null }); + expect(run!.error).toContain("backlog"); + expect((await db.select().from(issues).where(eq(issues.id, issueId)))[0]!.status).toBe("backlog"); + }); + + it("still starts a comment wake on a backlog task", async () => { + const { companyId, agentId } = await seedCompanyAndAgent(); + const issueId = randomUUID(); + await seedIssue({ companyId, issueId, assigneeAgentId: agentId, status: "backlog" }); + const runId = await seedRun({ companyId, agentId, contextSnapshot: { issueId, wakeReason: "issue_commented", wakeCommentId: randomUUID() } }); + const adapter = createPostgresRunDispatchAdapter(db); + + expect(await adapter.cancelStaleQueuedRun({ companyId, runId, expectedStatus: "queued", now: new Date() })) + .toMatchObject({ outcome: "not_stale" }); + }); + it.each([ { label: "chat source", source: "chat:slack", expected: "chat:slack" }, { diff --git a/server/src/modules/run-dispatch/domain/policy.ts b/server/src/modules/run-dispatch/domain/policy.ts index d1aa1426806..720d0651203 100644 --- a/server/src/modules/run-dispatch/domain/policy.ts +++ b/server/src/modules/run-dispatch/domain/policy.ts @@ -118,7 +118,8 @@ export type QueuedRunStalenessErrorCode = | "issue_execution_lock_changed" | "issue_blocked" | "issue_review_participant_changed" - | "issue_continuation_waiting_on_review"; + | "issue_continuation_waiting_on_review" + | "issue_in_backlog"; export type StalenessDecision = | { stale: false } @@ -603,6 +604,15 @@ export function decideQueuedRunStaleness( }; } + if (facts.wakeReason === "issue_assigned" && facts.issueStatus === "backlog") { + return { + stale: true, + errorCode: "issue_in_backlog", + reason: "Cancelled because the task moved to backlog before its assignment run could start", + details: { issueId: facts.issueId, currentStatus: facts.issueStatus }, + }; + } + if (facts.retryReasonKind === "native_safe_replacement" && facts.dependenciesBlocked) { return { stale: true, errorCode: "issue_dependencies_blocked", reason: "Cancelled because issue dependencies became blocked before replacement dispatch", diff --git a/server/src/services/pre-dispatch-review-wait.ts b/server/src/services/pre-dispatch-review-wait.ts index 68454275e1e..69d9a0a0998 100644 --- a/server/src/services/pre-dispatch-review-wait.ts +++ b/server/src/services/pre-dispatch-review-wait.ts @@ -21,6 +21,7 @@ const staleDispatchReconciliationExemptions = { issue_execution_lock_changed: true, issue_terminal_status: true, issue_review_participant_changed: true, + issue_in_backlog: true, // This code requires its own executionWait receipt in pre-dispatch-execution-wait.ts. execution_reconciliation_required: false, } satisfies Record; From 482063aeca7033f877e7aba8baab7a5f81c0091c Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Thu, 12 Nov 2026 06:28:27 -0600 Subject: [PATCH 5/7] fix(daytona): reuse or repair a read-only skill bundle instead of failing the sync (#21075) 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 turns run in a remote Runner in a Daytona sandbox. Before a turn starts, Paperclip copies each selected skill into the sandbox as a read-only bundle. > - A sandbox is often kept between turns, so the read-only bundle is already there when the next turn (or a recovery) copies it again. > - The server writes the same skill files again on its own disk, with new timestamps. The copy compared the bundles with `tar --diff`, which also compares timestamps. So the copy saw a difference, extracted over the read-only directories, and failed with "Cannot open: File exists". > - The turn then stopped and the task stayed blocked until a person sent a message. > - This pull request treats a timestamp-only difference as the same bundle, and repairs a bundle that really differs instead of failing. > - The benefit is that a kept sandbox no longer blocks a task when its skills are copied again. ## Linked Issues or Issue Description **What happened?** On staging, two tasks in 30 minutes stopped with "Daytona syncIn extract command failed (exit 43): tar: .paperclip-repository/...: Cannot open: File exists". One failure was a normal new turn on a kept sandbox. The other was a recovery of an interrupted turn. Neither one started again by itself. **Expected behavior** The turn uses the bundle that is already in the sandbox when its content and permissions match. When the content does not match, the copy repairs it. **Steps to reproduce** 1. Copy a read-only (0555/0444) skill directory into a sandbox. 2. Change only the timestamps of the copy (this is what a new server preparation does). 3. Copy the same skill again. GNU tar fails with "Cannot open: File exists". ## What Changed - `file-sync.ts` (read-only directory copy): run the `tar --diff` check with `LC_ALL=C` and ignore lines that only say "Mod time differs". Bytes, modes, file types and missing files still count as differences. - When the bundle really differs, make its read-only subdirectories writable before the extract. GNU tar then replaces the files and restores the archived directory modes (`--delay-directory-restore`). Extra files in the target stay. - If reopening the directories or the repair extract fails, re-seal only the directories that were reopened for it (their list is recorded first). Writable user directories beside the bundle keep their modes. - `file-sync.test.ts`: the existing GNU tar test now covers a timestamp-only resync (kept, no failure) and a damaged bundle (repaired to the source bytes and modes, instead of the old fail-closed result), and a repair that cannot finish (bundle directories re-sealed to 0555, a writable user directory left at 0755), and a reopen that hits an unreadable user directory (bundle re-sealed, no scratch files left). ## Verification - Red: with the old `file-sync.ts`, the updated test fails with the same error seen on staging: `tar: references/overview.md: Cannot open: File exists`. - Green: `npx vitest run src/file-sync.test.ts` in `packages/plugins/sandbox-providers/daytona` passes 33/33 with GNU tar. - I reproduced the root cause by hand with GNU tar 1.35: a re-extract over a 0555 directory fails with "Cannot open: File exists", and `tar -df` reports only "Mod time differs" for a copy that differs only in timestamps. ## Risks - Low risk. The change affects only read-only (immutable) directory copies on Daytona. - A bundle that really differs is now repaired in place instead of failing the turn. Each file is replaced by tar (unlink and create). The directory modes come back from the archive. - If a target has extra read-only subdirectories that are not in the archive, they become owner-writable after a repair. > 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`), Claude Code agent with tool use (shell, code search, test execution). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- .../daytona/src/file-sync.test.ts | 58 +++++++++++++++++-- .../daytona/src/file-sync.ts | 27 +++++++-- 2 files changed, 75 insertions(+), 10 deletions(-) diff --git a/packages/plugins/sandbox-providers/daytona/src/file-sync.test.ts b/packages/plugins/sandbox-providers/daytona/src/file-sync.test.ts index 466059be3d0..982e904179c 100644 --- a/packages/plugins/sandbox-providers/daytona/src/file-sync.test.ts +++ b/packages/plugins/sandbox-providers/daytona/src/file-sync.test.ts @@ -338,20 +338,70 @@ it.skipIf(!gnuTar)("extracts interleaved read-only skill directories with GNU ta expect(await fs.readFile(path.join(target, "references", "agents", "qa.md"), "utf8")).toBe("QA instructions"); expect((await fs.stat(path.join(target, "references", "agents"))).mode & 0o777).toBe(0o555); expect((await fs.stat(path.join(target, "references", "agents", "qa.md"))).mode & 0o777).toBe(0o444); + // Recovery re-materializes the same admitted bytes on the host with new + // timestamps. That is still the same bundle: keep it, never fail on it. + const qa = path.join(target, "references", "agents", "qa.md"); + const agentsDir = path.join(target, "references", "agents"); + const resumedAt = new Date(Date.now() + 3_600_000); + for (const entry of [qa, agentsDir, path.join(target, "references", "overview.md")]) await fs.utimes(entry, resumedAt, resumedAt); + await performSyncIn({ sandbox: sandbox as never, remoteDir, timeoutSeconds: 30, + operations: [{ operationId: "rematerialized-skill-resume", files: [{ sourcePath: source, targetPath: target, kind: "directory", mode: 0o555 }] }] }); + expect((await fs.stat(qa)).mtime.getTime()).toBe(resumedAt.getTime()); // Never treat a corrupted read-only bundle as a cache hit, even if its // file size, permissions and timestamp still match the source archive. - const qa = path.join(target, "references", "agents", "qa.md"); - const before = await fs.stat(qa); + // Repair it in place instead of failing the run. + const sourceTimes = await Promise.all([qa, agentsDir, path.join(target, "references", "overview.md")] + .map((entry) => fs.stat(path.join(source, path.relative(target, entry))))); + const before = sourceTimes[0]!; + await fs.chmod(agentsDir, 0o755); await fs.chmod(qa, 0o644); await fs.writeFile(qa, "XX instructions"); await fs.chmod(qa, 0o444); + await fs.chmod(agentsDir, 0o555); await fs.utimes(qa, before.atime, before.mtime); + await fs.utimes(agentsDir, sourceTimes[1]!.atime, sourceTimes[1]!.mtime); + await fs.utimes(path.join(target, "references", "overview.md"), sourceTimes[2]!.atime, sourceTimes[2]!.mtime); + await performSyncIn({ sandbox: sandbox as never, remoteDir, timeoutSeconds: 30, + operations: [{ operationId: "corrupt-skill-resume", files: [{ sourcePath: source, targetPath: target, kind: "directory", mode: 0o555 }] }] }); + expect(await fs.readFile(qa, "utf8")).toBe("QA instructions"); + expect((await fs.stat(agentsDir)).mode & 0o777).toBe(0o555); + expect((await fs.stat(qa)).mode & 0o777).toBe(0o444); + expect(await fs.readFile(path.join(target, "unrelated.txt"), "utf8")).toBe("keep me"); + expect((await fs.readdir(remoteDir)).filter((name) => name.startsWith(".paperclip-upload"))).toEqual([]); + // A repair that cannot finish still leaves the bundle sealed read-only. + const blocked = path.join(target, "references", "overview.md"); + await fs.chmod(path.join(target, "references"), 0o755); + await fs.rm(blocked); + await fs.mkdir(blocked); + await fs.writeFile(path.join(blocked, "child"), "x"); + await fs.chmod(path.join(target, "references"), 0o555); + // A writable directory the user keeps beside the bundle stays writable. + const userDir = path.join(target, "notes"); + await fs.mkdir(userDir, { mode: 0o755 }); await expect(performSyncIn({ sandbox: sandbox as never, remoteDir, timeoutSeconds: 30, - operations: [{ operationId: "corrupt-skill-resume", files: [{ sourcePath: source, targetPath: target, kind: "directory", mode: 0o555 }] }] })).rejects.toThrow("syncIn extract"); - expect(await fs.readFile(qa, "utf8")).toBe("XX instructions"); + operations: [{ operationId: "blocked-skill-resume", files: [{ sourcePath: source, targetPath: target, kind: "directory", mode: 0o555 }] }] })).rejects.toThrow("syncIn extract"); + for (const dir of ["references", "references/agents"]) { + expect((await fs.stat(path.join(target, dir))).mode & 0o777).toBe(0o555); + } + expect((await fs.stat(userDir)).mode & 0o777).toBe(0o755); + expect((await fs.stat(blocked)).mode & 0o200).toBe(0o200); + await fs.chmod(blocked, 0o700); + expect((await fs.readdir(remoteDir)).filter((name) => name.startsWith(".paperclip-upload"))).toEqual([]); + // A reopen that fails part-way (an unreadable user directory) re-seals the + // bundle and leaves no scratch files behind either. + const unreadable = path.join(target, "private"); + await fs.mkdir(unreadable); + await fs.chmod(unreadable, 0o300); + await expect(performSyncIn({ sandbox: sandbox as never, remoteDir, timeoutSeconds: 30, + operations: [{ operationId: "unreadable-skill-resume", files: [{ sourcePath: source, targetPath: target, kind: "directory", mode: 0o555 }] }] })).rejects.toThrow("syncIn extract"); + for (const dir of ["references", "references/agents"]) { + expect((await fs.stat(path.join(target, dir))).mode & 0o777).toBe(0o555); + } + expect((await fs.stat(unreadable)).mode & 0o777).toBe(0o300); expect((await fs.readdir(remoteDir)).filter((name) => name.startsWith(".paperclip-upload"))).toEqual([]); } finally { + await fs.chmod(path.join(target, "private"), 0o700).catch(() => undefined); for (const base of [source, target]) { for (const dir of ["references/agents", "references"]) await fs.chmod(path.join(base, dir), 0o700).catch(() => undefined); } diff --git a/packages/plugins/sandbox-providers/daytona/src/file-sync.ts b/packages/plugins/sandbox-providers/daytona/src/file-sync.ts index be958b0371a..3dabd49dbb9 100644 --- a/packages/plugins/sandbox-providers/daytona/src/file-sync.ts +++ b/packages/plugins/sandbox-providers/daytona/src/file-sync.ts @@ -1104,27 +1104,42 @@ async function syncInDirectoryMapping(input: { // A resumed sandbox can already contain these immutable 0444/0555 // assets. Repack a private extraction as the sandbox user: tar --diff // otherwise rejects identical bytes because the host UID/GID differ. - // Compare content and modes, never chmod the live bundle or skip - // unverified old files. Extra user files in the target stay untouched. + // Compare content and modes, never skip unverified old files. A + // recovery re-materializes the same admitted bytes on the host with + // new timestamps, so a timestamp-only difference is still a match. + // Extra user files in the target stay untouched. ...(immutable ? [ `compare_dir=${shellQuote(`${remoteTar}.compare`)};`, `compare_tar=${shellQuote(`${remoteTar}.normalized`)};`, `compare_list=${shellQuote(`${remoteTar}.members`)};`, - 'cleanup_compare() { if [ -d "$compare_dir" ]; then find "$compare_dir" -type d -exec chmod u+w {} +; rm -rf "$compare_dir"; fi; rm -f "$compare_tar" "$compare_list"; };', + `compare_out=${shellQuote(`${remoteTar}.differences`)};`, + 'cleanup_compare() { if [ -d "$compare_dir" ]; then find "$compare_dir" -type d -exec chmod u+w {} +; rm -rf "$compare_dir"; fi; rm -f "$compare_tar" "$compare_list" "$compare_out"; };', "trap cleanup_compare EXIT;", 'mkdir -m 700 "$compare_dir" || exit 43;', `tar -xf ${shellQuote(remoteTar)} --no-same-owner --delay-directory-restore -C "$compare_dir" || exit 43;`, '(cd "$compare_dir" && find . -mindepth 1 -maxdepth 1 -print0) > "$compare_list" || exit 43;', 'tar -cf "$compare_tar" --format=pax -C "$compare_dir" --null -T "$compare_list" || exit 43;', - `if tar -df "$compare_tar" -C ${shellQuote(mapping.targetPath)} >/dev/null 2>&1; then rm -f ${shellQuote(remoteTar)}; exit 0; fi;`, + `LC_ALL=C tar -df "$compare_tar" -C ${shellQuote(mapping.targetPath)} > "$compare_out" 2>&1; compare_status=$?;`, + `if [ "$compare_status" -le 1 ] && ! grep -v ': Mod time differs$' "$compare_out" >/dev/null; then rm -f ${shellQuote(remoteTar)}; exit 0; fi;`, "cleanup_compare;", "trap - EXIT;", + // The old copy really differs (a changed or damaged file). Its + // read-only directories would make tar fail with "Cannot open: File + // exists", so reopen them; the extract restores the archived modes. + // Record exactly which ones were reopened so a failed repair re-seals + // only those and never touches writable user directories. A reopen + // that fails part-way (an unreadable directory) re-seals the same way. + `reopened_list=${shellQuote(`${remoteTar}.reopened`)};`, + 'reseal_reopened() { if [ -s "$reopened_list" ]; then xargs -0 chmod u-w < "$reopened_list"; fi; rm -f "$reopened_list"; };', + `find ${shellQuote(mapping.targetPath)} -mindepth 1 -type d ! -perm -u+w -print0 -exec chmod u+w {} + > "$reopened_list" || { reseal_reopened; echo "reopen failed"; exit 43; };`, ] : []), // BSD archives may revisit a directory after its parent's files. Keep // GNU tar from restoring a read-only skill directory's mode before all // of its children are extracted; final permissions remain unchanged. - `tar -xf ${shellQuote(remoteTar)} --delay-directory-restore -C ${shellQuote(mapping.targetPath)} || { echo "extract failed"; exit 43; };`, - `rm -f ${shellQuote(remoteTar)};`, + // A failed repair must not leave the read-only bundle writable. + `tar -xf ${shellQuote(remoteTar)} --delay-directory-restore -C ${shellQuote(mapping.targetPath)} || { ${immutable + ? "reseal_reopened; " : ""}echo "extract failed"; exit 43; };`, + `rm -f ${shellQuote(remoteTar)}${immutable ? ' "$reopened_list"' : ""};`, ].join("\n"); // `extractTarball` span: one round trip — re-check the path, `tar -xf`, and // remove the scratch tarball. From 849f109f62ce226b46e0b35c9466b98124159609 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Thu, 12 Nov 2026 06:52:07 -0600 Subject: [PATCH 6/7] fix(server): agent inbox reads now apply private-task visibility (#21092) 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 read a person's Mine list with `GET /api/agents/me/inbox/mine`, and their own queue with `GET /api/agents/me/inbox-lite` > - The company task list routes apply private-task visibility for the reading actor > - The two agent inbox routes should use the same visibility rules, so that each route returns the same tasks for the same actor > - This pull request makes agent inbox reads apply private-task visibility > - The benefit is one consistent visibility rule across task list routes ## Linked Issues or Issue Description **What existing behavior does this improve?** Agent inbox reads now apply private-task visibility. **Subsystem affected** Server API: agent inbox routes. **Current behavior** The agent inbox routes build their lists without the issue read condition that the company task list routes use. **Proposed behavior** The agent inbox routes use the same issue read condition and per-row read decisions as the company task list routes. **Reason and benefit** All task list routes apply one visibility rule. ## What Changed - `server/src/routes/agents.ts`: `GET /api/agents/me/inbox/mine` adds `issueReadSqlCondition` to its list query and keeps only the rows that `access.decideReads` allows. - `GET /api/agents/me/inbox-lite` adds the same read condition to its list query. - `inbox-mine-routes.test.ts`: a new embedded-Postgres test for the agent Mine read with private and open tasks. - `agent-permissions-routes.test.ts`: the mocked route test expects the read condition and the read decisions. ## Verification - `pnpm vitest run src/__tests__/inbox-mine-routes.test.ts`: 7 passed. The new test was red before the route change and is green after it. - `pnpm vitest run src/__tests__/agent-permissions-routes.test.ts src/__tests__/openapi-routes.test.ts`: all passed. - A chat eval run on a branch that combines this change with three other fixes. The result is in a PR comment. ## Risks - Low risk. The routes return only tasks that the reading agent can open through the task routes. - The Mine route adds one batched read decision for each request. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, via Claude Code with tool use (shell, file edits, test execution). Extended reasoning enabled. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- .../agent-permissions-routes.test.ts | 26 +++++++++++ .../src/__tests__/inbox-mine-routes.test.ts | 45 +++++++++++++++++++ server/src/routes/agents.ts | 16 ++++++- 3 files changed, 85 insertions(+), 2 deletions(-) diff --git a/server/src/__tests__/agent-permissions-routes.test.ts b/server/src/__tests__/agent-permissions-routes.test.ts index 2c9759fd40a..422008d3214 100644 --- a/server/src/__tests__/agent-permissions-routes.test.ts +++ b/server/src/__tests__/agent-permissions-routes.test.ts @@ -63,6 +63,7 @@ const mockBuiltInAgentService = vi.hoisted(() => ({ const mockAccessService = vi.hoisted(() => ({ canUser: vi.fn(), decide: vi.fn(), + decideReads: vi.fn(), hasPermission: vi.fn(), getMembership: vi.fn(), ensureMembership: vi.fn(), @@ -2400,6 +2401,29 @@ describe("agent permission routes", () => { expect(mockAccessService.setPrincipalPermission).not.toHaveBeenCalled(); }); + it("returns only the inbox mine rows the agent may read", async () => { + mockIssueService.list.mockResolvedValue([ + { id: "issue-open", companyId, identifier: "PAP-1", title: "Readable", status: "todo" }, + { id: "issue-denied", companyId, identifier: "PAP-2", title: "Not readable", status: "todo" }, + ]); + mockAccessService.decideReads.mockResolvedValue([{ allowed: true }, { allowed: false }]); + const app = await createApp({ type: "agent", agentId, companyId, runId: "run-1", source: "agent_key" }); + + const res = await requestApp(app, (baseUrl) => request(baseUrl) + .get("/api/agents/me/inbox/mine") + .query({ userId: "board-user" })); + + expect(res.status).toBe(200); + expect(res.body.map((row: { id: string }) => row.id)).toEqual(["issue-open"]); + expect(mockAccessService.decideReads).toHaveBeenCalledWith( + expect.objectContaining({ type: "agent", agentId }), + [ + expect.objectContaining({ type: "issue", companyId, issueId: "issue-open" }), + expect.objectContaining({ type: "issue", companyId, issueId: "issue-denied" }), + ], + ); + }); + it("exposes a dedicated agent route for the inbox mine view", async () => { mockIssueService.list.mockResolvedValue([ { @@ -2409,6 +2433,7 @@ describe("agent permission routes", () => { status: "todo", }, ]); + mockAccessService.decideReads.mockResolvedValue([{ allowed: true }]); const app = await createApp({ type: "agent", @@ -2432,6 +2457,7 @@ describe("agent permission routes", () => { }, ]); expect(mockIssueService.list).toHaveBeenCalledWith(companyId, { + readCondition: expect.anything(), touchedByUserId: "board-user", inboxArchivedByUserId: "board-user", status: "backlog,todo,in_progress,in_review,blocked,done", diff --git a/server/src/__tests__/inbox-mine-routes.test.ts b/server/src/__tests__/inbox-mine-routes.test.ts index 485abe3977f..1cf40207d68 100644 --- a/server/src/__tests__/inbox-mine-routes.test.ts +++ b/server/src/__tests__/inbox-mine-routes.test.ts @@ -157,6 +157,51 @@ describeEmbeddedPostgres("Mine inbox snapshot routes", () => { expect(snapshot.failureRuns).toEqual(legacy.body); }); + it("limits an agent's Mine read to tasks the agent may open", async () => { + const f = await seed("Agent Mine privacy"); + const owner = `owner-${randomUUID()}`; + const agent = await addAgent(f.companyId); + const privateId = randomUUID(); + const visible = await addTask(f.companyId, owner, { title: "OPEN_OWNER_TASK" }); + await addTask(f.companyId, owner, { + id: privateId, identifier: "AMP-77", title: "PRIVATE_OWNER_TITLE", description: "PRIVATE_OWNER_DESCRIPTION", + visibility: "private", privacyRootIssueId: privateId, responsibleUserId: owner, + }); + const app = appFor(null, {}, { type: "agent", agentId: agent.id, companyId: f.companyId, source: "agent_key" }); + + await request(app).get(`/api/issues/${privateId}`).expect(404); + const res = await request(app).get("/api/agents/me/inbox/mine").query({ userId: owner }).expect(200); + + expect((res.body as Array<{ id: string }>).map(row => row.id)).toEqual([visible.id]); + for (const leaked of [privateId, "AMP-77", "PRIVATE_OWNER_TITLE", "PRIVATE_OWNER_DESCRIPTION"]) { + expect(JSON.stringify(res.body)).not.toContain(leaked); + } + }); + + it("keeps an agent's assigned private task in its queue only when its responsible user may open it", async () => { + const f = await seed("Agent queue privacy"); + const other = `other-${randomUUID()}`; + const agent = await addAgent(f.companyId); + const ownId = randomUUID(), otherId = randomUUID(); + await addTask(f.companyId, f.userId, { + id: ownId, title: "OWN_PRIVATE_TASK", visibility: "private", privacyRootIssueId: ownId, + responsibleUserId: f.userId, assigneeAgentId: agent.id, + }); + await addTask(f.companyId, other, { + id: otherId, title: "OTHER_PRIVATE_TASK", visibility: "private", privacyRootIssueId: otherId, + responsibleUserId: other, assigneeAgentId: agent.id, + }); + const app = appFor(null, {}, { + type: "agent", agentId: agent.id, companyId: f.companyId, source: "agent_key", onBehalfOfUserId: f.userId, + }); + + const queue = await request(app).get("/api/agents/me/inbox-lite").expect(200); + expect((queue.body as Array<{ id: string }>).map(row => row.id)).toEqual([ownId]); + const mine = await request(app).get("/api/agents/me/inbox/mine").query({ userId: f.userId }).expect(200); + expect((mine.body as Array<{ id: string }>).map(row => row.id)).toEqual([ownId]); + expect(JSON.stringify([queue.body, mine.body])).not.toContain("OTHER_PRIVATE_TASK"); + }); + it("owns the 100-task and 200-run bounds and rejects caller filters or unauthorized identities", async () => { const f = await seed("Snapshot bounds"); const ids = Array.from({ length: 105 }, () => randomUUID()); diff --git a/server/src/routes/agents.ts b/server/src/routes/agents.ts index 0775ce81a34..4de4e064c54 100644 --- a/server/src/routes/agents.ts +++ b/server/src/routes/agents.ts @@ -165,7 +165,7 @@ import type { AdapterAuthSignal, AdapterAuthSignalResponse, CodexAccountBindingC import { adapterSettingsService } from "../services/adapter-settings.js"; import { skillVersionSelectionMap } from "../services/runtime-skill-selections.js"; import { isFixedClaudeOAuthBinding, secretService } from "../services/secrets.js"; -import { authorizationDeniedDetails } from "../services/authorization.js"; +import { authorizationDeniedDetails, issueReadSqlCondition } from "../services/authorization.js"; import { providerTraceStore } from "../services/provider-trace-store.js"; import { AGENT_TERMINATED_STOP_REASON } from "../services/governance-pause-stop.js"; import { @@ -4173,6 +4173,7 @@ export function agentRoutes( const issuesSvc = issueService(db); const recoveryActionsSvc = issueRecoveryActionService(db); const rows = await issuesSvc.list(req.actor.companyId, { + readCondition: await issueReadSqlCondition(db, req.actor), assigneeAgentId: req.actor.agentId, status: "todo,in_progress,blocked", includeRoutineExecutions: true, @@ -4222,13 +4223,24 @@ export function agentRoutes( const query = agentMineInboxQuerySchema.parse(req.query); const issuesSvc = issueService(db); const rows = await issuesSvc.list(req.actor.companyId, { + readCondition: await issueReadSqlCondition(db, req.actor), touchedByUserId: query.userId, inboxArchivedByUserId: query.userId, status: query.status, limit: ISSUE_LIST_DEFAULT_LIMIT, }); + const decisions = await access.decideReads(req.actor, rows.map((issue) => ({ + type: "issue" as const, + companyId: issue.companyId, + issueId: issue.id, + projectId: issue.projectId, + parentIssueId: issue.parentId, + assigneeAgentId: issue.assigneeAgentId, + assigneeUserId: issue.assigneeUserId, + status: issue.status, + }))); - res.json(rows); + res.json(rows.filter((_, index) => decisions[index]?.allowed)); }); router.get("/agents/:id/identity", async (req, res) => { From 1d153f62b62b6b16703955aff7c8244c0be18c90 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Thu, 12 Nov 2026 07:10:11 -0600 Subject: [PATCH 7/7] feat(docker): build the image in the merge queue and promote it on master (#21096) 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 > - `docker.yml` builds, probes, gates and signs the standard Core image for every master push. Paperclip Cloud deploys a Core commit only after that image is published. > - Each master push rebuilds the image from scratch: about 10.6 min for amd64 and 7.8 min for arm64. > - The owner approved a merge queue for Core. A merge queue tests the exact commit that master will become, before the merge. > - This pull request builds and probes the image for that exact commit in the queue, with no registry credentials. The later master push pushes those exact bytes instead of rebuilding. When no matching verified build exists, master builds from source exactly as today. > - The benefit is that the image legs on master drop from about 8–11 min to about 3–4 min, and nothing changes until the owner turns the queue on. ## Linked Issues or Issue Description Refs #21013 (it measured the image path and proposed this plan). **What existing behavior does this improve?** Every master push rebuilds the standard image, even when the same commit could already have been built while it waited to merge. **Subsystem affected** `.github/workflows/docker.yml` (`build-and-push` only), new `.github/workflows/docker-merge-group.yml`, new `scripts/merge-group-image.mjs`. **Current behavior** `build-and-push` always runs the full BuildKit build on master: 639 s (amd64) and 468 s (arm64) in run 43133035209. **Proposed behavior** On a `merge_group` event, build both architectures for the merge-group commit, probe PID 1, and upload an OCI archive plus a record of commit, tree, architecture and digest. On the master push for the same commit, each leg pushes that archive by digest instead of building. Everything after the leg (probe, exact-source gate, signed-index check, attestation) is unchanged. **Reason and benefit** The build moves before the merge, where it runs in parallel with the queue's other checks. The master leg only downloads and pushes. **Breaking changes** None. Without `merge_group` events, `find` returns no run and the leg builds as before. **Additional context** This PR does not touch the exact-source gate jobs (`source_verification`, `publication_verification`, `merge-and-push`), `scripts/watch-release-source.mjs` or `cloud-readiness.yml`. Another change owns them. ## What Changed - **`docker-merge-group.yml` (new, `on: merge_group` only).** It runs only for this repository's master queue. Workflow permissions are `{}` and the job has `contents: read` only. There are no secrets, no registry login, no `cache-to`, no `push: true`, no environments, and checkout uses `persist-credentials: false`. It runs on GitHub-hosted runners, not the paid AWS fleets. Steps: build `target: production` with the same build args as master (`PAPERCLIP_BUILD_COMMIT` is the merge-group SHA, which becomes the master SHA). Read the public registry cache. Write `type=oci` to a tar. `docker load` it and run `scripts/assert-orphan-reaping.sh`. Only then write `record.json` and upload `merge-group-image-` (3-day retention). - **`scripts/merge-group-image.mjs` (new).** - `find` (master push only): selects a completed, successful run of this workflow, with event `merge_group`, the same `head_sha`, repository and head repository both `1170821064`, and a `gh-readonly-queue/master/` head branch. It needs exactly one unexpired artifact for the architecture. - `record` (merge group only): reads the archive's `index.json`, checks each blob's sha256 and that the image is `linux/`, and writes `{sha, tree, arch, digest}`. - `verify` (master push only): re-reads the archive the same way and requires record SHA = `GITHUB_SHA`, record tree = `git rev-parse HEAD^{tree}` of the master checkout, same architecture, and archive digest = recorded digest. - **`docker.yml` `build-and-push`.** - The leg gets `actions: read` so it can download the artifact. - New steps run after the registry login: find, download, then promote (`verify`, then `skopeo copy --all --preserve-digests oci-archive:… docker://ghcr.io/…@`). The step sets its `digest` output only after the push succeeds. - All three new steps are `continue-on-error`. Buildx, labels, metadata and "Build and push by digest" run when `steps.promote.outputs.digest == ''`, so any failure builds from source. - "Select image digest" feeds the existing PID 1 probe and digest export. - **Tests (`scripts/merge-group-image.test.mjs`, 8 tests):** - Run selection rejects another commit, another event, another workflow, a fork head, another repository, another queue base, and failed, cancelled or running builds. - Artifact selection. - Archive digest with and without provenance, a tampered blob, the wrong architecture, and a real tar read through the system `tar`. - Record checks for commit, tree, architecture and digest mismatch. - The CLI refuses `record` outside `merge_group` and `find`/`verify` outside a canonical master push. - Static checks of the merge-group workflow: credentials, triggers, permissions and runners. - Static checks of the `docker.yml` wiring: promotion is gated and falls back, the output is set only after the push, and every build step has the fallback condition. ### How promotion proves it publishes the verified tree 1. `find` accepts only a run whose `head_sha` equals `github.sha` of the push, meaning the queue landed the commit it tested (unverified: see "Merge method" in Risks). 2. `verify` compares the record's tree with the tree of the master checkout, and its commit with `GITHUB_SHA`. 3. The archive is content-addressed. The digest is recomputed from the archive blobs and must equal the recorded digest. `skopeo --preserve-digests` to that digest reference fails rather than produce other bytes. 4. The leg then runs the PID 1 probe on that registry digest. `merge-and-push` still signs only an index whose Linux images are the probed digests (#21013), after the unchanged exact-source gate. 5. The pipeline itself is trusted only as master already ran it. `find` and `verify` run the copy of `scripts/merge-group-image.mjs` from the push's `before` commit (`git show "$BEFORE:…"`), not the copy the push brings. `verify` refuses promotion if anything in `before..HEAD` (every commit of a multi-PR group, not only the tip) changes `docker-merge-group.yml`, `docker.yml`, the promotion script or the PID 1 probe. Such a push builds from source. So does the first push after this PR merges, because its `before` has no verifier. ## Verification - `node --test scripts/merge-group-image.test.mjs`: 10 pass. One builds a real git history in which a two-PR push changes the pipeline in its first commit only, and checks that the range check catches it. - `node --test` on the workflow and contract suites (cloud-readiness, docker-canary-promotion, post-merge-runner-routing, lockfile-refresh-workflows, release-verify-workflow, reuse-canary-image, standard-image-contract, cloud-source-verification, merge-group-image): 492 pass. - `vitest run server/src/__tests__/docker-build-stamp.test.ts server/src/__tests__/container-init-reaping.test.ts`: 22 pass. - `actionlint` on both workflows: no new findings (the 6 remaining are pre-existing `ls` and word-splitting notes in `docker.yml`). - Local: `skopeo 1.24.1 copy --all --preserve-digests` between OCI layouts kept the index digest. It accepted a `docker://…@sha256:` destination and failed only at the network step. Cannot be exercised before the queue exists, because no `merge_group` event fires: - the merge-group run itself: the hosted-runner build time, disk use with tar plus `docker load`, `docker load` of a BuildKit OCI tar, and a ~5 GB artifact upload; - the cross-run artifact download on master; - whether `skopeo` exists on the runs-on AMI and accepts digest destinations in its installed version. Each master-side failure falls back to the full build. A merge-group failure only blocks the queue if its check is required, which is why that check is required last in the steps below. ## Risks - **Inert until enabled.** No `merge_group` events fire before the owner adds a merge queue. On master, `find` lists runs (one API call per leg, about 1 s), finds none, and the leg builds as today. The only always-on change is the leg's `actions: read` permission. - **Build cache freshness.** A promoted master push writes no `buildcache-`, and merge-group builds read but never write it. With every push promoted, the cache ages, so dependency or weekly tool-layer changes rebuild in each merge-group run until a fallback build refreshes the cache. A follow-up can refresh the cache from master without blocking publication. - **Publication time is still gate-bound.** The exact-source gate (about 13–14 min after push) still decides when the image publishes. See "Expected timing". - **Merge method (unverified).** Promotion needs the master commit to be exactly the commit the queue tested, because the image stamps the commit SHA (`PAPERCLIP_BUILD_COMMIT`, `build-info.json`, the provider pack revision). Matching only the tree would publish an image stamped with another SHA, so this PR does not relax the check. I expect the queue to fast-forward master to its tested commit. GitHub's merge-queue page does not state this, and it cannot be tested before the queue exists. If the queue lands a different SHA, promotion never matches and every push builds from source. That is safe but inert. Step 4 below checks this. - **skopeo on the AWS fleet.** The promote step checks for `skopeo` first and logs "Merge-queue promotion unavailable" if it is missing, then builds from source. If that notice appears, add skopeo to the fleet image. - **Hosted runner capacity.** amd64 merge-group builds run on 4-core hosted runners, colder and slower than the AWS fleet. That adds queue latency, not master latency. ### Settings the owner must enable, in order 1. **Prerequisite, a code change, not a setting.** The `master` ruleset (id 13619726) requires `ci / verify` and `ci / e2e`. Those come from `pr.yml`, which triggers only on `pull_request`. A merge queue waits for required checks on the `merge_group` event too, so every entry would stall until its timeout. First decide, and merge in a separate PR, how `ci / verify` and `ci / e2e` report on `merge_group`: a full CI run on the merge-group commit, or a fast pass that relies on the PR-head result. Today the ruleset does not require up-to-date branches either. 2. Merge this PR. Nothing changes yet. 3. In Settings → Rules → Rulesets → `master` (13619726), add **Require merge queue**: - merge method Squash; - build concurrency 5, minimum group size 1, maximum group size 5, wait 0 min; - "Require all queue entries to pass required checks"; - status check timeout 60 min. Do not add the image build to the required checks yet. Promotion is then opportunistic: if the merge-group build has not finished when master is pushed, master builds from source. 4. After the first queued merge, confirm promotion can match. The master commit SHA must equal the `head_sha` of its `Docker merge-queue build` run, and the next master `Docker` run's "Promote the merge-queue image" step must succeed. If the SHAs differ, promotion stays inert under this merge method. Stop here and report it. 5. After about a week of green `Docker merge-queue build` runs, add `build (linux/amd64, ubuntu-latest, amd64)` and `build (linux/arm64, ubuntu-24.04-arm, arm64)` (app: GitHub Actions) to the ruleset's required status checks. Then every queued commit has a verified image ready to promote. 6. The existing bypass actors (org admins, repository admins, integration 5534676) can still merge outside the queue. Those pushes have no merge-group run and build from source. ### Rollback - Remove the image checks from the required status checks (step 5), or remove **Require merge queue** (step 3). Master pushes then find no merge-group run and build from source. Nothing to migrate. - Code: revert this PR. Old merge-group artifacts expire after 3 days. Promoted images are ordinary digests under `ghcr.io/paperclipai/paperclip` and stay valid. ### Expected timing - Image leg on master: about 3–4 min (download about 5 GB, push the new layers by digest, PID 1 probe) instead of 10.6 min (amd64) and 7.8 min (arm64). - Push to published: still bounded by the exact-source gate on master, about 14–15 min (gate plus about 45 s for `merge-and-push`). Today it is the same bound, but with the legs as a second 11-min path and the serialized-run queue in front. - If the gate later accepts proof produced in the merge queue (owned by the gate change), push to published would be about 4–5 min (leg promotion plus `merge-and-push`). ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, via Claude Code with tool use (shell, file edits, read-only GitHub API and registry reads). Default reasoning mode. ## 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 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- .github/workflows/docker-merge-group.yml | 169 ++++++++++++++++++ .github/workflows/docker.yml | 90 +++++++++- doc/RELEASING.md | 15 ++ scripts/merge-group-image.mjs | 184 ++++++++++++++++++++ scripts/merge-group-image.test.mjs | 210 +++++++++++++++++++++++ 5 files changed, 666 insertions(+), 2 deletions(-) create mode 100644 .github/workflows/docker-merge-group.yml create mode 100644 scripts/merge-group-image.mjs create mode 100644 scripts/merge-group-image.test.mjs diff --git a/.github/workflows/docker-merge-group.yml b/.github/workflows/docker-merge-group.yml new file mode 100644 index 00000000000..24c83b01808 --- /dev/null +++ b/.github/workflows/docker-merge-group.yml @@ -0,0 +1,169 @@ +name: Docker merge-queue build + +# Build-before-merge for the standard image. While a change waits in the merge +# queue, build the production image for the exact merge-group commit, probe it, +# and keep it as a run artifact. When the queue fast-forwards master to that +# commit, docker.yml pushes these exact bytes (scripts/merge-group-image.mjs) +# instead of rebuilding them. Without a matching successful run, docker.yml +# builds from source as before. Nothing here can publish: this workflow has no +# registry credentials, no secrets, and read-only contents access. +# +# Inert until the merge queue is enabled for master: no merge_group event fires +# before then. +on: + merge_group: + +permissions: {} + +# Each merge group has its own ref; a group that the queue rebuilt replaces the +# older run for that ref. +concurrency: + group: docker-merge-group-${{ github.ref }} + cancel-in-progress: true + +jobs: + build: + if: github.repository == 'paperclipai/paperclip' && github.repository_id == '1170821064' && github.event.merge_group.base_ref == 'refs/heads/master' + strategy: + fail-fast: false + matrix: + include: + - platform: linux/amd64 + runner: ubuntu-latest + arch: amd64 + - platform: linux/arm64 + runner: ubuntu-24.04-arm + arch: arm64 + # GitHub-hosted runners: the protected release fleets admit only + # docker.yml on master. + runs-on: ${{ matrix.runner }} + timeout-minutes: 60 + permissions: + contents: read + steps: + - name: Checkout + uses: actions/checkout@v7 + with: + persist-credentials: false + # Same history as docker.yml, for `git describe` below. + fetch-depth: 0 + filter: blob:none + + # The merge queue fast-forwards master to this exact commit, so these + # stamps match what a master build of the same commit would carry. + - name: Compute build version + id: build-version + run: | + set -euo pipefail + version="$(git describe --tags --match 'v*' --long --dirty 2>/dev/null || true)" + echo "version=${version}" >> "$GITHUB_OUTPUT" + echo "Stamping build version: ${version:-}" + + - name: Compute tool cache epoch + id: tools-epoch + run: echo "epoch=$(date -u +%G-W%V)" >> "$GITHUB_OUTPUT" + + - name: Setup pnpm + uses: pnpm/action-setup@v6 + with: + version: 9.15.4 + run_install: false + + - name: Setup Node.js + uses: actions/setup-node@v7 + with: + node-version: 24 + + - name: Refresh lockfile for Docker build context + run: | + set -euo pipefail + pnpm install --resolution-only --ignore-scripts --no-frozen-lockfile + changed="$(git status --porcelain)" + if [ -n "$changed" ] && printf '%s\n' "$changed" | grep -Fvq ' pnpm-lock.yaml'; then + echo "Unexpected files changed during lockfile refresh:" + echo "$changed" + exit 1 + fi + + - name: Free runner disk + run: | + set -euo pipefail + pnpm store prune || true + sudo apt-get clean || true + sudo rm -rf /usr/share/dotnet /usr/share/swift /usr/local/lib/android /usr/local/share/boost \ + /usr/local/share/powershell /opt/ghc /opt/hostedtoolcache/CodeQL /opt/hostedtoolcache/PyPy /opt/hostedtoolcache/Ruby || true + docker system prune -af || true + df -h + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v4 + with: + buildkitd-config-inline: | + [registry."docker.io"] + mirrors = ["mirror.gcr.io"] + + - name: Compute schema migration labels + id: schema + run: | + set -euo pipefail + last=$(find packages/db/src/migrations -maxdepth 1 -name '*.sql' -printf '%f\n' | LC_ALL=C sort | tail -1) + count=$(find packages/db/src/migrations -maxdepth 1 -name '*.sql' | wc -l | tr -d ' ') + echo "last=${last}" >> "$GITHUB_OUTPUT" + echo "count=${count}" >> "$GITHUB_OUTPUT" + + # Same labels as a master build. The version label names master, not the + # temporary merge-queue branch this commit is tested on. + - name: Docker meta + id: meta + uses: docker/metadata-action@v6 + with: + images: ghcr.io/${{ github.repository }} + labels: | + org.opencontainers.image.version=master + io.github.paperclipai.schema.last-migration=${{ steps.schema.outputs.last }} + io.github.paperclipai.schema.migration-count=${{ steps.schema.outputs.count }} + + # Reads the public registry cache anonymously and writes none of it. + - name: Build image archive + id: build + uses: docker/build-push-action@v7 + with: + context: . + target: production + build-args: | + PAPERCLIP_BUILD_VERSION=${{ steps.build-version.outputs.version }} + PAPERCLIP_BUILD_COMMIT=${{ github.sha }} + CLI_TOOLS_CACHE_EPOCH=${{ steps.tools-epoch.outputs.epoch }} + platforms: ${{ matrix.platform }} + push: false + outputs: type=oci,dest=${{ runner.temp }}/merge-group-image/image.tar,name=paperclip-merge-group:${{ matrix.arch }} + cache-from: type=registry,ref=ghcr.io/${{ github.repository }}:buildcache-${{ matrix.arch }} + labels: ${{ steps.meta.outputs.labels }} + + # PID 1 must be an init that reaps adopted orphans; see docker.yml. + - name: Verify PID 1 reaps orphaned processes + env: + ARCHIVE: ${{ runner.temp }}/merge-group-image/image.tar + PLATFORM: ${{ matrix.platform }} + IMAGE: paperclip-merge-group:${{ matrix.arch }} + run: | + set -euo pipefail + docker load --input "$ARCHIVE" + docker run --rm -i --pull never --platform "$PLATFORM" "$IMAGE" sh -s < scripts/assert-orphan-reaping.sh + docker image rm "$IMAGE" + + # Written only after the probe passes. Promotion trusts nothing without it. + - name: Record the verified image + run: node scripts/merge-group-image.mjs record --arch "${{ matrix.arch }}" --archive "${{ runner.temp }}/merge-group-image/image.tar" --out "${{ runner.temp }}/merge-group-image/record.json" + + - name: Upload the verified image + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: merge-group-image-${{ matrix.arch }} + path: | + ${{ runner.temp }}/merge-group-image/image.tar + ${{ runner.temp }}/merge-group-image/record.json + if-no-files-found: error + # Layers are already compressed. + compression-level: 0 + retention-days: 3 diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index 150e6a9097d..99c45466003 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -130,6 +130,7 @@ jobs: permissions: contents: read packages: write + actions: read # download a verified merge-queue image artifact of this commit steps: - name: Checkout uses: actions/checkout@v7 @@ -238,7 +239,77 @@ jobs: username: ${{ github.repository_owner }} password: ${{ secrets.GITHUB_TOKEN }} + # Build-before-merge. When the merge queue already built and probed this + # exact commit (docker-merge-group.yml, with no registry credentials), + # push those bytes instead of rebuilding. scripts/merge-group-image.mjs + # requires a successful merge-group run of this repository for this SHA + # and checks the record's commit, tree, architecture and archive digest. + # Any missing or mismatched proof, or any failure here, leaves + # `steps.promote.outputs.digest` empty and the build below runs as + # before. The probe below and the exact-source gate apply either way. + - name: Find the merge-queue build of this commit + id: find + if: github.repository == 'paperclipai/paperclip' && github.repository_id == '1170821064' && github.event_name == 'push' && github.ref == 'refs/heads/master' + continue-on-error: true + env: + GITHUB_TOKEN: ${{ github.token }} + BEFORE: ${{ github.event.before }} + ARCH: ${{ matrix.arch }} + # Master's copy from before this push selects the run; see the promote + # step below. + run: | + set -euo pipefail + trusted="$RUNNER_TEMP/merge-group-image-trusted.mjs" + git show "$BEFORE:scripts/merge-group-image.mjs" > "$trusted" + node "$trusted" find --arch "$ARCH" + + - name: Download the merge-queue image + if: steps.find.outputs.run_id != '' + continue-on-error: true + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8 + with: + name: merge-group-image-${{ matrix.arch }} + run-id: ${{ steps.find.outputs.run_id }} + github-token: ${{ github.token }} + path: ${{ runner.temp }}/merge-group-image + + - name: Promote the merge-queue image + id: promote + if: steps.find.outputs.run_id != '' + continue-on-error: true + env: + ARCH: ${{ matrix.arch }} + DIRECTORY: ${{ runner.temp }}/merge-group-image + IMAGE_NAME: ghcr.io/${{ github.repository }} + BEFORE: ${{ github.event.before }} + run: | + set -euo pipefail + # Say plainly when this runner image cannot promote, instead of + # failing later inside the copy. + if ! command -v skopeo >/dev/null; then + echo "::notice title=Merge-queue promotion unavailable::skopeo is not installed on this runner; building from source." + exit 1 + fi + echo "Promoting with $(skopeo --version)" + # Run the verifier as master had it before this push, not the copy + # this push brings, so a push cannot weaken the check it must pass. + # The verifier refuses any push that changes the pipeline since + # BEFORE. A push whose BEFORE has no verifier builds from source. + trusted="$RUNNER_TEMP/merge-group-image-trusted.mjs" + git show "$BEFORE:scripts/merge-group-image.mjs" > "$trusted" + # Verify without writing a step output: the digest is set only after + # the exact bytes are in the registry. + verified="$(GITHUB_OUTPUT='' node "$trusted" verify --arch "$ARCH" --dir "$DIRECTORY" --since "$BEFORE")" + digest="$(printf '%s\n' "$verified" | sed -n 's/^digest=//p')" + printf '%s' "$digest" | grep -Eq '^sha256:[a-f0-9]{64}$' + # --preserve-digests fails rather than re-encode, so the registry + # holds exactly the archived image under the recorded digest. + skopeo copy --all --preserve-digests "oci-archive:$DIRECTORY/image.tar" "docker://$IMAGE_NAME@$digest" + echo "Promoted the merge-queue image $IMAGE_NAME@$digest" + echo "digest=$digest" >> "$GITHUB_OUTPUT" + - name: Set up Docker Buildx + if: steps.promote.outputs.digest == '' uses: docker/setup-buildx-action@v4 with: buildkitd-config-inline: | @@ -252,6 +323,7 @@ jobs: # way to check image/migrator compatibility up front. - name: Compute schema migration labels id: schema + if: steps.promote.outputs.digest == '' run: | set -euo pipefail last=$(ls packages/db/src/migrations/*.sql | sed 's|.*/||' | LC_ALL=C sort | tail -1) @@ -267,6 +339,7 @@ jobs: # so parallel canary builds cannot race it backwards. - name: Docker meta id: meta + if: steps.promote.outputs.digest == '' uses: docker/metadata-action@v6 with: images: ghcr.io/${{ github.repository }} @@ -283,6 +356,7 @@ jobs: io.github.paperclipai.schema.migration-count=${{ steps.schema.outputs.count }} - name: Build and push by digest id: build + if: steps.promote.outputs.digest == '' uses: docker/build-push-action@v7 with: context: . @@ -311,6 +385,18 @@ jobs: cache-to: type=registry,ref=ghcr.io/${{ github.repository }}:buildcache-${{ matrix.arch }},mode=max labels: ${{ steps.meta.outputs.labels }} + # Exactly one of the two paths produced this leg's digest. + - name: Select image digest + id: image + env: + PROMOTED: ${{ steps.promote.outputs.digest }} + BUILT: ${{ steps.build.outputs.digest }} + run: | + set -euo pipefail + digest="${PROMOTED:-$BUILT}" + test -n "$digest" + echo "digest=$digest" >> "$GITHUB_OUTPUT" + # PID 1 must be an init that reaps adopted orphans. With node there, the # orphans agent runs leave behind are never wait()ed and pin as zombies # until the cgroup pid limit is exhausted and every fork() in the @@ -325,7 +411,7 @@ jobs: - name: Verify PID 1 reaps orphaned processes env: # Through the environment, not interpolated into the script body. - IMAGE_DIGEST: ${{ steps.build.outputs.digest }} + IMAGE_DIGEST: ${{ steps.image.outputs.digest }} IMAGE_NAME: ghcr.io/${{ github.repository }} PLATFORM: ${{ matrix.platform }} run: | @@ -341,7 +427,7 @@ jobs: run: | set -euo pipefail mkdir -p /tmp/digests - digest="${{ steps.build.outputs.digest }}" + digest="${{ steps.image.outputs.digest }}" test -n "$digest" touch "/tmp/digests/${digest#sha256:}" diff --git a/doc/RELEASING.md b/doc/RELEASING.md index 20bb8ee203f..3f4bf936270 100644 --- a/doc/RELEASING.md +++ b/doc/RELEASING.md @@ -333,6 +333,21 @@ suppresses push-triggered workflow runs for those pushes. The release jobs therefore dispatch `docker.yml` explicitly at the new tag ref; the tag mapping keys off `github.ref` either way. +When the merge queue is enabled for `master`, +[`docker-merge-group.yml`](../.github/workflows/docker-merge-group.yml) builds +and probes the production image for each merge-group commit. It has no registry +credentials and uploads an OCI archive with a record of the commit, tree, +architecture and digest. The `master` push for that same commit then pushes +those exact bytes by digest instead of rebuilding +(`scripts/merge-group-image.mjs`). A commit that changes that pipeline (the +merge-group workflow, `docker.yml`, the promotion script or the PID 1 probe) +anywhere in the pushed range is always built from source. `docker.yml` runs the +promotion script as master had it before the push, so promotion trusts only a +pipeline that master already ran. +Without a matching successful merge-group +run, or on any mismatch or error, the push builds from source. The PID 1 probe, +exact-source gate and signing apply on both paths. + Canary dispatches first look up the full-SHA master image. Reuse requires a valid multi-platform index with both `linux/amd64` and `linux/arm64`, a matching registry digest, and signed provenance from this repository's `docker.yml` diff --git a/scripts/merge-group-image.mjs b/scripts/merge-group-image.mjs new file mode 100644 index 00000000000..b22e311a468 --- /dev/null +++ b/scripts/merge-group-image.mjs @@ -0,0 +1,184 @@ +// Build-before-merge image handoff between the merge queue and master. +// +// A `merge_group` run of docker-merge-group.yml builds the production image for +// the exact merge-group commit with no registry credentials, probes it, and +// uploads an OCI archive plus a record of what it built. When the merge queue +// then fast-forwards master to that commit, docker.yml may push those exact +// bytes instead of rebuilding them. Anything that does not prove the match +// returns no promotion, and docker.yml falls back to its normal build. +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { createHash } from "node:crypto"; +import { appendFile, readFile, writeFile } from "node:fs/promises"; +import { pathToFileURL } from "node:url"; + +export const repository = "paperclipai/paperclip"; +export const repositoryId = 1170821064; +export const workflowPath = ".github/workflows/docker-merge-group.yml"; +export const recordSchema = "paperclip/merge-group-image/v1"; +export const artifactName = arch => `merge-group-image-${arch}`; + +const architectures = ["amd64", "arm64"]; +const indexTypes = ["application/vnd.oci.image.index.v1+json", "application/vnd.docker.distribution.manifest.list.v2+json"]; +const manifestTypes = ["application/vnd.oci.image.manifest.v1+json", "application/vnd.docker.distribution.manifest.v2+json"]; +const fullSha = /^[a-f0-9]{40}$/; +const digestPattern = /^sha256:[a-f0-9]{64}$/; +const sha256 = bytes => `sha256:${createHash("sha256").update(bytes).digest("hex")}`; + +/** + * Choose the merge-queue build a master push may promote. Only a completed, + * successful run of this repository's merge-group workflow, on a merge-queue + * branch for master, for exactly this commit, qualifies. + * + * The commit must match, not only the tree: the image stamps the commit SHA + * (PAPERCLIP_BUILD_COMMIT, build-info.json, the provider pack revision). The + * merge queue lands the commit it tested for every merge method, squash + * included, by fast-forwarding master to it; a push that did not come through + * the queue has no matching run and builds from source. + */ +export function selectVerifiedRun({ sha, runs }) { + assert.match(sha ?? "", fullSha); + const eligible = runs.filter(run => run.head_sha === sha && run.event === "merge_group" && run.path === workflowPath && + run.repository?.id === repositoryId && run.head_repository?.id === repositoryId && + typeof run.head_branch === "string" && run.head_branch.startsWith("gh-readonly-queue/master/")); + if (eligible.length === 0) return { reason: "no merge-queue image build exists for this commit" }; + const passed = eligible.filter(run => run.status === "completed" && run.conclusion === "success").sort((a, b) => b.id - a.id); + if (passed.length === 0) return { reason: "the merge-queue image build for this commit did not succeed" }; + return { runId: passed[0].id }; +} + +/** The run's unexpired image artifact for one architecture, if there is exactly one. */ +export function selectArtifact({ artifacts, arch }) { + assert.ok(architectures.includes(arch)); + const matches = artifacts.filter(item => item.name === artifactName(arch) && !item.expired); + return matches.length === 1 ? { artifactId: matches[0].id } : { reason: `expected one unexpired ${artifactName(arch)} artifact, found ${matches.length}` }; +} + +/** + * The digest of the image an OCI archive holds, checked against the archive's + * own content-addressed blobs. `readEntry` returns the bytes of a tar entry. + */ +export function archiveImageDigest({ readEntry, arch }) { + assert.ok(architectures.includes(arch)); + const layout = JSON.parse(readEntry("index.json").toString("utf8")); + assert.equal(layout.manifests?.length, 1, "The OCI archive must hold exactly one image"); + const top = layout.manifests[0]; + assert.match(top.digest ?? "", digestPattern); + const blob = name => { + const bytes = readEntry(`blobs/sha256/${name.slice("sha256:".length)}`); + assert.equal(sha256(bytes), name, `Archive blob ${name} does not match its digest`); + return JSON.parse(bytes.toString("utf8")); + }; + const image = blob(top.digest); + const platformImages = indexTypes.includes(image.mediaType) + ? (image.manifests ?? []).filter(item => item.platform?.os === "linux") + : [{ digest: top.digest, platform: undefined }]; + assert.equal(platformImages.length, 1, "The OCI archive must hold exactly one Linux image"); + const manifest = platformImages[0].digest === top.digest ? image : blob(platformImages[0].digest); + assert.ok(manifestTypes.includes(manifest.mediaType), "The OCI archive does not hold an image manifest"); + const config = blob(manifest.config.digest); + assert.equal(config.os, "linux"); + assert.equal(config.architecture, arch, `The OCI archive holds a ${config.architecture} image, not ${arch}`); + return top.digest; +} + +/** What the merge-group build attests about the archive it uploads. */ +export function createRecord({ sha, tree, arch, digest }) { + assert.match(sha ?? "", fullSha); + assert.match(tree ?? "", fullSha); + assert.ok(architectures.includes(arch)); + assert.match(digest ?? "", digestPattern); + return { schema: recordSchema, repository, sha, tree, arch, digest }; +} + +/** + * Prove the archive is the build of the tree this master push publishes. The + * commit SHA covers its tree; the tree is compared too, so a record can never + * vouch for different content under a reused name. + */ +export function verifyRecord({ record, sha, tree, arch, archiveDigest }) { + assert.equal(record?.schema, recordSchema, "Unknown merge-group image record"); + assert.equal(record.repository, repository); + assert.equal(record.sha, sha, "The merge-group build is for a different commit"); + assert.equal(record.tree, tree, "The merge-group build is for a different tree"); + assert.equal(record.arch, arch, "The merge-group build is for a different architecture"); + assert.match(record.digest ?? "", digestPattern); + assert.equal(archiveDigest, record.digest, "The archive is not the image the merge-group build recorded"); + return record.digest; +} + +/** + * Files that produce, promote or vouch for a merge-group image. The merge-group + * run uses the queued commits' own copies, so a push that changes any of them + * is built from source on master instead: promotion then trusts only a + * pipeline that master already ran before this push. docker.yml runs this + * check from the copy of this script in the push's `before` commit, so a push + * cannot remove the check it is subject to. + */ +export const pipelineFiles = [workflowPath, ".github/workflows/docker.yml", "scripts/merge-group-image.mjs", "scripts/assert-orphan-reaping.sh"]; + +export function assertPipelineUnchanged(changedFiles) { + const changed = changedFiles.filter(file => pipelineFiles.includes(file)); + assert.equal(changed.length, 0, `This push changes the merge-group image pipeline (${changed.join(", ")})`); +} + +/** Pipeline files changed by everything this push landed: `since` (the push's `before`) to HEAD. */ +export function changedSince(since, cwd = process.cwd()) { + assert.match(since ?? "", fullSha, "--since must be the push's full `before` SHA"); + // Throws unless `since` is an ancestor: a push is a fast-forward of master. + execFileSync("git", ["merge-base", "--is-ancestor", since, "HEAD"], { cwd, stdio: "ignore" }); + return execFileSync("git", ["diff", "--name-only", since, "HEAD", "--", ...pipelineFiles], { cwd, encoding: "utf8" }).split("\n").filter(Boolean); +} +const tarReader = archive => entry => execFileSync("tar", ["-xOf", archive, entry], { maxBuffer: 16 * 1024 * 1024 }); +const gitTree = () => execFileSync("git", ["rev-parse", "HEAD^{tree}"], { encoding: "utf8" }).trim(); +const option = name => { + const index = process.argv.indexOf(`--${name}`); + const value = index > 0 ? process.argv[index + 1] : undefined; + assert.ok(value, `--${name} is required`); + return value; +}; +const output = async (key, value) => { + if (process.env.GITHUB_OUTPUT) await appendFile(process.env.GITHUB_OUTPUT, `${key}=${value}\n`); + console.log(`${key}=${value}`); +}; + +async function main(command) { + const sha = process.env.GITHUB_SHA; + const arch = option("arch"); + if (command === "record") { + // Runs in the credential-free merge-group build. + assert.equal(process.env.GITHUB_EVENT_NAME, "merge_group", "Records are written only by merge-group builds"); + const digest = archiveImageDigest({ readEntry: tarReader(option("archive")), arch }); + await writeFile(option("out"), `${JSON.stringify(createRecord({ sha, tree: gitTree(), arch, digest }), null, 2)}\n`); + return output("digest", digest); + } + assert.ok(process.env.GITHUB_REPOSITORY === repository && process.env.GITHUB_REF === "refs/heads/master" && + process.env.GITHUB_EVENT_NAME === "push", "Promotion runs only for canonical master pushes"); + if (command === "find") { + const token = process.env.GITHUB_TOKEN; + assert.ok(token, "GITHUB_TOKEN is required"); + const api = async path => { + const response = await fetch(`https://api.github.com/repos/${repository}${path}`, { redirect: "error", + headers: { Authorization: `Bearer ${token}`, Accept: "application/vnd.github+json" }, signal: AbortSignal.timeout(30_000) }); + assert.ok(response.ok, `GitHub API ${path}: HTTP ${response.status}`); + return response.json(); + }; + const { workflow_runs: runs } = await api(`/actions/workflows/docker-merge-group.yml/runs?event=merge_group&head_sha=${sha}&per_page=20`); + const run = selectVerifiedRun({ sha, runs }); + if (!run.runId) { console.log(`No promotion: ${run.reason}. Building from source.`); return; } + const { artifacts } = await api(`/actions/runs/${run.runId}/artifacts?per_page=100`); + const artifact = selectArtifact({ artifacts, arch }); + if (!artifact.artifactId) { console.log(`No promotion: ${artifact.reason}. Building from source.`); return; } + return output("run_id", run.runId); + } + if (command === "verify") { + const directory = option("dir"); + assertPipelineUnchanged(changedSince(option("since"))); + const record = JSON.parse(await readFile(`${directory}/record.json`, "utf8")); + const archiveDigest = archiveImageDigest({ readEntry: tarReader(`${directory}/image.tar`), arch }); + return output("digest", verifyRecord({ record, sha, tree: gitTree(), arch, archiveDigest })); + } + throw new Error(`Unknown command: ${command}`); +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) await main(process.argv[2]); diff --git a/scripts/merge-group-image.test.mjs b/scripts/merge-group-image.test.mjs new file mode 100644 index 00000000000..ce82abc5534 --- /dev/null +++ b/scripts/merge-group-image.test.mjs @@ -0,0 +1,210 @@ +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { createHash } from "node:crypto"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; +import { fileURLToPath } from "node:url"; +import { + archiveImageDigest, assertPipelineUnchanged, changedSince, createRecord, repositoryId, selectArtifact, selectVerifiedRun, verifyRecord, workflowPath, +} from "./merge-group-image.mjs"; + +const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); +const sha = "a".repeat(40), tree = "b".repeat(40); +const digestOf = bytes => `sha256:${createHash("sha256").update(bytes).digest("hex")}`; + +const run = overrides => ({ id: 10, head_sha: sha, event: "merge_group", path: workflowPath, status: "completed", conclusion: "success", + head_branch: `gh-readonly-queue/master/pr-1-${"c".repeat(40)}`, repository: { id: repositoryId }, head_repository: { id: repositoryId }, ...overrides }); + +test("promotes only a successful merge-queue build of this repository for this exact commit", () => { + assert.deepEqual(selectVerifiedRun({ sha, runs: [run()] }), { runId: 10 }); + assert.deepEqual(selectVerifiedRun({ sha, runs: [run({ id: 10 }), run({ id: 12 }), run({ id: 14, conclusion: "failure" })] }), { runId: 12 }); + for (const [label, candidate] of [ + ["another commit", run({ head_sha: "d".repeat(40) })], + ["a pull request run", run({ event: "pull_request" })], + ["a push run", run({ event: "push" })], + ["another workflow", run({ path: ".github/workflows/docker.yml" })], + ["a fork head repository", run({ head_repository: { id: 1 } })], + ["another repository", run({ repository: { id: 1 } })], + ["a queue for another branch", run({ head_branch: "gh-readonly-queue/release/pr-1-x" })], + ["an ordinary branch", run({ head_branch: "master" })], + ]) assert.match(selectVerifiedRun({ sha, runs: [candidate] }).reason, /no merge-queue image build/, label); + for (const candidate of [run({ conclusion: "failure" }), run({ conclusion: "cancelled" }), run({ status: "in_progress", conclusion: null })]) { + assert.match(selectVerifiedRun({ sha, runs: [candidate] }).reason, /did not succeed/); + } + assert.throws(() => selectVerifiedRun({ sha: "master", runs: [] })); +}); + +test("requires exactly one unexpired image artifact for the architecture", () => { + const item = (id, name, expired = false) => ({ id, name, expired }); + assert.deepEqual(selectArtifact({ arch: "amd64", artifacts: [item(1, "merge-group-image-amd64"), item(2, "merge-group-image-arm64")] }), { artifactId: 1 }); + assert.match(selectArtifact({ arch: "amd64", artifacts: [item(1, "merge-group-image-amd64", true)] }).reason, /found 0/); + assert.match(selectArtifact({ arch: "amd64", artifacts: [item(1, "merge-group-image-amd64"), item(2, "merge-group-image-amd64")] }).reason, /found 2/); + assert.throws(() => selectArtifact({ arch: "riscv64", artifacts: [] })); +}); + +// An OCI layout as BuildKit writes it for one platform with provenance: the +// layout index names a per-platform index of the image and its attestation. +function layout({ arch = "amd64", provenance = true, tamper } = {}) { + const blobs = new Map(); + const put = value => { const bytes = Buffer.from(JSON.stringify(value)); const digest = digestOf(bytes); blobs.set(digest, bytes); return { digest, size: bytes.length }; }; + const config = put({ architecture: arch, os: "linux", rootfs: { type: "layers", diff_ids: [] } }); + const manifest = put({ schemaVersion: 2, mediaType: "application/vnd.oci.image.manifest.v1+json", + config: { mediaType: "application/vnd.oci.image.config.v1+json", ...config }, layers: [] }); + const attestation = put({ schemaVersion: 2, mediaType: "application/vnd.oci.image.manifest.v1+json", config: { ...config }, layers: [] }); + const top = provenance ? { mediaType: "application/vnd.oci.image.index.v1+json", ...put({ schemaVersion: 2, mediaType: "application/vnd.oci.image.index.v1+json", manifests: [ + { mediaType: "application/vnd.oci.image.manifest.v1+json", ...manifest, platform: { os: "linux", architecture: arch } }, + { mediaType: "application/vnd.oci.image.manifest.v1+json", ...attestation, platform: { os: "unknown", architecture: "unknown" } }, + ] }) } : { mediaType: "application/vnd.oci.image.manifest.v1+json", ...manifest }; + if (tamper) blobs.set(manifest.digest, Buffer.from("{}")); + const entries = new Map([["index.json", Buffer.from(JSON.stringify({ schemaVersion: 2, manifests: [top] }))]]); + for (const [digest, bytes] of blobs) entries.set(`blobs/sha256/${digest.slice(7)}`, bytes); + return { entries, digest: top.digest }; +} +const reader = entries => name => { assert.ok(entries.has(name), `missing ${name}`); return entries.get(name); }; + +test("reads the image digest from an OCI archive and checks its content-addressed blobs", () => { + for (const provenance of [true, false]) { + const { entries, digest } = layout({ provenance }); + assert.equal(archiveImageDigest({ readEntry: reader(entries), arch: "amd64" }), digest); + } + assert.throws(() => archiveImageDigest({ readEntry: reader(layout().entries), arch: "arm64" }), /amd64 image, not arm64/); + assert.throws(() => archiveImageDigest({ readEntry: reader(layout({ tamper: true }).entries), arch: "amd64" }), /does not match its digest/); + const two = layout().entries; + two.set("index.json", Buffer.from(JSON.stringify({ manifests: [{ digest: `sha256:${"0".repeat(64)}` }, { digest: `sha256:${"1".repeat(64)}` }] }))); + assert.throws(() => archiveImageDigest({ readEntry: reader(two), arch: "amd64" }), /exactly one image/); +}); + +test("reads a real tar archive through the system tar", () => { + const directory = mkdtempSync(path.join(tmpdir(), "merge-group-image-")); + try { + const { entries, digest } = layout({ arch: "arm64" }); + for (const [name, bytes] of entries) { mkdirSync(path.dirname(path.join(directory, "layout", name)), { recursive: true }); writeFileSync(path.join(directory, "layout", name), bytes); } + execFileSync("tar", ["-cf", path.join(directory, "image.tar"), "-C", path.join(directory, "layout"), "index.json", "blobs"]); + const readEntry = name => execFileSync("tar", ["-xOf", path.join(directory, "image.tar"), name]); + assert.equal(archiveImageDigest({ readEntry, arch: "arm64" }), digest); + } finally { rmSync(directory, { recursive: true, force: true }); } +}); + +test("promotion proves commit, tree, architecture and archive digest", () => { + const digest = `sha256:${"e".repeat(64)}`; + const record = createRecord({ sha, tree, arch: "amd64", digest }); + assert.equal(verifyRecord({ record, sha, tree, arch: "amd64", archiveDigest: digest }), digest); + for (const [change, pattern] of [ + [{ sha: "f".repeat(40) }, /different commit/], + [{ tree: "f".repeat(40) }, /different tree/], + [{ arch: "arm64" }, /different architecture/], + [{ archiveDigest: `sha256:${"f".repeat(64)}` }, /not the image the merge-group build recorded/], + ]) assert.throws(() => verifyRecord({ record, sha, tree, arch: "amd64", archiveDigest: digest, ...change }), pattern); + assert.throws(() => verifyRecord({ record: { ...record, schema: "other" }, sha, tree, arch: "amd64", archiveDigest: digest }), /Unknown/); + assert.throws(() => verifyRecord({ record: { ...record, repository: "fork/paperclip" }, sha, tree, arch: "amd64", archiveDigest: digest })); + assert.throws(() => createRecord({ sha, tree: "HEAD", arch: "amd64", digest })); +}); + +test("a push that changes the merge-group pipeline is built from source, not promoted", () => { + assert.doesNotThrow(() => assertPipelineUnchanged([])); + assert.doesNotThrow(() => assertPipelineUnchanged(["Dockerfile", "server/src/index.ts", "scripts/standard-image-contract.mjs"])); + for (const file of [".github/workflows/docker-merge-group.yml", ".github/workflows/docker.yml", "scripts/merge-group-image.mjs", "scripts/assert-orphan-reaping.sh"]) { + assert.throws(() => assertPipelineUnchanged(["server/src/index.ts", file]), /changes the merge-group image pipeline/, file); + } +}); + +test("the pipeline check covers every commit the push landed, not only the last", () => { + const directory = mkdtempSync(path.join(tmpdir(), "merge-group-push-")); + const git = (...args) => execFileSync("git", ["-c", "user.name=t", "-c", "user.email=t@example.invalid", "-c", "commit.gpgsign=false", ...args], + { cwd: directory, encoding: "utf8" }).trim(); + const commit = (file, text) => { + mkdirSync(path.dirname(path.join(directory, file)), { recursive: true }); + writeFileSync(path.join(directory, file), text); + git("add", "-A"); git("commit", "-q", "-m", file); + return git("rev-parse", "HEAD"); + }; + try { + git("init", "-q", "-b", "main"); + const before = commit("scripts/merge-group-image.mjs", "v1"); + // A merge group of two PRs lands in one push: the first edits the + // pipeline, the second (the push's HEAD) only edits app code. + commit("scripts/merge-group-image.mjs", "v2"); + commit("server/src/index.ts", "app"); + assert.deepEqual(changedSince(git("rev-parse", "HEAD~1"), directory), []); + assert.deepEqual(changedSince(before, directory), ["scripts/merge-group-image.mjs"]); + assert.throws(() => assertPipelineUnchanged(changedSince(before, directory)), /changes the merge-group image pipeline/); + assert.throws(() => changedSince("HEAD~2", directory), /full `before` SHA/); + git("checkout", "-q", "--orphan", "other"); const unrelated = commit("README.md", "x"); + git("checkout", "-q", "main"); + assert.throws(() => changedSince(unrelated, directory), "a non-ancestor `before` is refused"); + } finally { rmSync(directory, { recursive: true, force: true }); } +}); + +test("the CLI refuses to record outside a merge group or promote outside a canonical master push", () => { + const script = path.join(root, "scripts", "merge-group-image.mjs"); + const run = (command, env) => { + try { execFileSync(process.execPath, [script, command, "--arch", "amd64", "--archive", "x", "--out", "y", "--dir", "z"], + { env: { PATH: process.env.PATH, GITHUB_SHA: sha, ...env }, stdio: "pipe" }); return ""; } + catch (error) { return String(error.stderr); } + }; + assert.match(run("record", { GITHUB_EVENT_NAME: "push" }), /only by merge-group builds/); + for (const env of [ + { GITHUB_EVENT_NAME: "merge_group", GITHUB_REPOSITORY: "paperclipai/paperclip", GITHUB_REF: "refs/heads/master" }, + { GITHUB_EVENT_NAME: "push", GITHUB_REPOSITORY: "fork/paperclip", GITHUB_REF: "refs/heads/master" }, + { GITHUB_EVENT_NAME: "push", GITHUB_REPOSITORY: "paperclipai/paperclip", GITHUB_REF: "refs/tags/v1" }, + { GITHUB_EVENT_NAME: "pull_request", GITHUB_REPOSITORY: "paperclipai/paperclip", GITHUB_REF: "refs/heads/master" }, + ]) for (const command of ["find", "verify"]) assert.match(run(command, env), /only for canonical master pushes/); +}); + +test("the merge-queue build has no publishing credentials or paid infrastructure", () => { + const workflow = readFileSync(path.join(root, ".github", "workflows", "docker-merge-group.yml"), "utf8"); + const triggers = workflow.split("\non:\n")[1].split("\n\n")[0]; + assert.equal(triggers.trim(), "merge_group:", "only the merge queue triggers this build"); + assert.match(workflow, /^permissions: \{\}$/m); + const permissions = [...workflow.matchAll(/^ permissions:\n((?: {6}.+\n)+)/gm)].map(match => match[1].trim()); + assert.ok(permissions.length > 0); + for (const block of permissions) assert.equal(block, "contents: read"); + assert.doesNotMatch(workflow, /secrets\.|packages: write|id-token|attestations|docker\/login-action|cache-to:|push: true|environment:|runs-on\//); + assert.doesNotMatch(workflow, /pull_request_target|workflow_run|workflow_dispatch/); + assert.match(workflow, /persist-credentials: false/); + assert.match(workflow, /github\.event\.merge_group\.base_ref == 'refs\/heads\/master'/); + assert.match(workflow, /github\.repository_id == '1170821064'/); + assert.match(workflow, /push: false/); + assert.match(workflow, /scripts\/assert-orphan-reaping\.sh/); + assert.ok(workflow.indexOf("assert-orphan-reaping.sh") < workflow.indexOf("merge-group-image.mjs record"), + "the record is written only after the probe passes"); +}); + +test("master promotes only after proof and otherwise builds exactly as before", () => { + const workflow = readFileSync(path.join(root, ".github", "workflows", "docker.yml"), "utf8"); + const leg = workflow.split("\n build-and-push:\n")[1].split("\n publication_verification:\n")[0]; + const steps = leg.split(/\n(?= - name: )/); + const step = name => { const found = steps.find(item => item.startsWith(` - name: ${name}\n`)); assert.ok(found, name); return found; }; + const order = name => steps.indexOf(step(name)); + assert.match(step("Find the merge-queue build of this commit"), + /if: github.repository == 'paperclipai\/paperclip' && github.repository_id == '1170821064' && github.event_name == 'push' && github.ref == 'refs\/heads\/master'/); + for (const name of ["Find the merge-queue build of this commit", "Download the merge-queue image", "Promote the merge-queue image"]) { + assert.match(step(name), /continue-on-error: true/, `${name} must fall back to the build`); + } + const promote = step("Promote the merge-queue image"); + // Both helpers run master's copy from before the push, so a push cannot + // weaken the checks it must pass. + for (const name of ["Find the merge-queue build of this commit", "Promote the merge-queue image"]) { + assert.match(step(name), /BEFORE: \$\{\{ github.event.before \}\}/); + assert.match(step(name), /git show "\$BEFORE:scripts\/merge-group-image.mjs" > "\$trusted"/); + assert.doesNotMatch(step(name), /node scripts\/merge-group-image\.mjs/); + } + assert.match(promote, /node "\$trusted" verify --arch "\$ARCH" --dir "\$DIRECTORY" --since "\$BEFORE"/); + assert.ok(promote.indexOf('"$trusted" verify') < promote.indexOf("skopeo copy")); + assert.ok(promote.indexOf("skopeo copy --all --preserve-digests") < promote.indexOf('echo "digest=$digest" >> "$GITHUB_OUTPUT"'), + "the promoted digest becomes an output only after the exact bytes are pushed"); + assert.match(promote, /GITHUB_OUTPUT='' node "\$trusted" verify/); + assert.ok(promote.indexOf("command -v skopeo") < promote.indexOf('"$trusted" verify'), + "a runner without skopeo reports that promotion is unavailable before it tries"); + for (const name of ["Set up Docker Buildx", "Compute schema migration labels", "Docker meta", "Build and push by digest"]) { + assert.match(step(name), /if: steps.promote.outputs.digest == ''/, `${name} runs whenever nothing was promoted`); + assert.ok(order(name) > order("Promote the merge-queue image")); + } + assert.match(step("Select image digest"), /digest="\$\{PROMOTED:-\$BUILT\}"/); + assert.ok(order("Select image digest") < order("Verify PID 1 reaps orphaned processes")); + assert.match(step("Verify PID 1 reaps orphaned processes"), /IMAGE_DIGEST: \$\{\{ steps.image.outputs.digest \}\}/); + assert.match(step("Export digest"), /digest="\$\{\{ steps.image.outputs.digest \}\}"/); + assert.match(leg, /permissions:\n\s+contents: read\n\s+packages: write\n\s+actions: read/); +});