From 77ddf260bf9a3de3dcb8456a60f4f809d67401fd Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Mon, 16 Nov 2026 10:08:11 -0600 Subject: [PATCH 1/6] fix(runner-e2e): keep the supervisor off the heartbeat graph and ship the plugin SDK build (#21860) 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 paid Runner Full-Stack E2E workflow proves chat features against a real source server > - Since master f7a3497e9d, every paid cell fails before any test runs: the source server cannot find `@paperclipai/plugin-sdk/dist/index.js` > - The supervisor builds the plugin SDK before it starts Paperclip, but its own static imports now load the SDK first > - This pull request removes the heavy import edge, adds a regression test for that class, and builds and checks the SDK once per campaign > - The benefit is that paid campaigns run again, and a missing workspace build fails once in the build job instead of in 199 paid cells ## Linked Issues or Issue Description Refs #21791 **What happened?** Chat-eval cohort 17 (master f7a3497e9d) failed in all 199 cells. Each cell exited in the "Run paid cell" step. The private Playwright log shows `ERR_MODULE_NOT_FOUND` for `server/node_modules/@paperclipai/plugin-sdk/dist/index.js`, imported from `server/src/services/reusable-sandbox-resume-error.ts`, and then `Process from config.webServer was not able to start`. Cohort 16 (master 819f61f1fd) passed 169/199 with the same workflow steps. **Root cause** #21791 (df9914dbd9) added `import { NATIVE_RETAINED_OWNER_WAIT } from "./native-controller-recovery.js"` to `native-runner-checkpoint.ts`. `tests/runner-e2e/server.ts` statically imports `controller-recovery-observer.ts`, which imports the checkpoint reader. The new edge connects it to the full heartbeat graph: `native-runner-checkpoint -> native-controller-recovery -> native-finalization-notifications -> external-agents -> muse -> heartbeat -> heartbeat/run-completion -> reusable-sandbox-resume-error -> @paperclipai/plugin-sdk`. The plugin SDK exports only its generated `dist`. The supervisor builds that `dist` in `prepareSourceServerDependencies`, but ES static imports load before that call. The workflow installs with `--ignore-scripts` and never built the SDK, so the supervisor crashes at load. #21554 is not involved: it changes only release workflows. **Expected behavior** The supervisor loads without generated SDK output. The campaign build job builds and checks the SDK once, and each cell restores it. **Steps to reproduce** 1. Remove `packages/plugins/sdk/dist`. 2. Run `node cli/node_modules/tsx/dist/cli.mjs tests/runner-e2e/server.ts`. 3. Before this change: `ERR_MODULE_NOT_FOUND` for the SDK. After this change: the normal `PAPERCLIP_RUNNER_E2E_SERVER_LOG is required` error, which shows that all static imports loaded. ## What Changed - Moved `NATIVE_RETAINED_OWNER_WAIT` and `NATIVE_AGENT_DIRECTORY_BUSY_WAIT` to a new leaf module `native-recovery-wait-codes.ts`. `native-controller-recovery.ts` re-exports them, so other importers do not change. `native-runner-checkpoint.ts` imports the leaf. This also removes a checkpoint/controller-recovery import cycle. - Added `tests/runner-e2e/server-startup-import-graph.test.ts`. It uses esbuild to walk the static import graph of `tests/runner-e2e/server.ts` and fails with the full chain if it reaches `@paperclipai/plugin-sdk`. - `runner-full-stack-e2e.yml`: the "Build reusable runner campaign artifacts" job runs `scripts/ensure-plugin-build-deps.mjs` (the same certified helper the cell uses), checks that `shared` and `plugin-sdk` dist and their completion markers exist with a clear `::error::`, and ships both dist trees in the campaign bundle. The cell restore step checks both entry points with a clear `::error::`. The helper's fingerprint receipt lets the cell reuse the shipped output instead of a rebuild. - `workflow-security.test.ts` pins the build, packaging and guard. ## Verification - Red/green: `npx vitest run --config tests/runner-e2e/vitest.config.ts server-startup-import-graph` fails with the old import and passes with the fix. - Local reproduction above: fails before, loads after. - `npx vitest run --config tests/runner-e2e/vitest.config.ts workflow-security server-startup-import-graph native-completion`: 137 passed. - `node --test tests/runner-e2e/native-completion-git-source.test.mjs`: 36 passed. - Server `tsc --noEmit`: clean. - Paid proof of the source fix: one cell (`chat-features.runner-opencode.local.access.private-resource`), dispatched with `--ref master -f target_branch=fix/runner-e2e-plugin-sdk-dist`: https://github.com/paperclipai/paperclip/actions/runs/43804619166 . That run uses the master workflow and this branch's source, so it proves the import-graph fix alone restores the cells. - The workflow changes (SDK build, bundle and guards) cannot run in a paid campaign before merge, because paid runs use the default-branch workflow. `workflow-security.test.ts` pins them. A 1-case paid check from master follows the merge. - The failed "Authorize paid campaign" check on this commit is from a dispatch with a branch `--ref`. The default-branch gate rejected it as designed. It is not a PR-event check. ## Risks - Low risk. The constants keep their values and are re-exported from the old module. - The campaign bundle grows by the `shared` and `plugin-sdk` dist trees (small). If the fingerprints do not match in a cell, the helper rebuilds, as before. ## Model Used - Claude, `claude-opus-5-5`, via Claude Code with tool use (shell, file edit, GitHub CLI). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 --- .github/workflows/runner-full-stack-e2e.yml | 18 +++++++ .../native-controller-recovery.ts | 5 +- .../native-recovery-wait-codes.ts | 5 ++ .../native-runner-checkpoint.ts | 2 +- .../server-startup-import-graph.test.ts | 51 +++++++++++++++++++ tests/runner-e2e/workflow-security.test.ts | 5 ++ 6 files changed, 83 insertions(+), 3 deletions(-) create mode 100644 server/src/services/native-runtime/native-recovery-wait-codes.ts create mode 100644 tests/runner-e2e/server-startup-import-graph.test.ts diff --git a/.github/workflows/runner-full-stack-e2e.yml b/.github/workflows/runner-full-stack-e2e.yml index 297f74da7ae..df00eb932fa 100644 --- a/.github/workflows/runner-full-stack-e2e.yml +++ b/.github/workflows/runner-full-stack-e2e.yml @@ -797,6 +797,16 @@ jobs: if [ "$NEEDS_NATIVE_BINARIES" = true ]; then pnpm --filter @paperclipai/paperclip-runner build:runner-binaries fi + # The source server imports the plugin SDK from its generated dist. + # Build it once here, with the same certified helper the cell uses, + # instead of in every paid cell. + node scripts/ensure-plugin-build-deps.mjs + for entry in packages/shared/dist/index.js packages/plugins/sdk/dist/index.js; do + if [ ! -f "$entry" ] || [ ! -f "$(dirname "$entry")/.paperclip-build-complete" ]; then + echo "::error::Workspace build output $entry is missing; paid cells would fail before any test runs." + exit 1 + fi + done - name: Package immutable campaign outputs env: @@ -814,6 +824,8 @@ jobs: ) archive_paths=( packages/paperclip-eval-kernel/dist + packages/shared/dist + packages/plugins/sdk/dist ) if [ "$NEEDS_RUNNER_TYPESCRIPT" = true ]; then test -d packages/paperclip-runner/dist @@ -1235,6 +1247,12 @@ jobs: --file runner-e2e-build/runner-e2e-build-bundle.tar.gz \ --directory "$GITHUB_WORKSPACE" test -d packages/paperclip-eval-kernel/dist + for entry in packages/shared/dist/index.js packages/plugins/sdk/dist/index.js; do + if [ ! -f "$entry" ]; then + echo "::error::Campaign outputs lack $entry; the source server cannot start without it." + exit 1 + fi + done if [ "$NEEDS_RUNNER_TYPESCRIPT" = true ]; then test -d packages/paperclip-runner/dist fi diff --git a/server/src/services/native-runtime/native-controller-recovery.ts b/server/src/services/native-runtime/native-controller-recovery.ts index c7523d642f0..806cc82b1b0 100644 --- a/server/src/services/native-runtime/native-controller-recovery.ts +++ b/server/src/services/native-runtime/native-controller-recovery.ts @@ -11,6 +11,9 @@ import { findNativeSessionResumeRun, isNativeSessionId, isUnusedNativeSessionBoo import { insertMigratedNativeRunnerCheckpoint, loadNativeRunnerCheckpoint } from "./native-runner-checkpoint.js"; import { offlineMigrationExecutionWhere } from "../offline-migration-execution.js"; import { redactRunnerApiPayloads } from "./runner-api-log-redaction.js"; +import { NATIVE_AGENT_DIRECTORY_BUSY_WAIT, NATIVE_RETAINED_OWNER_WAIT } from "./native-recovery-wait-codes.js"; + +export { NATIVE_AGENT_DIRECTORY_BUSY_WAIT, NATIVE_RETAINED_OWNER_WAIT }; export const NATIVE_CONTROLLER_RECOVERY_MAX_BYTES = 4 * 1024; @@ -68,7 +71,6 @@ export type NativeControllerRecoveryOutcome = | { kind: "missing_evidence" | "unsupported" | "dependency_unavailable"; reason: string; cause?: unknown } | { kind: "no_prior_execution" }; -export const NATIVE_RETAINED_OWNER_WAIT = "native_controller_recovery_waiting_for_owner"; export type NativeRetainedOwnerWait = { runId: string; controllerBootId: string }; @@ -138,7 +140,6 @@ export async function deferNativeControllerRecovery(db: Db, input: { }); } -export const NATIVE_AGENT_DIRECTORY_BUSY_WAIT = "agent_directory_operation_busy"; export async function deferNativeRunForBusyAgentDirectory(db: Db, input: { companyId: string; runId: string; leaseOwner?: string; retryAt: Date; maxDeferrals: number; diff --git a/server/src/services/native-runtime/native-recovery-wait-codes.ts b/server/src/services/native-runtime/native-recovery-wait-codes.ts new file mode 100644 index 00000000000..cd2b7d46422 --- /dev/null +++ b/server/src/services/native-runtime/native-recovery-wait-codes.ts @@ -0,0 +1,5 @@ +// Dependency-free failure codes shared by native recovery modules. Keep this a +// leaf: checkpoint readers import it, and those readers are also loaded by +// standalone tools that must not pull in the heartbeat service graph. +export const NATIVE_RETAINED_OWNER_WAIT = "native_controller_recovery_waiting_for_owner"; +export const NATIVE_AGENT_DIRECTORY_BUSY_WAIT = "agent_directory_operation_busy"; diff --git a/server/src/services/native-runtime/native-runner-checkpoint.ts b/server/src/services/native-runtime/native-runner-checkpoint.ts index 3a76c84ac17..4a93568dc75 100644 --- a/server/src/services/native-runtime/native-runner-checkpoint.ts +++ b/server/src/services/native-runtime/native-runner-checkpoint.ts @@ -9,7 +9,7 @@ import { createLocalEncryptedCipher, deriveLocalEncryptedInstanceSecret } from " import { legacyControllerBootId } from "../legacy-controller-lease.js"; import { assertNativeSourceCheckpointConsumer, lockSourceRecoveryCoordinators } from "./native-source-recovery-ownership.js"; import { runnerdStateHasNoProviderTurn, runnerdStateIsIncompleteBootstrap } from "./native-bootstrap-proof.js"; -import { NATIVE_RETAINED_OWNER_WAIT } from "./native-controller-recovery.js"; +import { NATIVE_RETAINED_OWNER_WAIT } from "./native-recovery-wait-codes.js"; import { OWN_PROCESS_START_EVENT_TYPES } from "../native-process-start-events.js"; type Binding = { companyId: string; issueId: string; runId: string }; diff --git a/tests/runner-e2e/server-startup-import-graph.test.ts b/tests/runner-e2e/server-startup-import-graph.test.ts new file mode 100644 index 00000000000..d5d1e040f63 --- /dev/null +++ b/tests/runner-e2e/server-startup-import-graph.test.ts @@ -0,0 +1,51 @@ +import path from "node:path"; +import { build, type Plugin } from "esbuild"; +import { describe, expect, it } from "vitest"; + +const repositoryRoot = path.resolve(import.meta.dirname, "../.."); + +// The source-server supervisor builds the plugin SDK (scripts/ensure-plugin-build-deps.mjs) +// before it starts Paperclip. Its own static imports load before that build, so they must +// never reach a workspace package whose entry point is generated output. When they did, +// every paid source cell failed with ERR_MODULE_NOT_FOUND before any test ran. +const BUILT_ONLY_PACKAGES = ["@paperclipai/plugin-sdk"]; + +async function staticImportPath(entry: string, target: string) { + const reached = new Map(); + const externalBare: Plugin = { + name: "external-bare", + setup(context) { + context.onResolve({ filter: /^[^./]/ }, args => { + if (args.path.startsWith("@paperclipai/") && !BUILT_ONLY_PACKAGES.some(name => args.path === name || args.path.startsWith(`${name}/`))) return undefined; + if (args.path === target || args.path.startsWith(`${target}/`)) reached.set(args.path, args.importer); + return { path: args.path, external: true }; + }); + }, + }; + const result = await build({ + entryPoints: [path.join(repositoryRoot, entry)], absWorkingDir: repositoryRoot, + bundle: true, write: false, metafile: true, platform: "node", format: "esm", logLevel: "silent", + plugins: [externalBare], + }); + if (!reached.size) return null; + const parents = new Map([[entry, ""]]); + const queue = [entry]; + while (queue.length) { + const file = queue.shift()!; + for (const imported of result.metafile.inputs[file]?.imports ?? []) { + if (imported.external || parents.has(imported.path)) continue; + parents.set(imported.path, file); + queue.push(imported.path); + } + } + const importer = path.relative(repositoryRoot, [...reached.values()][0]!); + const chain = [target, importer]; + for (let file = parents.get(importer); file; file = parents.get(file)) chain.push(file); + return chain.reverse().join(" -> "); +} + +describe("runner E2E source-server supervisor", () => { + it.each(BUILT_ONLY_PACKAGES)("loads without the generated %s output", async name => { + expect(await staticImportPath("tests/runner-e2e/server.ts", name)).toBeNull(); + }, 60_000); +}); diff --git a/tests/runner-e2e/workflow-security.test.ts b/tests/runner-e2e/workflow-security.test.ts index 49c28b6b7f6..ecf320784b6 100644 --- a/tests/runner-e2e/workflow-security.test.ts +++ b/tests/runner-e2e/workflow-security.test.ts @@ -704,6 +704,11 @@ describe("public repository paid workflow security", () => { expect(buildJob).toContain( "node packages/paperclip-runner/scripts/materialize-opencode-binary.mjs", ); + // The source server imports the plugin SDK from generated output. Build, + // check and ship it once so a missing dist fails here, not in every cell. + expect(buildJob).toContain("node scripts/ensure-plugin-build-deps.mjs"); + expect(buildJob).toMatch(/archive_paths=\(\n(?:\s+\S+\n)*?\s+packages\/plugins\/sdk\/dist\n/u); + expect(testJob).toContain("Campaign outputs lack $entry"); expect(buildJob).toContain("runner-e2e-build-bundle.tar.gz.sha256"); expect(buildJob).toContain("runner-e2e-provider-pack.tar.gz.sha256"); expect(buildJob).toContain( From 20b0d4e5a51f9b730721dc5078cc74f2f21eec60 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Mon, 16 Nov 2026 10:10:09 -0600 Subject: [PATCH 2/6] fix(wake-queue): reopen a finished task for a person's comment merged into a system wake (#21914) 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 wake queue holds new input for a task while an agent run is active, and releases it when the run ends > - A person's comment on a task always reopens the task when the run that closed it did not receive the comment > - A restart test found a person's comment that was posted while the run was finishing. The run marked the task done and no later run started. The comment was lost > - The comment joined a deferred child-completion wake that a system actor requested. The release step only looked at the wake requester, which was "system", so it did not see the person > - This pull request makes the release step look at who wrote the undelivered comments in the wake > - The benefit is that a person's comment is never dropped because it shares a queued wake with system work ## Linked Issues or Issue Description **What happened?** A person posted a comment on a task while the assigned agent's run was active. The run then marked the task done. The task stayed done, and no run received the comment. The deferred wake that held the comment was cancelled with "Deferred execution wake no longer applies to a terminal task". **Expected behavior** The task reopens and a new run receives the person's comment. **Steps to reproduce** 1. Start a run for a task. 2. While the run is active, let the system defer a wake for the same task (for example, a child task completes). 3. Post a comment as a person. The comment wake merges into the deferred system wake. 4. Let the run mark the task done. 5. The task stays done. No run receives the comment. **Paperclip version or commit** `master` at b4fa1c7fb1 (first seen at c5218f5ec4). **Relevant logs or output** The merged deferred wake had `reason = issue_execution_deferred` and `requestedByActorType = system`. Its payload held the person's comment id. The coalesced comment receipt had `requestedByActorType = user`. Release cancelled the merged wake as terminal-task work. ## What Changed - `getCommentSelfAuthorship` in the wake-queue Postgres adapter also returns `includesPersonComment`. This value is true when one of the wake's undelivered comments was written by a person and not by an agent run. - `promoteDeferredWake` reopens a done or cancelled task when `includesPersonComment` is true, also when the wake requester is the system. - The delivered-comment filter is not changed. A comment that a run already received does not reopen the task. - New embedded-Postgres tests in `heartbeat-comment-wake-batching.test.ts`: - A person's comment merges into a deferred child-completion wake during a run. The run closes the task. The task reopens and the next run receives the comment. This test is red on `master` with the exact production cancel reason. - Negative: the person's comment in the merged wake is the comment that the closing run received as its input. The task stays done and no new run starts. ## Verification - `cd server && npx vitest run src/__tests__/heartbeat-comment-wake-batching.test.ts src/modules/wake-queue` passes (15 files, 391 tests). - `cd server && npx vitest run src/__tests__/heartbeat-held-comment-wake.test.ts src/__tests__/heartbeat-issue-rewake-throttle.test.ts src/__tests__/heartbeat-answer-behind-settling-run.test.ts` passes (57 tests). - `cd server && npx tsc --noEmit` passes. - Red check: with only the source change reverted, the new positive test fails with `expected 'Deferred execution wake no longer app…' to be null`. - `pnpm verify` exits 2 (an opaque setup dependency). Required CI supplies broad coverage. ## Risks - Low risk. The change only adds a reopen reason for a done or cancelled task. The comment must be live, undelivered, not written by the finishing run, and written by a person. - A comment from a local CLI agent can carry a user id. The check excludes comments that have a creating run or an agent author, so these comments do not count as person comments. > 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 - Anthropic Claude Opus 5.5 (`claude-opus-5-5`), used through Claude Code with tool use (shell, file edits, test runs). ## 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 --- .../heartbeat-comment-wake-batching.test.ts | 163 ++++++++++++++++++ .../modules/wake-queue/adapters/postgres.ts | 12 +- .../modules/wake-queue/application/ports.ts | 2 +- .../wake-queue/application/use-cases.test.ts | 4 +- .../wake-queue/application/use-cases.ts | 1 + 5 files changed, 177 insertions(+), 5 deletions(-) diff --git a/server/src/__tests__/heartbeat-comment-wake-batching.test.ts b/server/src/__tests__/heartbeat-comment-wake-batching.test.ts index 855d99c4286..77a75841b62 100644 --- a/server/src/__tests__/heartbeat-comment-wake-batching.test.ts +++ b/server/src/__tests__/heartbeat-comment-wake-batching.test.ts @@ -2164,6 +2164,169 @@ describeEmbeddedPostgres("heartbeat comment wake batching", () => { } }, 120_000); + async function startAssignedRunWithDeferredChildCompletion(input: { + gateway: Awaited>; + title: string; + firstRunComment?: boolean; + }) { + const companyId = randomUUID(); + const agentId = randomUUID(); + const issueId = randomUUID(); + const issuePrefix = `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`; + const heartbeat = heartbeatService(db); + await db.insert(companies).values(wakeCompanyRow(companyId, issuePrefix)); + await grantFixtureWorkspaceAccess(companyId, ["responsible-user", "user-1"]); + await db.insert(agents).values(wakeGatewayAgentRow(agentId, companyId, "Gateway Agent", input.gateway)); + await db.insert(issues).values(wakeIssueRow(issueId, companyId, input.title, agentId, issuePrefix)); + + const firstRunComment = input.firstRunComment + ? await db.insert(issueComments) + .values(wakeUserCommentRow(companyId, issueId, "user-1", "Start with this instruction")) + .returning().then((rows) => rows[0]) + : null; + const firstRun = await heartbeat.wakeup(agentId, firstRunComment + ? { + source: "automation", triggerDetail: "system", reason: "issue_commented", + payload: { issueId, commentId: firstRunComment.id }, + contextSnapshot: { issueId, taskId: issueId, commentId: firstRunComment.id, wakeCommentId: firstRunComment.id, + wakeReason: "issue_commented" }, + requestedByActorType: "user", requestedByActorId: "user-1", + } + : { + source: "assignment", triggerDetail: "system", reason: "issue_assigned", + payload: { issueId }, contextSnapshot: { issueId, taskId: issueId, wakeReason: "issue_assigned" }, + requestedByActorType: "user", requestedByActorId: "user-1", + }); + expect(firstRun).not.toBeNull(); + await waitFor(async () => { + const run = await db.select({ status: heartbeatRuns.status }).from(heartbeatRuns) + .where(eq(heartbeatRuns.id, firstRun!.id)).then((rows) => rows[0] ?? null); + return run?.status === "running"; + }); + await waitFor(() => input.gateway.getAgentPayloads().length >= 1); + + const childCompletionIntentId = randomUUID(); + const childCompletionWakeId = randomUUID(); + const childCompletionContext = { issueId, taskId: issueId, wakeReason: "issue_children_completed" }; + await db.insert(agentWakeupRequests).values([{ + id: childCompletionIntentId, companyId, agentId, source: "automation", triggerDetail: "system", + reason: "issue_children_completed", status: "coalesced", + requestedByActorType: "system", requestedByActorId: "native-status-committer", + payload: { issueId, taskId: issueId }, finishedAt: new Date(), + }, { + id: childCompletionWakeId, companyId, agentId, source: "automation", triggerDetail: "system", + reason: "issue_execution_deferred", status: "deferred_issue_execution", + requestedByActorType: "system", requestedByActorId: `native-status-wake-dispatch:${childCompletionIntentId}`, + payload: { issueId, taskId: issueId, _paperclipWakeContext: childCompletionContext }, + }]); + return { companyId, agentId, issueId, heartbeat, firstRun: firstRun!, firstRunComment, childCompletionWakeId }; + } + + async function closeIssueAndFinishFirstRun( + gateway: Awaited>, + issueId: string, + firstRunId: string, + ) { + await db.update(issues).set({ + status: "done", completedAt: new Date(), executionRunId: null, executionAgentNameKey: null, + executionLockedAt: null, updatedAt: new Date(), + }).where(eq(issues.id, issueId)); + gateway.releaseFirstWait(); + await waitFor(async () => { + const run = await db.select({ status: heartbeatRuns.status }).from(heartbeatRuns) + .where(eq(heartbeatRuns.id, firstRunId)).then((rows) => rows[0] ?? null); + return run?.status === "succeeded"; + }, 90_000); + } + + it("reopens a finished task when a person's comment joined a deferred system wake during the run", async () => { + const gateway = await createControlledGatewayServer(); + try { + const { companyId, agentId, issueId, heartbeat, firstRun, childCompletionWakeId } = + await startAssignedRunWithDeferredChildCompletion({ gateway, title: "Person comment behind a child result" }); + + const personComment = await db.insert(issueComments) + .values(wakeUserCommentRow(companyId, issueId, "user-1", "Additional requirement posted while the run was finishing")) + .returning().then((rows) => rows[0]); + const commentWake = await heartbeat.wakeup(agentId, { + source: "automation", triggerDetail: "system", reason: "issue_commented", + payload: { issueId, commentId: personComment.id }, + contextSnapshot: { issueId, taskId: issueId, commentId: personComment.id, wakeCommentId: personComment.id, + wakeReason: "issue_commented" }, + requestedByActorType: "user", requestedByActorId: "user-1", + }); + expect(commentWake).toBeNull(); + const merged = await selectDeferredWakeForAgent(companyId, agentId); + expect(merged).toMatchObject({ id: childCompletionWakeId, requestedByActorType: "system" }); + expect(JSON.stringify(merged?.payload)).toContain(personComment.id); + + await closeIssueAndFinishFirstRun(gateway, issueId, firstRun.id); + + await waitFor(async () => { + const wake = await db.select({ status: agentWakeupRequests.status }).from(agentWakeupRequests) + .where(eq(agentWakeupRequests.id, childCompletionWakeId)).then((rows) => rows[0] ?? null); + return wake?.status !== "deferred_issue_execution"; + }, 30_000); + const settledWake = await db.select({ status: agentWakeupRequests.status, error: agentWakeupRequests.error }) + .from(agentWakeupRequests).where(eq(agentWakeupRequests.id, childCompletionWakeId)).then((rows) => rows[0] ?? null); + expect(settledWake?.error).toBeNull(); + expect(settledWake?.status).not.toBe("cancelled"); + await waitFor(() => gateway.getAgentPayloads().length >= 2, 90_000); + const issueAfter = await db.select({ status: issues.status, completedAt: issues.completedAt }) + .from(issues).where(eq(issues.id, issueId)).then((rows) => rows[0] ?? null); + expect(issueAfter).toMatchObject({ status: "in_progress", completedAt: null }); + const runs = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.agentId, agentId)) + .orderBy(asc(heartbeatRuns.createdAt)); + expect(runs).toHaveLength(2); + expect(runs[1]?.wakeupRequestId).toBe(childCompletionWakeId); + expect(String(gateway.getAgentPayloads()[1]?.message ?? "")).toContain( + "Additional requirement posted while the run was finishing", + ); + } finally { + gateway.releaseFirstWait(); + await gateway.close(); + } + }, 120_000); + + it("keeps a finished task closed when the only person comment in a deferred system wake was the run's own input", async () => { + const gateway = await createControlledGatewayServer(); + try { + const { companyId, agentId, issueId, heartbeat, firstRun, firstRunComment, childCompletionWakeId } = + await startAssignedRunWithDeferredChildCompletion({ + gateway, title: "Delivered person comment behind a child result", firstRunComment: true, + }); + + const repeatedWake = await heartbeat.wakeup(agentId, { + source: "automation", triggerDetail: "system", reason: "issue_commented", + payload: { issueId, commentId: firstRunComment!.id }, + contextSnapshot: { issueId, taskId: issueId, commentId: firstRunComment!.id, wakeCommentId: firstRunComment!.id, + wakeReason: "issue_commented" }, + requestedByActorType: "user", requestedByActorId: "user-1", + }); + expect(repeatedWake).toBeNull(); + const merged = await selectDeferredWakeForAgent(companyId, agentId); + expect(merged?.id).toBe(childCompletionWakeId); + expect(JSON.stringify(merged?.payload)).toContain(firstRunComment!.id); + + await closeIssueAndFinishFirstRun(gateway, issueId, firstRun.id); + + await waitFor(async () => { + const wake = await db.select({ status: agentWakeupRequests.status }).from(agentWakeupRequests) + .where(eq(agentWakeupRequests.id, childCompletionWakeId)).then((rows) => rows[0] ?? null); + return wake?.status === "cancelled"; + }, 90_000); + const issueAfter = await db.select({ status: issues.status }).from(issues) + .where(eq(issues.id, issueId)).then((rows) => rows[0] ?? null); + expect(issueAfter?.status).toBe("done"); + const runs = await db.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(eq(heartbeatRuns.agentId, agentId)); + expect(runs.map((run) => run.id)).toEqual([firstRun.id]); + expect(gateway.getAgentPayloads()).toHaveLength(1); + } finally { + gateway.releaseFirstWait(); + await gateway.close(); + } + }, 120_000); + it("cancels a deferred comment wake when its only queued comment is deleted before promotion", async () => { const gateway = await createControlledGatewayServer(); const companyId = randomUUID(); diff --git a/server/src/modules/wake-queue/adapters/postgres.ts b/server/src/modules/wake-queue/adapters/postgres.ts index 3d9a0ab20e1..1803aab486a 100644 --- a/server/src/modules/wake-queue/adapters/postgres.ts +++ b/server/src/modules/wake-queue/adapters/postgres.ts @@ -474,10 +474,18 @@ function buildTransaction(tx: Db, deps: WakeQueuePostgresAdapterDeps, db: Db, ru async getCommentSelfAuthorship({ companyId, issueId, finishingRunId, commentIds }) { const rows = await tx - .select({ createdByRunId: issueComments.createdByRunId }) + .select({ + createdByRunId: issueComments.createdByRunId, authorType: issueComments.authorType, + authorUserId: issueComments.authorUserId, authorAgentId: issueComments.authorAgentId, + derivedAuthorAgentId: issueComments.derivedAuthorAgentId, deletedAt: issueComments.deletedAt, + }) .from(issueComments) .where(and(eq(issueComments.companyId, companyId), eq(issueComments.issueId, issueId), inArray(issueComments.id, commentIds))); - return { allSelfAuthored: rows.length > 0 && rows.every((row) => row.createdByRunId === finishingRunId) }; + return { + allSelfAuthored: rows.length > 0 && rows.every((row) => row.createdByRunId === finishingRunId), + includesPersonComment: rows.some((row) => !row.deletedAt && row.authorUserId !== null && row.createdByRunId === null && + row.authorAgentId === null && row.derivedAuthorAgentId === null && (row.authorType === "user" || row.authorType === null)), + }; }, async isWatcherCommentDuringFinishingRun({ companyId, issueId, finishingRunId, commentIds }) { diff --git a/server/src/modules/wake-queue/application/ports.ts b/server/src/modules/wake-queue/application/ports.ts index ffda4692b36..2ee3256260f 100644 --- a/server/src/modules/wake-queue/application/ports.ts +++ b/server/src/modules/wake-queue/application/ports.ts @@ -178,7 +178,7 @@ export interface WakeQueueTransaction { issueId: string; finishingRunId: string; commentIds: string[]; - }): Promise<{ allSelfAuthored: boolean }>; + }): Promise<{ allSelfAuthored: boolean; includesPersonComment: boolean }>; /** Proves all candidate comments only report completed child work in the finishing parent's own run. */ isCompletedDelegationMention(input: { companyId: string; diff --git a/server/src/modules/wake-queue/application/use-cases.test.ts b/server/src/modules/wake-queue/application/use-cases.test.ts index f5c6999e852..8cf2e851f00 100644 --- a/server/src/modules/wake-queue/application/use-cases.test.ts +++ b/server/src/modules/wake-queue/application/use-cases.test.ts @@ -115,7 +115,7 @@ function createFakeTransaction(overrides: Partial = {}): W reason: null, releasePolicy: null, })), - getCommentSelfAuthorship: vi.fn(async () => ({ allSelfAuthored: false })), + getCommentSelfAuthorship: vi.fn(async () => ({ allSelfAuthored: false, includesPersonComment: false })), isWatcherCommentDuringFinishingRun: vi.fn(async () => false), owedInteractionAnswer: vi.fn(async (): Promise<"deliver" | "blocked" | null> => null), isCompletedDelegationMention: vi.fn(async () => false), @@ -681,7 +681,7 @@ describe("releaseIssueExecution", () => { liveNonSelfCommentIds: scenario === "done_missing" || scenario === "done_self" ? [] : commentIds, containedSelfAuthoredComment: scenario === "done_self", })), - getCommentSelfAuthorship: vi.fn(async () => ({ allSelfAuthored: scenario === "done_self" })), + getCommentSelfAuthorship: vi.fn(async () => ({ allSelfAuthored: scenario === "done_self", includesPersonComment: false })), isWatcherCommentDuringFinishingRun: vi.fn(async () => scenario === "done_watcher_during_run"), reopenIssue: vi.fn(async () => ({ ...ISSUE, status: "todo" })), }); diff --git a/server/src/modules/wake-queue/application/use-cases.ts b/server/src/modules/wake-queue/application/use-cases.ts index 70a4ad5732a..f10416fe4c8 100644 --- a/server/src/modules/wake-queue/application/use-cases.ts +++ b/server/src/modules/wake-queue/application/use-cases.ts @@ -392,6 +392,7 @@ async function promoteDeferredWake( shouldReopen = !selfAuthorship.allSelfAuthored && (workingCandidate.requestedByActorType === "user" || + selfAuthorship.includesPersonComment || workingCandidate.wakeReason === "issue_reopened_via_comment" || // The agent watching the task posted it while the run that closed the // task was active. That agent receives the completed result and can From db73178bcf21c9d9664410b471968d5ffdad08fd Mon Sep 17 00:00:00 2001 From: Nicky Leach Date: Mon, 16 Nov 2026 08:24:47 -0800 Subject: [PATCH 3/6] fix(heartbeat): keep saved sessions across config edits the provider thread cannot see (#21862) 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 heartbeat run resumes the agent's saved task session, which holds the provider thread and its history. > - Before resume, Paperclip compares a fingerprint of the effective run configuration with the fingerprint that the session saved. A difference discards the thread. > - The fingerprint hashed the agent config revision row (id, changed keys, time). Every saved agent edit therefore discarded the thread, also an edit that set a value back to what it was. > - The fingerprint also hashed settings that never reach the thread or the native execution input, for example turn timeouts, wake scheduling, and the environment row's update time. > - This pull request removes those inputs from the fingerprint, classifies every input with its reason, and adds backstop tests so that a new input cannot join or leave the fingerprint without a decision. > - The benefit is that agents keep their thread history across edits that cannot change what the thread saw or may do, while real changes still start a new thread. ## Linked Issues or Issue Description Related: #9977 (semantic task-session fingerprints, open) and #8797 (added the effective run config fingerprint). **What happened?** An operator changed an agent's warm idle window from 60000 to unset, and then back to 60000, between two turns on the same issue. The next run logged `Skipping saved session resume for task "" because effective run configuration changed: adapter.` Only the `adapter` category changed, because the new config revision row was in it. The adapter config itself was identical. The run started a new provider thread. The environment lease was reused, so the run stopped the retained remote task before it started a new one. That stop raced the task's exit, and the run failed with `Plugin Runner termination is unconfirmed; reconcile the saved task`. An automatic retry then succeeded on a fresh environment. **Expected behavior** An edit that cannot change what the provider thread saw or may do, and cannot change the native execution input, keeps the saved session. An edit to the model, provider, active permission mode, lifecycle mode or warm idle window, instructions, skills, environment, secrets, or another thread input still starts a new session. **Steps to reproduce** 1. Run an agent turn on an issue so that the task session saves its fingerprint. 2. Save an agent config edit that does not change a thread input, for example set `adapterConfig.idleTimeoutMs` to another value and back, or rename the agent. 3. Wake the agent on the same issue. On master the run log shows "effective run configuration changed: adapter" and the run starts a new thread. ## What Changed - New `server/src/services/heartbeat/session-fingerprint-inputs.ts`. It classifies each fingerprint input as kept or excluded, with the reason: - agent config revision fields (`CONFIG_REVISION_FIELDS`); - `paperclip_runner` adapter config keys; - top-level environment driver config keys; - agent runtime config keys; - selected-environment and environment-selection fields. - The session fingerprint no longer hashes these inputs: - the config revision row (id, changed keys, time); - for `paperclip_runner`: `timeoutSec`, `graceSec`, the permission keys of providers that are not selected, and `search` when the provider is not Codex; - `runtimeConfig.heartbeat` (wake scheduling, concurrency, daily caps, max-turn continuation); - the selected environment's `configRevisionAt` (row update time) and the `selectionSource`; - environment config `archiveOnRelease`, `streamRunLogs`, and `timeoutMs` (sandbox RPC timeout). - Unknown adapter and runtime config keys are still hashed. A missing classification can only keep the old reset behavior; it cannot skip a reset. - Lifecycle inputs stay in the fingerprint: `lifecycleMode`, `idleTimeoutMs`, and the environment's `runnerLifecycleMode`, `runnerIdleTimeoutMs`, and `reuseLease`. They become `session.lifecyclePolicy`, which the native session digest compares before a follow-up turn attaches to its warm Runner. A kept session with a different policy would be refused (`warm_recovery_refused=execution_mismatch`). - Session preparation accepts a saved fingerprint built with the previous composition (`legacyComposition`) for the same inputs. The upgrade therefore does not discard every saved session once. The run then saves the new fingerprint. - Backstop tests in `session-fingerprint-inputs.test.ts`: - every agent revision field, runner config schema field, provider permission key, and environment driver config key has a classification; - the shape of each hashed category is pinned, so a new field cannot reach the fingerprint without a decision; - every runner key classified as excluded leaves the native provider input and the lifecycle policy unchanged (this test fails if `idleTimeoutMs` is reclassified as excluded); - behavior tests for each exclusion and for the thread and lifecycle inputs that must still reset; - a pinned fingerprint proves that the legacy composition reproduces the master fingerprint exactly. - `ai-connection-session.test.ts`: two tests used a rename or a `heartbeat` edit as the "unrelated change". They now use a model change or an unclassified runtime setting, and two new tests pin that a rename and a scheduling change keep the session. - `doc/heartbeat-internals.md` (Config Freshness) describes the rule and the backstop. The PR adds no code comments, as `CONTRIBUTING.md` requires; the reasons live in the classification tables and the doc. ## Verification - Red/green: on master, the exclusion cases, the category-shape pin, and the legacy acceptance case fail. With the change, all pass. - Backstop check: with `idleTimeoutMs` temporarily reclassified as excluded, the native-input test and the idle-window reset test fail. - Legacy bridge: I computed the fingerprint for one runner fixture and one `codex_local` fixture with master's `workspaces.ts` and with `legacyComposition: true` on this branch. The output files were byte-identical, category fingerprints included. The pinned test uses those values. - `cd server && npx vitest run src/services/heartbeat/session-fingerprint-inputs.test.ts src/__tests__/ai-connection-session.test.ts src/__tests__/heartbeat-workspace-session.test.ts src/__tests__/heartbeat-execution-configuration.test.ts src/__tests__/ai-connection-router.test.ts src/__tests__/native-session-resumption.test.ts src/__tests__/environment-service.test.ts`: 7 files, 397 tests, all pass. - `npx tsc --noEmit -p server`: no errors. - `pnpm verify` exited 2 (broader coverage needed), so the focused checks above and required CI give the coverage. ## Risks - Behavior change: an agent rename, role, title, icon, appearance, reports-to, capabilities, budget, or metadata edit no longer starts a new thread. Agent tools read these fields live at call time (`runner-semantic-authority.ts`, `paperclip-runner-tool-authority.ts`), so the thread never holds a frozen copy. - Behavior change: wake-scheduling and turn-timeout edits no longer start a new thread. Neither value is part of the native execution input, so warm Runner attachment is unaffected. - A warm idle window edit still starts a new thread. Setting it and setting it back between turns no longer does, because the revision row is not hashed. - The legacy bridge computes extra candidate fingerprints only when the saved fingerprint differs. It accepts a legacy fingerprint only for the same current inputs; it never widens what a reset protects. - During the transition, a real change on a session that still holds a legacy fingerprint can list extra categories in the reset reason. The reset decision is correct. - No schema or API change. The fingerprint version stays 1. > 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 - Anthropic Claude Opus 5.5 (`claude-opus-5-5`), used in Claude Code with tool use (shell, file edit) and extended thinking. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- doc/heartbeat-internals.md | 2 + .../__tests__/ai-connection-session.test.ts | 19 +- server/src/lib/agent-records.ts | 2 +- server/src/services/environment-config.ts | 7 + .../session-fingerprint-inputs.test.ts | 248 ++++++++++++++++++ .../heartbeat/session-fingerprint-inputs.ts | 163 ++++++++++++ .../services/heartbeat/session-preparation.ts | 30 ++- server/src/services/heartbeat/workspaces.ts | 17 +- 8 files changed, 464 insertions(+), 24 deletions(-) create mode 100644 server/src/services/heartbeat/session-fingerprint-inputs.test.ts create mode 100644 server/src/services/heartbeat/session-fingerprint-inputs.ts diff --git a/doc/heartbeat-internals.md b/doc/heartbeat-internals.md index 71f32893afc..59be8eafd62 100644 --- a/doc/heartbeat-internals.md +++ b/doc/heartbeat-internals.md @@ -78,6 +78,8 @@ configuration variables; task bindings cannot override them. When effective run config changes, Paperclip may intentionally skip a saved adapter session, refresh persisted workspace runtime config, replace a reused execution workspace, or avoid reusing a sandbox/environment lease. Fresh execution can lose adapter-specific session, workspace, or sandbox state; correctness of the next run's config takes priority over continuity. Plain environment values affect freshness through value hashes; run result JSON and workspace operation logs expose only the non-sensitive freshness decision categories, without storing secret values, full env maps, provider credentials, or private path details. +The saved-session fingerprint covers only inputs that can change what the provider thread saw or may do, or what the native session digest compares before a follow-up turn attaches to its warm Runner. It leaves out the agent config revision row itself (its id and time), agent identity and display fields that tools read live, turn timeouts, the legacy kill grace, permission keys of a provider that is not selected, wake scheduling (`runtimeConfig.heartbeat`), the environment row's update time and selection source, and the environment's release, log-streaming, and RPC-timeout settings. Lifecycle inputs stay in: the lifecycle mode, the agent and environment warm idle windows, and the environment's lease reuse, because they become `session.lifecyclePolicy`, and a kept session with a different policy cannot attach to its warm Runner. `server/src/services/heartbeat/session-fingerprint-inputs.ts` classifies every input with the reason. Its tests fail when an agent revision field, a runner config schema field, a provider permission key, or an environment config key appears without a classification, when a new field reaches a hashed category, or when an excluded runner key reaches the native execution input. An unknown adapter or runtime config key is hashed. A session saved with the previous fingerprint composition is accepted once for the same inputs, so an upgrade does not discard saved sessions. + An explicit `reuse_existing` Git workspace keeps its recorded source repository, including after its project-workspace row is deleted or the project primary changes. The server verifies the original company, project, repository origin, and worktree registration before reuse. It does not attach a deleted association to the new primary. A conflicting explicit project-workspace selection, missing source identity, or an unverified legacy local checkout blocks the run. Restore the original source. Before intentionally clearing the existing-workspace binding to choose a new repository, review and preserve its retained work. Missing worktrees may be reconstructed only from the verified original source; current project defaults are not a fallback. ## Heartbeat Service Extractions diff --git a/server/src/__tests__/ai-connection-session.test.ts b/server/src/__tests__/ai-connection-session.test.ts index 81bed1e2c4c..dbd1b13fe0f 100644 --- a/server/src/__tests__/ai-connection-session.test.ts +++ b/server/src/__tests__/ai-connection-session.test.ts @@ -40,22 +40,33 @@ describe("AI pool session adoption", () => { const switchPool = revision("revision-3", { mode: "router", connectionId: "previous-pool" }, pool); expect((await decision({ agentRuntimeConfig: { aiConnection: binding }, agentConfigRevision: aiConnectionRevisionMetadata(first) }, { agentConfigRevision: aiConnectionRevisionMetadata(switchPool) }, { revisions: [switchPool, adoption, first] })).reset).toBe(false); }); - it("retains resets when the same edit also changes unrelated configuration", async () => { + it("retains resets when the same edit also changes a setting the thread uses", async () => { + const first = revision("revision-1", null, binding); + const edit = revision("revision-2", binding, pool, { adapterConfig: { model: "gpt-5.6-terra" } }); + expect(aiConnectionOnlyConfigRevision(edit)).toBe(false); + expect((await decision({ agentRuntimeConfig: { aiConnection: binding }, agentConfigRevision: aiConnectionRevisionMetadata(first) }, { agentConfigRevision: aiConnectionRevisionMetadata(edit), effectiveAdapterConfig: { ...config, model: "gpt-5.6-terra" } }, { revisions: [edit, first] })).reset).toBe(true); + }); + it("keeps the session when the same edit also renames the agent", async () => { const first = revision("revision-1", null, binding); const edit = revision("revision-2", binding, pool, { name: "Renamed agent" }); expect(aiConnectionOnlyConfigRevision(edit)).toBe(false); - expect((await decision({ agentRuntimeConfig: { aiConnection: binding }, agentConfigRevision: aiConnectionRevisionMetadata(first) }, { agentConfigRevision: aiConnectionRevisionMetadata(edit) }, { revisions: [edit, first] })).reset).toBe(true); + expect((await decision({ agentRuntimeConfig: { aiConnection: binding }, agentConfigRevision: aiConnectionRevisionMetadata(first) }, { agentConfigRevision: aiConnectionRevisionMetadata(edit) }, { revisions: [edit, first] })).reset).toBe(false); }); it("does not bridge a stale revision over a newer runtime settings change", async () => { const first = revision("revision-1", null, binding); const adoption = revision("revision-2", binding, pool); - expect((await decision({ agentRuntimeConfig: { aiConnection: binding }, agentConfigRevision: aiConnectionRevisionMetadata(first) }, { agentRuntimeConfig: { aiConnection: pool, heartbeat: { enabled: false } }, agentConfigRevision: aiConnectionRevisionMetadata(adoption) }, { revisions: [adoption, first] })).reset).toBe(true); + expect((await decision({ agentRuntimeConfig: { aiConnection: binding }, agentConfigRevision: aiConnectionRevisionMetadata(first) }, { agentRuntimeConfig: { aiConnection: pool, futureSetting: true }, agentConfigRevision: aiConnectionRevisionMetadata(adoption) }, { revisions: [adoption, first] })).reset).toBe(true); + }); + it("keeps the session across a wake-scheduling change after a binding edit", async () => { + const first = revision("revision-1", null, binding); + const adoption = revision("revision-2", binding, pool); + expect((await decision({ agentRuntimeConfig: { aiConnection: binding }, agentConfigRevision: aiConnectionRevisionMetadata(first) }, { agentRuntimeConfig: { aiConnection: pool, heartbeat: { enabled: false } }, agentConfigRevision: aiConnectionRevisionMetadata(adoption) }, { revisions: [adoption, first] })).reset).toBe(false); }); it.each([ { effectiveAdapterConfig: { ...config, model: "gpt-5.6-terra" } }, { effectiveAdapterConfig: { ...config, provider: "acpx", acpxAgent: "codex" } }, { effectiveAdapterConfig: { ...config, env: { ...config.env, OTHER: "changed" } } }, - { agentRuntimeConfig: { aiConnection: pool, heartbeat: { maxConcurrentRuns: 2 } } }, + { agentRuntimeConfig: { aiConnection: pool, futureSetting: true } }, { workspaceConfig: { effectiveMode: "isolated_workspace" } }, ])("preserves normal resets for effective settings changes: %j", async next => { expect((await decision({ agentRuntimeConfig: { aiConnection: binding } }, next)).reset).toBe(true); diff --git a/server/src/lib/agent-records.ts b/server/src/lib/agent-records.ts index f5b7500cabf..fccfe212605 100644 --- a/server/src/lib/agent-records.ts +++ b/server/src/lib/agent-records.ts @@ -20,7 +20,7 @@ export function createToken() { return `pcp_${randomBytes(24).toString("hex")}`; } -const CONFIG_REVISION_FIELDS = [ +export const CONFIG_REVISION_FIELDS = [ "name", "role", "title", diff --git a/server/src/services/environment-config.ts b/server/src/services/environment-config.ts index 3fcb01fc93e..fd592f270b5 100644 --- a/server/src/services/environment-config.ts +++ b/server/src/services/environment-config.ts @@ -138,6 +138,13 @@ const pluginEnvironmentConfigSchema = z.object({ driverConfig: z.record(z.string(), z.unknown()).optional().default({}), }).strict(); +export const ENVIRONMENT_CONFIG_SCHEMA_KEYS = { + ssh: Object.keys(sshEnvironmentConfigPersistenceSchema.shape), + fakeSandbox: Object.keys(fakeSandboxEnvironmentConfigSchema.shape), + pluginSandbox: Object.keys(pluginSandboxEnvironmentConfigSchema.shape), + plugin: Object.keys(pluginEnvironmentConfigSchema.shape), +} as const; + export type ParsedEnvironmentConfig = | { driver: "local"; config: LocalEnvironmentConfig } | { driver: "ssh"; config: SshEnvironmentConfig } diff --git a/server/src/services/heartbeat/session-fingerprint-inputs.test.ts b/server/src/services/heartbeat/session-fingerprint-inputs.test.ts new file mode 100644 index 00000000000..39ede31d455 --- /dev/null +++ b/server/src/services/heartbeat/session-fingerprint-inputs.test.ts @@ -0,0 +1,248 @@ +import { describe, expect, it } from "vitest"; +import { PAPERCLIP_RUNNER_PERMISSION_CAPABILITIES } from "@paperclipai/adapter-utils"; +import { getServerAdapter } from "../../adapters/registry.js"; +import { resolvePaperclipRunnerNativeProviderInput, resolvePaperclipRunnerProviderProfile } from "../native-runtime/provider-profile.js"; +import { resolveHeartbeatNativeLifecyclePolicy } from "./native-lifecycle.js"; +import { CONFIG_REVISION_FIELDS } from "../../lib/agent-records.js"; +import { ENVIRONMENT_CONFIG_SCHEMA_KEYS } from "../environment-config.js"; +import { + AGENT_REVISION_FIELD_SESSION_INPUTS, + AGENT_RUNTIME_CONFIG_SESSION_INPUTS, + ENVIRONMENT_CONFIG_SESSION_INPUTS, + ENVIRONMENT_SELECTION_SESSION_INPUTS, + PAPERCLIP_RUNNER_ADAPTER_CONFIG_SESSION_INPUTS, + SELECTED_ENVIRONMENT_SESSION_INPUTS, +} from "./session-fingerprint-inputs.js"; +import { + buildEffectiveRunSessionConfigMetadata, + buildSessionConfigCategoryValues, + resolveTaskSessionConfigFreshness, +} from "./workspaces.js"; + +const CLASSIFY = + "Classify it in session-fingerprint-inputs.ts: kept if a change can alter what the provider thread saw or may do, " + + "excluded (with the reason) if it cannot. An unclassified field discards saved sessions blindly or keeps them unsafely."; + +const unclassified = (keys: Iterable, table: Record) => + [...new Set(keys)].filter(key => !Object.hasOwn(table, key)).sort(); + +describe("session fingerprint input classification (backstop)", () => { + it("classifies every agent field that records a configuration revision", () => { + expect(unclassified(CONFIG_REVISION_FIELDS, AGENT_REVISION_FIELD_SESSION_INPUTS), CLASSIFY).toEqual([]); + expect(Object.keys(AGENT_REVISION_FIELD_SESSION_INPUTS).sort()).toEqual([...CONFIG_REVISION_FIELDS].sort()); + }); + + it("classifies every paperclip_runner config schema field and provider permission key", async () => { + const schema = await getServerAdapter("paperclip_runner").getConfigSchema?.(); + const schemaKeys = (schema?.fields ?? []).map(field => field.key); + expect(schemaKeys.length).toBeGreaterThan(0); + const permissionKeys = Object.values(PAPERCLIP_RUNNER_PERMISSION_CAPABILITIES) + .flatMap(capability => capability.configurable ? [capability.configKey] : []); + expect(unclassified([...schemaKeys, ...permissionKeys], PAPERCLIP_RUNNER_ADAPTER_CONFIG_SESSION_INPUTS), CLASSIFY).toEqual([]); + }); + + it("classifies every top-level environment driver config key, and only real keys", () => { + const schemaKeys = Object.values(ENVIRONMENT_CONFIG_SCHEMA_KEYS).flat(); + expect(unclassified(schemaKeys, ENVIRONMENT_CONFIG_SESSION_INPUTS), CLASSIFY).toEqual([]); + expect(Object.keys(ENVIRONMENT_CONFIG_SESSION_INPUTS).filter(key => !schemaKeys.includes(key))).toEqual([]); + }); + + it.each([ + { provider: "codex", model: "gpt-5.4-mini", codexPermissionMode: "never", lifecycleMode: "warm", idleTimeoutMs: 60_000 }, + { provider: "opencode", model: "openai/gpt-5.4-mini", opencodePermissionMode: "allow" }, + ])("keeps every excluded runner key out of the native execution input: %j", base => { + const nativeInputs = (config: Record) => { + const backend = resolvePaperclipRunnerProviderProfile(config).backend; + return { + provider: resolvePaperclipRunnerNativeProviderInput({ backend, adapterConfig: config }), + lifecyclePolicy: resolveHeartbeatNativeLifecyclePolicy({ + adapterType: "paperclip_runner", backend, agentMode: config.lifecycleMode, agentIdleTimeoutMs: config.idleTimeoutMs, + managedAiSelected: false, taskOwned: true, localTarget: false, + }), + }; + }; + const reference = nativeInputs(base); + const inertKeys = [ + ...Object.entries(PAPERCLIP_RUNNER_ADAPTER_CONFIG_SESSION_INPUTS).filter(([, value]) => value.kind === "excluded").map(([key]) => key), + ...Object.values(PAPERCLIP_RUNNER_PERMISSION_CAPABILITIES).flatMap(capability => capability.configurable ? [capability.configKey] : []) + .filter(key => key !== PAPERCLIP_RUNNER_PERMISSION_CAPABILITIES[base.provider as "codex" | "opencode"].configKey), + ]; + expect(inertKeys.length).toBeGreaterThan(0); + for (const key of inertKeys) { + expect(nativeInputs({ ...base, [key]: 12_345 }), `${key} reaches the native execution input; keep it in the fingerprint`).toEqual(reference); + } + expect(nativeInputs({ ...base, idleTimeoutMs: 120_000, lifecycleMode: "warm" }).lifecyclePolicy) + .not.toEqual(nativeInputs({ ...base, idleTimeoutMs: 60_000, lifecycleMode: "warm" }).lifecyclePolicy); + }); + + it("pins the shape of every hashed category, so a new field cannot join the fingerprint unclassified", () => { + const values = buildSessionConfigCategoryValues({ + adapterType: "paperclip_runner", + agentIdentityKeyId: "key-1", + effectiveAdapterConfig: { provider: "codex", model: "model-a" }, + agentRuntimeConfig: { aiConnection: { mode: "shared" }, heartbeat: { enabled: true } }, + instructions: { configured: true }, + issueOverrides: { model: "model-b" }, + workspaceConfig: { requestedMode: "agent_default", effectiveMode: "agent_default" }, + environment: { + selectionSource: "agent_default", + selectedEnvironmentId: "environment-1", + selectedEnvironment: { id: "environment-1", driver: "plugin", config: { pluginKey: "p" }, configRevisionAt: "2099-01-01T00:00:00.000Z" }, + executionPolicy: { mode: "default" }, + }, + environmentEnv: { A: "1" }, + projectEnv: { B: "2" }, + routineEnv: { C: "3" }, + secretManifest: [], + runtimeSkills: [], + agentConfigRevision: { id: "revision-1", changedKeys: ["adapterConfig"], configRevisionAt: "2099-01-01T00:00:00.000Z" }, + }); + expect(Object.keys(values).sort(), CLASSIFY).toEqual([ + "adapter", "adapterConfig", "agentRuntimeConfig", "envBindings", "environment", "instructions", + "issueOverrides", "runtimeSkills", "secrets", "workspaceConfig", + ]); + expect(Object.keys(values.adapter).sort(), CLASSIFY).toEqual(["adapterType", "agentIdentityKeyId"]); + const environment = values.environment as Record; + expect(Object.keys(environment).sort(), CLASSIFY).toEqual( + Object.entries(ENVIRONMENT_SELECTION_SESSION_INPUTS).filter(([, value]) => value.kind === "kept").map(([key]) => key).sort(), + ); + expect(Object.keys(environment.selectedEnvironment as object).sort(), CLASSIFY).toEqual( + Object.entries(SELECTED_ENVIRONMENT_SESSION_INPUTS).filter(([, value]) => value.kind === "kept").map(([key]) => key).sort(), + ); + expect(Object.keys(values.agentRuntimeConfig as object)).toEqual(["aiConnection"]); + expect(Object.keys(values.envBindings).sort()).toEqual(["environment", "project", "routine"]); + expect(AGENT_RUNTIME_CONFIG_SESSION_INPUTS.heartbeat.kind).toBe("excluded"); + }); +}); + +type MetadataInput = Parameters[0]; + +const baseInput: MetadataInput = { + adapterType: "paperclip_runner", + effectiveAdapterConfig: { + provider: "codex", model: "model-a", codexPermissionMode: "never", lifecycleMode: "warm", + idleTimeoutMs: 60_000, timeoutSec: 0, graceSec: 15, opencodePermissionMode: "allow", acpxPermissionMode: "approve-all", + }, + agentRuntimeConfig: { aiConnection: { mode: "shared", grantId: "grant-1" }, heartbeat: { enabled: false, maxConcurrentRuns: 20 } }, + issueOverrides: null, + workspaceConfig: { requestedMode: "agent_default", effectiveMode: "agent_default" }, + environment: { + selectionSource: "agent_default", + selectedEnvironmentId: "environment-1", + selectedEnvironment: { + id: "environment-1", driver: "plugin", configRevisionAt: "2099-01-01T00:00:00.000Z", + config: { pluginKey: "plugin-a", driverKey: "tasks", driverConfig: { image: "image-a" }, runnerIdleTimeoutMs: 60_000 }, + }, + }, + environmentEnv: null, + projectEnv: null, + routineEnv: null, + runtimeSkills: [], + agentConfigRevision: { id: "revision-1", changedKeys: ["adapterConfig"], configRevisionAt: "2099-01-01T00:00:00.000Z" }, +}; + +const withAdapterConfig = (patch: Record): Partial => ({ + effectiveAdapterConfig: { ...baseInput.effectiveAdapterConfig, ...patch }, +}); +const withSelectedEnvironment = (patch: Record, configPatch: Record = {}): Partial => { + const environment = baseInput.environment as { selectedEnvironment: { config: Record } & Record }; + return { environment: { ...(baseInput.environment as object), selectedEnvironment: { + ...environment.selectedEnvironment, ...patch, config: { ...environment.selectedEnvironment.config, ...configPatch }, + } } }; +}; + +async function freshness(next: Partial, compatible: Partial[] = []) { + const saved = await buildEffectiveRunSessionConfigMetadata(baseInput); + const configMetadata = await buildEffectiveRunSessionConfigMetadata({ ...baseInput, ...next }); + const compatibleConfigMetadata = await Promise.all(compatible.map(input => buildEffectiveRunSessionConfigMetadata({ ...baseInput, ...next, ...input }))); + return resolveTaskSessionConfigFreshness({ + hasTaskSession: true, configuredModel: "model-a", configMetadata, compatibleConfigMetadata, + taskSessionParams: { + __paperclipConfiguredModel: "model-a", __paperclipConfigFingerprint: saved.fingerprint, + __paperclipConfigFingerprintVersion: saved.version, __paperclipConfigCategoryFingerprints: saved.categoryFingerprints, + }, + }); +} + +describe("session fingerprint keeps sessions across non-thread changes", () => { + it.each<[string, Partial]>([ + ["a new config revision, even one that restores the same values", + { agentConfigRevision: { id: "revision-2", changedKeys: ["adapterConfig"], configRevisionAt: "2099-01-02T00:00:00.000Z" } }], + ["a revision of display-only agent fields", { agentConfigRevision: { id: "revision-3", changedKeys: ["name", "icon"], configRevisionAt: "2099-01-03T00:00:00.000Z" } }], + ["the turn time limit", withAdapterConfig({ timeoutSec: 3600 })], + ["the legacy kill grace", withAdapterConfig({ graceSec: 30 })], + ["another provider's permission mode", withAdapterConfig({ opencodePermissionMode: "deny", acpxPermissionMode: "deny-all" })], + ["wake scheduling", { agentRuntimeConfig: { aiConnection: { mode: "shared", grantId: "grant-1" }, heartbeat: { enabled: true, intervalSec: 300 } } }], + ["the environment row's update time", withSelectedEnvironment({ configRevisionAt: "2099-02-01T00:00:00.000Z" })], + ["how the same environment was selected", { environment: { ...(baseInput.environment as object), selectionSource: "issue" } }], + ["the environment's release, log streaming, and RPC timeout settings", + withSelectedEnvironment({}, { archiveOnRelease: true, streamRunLogs: false, timeoutMs: 30_000 })], + ])("does not reset for %s", async (_label, next) => { + expect(await freshness(next)).toMatchObject({ reset: false, changedCategories: [] }); + }); + + it("drops Codex-only search for another provider but keeps it for Codex", async () => { + const opencode = { provider: "opencode", opencodePermissionMode: "allow" }; + const saved = await buildEffectiveRunSessionConfigMetadata({ ...baseInput, ...withAdapterConfig(opencode) }); + const next = await buildEffectiveRunSessionConfigMetadata({ ...baseInput, ...withAdapterConfig({ ...opencode, search: false }) }); + expect(next.fingerprint).toBe(saved.fingerprint); + expect((await freshness(withAdapterConfig({ search: false }))).reset).toBe(true); + }); +}); + +describe("session fingerprint still resets for thread changes", () => { + it.each<[string, Partial]>([ + ["the model", withAdapterConfig({ model: "model-b" })], + ["the provider", withAdapterConfig({ provider: "opencode" })], + ["the active provider's permission mode", withAdapterConfig({ codexPermissionMode: "on-request" })], + ["the lifecycle mode", withAdapterConfig({ lifecycleMode: "per_turn" })], + ["the warm idle window, which the native session digest compares", withAdapterConfig({ idleTimeoutMs: 300_000 })], + ["the environment's warm idle window", withSelectedEnvironment({}, { runnerIdleTimeoutMs: 300_000 })], + ["the environment's lease reuse, which can change the default lifecycle", withSelectedEnvironment({}, { reuseLease: true })], + ["the provider account", { agentRuntimeConfig: { aiConnection: { mode: "shared", grantId: "grant-2" }, heartbeat: { enabled: false, maxConcurrentRuns: 20 } } }], + ["an unclassified runtime setting", { agentRuntimeConfig: { aiConnection: { mode: "shared", grantId: "grant-1" }, futureSetting: true } }], + ["an unclassified adapter setting", withAdapterConfig({ futureSetting: true })], + ["the environment", { environment: { ...(baseInput.environment as object), selectedEnvironmentId: "environment-2" } }], + ["the plugin driver config", withSelectedEnvironment({}, { driverConfig: { image: "image-b" } })], + ["the environment's lifecycle mode", withSelectedEnvironment({}, { runnerLifecycleMode: "per_turn" })], + ])("resets for %s", async (_label, next) => { + expect((await freshness(next)).reset).toBe(true); + }); +}); + +describe("legacy session fingerprints", () => { + it("reproduces the fingerprint saved before non-thread inputs left it", async () => { + const input: MetadataInput = { + adapterType: "paperclip_runner", + effectiveAdapterConfig: { provider: "codex", model: "model-a", codexPermissionMode: "never", lifecycleMode: "warm", idleTimeoutMs: 60000, timeoutSec: 0, graceSec: 15, opencodePermissionMode: "allow" }, + agentRuntimeConfig: { aiConnection: { mode: "shared" }, heartbeat: { enabled: false } }, + issueOverrides: null, workspaceConfig: { requestedMode: "agent_default" }, + environment: { selectionSource: "agent_default", selectedEnvironmentId: "e1", selectedEnvironment: { + id: "e1", driver: "plugin", configRevisionAt: "2099-01-01T00:00:00.000Z", config: { pluginKey: "p", runnerIdleTimeoutMs: 60000, reuseLease: true }, + } }, + environmentEnv: null, projectEnv: null, routineEnv: null, runtimeSkills: [], + agentConfigRevision: { id: "r1", changedKeys: ["adapterConfig"], configRevisionAt: "2099-01-01T00:00:00.000Z" }, + }; + expect((await buildEffectiveRunSessionConfigMetadata({ ...input, legacyComposition: true })).fingerprint) + .toBe("v1:sha256:1fbf35727ca022f7abe258b6277419c7fb19f6f911d7b02e52670681479528b5"); + expect((await buildEffectiveRunSessionConfigMetadata({ ...input, adapterType: "codex_local", legacyComposition: true })).fingerprint) + .toBe("v1:sha256:59f18fe1541c686ab9d29476b1b0525ab492053ab7b4d5fbd910a5b7503ca203"); + }); + + it("accepts a session saved with the legacy composition for the same inputs, once", async () => { + const legacySaved = await buildEffectiveRunSessionConfigMetadata({ ...baseInput, legacyComposition: true }); + const current = await buildEffectiveRunSessionConfigMetadata(baseInput); + expect(legacySaved.fingerprint).not.toBe(current.fingerprint); + const decide = async (next: Partial) => resolveTaskSessionConfigFreshness({ + hasTaskSession: true, configuredModel: "model-a", + configMetadata: await buildEffectiveRunSessionConfigMetadata({ ...baseInput, ...next }), + compatibleConfigMetadata: [await buildEffectiveRunSessionConfigMetadata({ ...baseInput, ...next, legacyComposition: true })], + taskSessionParams: { + __paperclipConfiguredModel: "model-a", __paperclipConfigFingerprint: legacySaved.fingerprint, + __paperclipConfigFingerprintVersion: legacySaved.version, __paperclipConfigCategoryFingerprints: legacySaved.categoryFingerprints, + }, + }); + expect((await decide({})).reset).toBe(false); + expect((await decide({ agentConfigRevision: { id: "revision-2", changedKeys: ["adapterConfig"], configRevisionAt: "2099-01-02T00:00:00.000Z" } })).reset).toBe(true); + }); +}); diff --git a/server/src/services/heartbeat/session-fingerprint-inputs.ts b/server/src/services/heartbeat/session-fingerprint-inputs.ts new file mode 100644 index 00000000000..463d866c763 --- /dev/null +++ b/server/src/services/heartbeat/session-fingerprint-inputs.ts @@ -0,0 +1,163 @@ +import { + isPaperclipRunnerProvider, + PAPERCLIP_RUNNER_PERMISSION_CAPABILITIES, +} from "@paperclipai/adapter-utils"; + +export type SessionFingerprintClassification = + | { kind: "kept"; reason: string } + | { kind: "excluded"; reason: string }; + +const kept = (reason: string): SessionFingerprintClassification => ({ kind: "kept", reason }); +const excluded = (reason: string): SessionFingerprintClassification => ({ kind: "excluded", reason }); + +const LIVE_AGENT_IDENTITY = + "Agent tools read this from the agent row at call time; the thread holds no frozen copy, and the native execution input does not carry it."; +const NATIVE_LIFECYCLE = + "Becomes part of session.lifecyclePolicy. The native session digest compares that policy before a follow-up turn attaches to its warm Runner, so a change needs a new session."; + +export const AGENT_REVISION_FIELD_SESSION_INPUTS = { + adapterType: kept("Hashed as adapter.adapterType."), + adapterConfig: kept("Hashed by content as adapterConfig."), + runtimeConfig: kept("Hashed by content as agentRuntimeConfig."), + defaultEnvironmentId: kept("Resolves to environment.selectedEnvironmentId, which is hashed."), + name: excluded(LIVE_AGENT_IDENTITY), + role: excluded(`${LIVE_AGENT_IDENTITY} Permission checks also read it per request.`), + title: excluded(LIVE_AGENT_IDENTITY), + capabilities: excluded(LIVE_AGENT_IDENTITY), + reportsTo: excluded(LIVE_AGENT_IDENTITY), + icon: excluded("Board display only."), + appearance: excluded("Board display only."), + budgetMonthlyCents: excluded("Budget admission runs before a run starts; it is not run input."), + metadata: excluded("No run preparation or native execution path reads agent metadata."), +} as const satisfies Record; + +export const PAPERCLIP_RUNNER_ADAPTER_CONFIG_SESSION_INPUTS = { + provider: kept("Selects the harness."), + model: kept("Selects the model."), + acpxAgent: kept("Selects the ACP agent."), + acpxSessionMode: kept("Cursor session mode."), + codexPermissionMode: kept("Codex approval policy, when Codex is the provider; dropped for another provider."), + opencodePermissionMode: kept("OpenCode tool permissions, when OpenCode is the provider; dropped for another provider."), + acpxPermissionMode: kept("ACP tool permissions, when ACPX is the provider; dropped for another provider."), + search: kept("Codex web search, when Codex is the provider; dropped for another provider."), + lifecycleMode: kept(`${NATIVE_LIFECYCLE} An explicit switch to warm also deliberately starts a new session.`), + idleTimeoutMs: kept(NATIVE_LIFECYCLE), + managedProfileId: kept("Managed agent profile."), + managedAgentsRetentionAcknowledged: kept("Managed agent retention terms."), + maxSessionListCostUsd: kept("Managed agent spend ceiling."), + agentCoreProfileId: kept("AgentCore profile."), + agentCoreRetentionAcknowledged: kept("AgentCore retention terms."), + maxEstimatedSessionCostUsd: kept("AgentCore spend ceiling."), + maxIterations: kept("AgentCore invocation limit."), + maxOutputTokens: kept("AgentCore invocation limit."), + timeoutSeconds: kept("AgentCore invocation limit."), + repoUrl: kept("Cursor Cloud repository."), + repoRef: kept("Cursor Cloud repository ref."), + prUrl: kept("Cursor Cloud pull request."), + cloudEnvName: kept("Cursor Cloud environment."), + workOnCurrentBranch: kept("Cursor Cloud branch policy."), + autoCreatePR: kept("Cursor Cloud pull request policy."), + skipReviewerRequest: kept("Cursor Cloud review policy."), + cwd: kept("Workspace location."), + instructionsFilePath: kept("Instructions; replaced by a content hash for managed bundles."), + env: kept("Process environment and secret bindings."), + workspaceStrategy: kept("Workspace strategy."), + workspaceRuntime: kept("Workspace runtime services."), + timeoutSec: excluded("Whole-turn time limit; the executor receives it apart from the native execution input."), + graceSec: excluded("Legacy child-process kill grace; the native runner path never reads it."), +} as const satisfies Record; + +export const ENVIRONMENT_CONFIG_SESSION_INPUTS = { + provider: kept("Sandbox provider."), + image: kept("Sandbox image."), + pluginKey: kept("Environment plugin."), + driverKey: kept("Environment plugin driver."), + driverConfig: kept("Plugin-owned driver configuration; every key under it is kept."), + runnerLifecycleMode: kept(`${NATIVE_LIFECYCLE} An explicit switch to warm also deliberately starts a new session.`), + runnerIdleTimeoutMs: kept(NATIVE_LIFECYCLE), + reuseLease: kept(`Decides whether a remote sandbox run defaults to warm. ${NATIVE_LIFECYCLE}`), + useHostAuth: kept("SSH authentication."), + tailscaleConnectionId: kept("SSH network path."), + tailscaleDeviceId: kept("SSH target machine."), + network: kept("SSH network path."), + tailscaleAuthKey: kept("SSH network credential."), + tailscaleAuthKeySecretRef: kept("SSH network credential."), + host: kept("SSH target machine."), + port: kept("SSH target machine."), + username: kept("SSH account."), + remoteWorkspacePath: kept("SSH workspace location."), + privateKey: kept("SSH credential."), + privateKeySecretRef: kept("SSH credential."), + knownHosts: kept("SSH host identity."), + strictHostKeyChecking: kept("SSH host identity policy."), + archiveOnRelease: excluded("What happens to a released sandbox; lease reuse decisions already ignore it."), + streamRunLogs: excluded("Host log streaming during a run."), + timeoutMs: excluded("Sandbox provider RPC timeout."), +} as const satisfies Record; + +export const AGENT_RUNTIME_CONFIG_SESSION_INPUTS = { + aiConnection: kept("Provider account and credentials."), + heartbeat: excluded("Wake scheduling, concurrency, daily caps, and max-turn continuation; none of it reaches the thread or the native execution input."), +} as const satisfies Record; + +export const SELECTED_ENVIRONMENT_SESSION_INPUTS = { + id: kept("A different environment is a different machine."), + driver: kept("Execution driver."), + config: kept("Hashed by key, as classified in ENVIRONMENT_CONFIG_SESSION_INPUTS."), + configRevisionAt: excluded( + "The row's update time. It moves on status, name, and description changes; the config is hashed by content.", + ), +} as const satisfies Record; + +export const ENVIRONMENT_SELECTION_SESSION_INPUTS = { + selectedEnvironmentId: kept("A different environment is a different machine."), + selectedEnvironment: kept("Hashed by field, as classified in SELECTED_ENVIRONMENT_SESSION_INPUTS."), + executionPolicy: kept("Execution policy."), + selectionSource: excluded("Records how the environment was chosen; nothing reads it to run."), +} as const satisfies Record; + +function excludedKeys(table: Record): Set { + return new Set(Object.entries(table).filter(([, value]) => value.kind === "excluded").map(([key]) => key)); +} + +const RUNNER_EXCLUDED_KEYS = excludedKeys(PAPERCLIP_RUNNER_ADAPTER_CONFIG_SESSION_INPUTS); +const ENVIRONMENT_CONFIG_EXCLUDED_KEYS = excludedKeys(ENVIRONMENT_CONFIG_SESSION_INPUTS); +const RUNTIME_CONFIG_EXCLUDED_KEYS = excludedKeys(AGENT_RUNTIME_CONFIG_SESSION_INPUTS); +const SELECTED_ENVIRONMENT_EXCLUDED_KEYS = excludedKeys(SELECTED_ENVIRONMENT_SESSION_INPUTS); +const ENVIRONMENT_SELECTION_EXCLUDED_KEYS = excludedKeys(ENVIRONMENT_SELECTION_SESSION_INPUTS); +const CODEX_ONLY_KEYS = ["search"] as const; + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +function omitKeys(value: Record, keys: Iterable): Record { + const result = { ...value }; + for (const key of keys) delete result[key]; + return result; +} + +export function paperclipRunnerSessionAdapterConfig(config: Record): Record { + const result = omitKeys(config, RUNNER_EXCLUDED_KEYS); + const provider = config.provider ?? "codex"; + if (!isPaperclipRunnerProvider(provider)) return result; + const active = PAPERCLIP_RUNNER_PERMISSION_CAPABILITIES[provider]; + const activeKey = active.configurable ? active.configKey : null; + const inactivePermissionKeys = Object.values(PAPERCLIP_RUNNER_PERMISSION_CAPABILITIES) + .flatMap(capability => capability.configurable ? [capability.configKey] : []) + .filter(key => key !== activeKey); + return omitKeys(result, [...inactivePermissionKeys, ...(provider === "codex" ? [] : CODEX_ONLY_KEYS)]); +} + +export function sessionAgentRuntimeConfig(runtimeConfig: unknown): unknown { + return isRecord(runtimeConfig) ? omitKeys(runtimeConfig, RUNTIME_CONFIG_EXCLUDED_KEYS) : runtimeConfig; +} + +export function sessionEnvironment(environment: unknown): unknown { + if (!isRecord(environment)) return environment; + const result = omitKeys(environment, ENVIRONMENT_SELECTION_EXCLUDED_KEYS); + if (!isRecord(result.selectedEnvironment)) return result; + const selected = omitKeys(result.selectedEnvironment, SELECTED_ENVIRONMENT_EXCLUDED_KEYS); + if (isRecord(selected.config)) selected.config = omitKeys(selected.config, ENVIRONMENT_CONFIG_EXCLUDED_KEYS); + return { ...result, selectedEnvironment: selected }; +} diff --git a/server/src/services/heartbeat/session-preparation.ts b/server/src/services/heartbeat/session-preparation.ts index 9d7729f0954..b993f84c169 100644 --- a/server/src/services/heartbeat/session-preparation.ts +++ b/server/src/services/heartbeat/session-preparation.ts @@ -153,16 +153,14 @@ export async function prepareHeartbeatSession(db: Db, input: HeartbeatSessionPre : null, }; const sessionConfigMetadata = await buildEffectiveRunSessionConfigMetadata(sessionConfigMetadataInput); - const compatibleConfigMetadata: EffectiveRunSessionConfigMetadata[] = []; - const importedManagedInstructions = Boolean(taskSession && sessionConfigMetadataInput.managedInstructions?.contentHash - && readConfigFingerprintFromSessionParams(taskSession.sessionParamsJson)?.fingerprint !== sessionConfigMetadata.fingerprint); + const storedFingerprint = taskSession ? readConfigFingerprintFromSessionParams(taskSession.sessionParamsJson)?.fingerprint : undefined; + const storedFingerprintDiffers = Boolean(taskSession) && storedFingerprint !== sessionConfigMetadata.fingerprint; + const compatibleInputs: SessionMetadataInput[] = []; + const importedManagedInstructions = Boolean(storedFingerprintDiffers && sessionConfigMetadataInput.managedInstructions?.contentHash); if (importedManagedInstructions) { - compatibleConfigMetadata.push(await buildEffectiveRunSessionConfigMetadata({ - ...sessionConfigMetadataInput, retainManagedInstructionPaths: true, - })); + compatibleInputs.push({ ...sessionConfigMetadataInput, retainManagedInstructionPaths: true }); } - if (managedAiRuntime && aiBinding && taskSession && - readConfigFingerprintFromSessionParams(taskSession.sessionParamsJson)?.fingerprint !== sessionConfigMetadata.fingerprint) { + if (managedAiRuntime && aiBinding && taskSession && storedFingerprintDiffers) { const revisions = requestedAiBinding?.mode === "router" ? await db.select().from(agentConfigRevisions).where(and(eq(agentConfigRevisions.companyId, agent.companyId), eq(agentConfigRevisions.agentId, agent.id))).orderBy(desc(agentConfigRevisions.createdAt), desc(agentConfigRevisions.id)).limit(21) : []; @@ -174,13 +172,17 @@ export async function prepareHeartbeatSession(db: Db, input: HeartbeatSessionPre storedIdentity: taskSession.sessionParamsJson?.paperclipAiCredentialIdentity, sessionIdentity: managedAiRuntime.sessionIdentity, credentialIdentity: managedAiRuntime.identity, revisions, }); - compatibleConfigMetadata.push(...await Promise.all(candidates.flatMap(candidate => [ - buildEffectiveRunSessionConfigMetadata({ ...sessionConfigMetadataInput, ...candidate }), - ...(importedManagedInstructions ? [buildEffectiveRunSessionConfigMetadata({ - ...sessionConfigMetadataInput, ...candidate, retainManagedInstructionPaths: true, - })] : []), - ]))); + compatibleInputs.push(...candidates.flatMap(candidate => [ + { ...sessionConfigMetadataInput, ...candidate }, + ...(importedManagedInstructions ? [{ ...sessionConfigMetadataInput, ...candidate, retainManagedInstructionPaths: true }] : []), + ])); } + const legacyInputs = storedFingerprintDiffers + ? [sessionConfigMetadataInput, ...compatibleInputs].map(candidate => ({ ...candidate, legacyComposition: true })) + : []; + const compatibleConfigMetadata: EffectiveRunSessionConfigMetadata[] = await Promise.all( + [...compatibleInputs, ...legacyInputs].map(candidate => buildEffectiveRunSessionConfigMetadata(candidate)), + ); const configuredModel = readConfiguredModelFromAdapterConfig(runtimeConfig); if (context.refreshTools === true && agent.adapterType !== "paperclip_runner") { diff --git a/server/src/services/heartbeat/workspaces.ts b/server/src/services/heartbeat/workspaces.ts index 5e352f2b582..8f28452360e 100644 --- a/server/src/services/heartbeat/workspaces.ts +++ b/server/src/services/heartbeat/workspaces.ts @@ -16,6 +16,7 @@ import { sql } from "drizzle-orm"; import { materializeIsolatedTaskDirectory } from "../isolated-task-directory.js"; import { readConnectionFailure, type GitConnectionFailure } from "@paperclipai/adapter-utils/connection-failure"; import { managedAiSessionFingerprintConfig } from "../ai-connection-runtime.js"; +import { paperclipRunnerSessionAdapterConfig, sessionAgentRuntimeConfig, sessionEnvironment } from "./session-fingerprint-inputs.js"; import { PROJECT_REPOSITORIES_DIR, readGitWorkspaceSnapshot, @@ -2781,7 +2782,7 @@ async function resolveInstructionsConfigFingerprintMetadata( return metadata; } -function buildSessionConfigCategoryValues(input: { +export function buildSessionConfigCategoryValues(input: { adapterType: string; effectiveAdapterConfig: Record; agentRuntimeConfig: unknown; @@ -2796,6 +2797,7 @@ function buildSessionConfigCategoryValues(input: { runtimeSkills: unknown; agentConfigRevision: unknown; agentIdentityKeyId?: string; + legacyComposition?: boolean; }) { const sanitizedSecretManifest = sanitizeSecretManifestForConfigFingerprint( input.secretManifest, @@ -2818,18 +2820,21 @@ function buildSessionConfigCategoryValues(input: { const issueSettings = { ...parseObject(workspaceConfig.issueSettings) }; if (issueSettings.mode === workspaceConfig.requestedMode) delete issueSettings.mode; workspaceConfig.issueSettings = Object.keys(issueSettings).length ? issueSettings : null; + const legacy = input.legacyComposition === true; return { adapter: { adapterType: input.adapterType, ...(input.agentIdentityKeyId ? { agentIdentityKeyId: input.agentIdentityKeyId } : {}), - agentConfigRevision: input.agentConfigRevision, + ...(legacy ? { agentConfigRevision: input.agentConfigRevision } : {}), }, - adapterConfig: input.effectiveAdapterConfig, - agentRuntimeConfig: input.agentRuntimeConfig, + adapterConfig: legacy || input.adapterType !== "paperclip_runner" + ? input.effectiveAdapterConfig + : paperclipRunnerSessionAdapterConfig(input.effectiveAdapterConfig), + agentRuntimeConfig: legacy ? input.agentRuntimeConfig : sessionAgentRuntimeConfig(input.agentRuntimeConfig), instructions: input.instructions, issueOverrides: input.issueOverrides, workspaceConfig, - environment: input.environment, + environment: legacy ? input.environment : sessionEnvironment(input.environment), envBindings: { environment: { env: input.environmentEnv }, project: { env: input.projectEnv }, @@ -2857,6 +2862,7 @@ export async function buildEffectiveRunSessionConfigMetadata(input: { runtimeSkills: unknown; agentConfigRevision?: unknown; agentIdentityKeyId?: string; + legacyComposition?: boolean; }): Promise { const secretManifest = input.secretManifest ?? []; const instructions = input.managedInstructions ? { @@ -2902,6 +2908,7 @@ export async function buildEffectiveRunSessionConfigMetadata(input: { runtimeSkills: versionedSkills(input.runtimeSkills), agentConfigRevision: input.agentConfigRevision ?? null, agentIdentityKeyId: input.agentIdentityKeyId, + legacyComposition: input.legacyComposition, }); const fingerprints = createEffectiveRunConfigFingerprints({ session: categoryValues, From 4da6902cb351354330477e354fda0428ba8e07b6 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Mon, 16 Nov 2026 10:35:42 -0600 Subject: [PATCH 4/6] fix(dispatch): start work on a task tree a person created in the person tier (#21916) 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 heartbeat queue chooses which queued run starts when an agent at its concurrency limit frees a slot > - The queue puts runs a person asked for in a "person" tier ahead of agent "work" > - Subtasks of a person's task, and the parent's resume after its children complete, ranked as agent work > - Under load these runs started only through the 60-minute oldest-run share, so a half-finished task waited about 55 minutes per step behind newer tasks > - This pull request puts every non-recovery run on a task tree a person created in the person tier > - The benefit is that a person's started work finishes before newer work starts, and the fairness bounds stay in place ## Linked Issues or Issue Description **What existing behavior does this improve?** The order in which an agent at its concurrency limit starts queued runs. **Subsystem affected** Server heartbeat queue: `server/src/services/heartbeat/queued-run-dispatch-order.ts` and `queued-run-line.ts`. **Current behavior** A board user's new assignment ranks as person work. An agent's subtask of that person's task, and the parent's `issue_children_completed` resume, rank as agent work. In a restart chaos run with agents at capacity, the median queue wait of a parent resume was about 1,640 s. The median wait of a new assignment was about 190 to 290 s. One parent waited while 14 newer tasks started first. Subtasks and parent resumes started only near the 60-minute aging bound. **Proposed behavior** A non-recovery run on a task tree that a person created goes in the person tier. A task is in such a tree when the task, or any task above it, has `createdByUserId`. In the tier, runs keep the existing order: readiness, then priority, then age (oldest first). **Reason and benefit** A person waits on the whole tree, not only on the top task. Work that a person started now finishes before newer tasks take its slots. **Breaking changes** None. There is no schema or API change. ## What Changed - `queuedRunDispatchClass` puts a run with `personTask` in the person tier. System recovery stays in the recovery tiers, also on a person's tree. - `personTask` now means "the task, or a task above it, was created by a person". The existing `createdByUserId` marker is the source. - New `listPersonTreeIssueIds`: one recursive query per dispatch pass. It walks each queued task's parent chain through the `(company_id, id)` unique index. It stops at the first person-created task, at most 32 levels. It runs only when the agent has more than one queued run. The start-history read uses the same query in place of its old direct `createdByUserId` read, so the query count does not change there. - Recovery's 1-in-4 share is held only while a run a person asked for (`isPersonRequestedRun`) is ready, not for the rest of a person's tree. So a deep tree cannot hold recovery indefinitely. The dispatcher and the place-in-line replay use the same rule. - The claim backoff for a declined claim keeps the short person backoff only for runs a person asked for (unchanged behavior for tree runs). - `doc/heartbeat-internals.md`: new "Queued run dispatch order" section with the tiers, the order and the fairness bounds. Fairness bound: the oldest-run share is unchanged. Every 4th start goes to the longest-waiting ready run past 60 minutes, preferring runs people wait on. So another person's new task starts within 60 minutes plus 4 x (aged person-tier runs queued before it + 1) starts, even while a deep tree keeps adding in-progress or higher-priority work. A newer tree run never passes an older, equally ranked person task. Queues are per agent, and an agent belongs to one company, so no agent or company gets ahead of another. ## Verification - Red on master, green with this change: - `queued-run-dispatch-order.test.ts`: an older parent resume (`issue_children_completed`, person tree) starts before a newer person assignment. The place-in-line replay agrees. - `queued-run-dispatch-order.test.ts`: an older subtask of a person's task starts before a newer person assignment. - `queued-run-dispatch-order.test.ts`: fairness simulation. A deep tree adds two in-progress, higher-priority runs per start. Another person's new task starts within `QUEUED_RUN_AGING_MS` + `OLDEST_DISPATCH_SHARE` starts. - `execution-projection-agent-queue.test.ts` (embedded Postgres, real SQL): line is subtask (grandchild of a person's task), parent resume, newer person assignment, then work on an agent-created tree. Master gives the person assignment first and the tree runs last. - Negative and guard tests (green on both): work on an agent-created tree stays in the work tier behind a newer person assignment; system recovery on a person's tree stays in the recovery tier; newer tree work does not pass an older equally ranked person task; recovery still gets its share while only tree work waits. - Query plan on embedded Postgres with 300,000 issues and 200 queued tasks six levels deep: every step is an index scan on `issues_company_id_uq`, 1.5 ms execution. - `pnpm verify` exited 2 (a doc is a global CI input). Focused run: `queued-run-dispatch-order`, `queued-run-line`, `execution-projection-agent-queue`, `fresh-continuation-retry-delivery`, `assigned-work-stalled-queued-run`, `automatic-run-start-gate`, `automatic-run-brake-recovery-passes`, `heartbeat-stale-queue-invalidation`: 8 files, 173 tests passed. `tsc --noEmit` for the server passed. ## Risks - Behavior shift: in a company where people create most top-level tasks, most issue runs are now person tier. The "work" tier then holds agent-started trees, routines and runs without a task. Recovery keeps its share because only runs a person asked for hold it. - An in-progress run on a person's tree now ranks ahead of a new person task that is not in progress (readiness rank). The oldest-run share bounds that wait at about 60 minutes plus a few starts, the same bound agent work had before. - A tree deeper than 32 levels above a queued task is treated as not a person tree. It falls back to the work tier and the aging share. - The extra query runs only when an agent has more than one queued run, and only for queued tasks without `createdByUserId`. ## Model Used - Anthropic Claude Opus 5.5 (`claude-opus-5-5`), used through Claude Code with tool use and code 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 --- doc/heartbeat-internals.md | 44 +++++ .../heartbeat-person-tree-dispatch.test.ts | 158 ++++++++++++++++++ .../execution-projection-agent-queue.test.ts | 34 +++- server/src/services/heartbeat/queue.ts | 4 +- .../queued-run-dispatch-order.test.ts | 74 ++++++++ .../heartbeat/queued-run-dispatch-order.ts | 24 ++- .../src/services/heartbeat/queued-run-line.ts | 38 ++++- 7 files changed, 359 insertions(+), 17 deletions(-) create mode 100644 server/src/__tests__/heartbeat-person-tree-dispatch.test.ts diff --git a/doc/heartbeat-internals.md b/doc/heartbeat-internals.md index 59be8eafd62..174f167cd51 100644 --- a/doc/heartbeat-internals.md +++ b/doc/heartbeat-internals.md @@ -56,6 +56,50 @@ orphan recovery. pnpm exec vitest run server/src/services/heartbeat/agent-status.test.ts server/src/__tests__/heartbeat-agent-status-recovery.test.ts ``` +## Queued run dispatch order + +When an agent is at its concurrency limit, each freed slot starts the next +queued run chosen by `server/src/services/heartbeat/queued-run-dispatch-order.ts`. +The "place in line" a waiting task shows uses the same facts and order +(`queued-run-line.ts`). + +Runs fall into four tiers, started in this order: + +1. **Person.** A run a person asked for (an assignment, comment, chat message + or Retry by a board user, itself or through its source chain), and any other + non-recovery run on a task tree a person created. A task belongs to such a + tree when it, or any task above it, has `createdByUserId`. This covers an + agent's subtasks of a person's task and the parent's resume once they + complete (`issue_children_completed`), so a half-finished task is not left + behind newer tasks. +2. **Work.** Other agent work, such as a tree an agent or routine started. +3. **Recovery** and 4. **old recovery backlog.** System recovery wakes, even on + a person's tree. + +Within a tier, runs are ordered by readiness (in progress first), then task +priority, then age, oldest first. A newer run on a person's tree never passes +another person's equally ranked task that has waited longer. + +Fairness bounds: + +- **Oldest-run share.** Every `OLDEST_DISPATCH_SHARE` (4th) start goes to the + longest-waiting ready run that has waited past `QUEUED_RUN_AGING_MS` + (60 minutes), preferring runs people wait on. So even while a deep tree keeps + adding in-progress or higher-priority work, another person's new task starts + within 60 minutes plus 4 x (aged person-tier runs queued before it + 1) + starts. +- **Recovery share.** Recovery takes every `RECOVERY_DISPATCH_SHARE` (4th) + start from lower-tier work. It is held only while a run a person asked for is + ready, not for the rest of a person's tree, so a deep tree cannot hold + recovery indefinitely. +- **Scope.** Queues are per agent, and agents belong to one company, so tree + priority never moves one agent's or company's runs ahead of another's. + +Tree membership is read in one recursive query per dispatch pass, walking each +queued task's parent chain by the `(company_id, id)` unique index and stopping +at the first person-created task (at most 32 levels). It runs only when the +agent has more than one queued run. + ## Run history authorization reads Run history reuses the authorization service's batch read API for distinct task diff --git a/server/src/__tests__/heartbeat-person-tree-dispatch.test.ts b/server/src/__tests__/heartbeat-person-tree-dispatch.test.ts new file mode 100644 index 00000000000..f3fa82443c8 --- /dev/null +++ b/server/src/__tests__/heartbeat-person-tree-dispatch.test.ts @@ -0,0 +1,158 @@ +import { randomUUID } from "node:crypto"; +import { and, eq, inArray, sql } from "drizzle-orm"; +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; +import { agentWakeupRequests, agents, authUsers, companies, companyMemberships, createDb, heartbeatRuns, issues } from "@paperclipai/db"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; +import { heartbeatService } from "../services/heartbeat.ts"; +import { runningProcesses } from "../adapters/index.ts"; +import { automaticRunBrake } from "../services/recovery/automatic-run-brake.js"; +import { logger } from "../middleware/logger.js"; + +const gate = vi.hoisted(() => ({ open: false, releases: [] as Array<() => void> })); + +const mockAdapterExecute = vi.hoisted(() => vi.fn(async () => { + if (!gate.open) await new Promise(resolve => gate.releases.push(resolve)); + return { exitCode: 0, signal: null, timedOut: false, errorMessage: null, summary: "Person tree dispatch test run.", + provider: "test", model: "test-model" }; +})); + +vi.mock("../adapters/index.ts", async () => { + const actual = await vi.importActual("../adapters/index.ts"); + return { ...actual, getServerAdapter: vi.fn(() => ({ supportsLocalAgentJwt: false, execute: mockAdapterExecute })) }; +}); + +const support = await getEmbeddedPostgresTestSupport(); +const suite = support.supported ? describe : describe.skip; +const MINUTE = 60_000; + +suite("dispatch of work on a task tree a person created, through the heartbeat queue", () => { + let db!: ReturnType; + let temporary: Awaited> | null = null; + let heartbeat!: ReturnType; + const userId = randomUUID(); + + beforeAll(async () => { + temporary = await startEmbeddedPostgresTestDatabase("paperclip-person-tree-dispatch-"); + db = createDb(temporary.connectionString); + heartbeat = heartbeatService(db); + await db.insert(authUsers).values({ id: userId, name: "Board", email: `${userId}@example.test`, emailVerified: true, + createdAt: new Date(), updatedAt: new Date() }); + }, 60_000); + + afterEach(async () => { + gate.open = true; + for (const release of gate.releases.splice(0)) release(); + await heartbeat.drainActiveRunExecutions(); + gate.open = false; + mockAdapterExecute.mockClear(); + runningProcesses.clear(); + automaticRunBrake.reset(); + await db.execute(sql`truncate table ${companies} cascade`); + }, 180_000); + + afterAll(async () => { await db?.$client.end(); await temporary?.cleanup(); }, 120_000); + + async function seed() { + const companyId = randomUUID(), agentId = randomUUID(); + await db.insert(companies).values({ id: companyId, name: "Person tree", status: "active", + issuePrefix: `T${companyId.replaceAll("-", "").slice(0, 6).toUpperCase()}`, requireBoardApprovalForNewAgents: false, + defaultResponsibleUserId: userId }); + await db.insert(companyMemberships).values({ companyId, principalType: "user", principalId: userId, status: "active", + membershipRole: "owner" }); + await db.insert(agents).values({ id: agentId, companyId, name: "Codie", role: "engineer", status: "idle", + adapterType: "codex_local", adapterConfig: {}, permissions: {}, + runtimeConfig: { heartbeat: { enabled: true, intervalSec: 60, wakeOnDemand: true, maxConcurrentRuns: 1 } } }); + const [busy] = await db.insert(heartbeatRuns).values({ companyId, agentId, invocationSource: "automation", + triggerDetail: "system", status: "running", createdAt: new Date(Date.now() - 90 * MINUTE), + startedAt: new Date(Date.now() - 90 * MINUTE) }).returning(); + const task = async (input: { title: string; parentId?: string; byPerson: boolean; status?: string }) => { + const [row] = await db.insert(issues).values({ companyId, title: input.title, status: input.status ?? "todo", + assigneeAgentId: agentId, parentId: input.parentId ?? null, createdByUserId: input.byPerson ? userId : null, + createdByAgentId: input.byPerson ? null : agentId }).returning({ id: issues.id }); + return row!.id; + }; + const queue = async (issueId: string, wakeReason: string, ageMinutes: number, byPerson = false) => { + const createdAt = new Date(Date.now() - ageMinutes * MINUTE); + const [run] = await db.insert(heartbeatRuns).values({ companyId, agentId, issueId, scopeKind: "issue" as const, + invocationSource: byPerson ? "assignment" : "automation", triggerDetail: byPerson ? "manual" : "system", + status: "queued", createdAt, contextSnapshot: { wakeReason, issueId, taskId: issueId } }).returning(); + if (byPerson) { + const [wake] = await db.insert(agentWakeupRequests).values({ companyId, agentId, source: "assignment", reason: wakeReason, + status: "queued", requestedByActorType: "user", requestedByActorId: userId, runId: run!.id, requestedAt: createdAt, + createdAt }).returning({ id: agentWakeupRequests.id }); + await db.update(heartbeatRuns).set({ wakeupRequestId: wake!.id }).where(eq(heartbeatRuns.id, run!.id)); + } + return run!.id; + }; + const freeSlot = async () => { + await db.update(heartbeatRuns).set({ status: "succeeded", finishedAt: new Date() }).where(eq(heartbeatRuns.id, busy!.id)); + await heartbeat.resumeQueuedRunsAfterDrain({ companyId }); + }; + return { companyId, agentId, task, queue, freeSlot }; + } + + const statusOf = async (ids: string[]) => new Map((await db.select({ id: heartbeatRuns.id, status: heartbeatRuns.status, + startedAt: heartbeatRuns.startedAt }).from(heartbeatRuns).where(inArray(heartbeatRuns.id, ids))).map(row => [row.id, row])); + + async function expectStartsFirst(f: Awaited>, first: string, waiting: string) { + await heartbeat.resumeQueuedRunsAfterDrain({ companyId: f.companyId }); + expect([...(await statusOf([first, waiting])).values()].every(run => run.status === "queued")).toBe(true); + await f.freeSlot(); + await vi.waitFor(async () => expect((await statusOf([first])).get(first)?.status).toBe("running"), { timeout: 20_000 }); + const runs = await statusOf([first, waiting]); + expect(runs.get(first)?.startedAt).toBeInstanceOf(Date); + expect(runs.get(waiting)).toMatchObject({ status: "queued", startedAt: null }); + } + + it("starts an agent's subtask of a person's task before a newer assignment by a person when a slot frees", async () => { + const f = await seed(); + const root = await f.task({ title: "Person's task", byPerson: true, status: "blocked" }); + const subtask = await f.task({ title: "Agent's subtask", parentId: root, byPerson: false, status: "blocked" }); + const grandchild = await f.task({ title: "Agent's sub-subtask", parentId: subtask, byPerson: false }); + const subtaskRun = await f.queue(grandchild, "issue_assigned", 40); + const newAssignment = await f.queue(await f.task({ title: "New task", byPerson: true }), "issue_assigned", 5, true); + await expectStartsFirst(f, subtaskRun, newAssignment); + }, 120_000); + + it("starts a person's parent task's resume after its children complete before a newer assignment by a person", async () => { + const f = await seed(); + const parent = await f.task({ title: "Person's task", byPerson: true }); + await f.task({ title: "Done subtask", parentId: parent, byPerson: false, status: "done" }); + const resume = await f.queue(parent, "issue_children_completed", 30); + const newAssignment = await f.queue(await f.task({ title: "New task", byPerson: true }), "issue_assigned", 5, true); + await expectStartsFirst(f, resume, newAssignment); + }, 120_000); + + it("keeps an agent-started tree's subtask behind a newer assignment by a person", async () => { + const f = await seed(); + const root = await f.task({ title: "Agent's task", byPerson: false, status: "blocked" }); + const subtaskRun = await f.queue(await f.task({ title: "Agent's subtask", parentId: root, byPerson: false }), "issue_assigned", 40); + const newAssignment = await f.queue(await f.task({ title: "New task", byPerson: true }), "issue_assigned", 5, true); + await expectStartsFirst(f, newAssignment, subtaskRun); + }, 120_000); + + it("backs off a refused run on a person's tree like agent work, and offers it again once the backoff passes", async () => { + const f = await seed(); + await db.update(companies).set({ defaultResponsibleUserId: null }).where(eq(companies.id, f.companyId)); + await db.delete(companyMemberships).where(eq(companyMemberships.companyId, f.companyId)); + const root = await f.task({ title: "Person's task", byPerson: true, status: "blocked" }); + const refused = await f.queue(await f.task({ title: "Agent's subtask", parentId: root, byPerson: false }), "issue_assigned", 180); + await f.queue(await f.task({ title: "Another subtask", parentId: root, byPerson: false }), "issue_assigned", 170); + await db.update(heartbeatRuns).set({ status: "succeeded", finishedAt: new Date() }) + .where(and(eq(heartbeatRuns.companyId, f.companyId), eq(heartbeatRuns.status, "running"))); + const warn = vi.spyOn(logger, "warn"); + const offers = () => warn.mock.calls.filter(([fields, message]) => typeof message === "string" + && message.startsWith("long-queued heartbeat run was offered a free slot") + && (fields as { runId?: string }).runId === refused).length; + await heartbeat.resumeQueuedRunsForAgent(f.companyId, f.agentId); + expect(offers()).toBe(1); + await new Promise(resolve => setTimeout(resolve, 3_000)); + await heartbeat.resumeQueuedRunsForAgent(f.companyId, f.agentId); + expect(offers()).toBe(1); + await vi.waitFor(async () => { + await heartbeat.resumeQueuedRunsForAgent(f.companyId, f.agentId); + expect(offers()).toBe(2); + }, { timeout: 20_000, interval: 1_000 }); + expect((await statusOf([refused])).get(refused)?.status).toBe("queued"); + }, 120_000); +}); diff --git a/server/src/services/execution-projection-agent-queue.test.ts b/server/src/services/execution-projection-agent-queue.test.ts index ea86124347b..81dc9ce290f 100644 --- a/server/src/services/execution-projection-agent-queue.test.ts +++ b/server/src/services/execution-projection-agent-queue.test.ts @@ -1,7 +1,7 @@ import { randomUUID } from "node:crypto"; import { eq } from "drizzle-orm"; import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest"; -import { agents, companies, createDb, heartbeatRuns, issues } from "@paperclipai/db"; +import { agentWakeupRequests, agents, companies, createDb, heartbeatRuns, issues } from "@paperclipai/db"; import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../__tests__/helpers/embedded-postgres.js"; import { executionProjectionsForRuns } from "./execution-projection.js"; import { agentQueuedRunLine, clearAgentQueueLineCache, worktreeExecutionCutoff } from "./heartbeat/queued-run-line.js"; @@ -146,6 +146,38 @@ const minutesAgo = (minutes: number) => new Date(now.getTime() - minutes * 60_00 expect(elapsedMs).toBeLessThan(5_000); }); + it("starts work on a task tree a person created ahead of a newer person assignment, and leaves an agent's tree behind it", async () => { + const f = await fixture({ maxConcurrentRuns: 1, running: 1 }); + const task = async (input: { createdByUserId?: string; parentId?: string }) => { + const issueId = randomUUID(); + await db.insert(issues).values({ id: issueId, companyId: f.companyId, title: "Task", assigneeAgentId: f.agentId, status: "todo", + priority: "medium", parentId: input.parentId ?? null, createdByUserId: input.createdByUserId ?? null, + createdByAgentId: input.createdByUserId ? null : f.agentId }); + return issueId; + }; + const queueOn = async (issueId: string, wakeReason: string, createdMinutesAgo: number, byPerson = false) => { + const runId = randomUUID(); + const wakeupRequestId = byPerson ? randomUUID() : null; + if (wakeupRequestId) await db.insert(agentWakeupRequests).values({ id: wakeupRequestId, companyId: f.companyId, + agentId: f.agentId, source: "assignment", reason: wakeReason, requestedByActorType: "user", requestedByActorId: "board-user" }); + await db.insert(heartbeatRuns).values({ id: runId, companyId: f.companyId, agentId: f.agentId, status: "queued", issueId, + wakeupRequestId, createdAt: minutesAgo(createdMinutesAgo), contextSnapshot: { issueId, wakeReason } }); + return runId; + }; + const personRoot = await task({ createdByUserId: "board-user" }); + const child = await task({ parentId: personRoot }); + const grandchild = await task({ parentId: child }); + const agentRoot = await task({}); + const agentChild = await task({ parentId: agentRoot }); + const agentTreeWork = await queueOn(agentChild, "issue_assigned", 50); + const subtask = await queueOn(grandchild, "issue_assigned", 40); + const parentResume = await queueOn(personRoot, "issue_children_completed", 30); + const newAssignment = await queueOn(await task({ createdByUserId: "board-user" }), "issue_assigned", 5, true); + + const [agent] = await db.select().from(agents).where(eq(agents.id, f.agentId)); + expect(await agentQueuedRunLine(db, issueService(db), agent!, now)).toEqual([subtask, parentResume, newAssignment, agentTreeWork]); + }); + it("leaves running runs and other companies' runs out of the line", async () => { const f = await fixture({ maxConcurrentRuns: 1, running: 1 }); const mine = await f.queue({ priority: "medium", createdMinutesAgo: 5 }); diff --git a/server/src/services/heartbeat/queue.ts b/server/src/services/heartbeat/queue.ts index 74b219eb610..f104d29a928 100644 --- a/server/src/services/heartbeat/queue.ts +++ b/server/src/services/heartbeat/queue.ts @@ -12,7 +12,7 @@ import { hasAutomaticInteractionDeliveryHold, INTERACTION_DELIVERY_DENIED, reche import { deferredWorkIntentWait } from "../work-intent-outbox.js"; import { notifyIssueGraphRecovery } from "../issue-recovery-notifications.js"; import { createHeartbeatTimerPolicy } from "./timer-policy.js"; -import { QUEUED_RUN_AGING_MS, RECOVERY_WAKE_REASONS, createQueuedRunDispatcher, hasQueuedRunAged, queuedRunDispatchClass } from "./queued-run-dispatch-order.js"; +import { QUEUED_RUN_AGING_MS, RECOVERY_WAKE_REASONS, createQueuedRunDispatcher, hasQueuedRunAged, isPersonRequestedRun, queuedRunDispatchClass } from "./queued-run-dispatch-order.js"; import { reserveAutomaticRunStart } from "../recovery/automatic-run-brake.js"; import { queuedRunDispatchFacts } from "./queued-run-line.js"; import { notifyExecutionRunWork } from "../execution-control-notifications.js"; @@ -2527,7 +2527,7 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende claimed: (run: QueuedRunCandidate) => { const entry = byRun.get(run); if (entry) dispatcher.claimed(entry); }, personRun: (run: QueuedRunCandidate) => { const entry = byRun.get(run); - return Boolean(entry && queuedRunDispatchClass(entry, now) === "person"); + return Boolean(entry && queuedRunDispatchClass(entry, now) === "person" && isPersonRequestedRun(entry)); }, personOrigin: (run: QueuedRunCandidate) => personOriginChecked ? byRun.get(run)?.requestedByUser ?? false : undefined, }; diff --git a/server/src/services/heartbeat/queued-run-dispatch-order.test.ts b/server/src/services/heartbeat/queued-run-dispatch-order.test.ts index 3ae58093c2d..c29305247ed 100644 --- a/server/src/services/heartbeat/queued-run-dispatch-order.test.ts +++ b/server/src/services/heartbeat/queued-run-dispatch-order.test.ts @@ -208,6 +208,80 @@ describe("queued run dispatch order", () => { }); }); +describe("work on a task tree a person created", () => { + const newAssignment = (createdMinutesAgo: number) => run({ wakeReason: "issue_assigned", requestedByUser: true, + readinessRank: 1, createdAt: minutesAgo(createdMinutesAgo) }); + const first = (queue: QueuedRunDispatchFacts[]) => { + const input = { now, startsSinceRecovery: 0, startsSinceOldest: 0 }; + const [next] = orderQueuedRunsForDispatch(queue, input); + expect(queuedRunDispatchLine(queue, input)[0]!.id).toBe(next!.id); + return next!; + }; + + it("starts the parent's resume after its children complete ahead of a newer assignment by a person", () => { + const resume = run({ wakeReason: "issue_children_completed", personTask: true, readinessRank: 1, createdAt: minutesAgo(20) }); + const assignment = newAssignment(10); + expect(queuedRunDispatchClass(resume, now)).toBe("person"); + expect(first([assignment, resume]).id).toBe(resume.id); + }); + + it("starts a subtask of a person's task ahead of a newer assignment by a person", () => { + const subtask = run({ wakeReason: "issue_assigned", personTask: true, readinessRank: 1, createdAt: minutesAgo(20) }); + const assignment = newAssignment(10); + expect(first([assignment, subtask]).id).toBe(subtask.id); + }); + + it("keeps work on a tree an agent started in the work tier, behind a newer assignment by a person", () => { + const agentTree = run({ wakeReason: "issue_children_completed", readinessRank: 1, createdAt: minutesAgo(20) }); + const assignment = newAssignment(10); + expect(queuedRunDispatchClass(agentTree, now)).toBe("work"); + expect(first([agentTree, assignment]).id).toBe(assignment.id); + }); + + it("keeps system recovery on a person's tree in the recovery tier", () => { + const recovery = run({ wakeReason: "issue_continuation_needed", personTask: true, sourceEndedAt: minutesAgo(5), + createdAt: minutesAgo(4) }); + expect(queuedRunDispatchClass(recovery, now)).toBe("recovery"); + }); + + it("starts another person's new task within the oldest-run share while a deep tree keeps adding in-progress work", () => { + const start = new Date(now.getTime() - 2 * 60 * 60_000); + const at = (minutes: number) => new Date(start.getTime() + minutes * 60_000); + let id = 0; + const treeRun = (minutes: number) => ({ id: `tree-${++id}`, wakeReason: "issue_commented", requestedByUser: false, + personTask: true, sourceEndedAt: null, readinessRank: 0, priorityRank: 1, createdAt: at(minutes) }); + const otherPerson = { ...newAssignment(0), createdAt: at(0) }; + let pending: QueuedRunDispatchFacts[] = [otherPerson, ...Array.from({ length: 10 }, () => treeRun(0))]; + const started: QueuedRunDispatchFacts[] = []; + // One start a minute, and the tree adds two higher-ranked runs for every one that starts. + for (let minute = 0; minute < 120 && !started.includes(otherPerson); minute += 1) { + pending.push(treeRun(minute), treeRun(minute)); + const clock = at(minute); + const history = [...started].reverse().map(entry => queuedRunStartOf(entry, clock)); + const [next] = orderQueuedRunsForDispatch(pending, { now: clock, ...dispatchCountersFromStarts(pending, history, clock) }); + started.push(next!); + pending = pending.filter(entry => entry.id !== next!.id); + } + const position = started.indexOf(otherPerson); + expect(position).toBeGreaterThanOrEqual(0); + expect(position).toBeLessThan(QUEUED_RUN_AGING_MS / 60_000 + OLDEST_DISPATCH_SHARE); + }); + + it("never lets newer tree work pass another person's waiting task of the same rank", () => { + const otherPerson = newAssignment(5); + const tree = Array.from({ length: 20 }, (_, index) => run({ wakeReason: "issue_assigned", personTask: true, readinessRank: 1, + createdAt: minutesAgo(4 - index * 0.1) })); + expect(first([...tree, otherPerson]).id).toBe(otherPerson.id); + }); + + it("does not hold recovery's share for tree work a person did not ask for", () => { + const recovery = run({ wakeReason: "issue_recovery_action_restored", createdAt: minutesAgo(3), sourceEndedAt: minutesAgo(4) }); + const tree = Array.from({ length: 5 }, () => run({ wakeReason: "issue_assigned", personTask: true, createdAt: minutesAgo(2) })); + const ordered = orderQueuedRunsForDispatch([...tree, recovery], { now, startsSinceRecovery: RECOVERY_DISPATCH_SHARE - 1 }); + expect(ordered[0]!.id).toBe(recovery.id); + }); +}); + describe("deep per-agent queue: a recovery burst behind 20 busy slots (paperclip.staging, 2026-11-13)", () => { // Codie, maxConcurrentRuns 20, every slot busy: each freed slot is one dispatch. const at = new Date("2026-11-13T14:30:00.000Z"); diff --git a/server/src/services/heartbeat/queued-run-dispatch-order.ts b/server/src/services/heartbeat/queued-run-dispatch-order.ts index 0aef1f561c5..8f8012faa7a 100644 --- a/server/src/services/heartbeat/queued-run-dispatch-order.ts +++ b/server/src/services/heartbeat/queued-run-dispatch-order.ts @@ -27,7 +27,10 @@ export type QueuedRunDispatchFacts = { readinessRank: number; priorityRank: number; shareDeferred?: boolean; - /** The task was created by a person, who waits on its outcome whichever system wake moves it. */ + /** + * The task, or a task above it, was created by a person, who waits on the + * whole tree's outcome whichever wake moves it. + */ personTask?: boolean; }; @@ -41,12 +44,16 @@ export function isSystemRecoveryRun(run: Pick) { + return run.requestedByUser || Boolean(run.wakeReason && PERSON_WAKE_REASONS.has(run.wakeReason)); +} + export function queuedRunDispatchClass(run: QueuedRunDispatchFacts, now: Date): QueuedRunDispatchClass { if (isSystemRecoveryRun(run)) { const endedAt = run.sourceEndedAt ?? run.createdAt; return now.getTime() - endedAt.getTime() > RECOVERY_BACKLOG_AGE_MS ? "recovery_backlog" : "recovery"; } - if (run.requestedByUser || (run.wakeReason && PERSON_WAKE_REASONS.has(run.wakeReason))) return "person"; + if (isPersonRequestedRun(run) || run.personTask) return "person"; return "work"; } @@ -59,7 +66,8 @@ const NOT_READY_TIER = 4; const isReady = (run: QueuedRunDispatchFacts) => run.readinessRank < NOT_READY_RANK; const isPersonRun = (run: QueuedRunDispatchFacts, now: Date) => queuedRunDispatchClass(run, now) === "person"; -/** A run a person asked for, or any run on a task a person created. */ +const holdsRecoveryShare = (run: QueuedRunDispatchFacts) => isReady(run) && !isSystemRecoveryRun(run) && isPersonRequestedRun(run); +/** A run a person asked for, or any run on a task tree a person created. */ const isPersonWaitingRun = (run: QueuedRunDispatchFacts, now: Date) => Boolean(run.personTask) || isPersonRun(run, now); const isOldestShareEligible = (run: QueuedRunDispatchFacts) => isReady(run) && !run.shareDeferred; @@ -107,7 +115,7 @@ export type QueuedRunStart = { wakeReason: string | null; createdAt: Date; start /** A dispatched run as the start history records it. */ export function queuedRunStartOf(run: QueuedRunDispatchFacts, now: Date): QueuedRunStart { - return { wakeReason: run.wakeReason, createdAt: run.createdAt, personOrigin: isPersonRun(run, now), + return { wakeReason: run.wakeReason, createdAt: run.createdAt, personOrigin: !isSystemRecoveryRun(run) && isPersonRequestedRun(run), personWaiting: isPersonWaitingRun(run, now) }; } @@ -185,8 +193,8 @@ export function createQueuedRunDispatcher( if (!remaining.length) return null; const oldest = sinceOldest >= OLDEST_DISPATCH_SHARE - 1 ? oldestShareCandidate(remaining, input.now) : null; if (oldest) return remaining.splice(remaining.indexOf(oldest), 1)[0]!; - // Recovery's share comes out of agent work, never out of a person's turn. - const personWaiting = remaining.some(run => isReady(run) && isPersonRun(run, input.now)); + // Recovery's share comes out of agent work, never out of the turn of a run a person asked for. + const personWaiting = remaining.some(holdsRecoveryShare); // The share goes to the longest-waiting recovery run once one has waited // past the aging bound, so fresh recovery cannot keep an old one waiting. const agedRecovery = oldestReadyQueuedRun(remaining, run => isSystemRecoveryRun(run) && hasQueuedRunAged(run, input.now)); @@ -254,7 +262,7 @@ export function queuedRunDispatchLine( const oldestRecovery = agedFirst(cursor(byAge(indexes(run => isOldestShareEligible(run) && isSystemRecoveryRun(run))))); const firstRecovery = cursor(indexes(run => isReady(run) && isSystemRecoveryRun(run))); const head = cursor(order.map((_, index) => index)); - let readyPeople = order.filter(run => isReady(run) && isPersonRun(run, now)).length; + let readyPeople = order.filter(holdsRecoveryShare).length; let sinceRecovery = input.startsSinceRecovery; let sinceOldest = input.startsSinceOldest ?? 0; const result: T[] = []; @@ -268,7 +276,7 @@ export function queuedRunDispatchLine( if (pick < 0) pick = head(); removed[pick] = 1; const run = order[pick]!; - if (isReady(run) && isPersonRun(run, now)) readyPeople -= 1; + if (holdsRecoveryShare(run)) readyPeople -= 1; result.push(run); sinceRecovery = isSystemRecoveryRun(run) ? 0 : sinceRecovery + 1; sinceOldest = candidate < 0 || servesOldestShare({ createdAt: run.createdAt, personWaiting: isPersonWaitingRun(run, now) }, diff --git a/server/src/services/heartbeat/queued-run-line.ts b/server/src/services/heartbeat/queued-run-line.ts index 573b7e3e348..955eb454f1a 100644 --- a/server/src/services/heartbeat/queued-run-line.ts +++ b/server/src/services/heartbeat/queued-run-line.ts @@ -90,6 +90,28 @@ export async function listPersonOriginSourceRunIds(db: Db, companyId: string, so return [...result].map(row => String(row.root_id)); } +const PERSON_TREE_ANCESTOR_DEPTH = 32; + +export async function listPersonTreeIssueIds(db: Db, companyId: string, issueIds: string[]): Promise> { + const ids = [...new Set(issueIds.filter(id => RUN_ID_PATTERN.test(id)))]; + if (!ids.length) return new Set(); + const result = await db.execute<{ issue_id: string }>(sql` + with recursive chain(issue_id, ancestor_id, depth) as ( + select ${issues.id}, ${issues.id}, 0 from ${issues} + where ${issues.companyId} = ${companyId} and ${issues.id} in (${sql.join(ids.map(id => sql`${id}::uuid`), sql`, `)}) + union all + select chain.issue_id, ancestor.parent_id, chain.depth + 1 + from chain + join ${issues} ancestor on ancestor.id = chain.ancestor_id + where ancestor.company_id = ${companyId} and ancestor.created_by_user_id is null + and chain.depth < ${PERSON_TREE_ANCESTOR_DEPTH} + ) + select distinct chain.issue_id from chain + join ${issues} ancestor on ancestor.id = chain.ancestor_id + where ancestor.company_id = ${companyId} and ancestor.created_by_user_id is not null`); + return new Set([...result].map(row => String(row.issue_id))); +} + /** * The facts and share counters the queued-run dispatcher orders an agent's * queued runs by. The dispatch path and the "position in line" a waiting task @@ -146,8 +168,15 @@ export async function queuedRunDispatchFacts( const sourceRunId = sourceRunIdOf(run); return Boolean(sourceRunId && personSourceRunIds.has(sourceRunId)); }; + const issueIdOf = (run: R) => readNonEmptyString(parseObject(run.contextSnapshot).issueId); + const personTreeIssueIds = personOriginChecked + ? await listPersonTreeIssueIds(db, agent.companyId, queuedRuns.flatMap(run => { + const issueId = issueIdOf(run); + return issueId && issueById.has(issueId) && !issueById.get(issueId)?.createdByUserId ? [issueId] : []; + })) + : new Set(); const facts = queuedRuns.map(run => { - const issueId = readNonEmptyString(parseObject(run.contextSnapshot).issueId); + const issueId = issueIdOf(run); const ready = issueId ? (dependencyReadiness.get(issueId)?.isDependencyReady ?? true) : true; const issue = issueId ? issueById.get(issueId) : null; const sourceRunId = sourceRunIdOf(run); @@ -161,7 +190,7 @@ export async function queuedRunDispatchFacts( readinessRank: issueId ? (ready ? (issue?.status === "in_progress" ? 0 : 1) : 3) : 2, priorityRank: issueRunPriorityRank(issue?.priority), shareDeferred: input.shareDeferred?.(run.id) ?? false, - personTask: Boolean(issue?.createdByUserId), + personTask: Boolean(issue?.createdByUserId) || Boolean(issueId && personTreeIssueIds.has(issueId)), }; }); const since = dispatchHistoryStart(facts, now); @@ -178,10 +207,7 @@ export async function queuedRunDispatchFacts( const personStarts = new Set(startRows.length ? await listPersonOriginSourceRunIds(db, agent.companyId, startRows.map(row => row.id)) : []); const startedTaskIds = [...new Set(startRows.flatMap(row => row.issueId && RUN_ID_PATTERN.test(row.issueId) ? [row.issueId] : []))]; - const personTaskIds = new Set(startedTaskIds.length - ? (await db.select({ id: issues.id }).from(issues).where(and(eq(issues.companyId, agent.companyId), - inArray(issues.id, startedTaskIds), isNotNull(issues.createdByUserId)))).map(row => row.id) - : []); + const personTaskIds = await listPersonTreeIssueIds(db, agent.companyId, startedTaskIds); const recentStarts = startRows.map(row => ({ ...row, personOrigin: personStarts.has(row.id), personWaiting: personStarts.has(row.id) || Boolean(row.issueId && personTaskIds.has(row.issueId)) })); const { startsSinceRecovery, startsSinceOldest } = dispatchCountersFromStarts(facts, recentStarts, now); From 93111b175ba07ff4f1536f2bbc574c8edf8ad549 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Mon, 16 Nov 2026 10:37:46 -0600 Subject: [PATCH 5/6] fix(wake-queue): keep the child-completion reason when a person's comment merges into its held wake (#21918) 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 wake queue holds new work for a task while an agent run is active. A later wake for the same task merges into the held wake > - A parent task must not finish while a finished child's result is still waiting for a parent turn. The finish gate checks for this pending child result > - The gate finds the held child-completion wake by its context wake reason > - When a person's comment merged into that held wake, the merge replaced the wake reason with `issue_commented`. The gate then did not see the pending child result > - This pull request keeps every merged reason in the held wake and makes the gate read that list > - The benefit is that a merge keeps the meaning of both wakes: the comment is delivered, and the pending child result still blocks a premature finish ## Linked Issues or Issue Description Refs #21914 **What happened?** A restart test held a child-completion wake behind a running parent run. A person then posted a comment. The comment wake merged into the held wake. After the merge, the held wake's `_paperclipWakeContext.wakeReason` was `issue_commented`, not `issue_children_completed`. `hasPendingNativeChildCompletion` matches held wakes by that field only. So the finish gate could no longer see the pending child result. **Expected behavior** The held wake keeps both reasons. The finish gate still sees the pending child result. The next run still receives the person's comment. **Steps to reproduce** 1. Start a run for a parent task. 2. Hold a child-completion wake behind the run. 3. Post a person's comment on the parent. The comment wake merges into the held wake. 4. Call `hasPendingNativeChildCompletion` for the running parent run. It returns `false`. **Paperclip version or commit** `master` at 20b0d4e5a5. **Relevant logs or output** The suspected effect on finish timing in the test run was not real. The two rejected finish calls failed for other reasons: the first had invalid tool input (a missing `remainingWork` field) and the second had no accessible deliverable. Both happened before the comment merge. Also, the run had already read the finished child before the merge, so the gate was already satisfied for that child. The gap is real for a run that has not read the child yet. The new test proves it. ## What Changed - `admitWakeBehindIssueExecution` records `wakeReasons` in the merged held-wake context when two different reasons merge. `wakeReason` keeps the latest reason, as before, so comment delivery and person-wake handling do not change. - New `withMergedWakeReasons` helper in the wake-queue domain context module. - `hasPendingNativeChildCompletion` matches a held wake when `wakeReason` is `issue_children_completed` or when `wakeReasons` contains it. - New embedded-Postgres test in `heartbeat-comment-wake-batching.test.ts`: a child-completion wake is held behind a running parent, then a person's comment merges in. The gate still sees the pending child result, and the next run receives the comment. ## Verification - `cd server && npx vitest run src/__tests__/heartbeat-comment-wake-batching.test.ts src/__tests__/native-child-task-read-routes.test.ts src/modules/wake-queue` passes (16 files, 400 tests). This includes both #21914 reopen tests. - `cd server && npx vitest run src/__tests__/native-status-arbiter-corpus.test.ts src/services/workspace-recovery-admission.test.ts src/__tests__/heartbeat-held-comment-wake.test.ts` passes (343 tests). - `cd server && npx tsc --noEmit` passes. - Red check: with only the source change reverted, the new test fails. The merged context has no `wakeReasons`, and the gate check after the merge fails with `expected false to be true`. - `pnpm verify` exits 2 (an opaque setup dependency). Required CI supplies broad coverage. ## Risks - Low risk. The change adds one context key on merged held wakes and widens one gate query. `wakeReason` does not change. - A wider gate can hold a parent finish for a child result that a merge used to hide. That is the intended behavior. The gate still ignores a child result that the run already read. > 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 - Anthropic Claude Opus 5.5 (`claude-opus-5-5`), used through Claude Code with tool use (shell, file edits, test runs). ## 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 --- .../heartbeat-comment-wake-batching.test.ts | 45 ++++++++++++++++++- .../wake-queue/application/use-cases.ts | 14 +++--- .../src/modules/wake-queue/domain/context.ts | 17 +++++++ .../native-child-completion-delivery.ts | 3 +- 4 files changed, 72 insertions(+), 7 deletions(-) diff --git a/server/src/__tests__/heartbeat-comment-wake-batching.test.ts b/server/src/__tests__/heartbeat-comment-wake-batching.test.ts index 77a75841b62..2e7c35ed30b 100644 --- a/server/src/__tests__/heartbeat-comment-wake-batching.test.ts +++ b/server/src/__tests__/heartbeat-comment-wake-batching.test.ts @@ -33,6 +33,7 @@ import { } from "@paperclipai/db"; import { runningProcesses } from "../adapters/index.js"; import { heartbeatService } from "../services/heartbeat.ts"; +import { hasPendingNativeChildCompletion } from "../services/native-runtime/native-child-completion-delivery.js"; import { issueThreadInteractionService } from "../services/issue-thread-interactions.js"; import { isRetiredExternalChatQuestionSource, questionResponseDeliveryService } from "../services/question-response-delivery.js"; import { SUCCESSFUL_RUN_HANDOFF_REQUIRED_NOTICE_BODY } from "../services/recovery/index.ts"; @@ -2207,7 +2208,8 @@ describeEmbeddedPostgres("heartbeat comment wake batching", () => { const childCompletionIntentId = randomUUID(); const childCompletionWakeId = randomUUID(); - const childCompletionContext = { issueId, taskId: issueId, wakeReason: "issue_children_completed" }; + const childCompletionContext = { issueId, taskId: issueId, wakeReason: "issue_children_completed", + nativeChildCompletionDecisionId: randomUUID(), completedChildIssueId: randomUUID() }; await db.insert(agentWakeupRequests).values([{ id: childCompletionIntentId, companyId, agentId, source: "automation", triggerDetail: "system", reason: "issue_children_completed", status: "coalesced", @@ -2239,6 +2241,47 @@ describeEmbeddedPostgres("heartbeat comment wake batching", () => { }, 90_000); } + it("keeps a pending child completion visible to the finish gate after a person's comment merges into its deferred wake", async () => { + const gateway = await createControlledGatewayServer(); + try { + const { companyId, agentId, issueId, heartbeat, firstRun, childCompletionWakeId } = + await startAssignedRunWithDeferredChildCompletion({ gateway, title: "Child result and person comment behind a run" }); + const pendingChildCompletion = () => hasPendingNativeChildCompletion(db, { + companyId, issueId, agentId, runId: firstRun.id, sourceIntentId: null, + }); + expect(await pendingChildCompletion()).toBe(true); + + const personComment = await db.insert(issueComments) + .values(wakeUserCommentRow(companyId, issueId, "user-1", "Also include the summary table")) + .returning().then((rows) => rows[0]); + expect(await heartbeat.wakeup(agentId, { + source: "automation", triggerDetail: "system", reason: "issue_commented", + payload: { issueId, commentId: personComment.id }, + contextSnapshot: { issueId, taskId: issueId, commentId: personComment.id, wakeCommentId: personComment.id, + wakeReason: "issue_commented" }, + requestedByActorType: "user", requestedByActorId: "user-1", + })).toBeNull(); + const merged = await selectDeferredWakeForAgent(companyId, agentId); + expect(merged?.id).toBe(childCompletionWakeId); + expect((merged?.payload as Record)._paperclipWakeContext).toMatchObject({ + wakeReason: "issue_commented", + wakeReasons: ["issue_children_completed", "issue_commented"], + wakeCommentIds: [personComment.id], + }); + expect(await pendingChildCompletion()).toBe(true); + + await closeIssueAndFinishFirstRun(gateway, issueId, firstRun.id); + await waitFor(() => gateway.getAgentPayloads().length >= 2, 90_000); + const runs = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.agentId, agentId)) + .orderBy(asc(heartbeatRuns.createdAt)); + expect(runs[1]?.wakeupRequestId).toBe(childCompletionWakeId); + expect(String(gateway.getAgentPayloads()[1]?.message ?? "")).toContain("Also include the summary table"); + } finally { + gateway.releaseFirstWait(); + await gateway.close(); + } + }, 120_000); + it("reopens a finished task when a person's comment joined a deferred system wake during the run", async () => { const gateway = await createControlledGatewayServer(); try { diff --git a/server/src/modules/wake-queue/application/use-cases.ts b/server/src/modules/wake-queue/application/use-cases.ts index f10416fe4c8..fb6a31c0f61 100644 --- a/server/src/modules/wake-queue/application/use-cases.ts +++ b/server/src/modules/wake-queue/application/use-cases.ts @@ -1,5 +1,5 @@ import { readWakeChatConversationId } from "../../run-dispatch/index.js"; -import { enrichPromotedWakeContext, wakeMustNotJoinActiveRun } from "../domain/context.js"; +import { enrichPromotedWakeContext, wakeMustNotJoinActiveRun, withMergedWakeReasons } from "../domain/context.js"; import { QUEUED_MESSAGES_DELIVERED_REASON } from "../domain/policy.js"; import { decideQueuedCommentAction, @@ -979,12 +979,16 @@ export function createAdmitWakeBehindIssueExecution(deps: { }); if (existingDeferred && !existingDeferred.payload?.interactionId && !existingDeferred.deferredContext.interactionId) { - const mergedDeferredContext = deps.helpers.mergeCoalescedContextSnapshot( + const mergedDeferredContext = withMergedWakeReasons( + deps.helpers.mergeCoalescedContextSnapshot( + existingDeferred.deferredContext, + input.contextSnapshot, + { + preserveExistingInteractionContinuation: true, + }, + ), existingDeferred.deferredContext, input.contextSnapshot, - { - preserveExistingInteractionContinuation: true, - }, ); const mergedPayload = { ...existingDeferred.payload, diff --git a/server/src/modules/wake-queue/domain/context.ts b/server/src/modules/wake-queue/domain/context.ts index 7ce30654bdd..51a7c6e91f7 100644 --- a/server/src/modules/wake-queue/domain/context.ts +++ b/server/src/modules/wake-queue/domain/context.ts @@ -89,6 +89,23 @@ export function wakeMustNotJoinActiveRun( wakeChatConversationsConflict(activeRunContext, wakeContext); } +const WAKE_REASONS_KEY = "wakeReasons"; + +function readWakeReasons(context: unknown): string[] { + const parsed = parseObject(context); + const listed = Array.isArray(parsed[WAKE_REASONS_KEY]) ? parsed[WAKE_REASONS_KEY] as unknown[] : []; + return [...listed, parsed.wakeReason].flatMap((value) => readNonEmptyString(value) ?? []); +} + +export function withMergedWakeReasons( + merged: Record, + existing: unknown, + incoming: unknown, +): Record { + const reasons = [...new Set([...readWakeReasons(existing), ...readWakeReasons(incoming)])]; + return reasons.length > 1 ? { ...merged, [WAKE_REASONS_KEY]: reasons } : merged; +} + export function hasRetainedExternalChatRetry(context: unknown): boolean { const active = parseObject(context); const activeSource = readNonEmptyString(active.source); diff --git a/server/src/services/native-runtime/native-child-completion-delivery.ts b/server/src/services/native-runtime/native-child-completion-delivery.ts index 0ae2377fd5c..7d367edfa59 100644 --- a/server/src/services/native-runtime/native-child-completion-delivery.ts +++ b/server/src/services/native-runtime/native-child-completion-delivery.ts @@ -34,7 +34,8 @@ export async function hasPendingNativeChildCompletion(db: Db, input: NativeChild eq(agentWakeupRequests.agentId, input.agentId), or(eq(agentWakeupRequests.reason, "issue_children_completed"), and(eq(agentWakeupRequests.reason, "issue_execution_deferred"), - sql`${agentWakeupRequests.payload}->'_paperclipWakeContext'->>'wakeReason' = 'issue_children_completed'`)), + sql`(${agentWakeupRequests.payload}->'_paperclipWakeContext'->>'wakeReason' = 'issue_children_completed' + or ${agentWakeupRequests.payload}->'_paperclipWakeContext'->'wakeReasons' @> '["issue_children_completed"]'::jsonb)`)), eq(agentWakeupRequests.requestedByActorType, "system"), or(eq(agentWakeupRequests.requestedByActorId, "native-status-committer"), sql`${agentWakeupRequests.requestedByActorId} like 'native-status-wake-dispatch:%'`), From d16c06308d6e4eaad91f251b4de258f17ec23784 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Mon, 16 Nov 2026 11:37:20 -0600 Subject: [PATCH 6/6] perf(release): number canaries by master position and confirm them outside the release lock (#21917) 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 > - Every master push runs a canary, and only one canary at a time may run the release workflow > - After #21554 and #21555 a canary held that lock for 35.5 min, and 13-16 min of it was waiting for npm to show the new packages > - The wait was required: the next canary computed `canary.N` from npm's version list, so starting before npm showed the previous canary would reuse its number > - This pull request numbers a canary by its commit's position on master and moves the registry confirmation, the git tag, the Docker dispatch and the onboarding smoke to a separate `canary-finalize.yml` run > - The benefit is that the release lock is held for about 20-25 min per canary instead of 35, with the same checks before a canary is tagged ## Linked Issues or Issue Description **What existing behavior does this improve?** Canary throughput. In run 43715037497 (2026-11-15) `publish_canary` took 23.7 min, and 13.3 min of that was "Waiting for registry visibility" (13:08:50 to 13:22:11). The next canary could not start until that run ended. **Current behavior** `release.sh canary` sets `N` to (highest published `-canary.N` for today) + 1, then publishes, waits for npm to show every package, checks dist-tags, installs `paperclipai@canary`, and creates `canary/v`. `publish_canary` pushes the tag, dispatches `docker.yml`, and `smoke_canary_onboarding` runs in the same run. **Proposed behavior** `N` = `git rev-list --count HEAD` (full history required), or the registry number + 1 when that is higher (a rerun of the same commit). `release.sh canary --defer-registry-confirmation` ends after npm accepts every publish. `publish_canary` dispatches `canary-finalize.yml`, which does the confirmation, tag, Docker dispatch and smoke outside the release lock. Nightly, beta and stable numbering and flow are unchanged. Refs #21554, #21555 ## What Changed - `scripts/release-lib.sh`: `next_canary_version_from_source`. A publishing canary refuses a shallow checkout; a dry run (the PR Canary Dry Run job) falls back to the registry number. - `scripts/release.sh`: canary uses the new number; new canary-only `--defer-registry-confirmation` flag skips the registry wait, the dist-tag check and the local tag, and writes the version to `PAPERCLIP_RELEASE_VERSION_FILE`. - `scripts/confirm-canary-publication.sh` (new): waits for registry visibility, checks provenance, checks dist-tags with `--allow-newer-canary`, installs `paperclipai@`, then creates and pushes `canary/v`. A tag already on the same commit is accepted, so reruns are safe. - `scripts/verify-canary-provenance.mjs` (new): every package's npm SLSA provenance must name `.github/workflows/release.yml` on `refs/heads/master` in `paperclipai/paperclip` at the source commit. A dispatch with invented inputs cannot tag anything. - `scripts/verify-release-registry-state.mjs`: `--allow-newer-canary` accepts a `canary` dist-tag that a newer canary already moved; older, foreign or missing tags still fail. - `.github/workflows/canary-finalize.yml` (new, `workflow_dispatch`, master only): `confirm_canary` (contents: write, actions: write) and `smoke_canary_onboarding` (downloads the publisher's lockfile artifact by run id). Inputs reach shell steps only through a validating step. - `.github/workflows/release.yml`: `publish_canary` hands off to `canary-finalize.yml` and drops to `contents: read`; its tag push, Docker dispatch and smoke job move to `canary-finalize.yml`. - Tests and `doc/RELEASING.md`. ## Verification - `node --test .github/scripts/tests/*.test.mjs scripts/release-lib.test.mjs scripts/verify-release-registry-state.test.mjs scripts/verify-canary-provenance.test.mjs`: 846 pass. `scripts/__tests__/release-verify-workflow.test.mjs`: 73 pass. - New tests: numbering by master position, rerun moves past a published number, shallow refusal and dry-run fallback; newer/older/foreign dist-tags; provenance from another commit, workflow, branch, repository or package is rejected; finalize wiring, permissions and input handling. - Real npm data: `verify-canary-provenance.mjs 2026.1116.0-canary.7 b4fa1c7f... paperclipai @paperclipai/shared @paperclipai/server` passes; the same version with another commit fails. - `confirm-canary-publication.sh 2026.1116.0-canary.7 b4fa1c7f...` from a checkout of that commit ran all steps against npm in 61 s and ended with "canary/v2026.1116.0-canary.7 already points at b4fa1c7f...", pushing nothing. - `release.sh canary --dry-run --defer-registry-confirmation` and `release.sh nightly --defer-registry-confirmation` both stop with "only applies to a published canary". - `actionlint` reports no new findings compared with master. - Not verified before merge: a full publish through `canary-finalize.yml`. It can run only from master. The first canary after merge is the check. ## Risks - Canary numbers jump from `canary.7` to about `canary.8144` (master has 8,143 commits). This is valid semver and still higher than every earlier canary; users install through the `canary` dist-tag. - The `canary/v` tag, Docker image and smoke now finish after the release run ends. Nightly selects only tagged canaries, as before. If finalize fails, that canary is on npm without a tag, so nightly skips it, as it skips any canary whose old in-run verification failed. - A canary can now publish while the previous one is still being confirmed. Publishing itself is still serialized, so the `canary` dist-tag only moves forward. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, in Claude Code with tool use and code 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 - [ ] 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/canary-finalize.yml | 151 ++++++++++++++++++ .github/workflows/docker.yml | 4 +- .github/workflows/pr-trusted.yml | 5 +- .github/workflows/release.yml | 106 ++---------- doc/RELEASING.md | 28 ++-- .../__tests__/release-dry-run-notes.test.mjs | 1 + .../release-verify-workflow.test.mjs | 113 ++++++------- scripts/confirm-canary-publication.sh | 65 ++++++++ scripts/release-lib.sh | 83 ++++++++++ scripts/release-lib.test.mjs | 91 +++++++++++ scripts/release.sh | 45 ++++-- scripts/verify-canary-provenance.mjs | 102 ++++++++++++ scripts/verify-canary-provenance.test.mjs | 73 +++++++++ scripts/verify-release-registry-state.mjs | 29 +++- .../verify-release-registry-state.test.mjs | 25 +++ 15 files changed, 742 insertions(+), 179 deletions(-) create mode 100644 .github/workflows/canary-finalize.yml create mode 100755 scripts/confirm-canary-publication.sh create mode 100644 scripts/verify-canary-provenance.mjs create mode 100644 scripts/verify-canary-provenance.test.mjs diff --git a/.github/workflows/canary-finalize.yml b/.github/workflows/canary-finalize.yml new file mode 100644 index 00000000000..5950c076d2f --- /dev/null +++ b/.github/workflows/canary-finalize.yml @@ -0,0 +1,151 @@ +name: Canary finalize +run-name: Canary finalize ${{ inputs.version }} + +on: + workflow_dispatch: + inputs: + version: + description: Canary version that publish_canary published + required: true + type: string + source_sha: + description: Full source commit SHA of that canary + required: true + type: string + release_run_id: + description: Release workflow run that published it + required: true + type: string + +permissions: {} + +concurrency: + group: canary-finalize-${{ inputs.version }} + cancel-in-progress: false + +env: + NPM_PUBLISH_VERIFY_ATTEMPTS: "180" + NPM_PUBLISH_VERIFY_DELAY_SECONDS: "10" + +jobs: + confirm_canary: + name: Confirm canary on npm and tag it + if: github.repository == 'paperclipai/paperclip' && github.repository_id == '1170821064' && github.ref == 'refs/heads/master' + runs-on: ubuntu-latest + timeout-minutes: 45 + permissions: + contents: write + actions: write + outputs: + version: ${{ steps.inputs.outputs.version }} + source_sha: ${{ steps.inputs.outputs.source_sha }} + release_run_id: ${{ steps.inputs.outputs.release_run_id }} + steps: + - name: Validate inputs + id: inputs + env: + VERSION: ${{ inputs.version }} + SOURCE_SHA: ${{ inputs.source_sha }} + RELEASE_RUN_ID: ${{ inputs.release_run_id }} + run: | + set -euo pipefail + [[ "$VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+-canary\.[0-9]+$ ]] || { echo "Error: not a canary version" >&2; exit 1; } + [[ "$SOURCE_SHA" =~ ^[0-9a-f]{40}$ ]] || { echo "Error: not a full commit SHA" >&2; exit 1; } + [[ "$RELEASE_RUN_ID" =~ ^[1-9][0-9]*$ ]] || { echo "Error: not a run id" >&2; exit 1; } + { + echo "version=$VERSION" + echo "source_sha=$SOURCE_SHA" + echo "release_run_id=$RELEASE_RUN_ID" + } >> "$GITHUB_OUTPUT" + + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ steps.inputs.outputs.source_sha }} + fetch-depth: 0 + + - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7 + with: + node-version: 24 + + - name: Configure git author + run: | + git config user.name "github-actions[bot]" + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + + - name: Confirm the canary and push its tag + env: + VERSION: ${{ steps.inputs.outputs.version }} + SOURCE_SHA: ${{ steps.inputs.outputs.source_sha }} + PUBLISH_REMOTE: origin + run: ./scripts/confirm-canary-publication.sh "$VERSION" "$SOURCE_SHA" + + - name: Build Docker images for the canary tag + env: + GH_TOKEN: ${{ github.token }} + VERSION: ${{ steps.inputs.outputs.version }} + RELEASE_RUN_ID: ${{ steps.inputs.outputs.release_run_id }} + run: | + { + echo "## Canary published" + echo "" + echo "- Published canary: \`$VERSION\` ([release run](https://github.com/$GITHUB_REPOSITORY/actions/runs/$RELEASE_RUN_ID))" + echo "- Docker build dispatched at \`canary/v$VERSION\`" + } >> "$GITHUB_STEP_SUMMARY" + gh workflow run docker.yml --ref "refs/tags/canary/v$VERSION" --repo "$GITHUB_REPOSITORY" + + smoke_canary_onboarding: + needs: confirm_canary + runs-on: ubuntu-latest + timeout-minutes: 20 + permissions: + contents: read + actions: read + env: + PAPERCLIPAI_VERSION: ${{ needs.confirm_canary.outputs.version }} + PAPERCLIP_PLAYWRIGHT_CHANNEL: chrome + steps: + - name: Checkout repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ needs.confirm_canary.outputs.source_sha }} + persist-credentials: false + + - name: Setup pnpm + uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6 + with: + version: 9.15.4 + + - name: Setup Node.js + uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7 + with: + node-version: 24 + + - name: Restore canary smoke lockfile + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 + with: + name: canary-smoke-lockfile-${{ needs.confirm_canary.outputs.source_sha }} + run-id: ${{ needs.confirm_canary.outputs.release_run_id }} + github-token: ${{ github.token }} + + - name: Install test dependencies + run: pnpm install --frozen-lockfile + + - name: Show browser version + run: google-chrome --version + + - name: Smoke exact published canary through onboarding + env: + PAPERCLIP_CANARY_SMOKE_SERVER_LOG: ${{ runner.temp }}/canary-onboarding-server.log + run: pnpm run test:canary-onboarding-smoke + + - name: Upload failed canary onboarding diagnostics + if: failure() + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: canary-onboarding-smoke-${{ needs.confirm_canary.outputs.version }} + if-no-files-found: warn + retention-days: 14 + path: | + ${{ runner.temp }}/canary-onboarding-server.log + tests/canary-onboarding/playwright-report/ + tests/canary-onboarding/test-results/ diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index eb78a7e3d23..1f9443c596b 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -9,8 +9,8 @@ on: - "nightly/v*" - "beta/v*" # Release workflows push lane tags with GITHUB_TOKEN, and GitHub suppresses - # push-triggered runs for those, so release.yml dispatches this workflow at - # the new tag ref instead. The tag mapping below keys off github.ref either + # push-triggered runs for those, so release.yml (canary-finalize.yml for a + # canary) dispatches this workflow at the new tag ref instead. The tag mapping below keys off github.ref either # way. workflow_dispatch: diff --git a/.github/workflows/pr-trusted.yml b/.github/workflows/pr-trusted.yml index 94672521794..e66b7cee4b6 100644 --- a/.github/workflows/pr-trusted.yml +++ b/.github/workflows/pr-trusted.yml @@ -249,7 +249,10 @@ jobs: run: node "$CI_NODE_TEST" ./scripts/__tests__/e2e-shard.test.mjs - name: Test release verify workflow wiring - run: node "$CI_NODE_TEST" ./scripts/__tests__/release-verify-workflow.test.mjs ./scripts/__tests__/eval-schedule-monitor.test.mjs ./scripts/__tests__/prepare-runner-release-image.test.mjs ./scripts/cloud-source-verification.test.mjs ./scripts/cloud-readiness-runner-loss.test.mjs ./scripts/standard-image-contract.test.mjs ./scripts/reuse-canary-image.test.mjs + run: | + tests=(./scripts/__tests__/release-verify-workflow.test.mjs ./scripts/__tests__/eval-schedule-monitor.test.mjs ./scripts/__tests__/prepare-runner-release-image.test.mjs ./scripts/cloud-source-verification.test.mjs ./scripts/cloud-readiness-runner-loss.test.mjs ./scripts/standard-image-contract.test.mjs ./scripts/reuse-canary-image.test.mjs) + if [[ -f ./scripts/verify-canary-provenance.test.mjs ]]; then tests+=(./scripts/verify-canary-provenance.test.mjs); fi + node "$CI_NODE_TEST" "${tests[@]}" - name: Test merge-queue workflow wiring # This workflow loads from master and tests the caller's checkout. A diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 940cfd8c29f..744eea46d2a 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -396,9 +396,9 @@ jobs: outputs: canary_version: ${{ steps.canary_tag.outputs.version }} permissions: - contents: write + contents: read id-token: write - # For the explicit docker.yml dispatch below. + # For the canary-finalize.yml dispatch below. actions: write steps: @@ -488,7 +488,8 @@ jobs: - name: Publish canary env: GITHUB_ACTIONS: "true" - run: ./scripts/release.sh canary --skip-verify + PAPERCLIP_RELEASE_VERSION_FILE: ${{ runner.temp }}/canary-version + run: ./scripts/release.sh canary --skip-verify --defer-registry-confirmation - name: Dump npm debug logs if: failure() @@ -500,100 +501,25 @@ jobs: -e 's#((authorization|_authToken|_auth|node_auth_token|npm_token)"?[[:space:]]*[:=][[:space:]]*"?)(Bearer[[:space:]]+)?[^",[:space:]]+#\1***REDACTED***#Ig' done - - name: Push canary tag + - name: Hand off npm confirmation, the tag and the image to canary-finalize id: canary_tag - run: | - tag="$(git tag --points-at HEAD | grep '^canary/v' | head -1)" - if [ -z "$tag" ]; then - echo "Error: no canary tag points at HEAD after release." >&2 - exit 1 - fi - git push origin "refs/tags/${tag}" - echo "version=${tag#canary/v}" >> "$GITHUB_OUTPUT" - - # Canary images previously relied on the master-push docker.yml run, - # whose single pending concurrency slot gets superseded by every - # newer push — on a busy day no canary image publishes at all (five - # consecutive canaries shipped npm packages with no cloud image on - # 2026-09-06, starving downstream managed deploys for ~18 hours). - # Tag pushes made with GITHUB_TOKEN do not fire docker.yml's - # triggers, so dispatch the image build at the canary tag - # explicitly, exactly like the nightly and beta lanes: the run keys - # its concurrency off the tag ref, so no master push can supersede - # it, and docker.yml's `type=sha` mapping publishes the - # standard sha- images either way. - - name: Build Docker images for the canary tag env: GH_TOKEN: ${{ github.token }} + VERSION_FILE: ${{ runner.temp }}/canary-version + SOURCE_SHA: ${{ github.sha }} run: | + set -euo pipefail + version="$(cat "$VERSION_FILE")" + [[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+-canary\.[0-9]+$ ]] || { echo "Error: release.sh wrote no canary version" >&2; exit 1; } + echo "version=$version" >> "$GITHUB_OUTPUT" + gh workflow run canary-finalize.yml --ref master --repo "$GITHUB_REPOSITORY" \ + -f version="$version" -f source_sha="$SOURCE_SHA" -f release_run_id="$GITHUB_RUN_ID" { - echo "## Canary published" + echo "## Canary published to npm" echo "" - echo "- Published canary: \`${{ steps.canary_tag.outputs.version }}\`" - echo "- Docker build dispatched at \`canary/v${{ steps.canary_tag.outputs.version }}\`" + echo "- Version: \`$version\`" + echo "- npm confirmation, \`canary/v$version\`, the Docker build and the onboarding smoke run in Canary finalize." } >> "$GITHUB_STEP_SUMMARY" - gh workflow run docker.yml --ref "refs/tags/canary/v${{ steps.canary_tag.outputs.version }}" --repo "$GITHUB_REPOSITORY" - - # The package is already public when this gate runs. A red result leaves the - # immutable canary in npm, but makes the release workflow visibly fail before - # anyone mistakes an installable package for an onboardable one. - smoke_canary_onboarding: - needs: publish_canary - if: ${{ !cancelled() && needs.publish_canary.result == 'success' }} - runs-on: ubuntu-latest - timeout-minutes: 20 - permissions: - contents: read - env: - PAPERCLIPAI_VERSION: ${{ needs.publish_canary.outputs.canary_version }} - PAPERCLIP_PLAYWRIGHT_CHANNEL: chrome - - steps: - - name: Checkout repository - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - with: - ref: ${{ github.sha }} - persist-credentials: false - - - name: Setup pnpm - uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6 - with: - version: 9.15.4 - - - name: Setup Node.js - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7 - with: - node-version: 24 - - # Default download scope is this workflow run, including job reruns. - # A missing artifact fails instead of resolving a different dependency set. - - name: Restore canary smoke lockfile - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4 - with: - name: canary-smoke-lockfile-${{ github.sha }} - - - name: Install test dependencies - run: pnpm install --frozen-lockfile - - - name: Show browser version - run: google-chrome --version - - - name: Smoke exact published canary through onboarding - env: - PAPERCLIP_CANARY_SMOKE_SERVER_LOG: ${{ runner.temp }}/canary-onboarding-server.log - run: pnpm run test:canary-onboarding-smoke - - - name: Upload failed canary onboarding diagnostics - if: failure() - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 - with: - name: canary-onboarding-smoke-${{ needs.publish_canary.outputs.canary_version }} - if-no-files-found: warn - retention-days: 14 - path: | - ${{ runner.temp }}/canary-onboarding-server.log - tests/canary-onboarding/playwright-report/ - tests/canary-onboarding/test-results/ # ----- Nightly lane ----------------------------------------------------- # Once a night (or on a forced nightly dispatch), promote the newest master diff --git a/doc/RELEASING.md b/doc/RELEASING.md index d88794e7232..bd0317195ca 100644 --- a/doc/RELEASING.md +++ b/doc/RELEASING.md @@ -93,25 +93,33 @@ internal traceability tag. ### Canary -Every push to `master` runs the canary path inside [`.github/workflows/release.yml`](../.github/workflows/release.yml). +Every push to `master` runs the canary path inside [`.github/workflows/release.yml`](../.github/workflows/release.yml). Only one canary at a time runs that path. It ends as soon as npm has accepted every package, and [`.github/workflows/canary-finalize.yml`](../.github/workflows/canary-finalize.yml) finishes the canary outside that lock, so the next canary can publish while the previous one is still being confirmed. -It: +`release.yml` (`publish_canary`): - verifies the pushed commit -- computes the canary version for the current UTC date +- computes the canary version `YYYY.MDD.P-canary.N` for the current UTC date. `N` is 100 × the commit's position on master (`git rev-list --count HEAD`) plus the run attempt minus 1. Each commit owns its own range of 100, so neither a rerun nor an overlapping canary can take another commit's number. A number already published in that range (the same commit published again outside a GitHub rerun) is skipped, without leaving the range. This needs the full history; a publishing canary refuses a shallow checkout, and a dry run falls back to the next registry number. Nightly, beta and stable numbering are unchanged. - publishes workspace packages dependency-first under npm dist-tag `canary` -- waits for each package version to become registry-visible before continuing - publishes the user-facing `paperclipai` package last, so `paperclipai@canary` does not advance before the full package set exists -- verifies that `canary` resolves to the just-published version and that published internal dependencies exist on npm -- installs `paperclipai@canary` into a clean temporary prefix as the final npm gate -- starts the exact published canary through a separate fresh npm install for the onboarding smoke; npm `ETARGET` and verified canary tarball availability failures retry, up to three attempts within two minutes, before onboarding runs once under the existing five-minute startup deadline +- dispatches `canary-finalize.yml` with the version, the source commit and its own run id (`release.sh canary --defer-registry-confirmation`) + +`canary-finalize.yml`, which runs [`scripts/confirm-canary-publication.sh`](../scripts/confirm-canary-publication.sh): + +- waits for each package version to become registry-visible +- requires the source commit to be on master and the canary number to come from it (`N / 100` equals the commit's master position), so a dispatch with invented inputs cannot tag another commit +- checks npm provenance ([`scripts/verify-canary-provenance.mjs`](../scripts/verify-canary-provenance.mjs)): any package whose provenance names something other than `.github/workflows/release.yml` on `refs/heads/master` at the source commit fails the check. A package with no provenance is accepted, because that is the supported retry after a duplicate transparency-log entry, only the trusted release workflow can publish, and the number check above already ties the version to the commit. Brief npm errors are retried. +- verifies that `canary` resolves to this version or a newer canary, and that published internal dependencies exist on npm +- installs the exact `paperclipai@` into a clean temporary prefix - fails by default if npm leaves `latest` pointing at a canary; use `--allow-canary-latest` only when that state is intentional -- creates a git tag `canary/vYYYY.MDD.P-canary.N` +- creates and pushes the git tag `canary/vYYYY.MDD.P-canary.N` (a tag that already points at the same commit is accepted, so a rerun is safe). Nightly still selects only tagged canaries. +- dispatches `docker.yml` at the tag +- starts the exact published canary through a separate fresh npm install for the onboarding smoke; npm `ETARGET` and verified canary tarball availability failures retry, up to three attempts within two minutes, before onboarding runs once under the existing five-minute startup deadline. The smoke installs from the publisher run's lockfile artifact. #### Busy master and lost runners Master often receives a commit every few minutes, faster than one canary -publishes (about 60-90 minutes). The release workflow keeps one running canary +publishes (about 20-25 minutes inside `release.yml`, then its confirmation in +`canary-finalize.yml`). The release workflow keeps one running canary and one pending canary. A newer push replaces the pending one, so the canary that runs next is always the newest master commit. Commits in between are not published on their own; they ship inside the next canary. @@ -146,7 +154,7 @@ runs `build:binary`. After publication, the onboarding smoke checks out the same source SHA and installs its test dependencies from the publisher's resolved lockfile with -`--frozen-lockfile`. The same-run artifact is captured before tracked files are +`--frozen-lockfile`. The publisher's artifact is captured before tracked files are restored or release versions are rewritten. This lets a source commit use its current patches and manifests while the separate lockfile-refresh PR is still pending, without resolving new dependencies in the smoke job. The smoke still installs and tests diff --git a/scripts/__tests__/release-dry-run-notes.test.mjs b/scripts/__tests__/release-dry-run-notes.test.mjs index d42b302d3b0..a953d2fdd50 100644 --- a/scripts/__tests__/release-dry-run-notes.test.mjs +++ b/scripts/__tests__/release-dry-run-notes.test.mjs @@ -46,6 +46,7 @@ list_public_package_info() { package_publish_tool() { printf 'pnpm\\n'; } next_stable_version() { printf '2026.710.0\\n'; } next_prerelease_version() { printf '2026.710.0-%s.0\\n' "$1"; } +next_canary_version_from_source() { next_prerelease_version canary "$3"; } release_notes_file() { printf '%s/releases/v%s.md\\n' "$REPO_ROOT" "$1"; } stable_tag_name() { printf 'v%s\\n' "$1"; } prerelease_tag_name() { printf '%s/v%s\\n' "$1" "$2"; } diff --git a/scripts/__tests__/release-verify-workflow.test.mjs b/scripts/__tests__/release-verify-workflow.test.mjs index 5b4d4aaa1fd..24830f0d019 100644 --- a/scripts/__tests__/release-verify-workflow.test.mjs +++ b/scripts/__tests__/release-verify-workflow.test.mjs @@ -334,76 +334,63 @@ test("post-publish beta smoke survives the skipped candidate-verification ancest ); }); -test("published canaries are gated by the exact-version onboarding browser smoke", () => { - const releaseWorkflow = readWorkflow("release.yml"); +function canaryJobs() { + const release = readWorkflow("release.yml"); + const finalize = readWorkflow("canary-finalize.yml"); + return { + release, + finalize, + publish: release.split(" publish_canary:\n")[1].split(" # ----- Nightly lane")[0], + confirm: finalize.split(" confirm_canary:\n")[1].split(" smoke_canary_onboarding:\n")[0], + smoke: finalize.split(" smoke_canary_onboarding:\n")[1], + }; +} - assert.match( - releaseWorkflow, - /publish_canary:[\s\S]*?outputs:\n\s+canary_version: \$\{\{ steps\.canary_tag\.outputs\.version \}\}/, - ); - assert.match( - releaseWorkflow, - /smoke_canary_onboarding:\n\s+needs: publish_canary\n\s+if: \$\{\{ !cancelled\(\) && needs\.publish_canary\.result == 'success' \}\}/, - ); - const smoke = releaseWorkflow.split(" smoke_canary_onboarding:\n")[1].split(/\n [a-z_]+:\n/)[0]; - const condition = smoke.match(/^ if: \$\{\{ (.+) \}\}$/m)?.[1]; - assert.match(condition, /^!cancelled\(\) && needs\.publish_canary\.result == 'success'$/); - for (const [result, cancelled, expected] of [ - ["success", false, true], ["failure", false, false], - ["cancelled", false, false], ["skipped", false, false], ["success", true, false], - ]) { - const needs = { publish_canary: { result }, release_runner_source: { result: "success" }, - select_nightly: { result: "skipped" }, select_beta: { result: "skipped" }, preflight_stable: { result: "skipped" } }; - assert.equal(runInNewContext(condition, { cancelled: () => cancelled, needs }), expected, - `Canary smoke: publisher=${result}, cancelled=${cancelled}`); - } - assert.match( - releaseWorkflow, - /PAPERCLIPAI_VERSION: \$\{\{ needs\.publish_canary\.outputs\.canary_version \}\}/, - ); - assert.match(releaseWorkflow, /test:canary-onboarding-smoke/); - assert.match( - releaseWorkflow, - /smoke_canary_onboarding:[\s\S]*?uses: actions\/checkout@[0-9a-f]{40} # v7[\s\S]*?uses: pnpm\/action-setup@[0-9a-f]{40} # v6[\s\S]*?uses: actions\/setup-node@[0-9a-f]{40} # v7/, - ); - assert.match( - releaseWorkflow, - /smoke_canary_onboarding:[\s\S]*?Install test dependencies\n\s+run: pnpm install --frozen-lockfile/, - ); - assert.doesNotMatch( - releaseWorkflow.match( - /smoke_canary_onboarding:[\s\S]*?(?=\n # ----- Nightly lane)/, - )?.[0] ?? "", - /cache: pnpm/, - ); - assert.match( - releaseWorkflow, - /name: Smoke exact published canary through onboarding\n\s+env:\n\s+PAPERCLIP_CANARY_SMOKE_SERVER_LOG: \$\{\{ runner\.temp \}\}\/canary-onboarding-server\.log/, - ); - assert.match( - releaseWorkflow, - /smoke_canary_onboarding:[\s\S]*?uses: actions\/upload-artifact@[0-9a-f]{40} # v7/, - ); - assert.match(releaseWorkflow, /canary-onboarding-server\.log/); - assert.match(releaseWorkflow, /tests\/canary-onboarding\/playwright-report/); +test("published canaries are confirmed, tagged and onboarding-smoked outside the release lock", () => { + const { release, finalize, publish, confirm, smoke } = canaryJobs(); + assert.doesNotMatch(release, /smoke_canary_onboarding:|confirm-canary-publication/); + assert.match(publish, /outputs:\n\s+canary_version: \$\{\{ steps\.canary_tag\.outputs\.version \}\}/); + assert.match(publish, /run: \.\/scripts\/release\.sh canary --skip-verify --defer-registry-confirmation/); + assert.match(publish, /gh workflow run canary-finalize\.yml --ref master --repo "\$GITHUB_REPOSITORY" \\\n\s+-f version="\$version" -f source_sha="\$SOURCE_SHA" -f release_run_id="\$GITHUB_RUN_ID"/); + assert.match(publish, /SOURCE_SHA: \$\{\{ github\.sha \}\}/); + assert.match(publish, /permissions:\n\s+contents: read\n\s+id-token: write/); + assert.match(finalize, /^on:\n workflow_dispatch:\n/m); + assert.match(finalize, /^permissions: \{\}$/m); + assert.match(confirm, /if: github\.repository == 'paperclipai\/paperclip' && github\.repository_id == '1170821064' && github\.ref == 'refs\/heads\/master'/); + assert.match(confirm, /permissions:\n\s+contents: write\n\s+actions: write/); + assert.match(confirm, /run: \.\/scripts\/confirm-canary-publication\.sh "\$VERSION" "\$SOURCE_SHA"/); + assert.match(confirm, /ref: \$\{\{ steps\.inputs\.outputs\.source_sha \}\}\n\s+fetch-depth: 0/, "the master-position check needs full history"); + assert.match(confirm, /gh workflow run docker\.yml --ref "refs\/tags\/canary\/v\$VERSION"/); + const [validation, afterValidation] = confirm.split(" - uses: actions/checkout@"); + assert.match(validation, /name: Validate inputs/); + assert.equal((validation.match(/\$\{\{ inputs\./g) ?? []).length, 3); + assert.doesNotMatch(afterValidation, /\$\{\{ inputs\./, "later steps read only the validated step outputs"); + assert.doesNotMatch(smoke, /\$\{\{ inputs\./); + assert.match(smoke, /^ needs: confirm_canary$/m); + assert.doesNotMatch(smoke, /^ if: /m); + assert.match(smoke, /PAPERCLIPAI_VERSION: \$\{\{ needs\.confirm_canary\.outputs\.version \}\}/); + assert.match(smoke, /uses: actions\/checkout@[0-9a-f]{40} # v7[\s\S]*?uses: pnpm\/action-setup@[0-9a-f]{40} # v6[\s\S]*?uses: actions\/setup-node@[0-9a-f]{40} # v7/); + assert.match(smoke, /Install test dependencies\n\s+run: pnpm install --frozen-lockfile/); + assert.doesNotMatch(smoke, /cache: pnpm/); + assert.match(smoke, /run: pnpm run test:canary-onboarding-smoke/); + assert.match(smoke, /name: Smoke exact published canary through onboarding\n\s+env:\n\s+PAPERCLIP_CANARY_SMOKE_SERVER_LOG: \$\{\{ runner\.temp \}\}\/canary-onboarding-server\.log/); + assert.match(smoke, /uses: actions\/upload-artifact@[0-9a-f]{40} # v7/); + assert.match(smoke, /tests\/canary-onboarding\/playwright-report/); + assert.match(finalize, /NPM_PUBLISH_VERIFY_ATTEMPTS: "180"\n NPM_PUBLISH_VERIFY_DELAY_SECONDS: "10"/); }); test("canary smoke consumes its publisher's source-bound lockfile before frozen installation", () => { - const workflow = readWorkflow("release.yml"); - const publish = workflow.split(" publish_canary:\n")[1].split(" smoke_canary_onboarding:\n")[0]; - const smoke = workflow.split(" smoke_canary_onboarding:\n")[1].split(" # ----- Nightly lane")[0]; - for (const job of [publish, smoke]) { - assert.match(job, /name: Checkout repository\n\s+uses: actions\/checkout@[^\n]+\n\s+with:\n\s+ref: \$\{\{ github\.sha \}\}/); - assert.match(job, /name: canary-smoke-lockfile-\$\{\{ github\.sha \}\}/); - assert.match(job, /version: 9\.15\.4/); - } + const { publish, smoke } = canaryJobs(); + assert.match(publish, /name: Checkout repository\n\s+uses: actions\/checkout@[^\n]+\n\s+with:\n\s+ref: \$\{\{ github\.sha \}\}/); + assert.match(smoke, /name: Checkout repository\n\s+uses: actions\/checkout@[^\n]+\n\s+with:\n\s+ref: \$\{\{ needs\.confirm_canary\.outputs\.source_sha \}\}/); + for (const job of [publish, smoke]) assert.match(job, /version: 9\.15\.4/); assert.match(publish, /name: Save canary smoke lockfile\n\s+uses: actions\/upload-artifact@[0-9a-f]{40} # v4\n\s+with:\n\s+name: canary-smoke-lockfile-\$\{\{ github\.sha \}\}\n\s+path: pnpm-lock\.yaml\n\s+if-no-files-found: error\n\s+overwrite: true\n\s+retention-days: 14/); assert.ok(publish.indexOf("name: Install dependencies") < publish.indexOf("name: Save canary smoke lockfile")); assert.ok(publish.indexOf("name: Save canary smoke lockfile") < publish.indexOf("name: Restore tracked install-time changes")); assert.ok(publish.indexOf("name: Restore tracked install-time changes") < publish.indexOf("name: Publish canary")); - assert.match(smoke, /name: Restore canary smoke lockfile\n\s+uses: actions\/download-artifact@[0-9a-f]{40} # v4\n\s+with:\n\s+name: canary-smoke-lockfile-\$\{\{ github\.sha \}\}/); + assert.match(smoke, /name: Restore canary smoke lockfile\n\s+uses: actions\/download-artifact@[0-9a-f]{40} # v4\n\s+with:\n\s+name: canary-smoke-lockfile-\$\{\{ needs\.confirm_canary\.outputs\.source_sha \}\}\n\s+run-id: \$\{\{ needs\.confirm_canary\.outputs\.release_run_id \}\}\n\s+github-token: \$\{\{ github\.token \}\}/); assert.ok(smoke.indexOf("name: Restore canary smoke lockfile") < smoke.indexOf("name: Install test dependencies")); - assert.doesNotMatch(smoke, /run-id:|github-token:|repository:|continue-on-error|--no-frozen-lockfile/); + assert.doesNotMatch(smoke, /repository:|continue-on-error|--no-frozen-lockfile/); }); for (const drift of ["patch", "manifest"]) { @@ -429,9 +416,7 @@ for (const drift of ["patch", "manifest"]) { "--- a/index.js", "+++ b/index.js", "@@ -1 +1 @@", '-module.exports = "original";', `+module.exports = "${value}";`, "", ].join("\n")); - const workflow = readWorkflow("release.yml"); - const publish = workflow.split(" publish_canary:\n")[1].split(" smoke_canary_onboarding:\n")[0]; - const smoke = workflow.split(" smoke_canary_onboarding:\n")[1].split(" # ----- Nightly lane")[0]; + const { publish, smoke } = canaryJobs(); const installArgs = (name) => { const job = name === "Install dependencies" ? publish : smoke; const command = job.match(new RegExp(`name: ${name}\\n\\s+run: (pnpm install[^\\n]+)`))?.[1]; diff --git a/scripts/confirm-canary-publication.sh b/scripts/confirm-canary-publication.sh new file mode 100755 index 00000000000..47ace380829 --- /dev/null +++ b/scripts/confirm-canary-publication.sh @@ -0,0 +1,65 @@ +#!/usr/bin/env bash +set -euo pipefail + +REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)" +# shellcheck source=./release-lib.sh +. "$REPO_ROOT/scripts/release-lib.sh" + +usage() { + cat <<'EOF' +Usage: + ./scripts/confirm-canary-publication.sh + +Confirms a canary that ./scripts/release.sh canary --defer-registry-confirmation +published, then creates and pushes its canary/v tag at . +Run it from a checkout of . It waits for every public package +version to become registry-visible, requires npm provenance from the master +release workflow at , checks dist-tags and internal dependencies +(the canary dist-tag may already name a newer canary), and installs the exact +version into a clean prefix. A tag that already points at is +accepted, so a rerun is safe. +EOF +} + +[ $# -eq 2 ] || { usage; exit 1; } +version="$1" +source_sha="$2" + +[[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+-canary\.[0-9]+$ ]] || release_fail "not a canary version: $version" +[[ "$source_sha" =~ ^[0-9a-f]{40}$ ]] || release_fail "not a full commit SHA: $source_sha" +[ "$(git -C "$REPO_ROOT" rev-parse HEAD)" = "$source_sha" ] || release_fail "checkout is not $source_sha" +require_canary_number_from_master_commit "$version" "$source_sha" + +tag_name="$(canary_tag_name "$version")" +PUBLISH_REMOTE="$(resolve_release_remote)" + +PACKAGE_INFO="" +PACKAGE_NAMES=() +while IFS=$'\t' read -r pkg_dir pkg_name _pkg_version; do + [ -n "$pkg_name" ] || continue + PACKAGE_NAMES+=("$pkg_name") + PACKAGE_INFO+="${pkg_dir}"$'\t'"${pkg_name}"$'\t'"${version}"$'\n' +done < <(list_public_package_info) +[ "${#PACKAGE_NAMES[@]}" -gt 0 ] || release_fail "no public packages were found in the workspace." + +release_info "==> Waiting for registry visibility of ${#PACKAGE_NAMES[@]} packages at ${version}..." +wait_for_npm_package_versions "${NPM_PUBLISH_VERIFY_ATTEMPTS:-12}" "${NPM_PUBLISH_VERIFY_DELAY_SECONDS:-5}" "$PACKAGE_INFO" \ + || release_fail "npm did not expose every package at ${version}" + +release_info "==> Checking npm provenance..." +node "$REPO_ROOT/scripts/verify-canary-provenance.mjs" "$version" "$source_sha" "${PACKAGE_NAMES[@]}" \ + || release_fail "npm provenance does not tie ${version} to the master release workflow at ${source_sha}" + +release_info "==> Checking dist-tags and internal dependencies..." +verify_args=(--channel canary --dist-tag canary --target-version "$version" --allow-newer-canary) +for pkg_name in "${PACKAGE_NAMES[@]}"; do verify_args+=(--package "$pkg_name"); done +if wait_for_release_registry_state "${NPM_REGISTRY_STATE_VERIFY_ATTEMPTS:-12}" "${NPM_REGISTRY_STATE_VERIFY_DELAY_SECONDS:-5}" "${verify_args[@]}"; then + : +else + release_fail "npm dist-tags or registry metadata are wrong or never converged for ${version}" +fi + +release_info "==> Installing paperclipai@${version} into a clean prefix..." +verify_npm_installable "paperclipai@${version}" "$version" || release_fail "paperclipai@${version} did not install cleanly" + +push_release_tag_at "$PUBLISH_REMOTE" "$tag_name" "$source_sha" diff --git a/scripts/release-lib.sh b/scripts/release-lib.sh index 7b4a890ccec..798e34ba586 100644 --- a/scripts/release-lib.sh +++ b/scripts/release-lib.sh @@ -270,6 +270,89 @@ next_canary_version() { next_prerelease_version canary "$stable_version" "$@" } +canary_source_position() { + local repo_root="$1" + if [ "$(git -C "$repo_root" rev-parse --is-shallow-repository)" = "true" ]; then + return 1 + fi + git -C "$repo_root" rev-list --count HEAD +} + +next_canary_version_from_source() { + local repo_root="$1" + local allow_registry_fallback="$2" + local stable_version="$3" + local run_attempt="$4" + shift 4 + local position + + if ! [[ "$run_attempt" =~ ^[1-9][0-9]?$ ]]; then + release_fail "canary numbering needs a run attempt from 1 to 99, got '${run_attempt}'." + fi + if ! position="$(canary_source_position "$repo_root")"; then + if [ "$allow_registry_fallback" = true ]; then + release_warn "shallow checkout: canary number falls back to the next registry number." + next_prerelease_version canary "$stable_version" "$@" + printf '\n' + return 0 + fi + release_fail "canary numbering needs the full master history; this checkout is shallow." + fi + local candidate=$((position * 100 + run_attempt - 1)) + local range_end=$((position * 100 + 99)) + local published + published="$(node -e ' + const [file, stable, low, high] = process.argv.slice(1); + let cache = {}; + try { cache = JSON.parse(require("node:fs").readFileSync(file, "utf8")); } catch {} + const pattern = new RegExp(`^${stable.replace(/\./g, "\\.")}-canary\\.(\\d+)$`); + const numbers = new Set(); + for (const versions of Object.values(cache)) for (const version of Array.isArray(versions) ? versions : []) { + const number = Number(pattern.exec(version)?.[1]); + if (number >= Number(low) && number <= Number(high)) numbers.add(number); + } + process.stdout.write([...numbers].join(" ")); + ' "${RELEASE_PACKAGE_VERSIONS_FILE:-}" "$stable_version" "$candidate" "$range_end")" + while [[ " $published " == *" $candidate "* ]]; do + candidate=$((candidate + 1)) + done + [ "$candidate" -le "$range_end" ] || release_fail "every canary number for master position ${position} is already published." + printf '%s-canary.%s\n' "$stable_version" "$candidate" +} + +require_canary_number_from_master_commit() { + local version="$1" + local source_sha="$2" + local master_ref="${3:-origin/master}" + local number="${version##*-canary.}" + local position + + git -C "$REPO_ROOT" merge-base --is-ancestor "$source_sha" "$master_ref" \ + || release_fail "${source_sha} is not on ${master_ref}" + position="$(canary_source_position "$REPO_ROOT")" || release_fail "canary confirmation needs the full master history; this checkout is shallow." + [ "$((number / 100))" = "$position" ] \ + || release_fail "${version} was not numbered from ${source_sha} (master position ${position})" + release_info " ✓ ${version} was numbered from ${source_sha} (master position ${position})" +} + +push_release_tag_at() { + local remote="$1" + local tag_name="$2" + local source_sha="$3" + local existing_sha + + existing_sha="$(git -C "$REPO_ROOT" ls-remote --tags "$remote" "refs/tags/${tag_name}^{}" | awk '{print $1}')" + [ -n "$existing_sha" ] || existing_sha="$(git -C "$REPO_ROOT" ls-remote --tags "$remote" "refs/tags/${tag_name}" | awk '{print $1}')" + if [ -n "$existing_sha" ]; then + [ "$existing_sha" = "$source_sha" ] || release_fail "tag ${tag_name} already exists on ${existing_sha}, not ${source_sha}" + release_info " ✓ ${tag_name} already points at ${source_sha}" + return 0 + fi + git -C "$REPO_ROOT" tag "$tag_name" "$source_sha" + git -C "$REPO_ROOT" push "$remote" "refs/tags/${tag_name}" + release_info " ✓ Pushed ${tag_name} at ${source_sha}" +} + release_notes_file() { printf '%s/releases/v%s.md\n' "$REPO_ROOT" "$1" } diff --git a/scripts/release-lib.test.mjs b/scripts/release-lib.test.mjs index 93f32723592..c890ffee0ac 100644 --- a/scripts/release-lib.test.mjs +++ b/scripts/release-lib.test.mjs @@ -406,3 +406,94 @@ test("every publish job budgets for build time and four delayed packages", () => assert.ok(timeoutMinutes * 60 > requiredSeconds, `${job} must leave time beyond build and polling`); } }); + +function canaryNumberFixture({ commits, publishedVersions, shallow = false }) { + const dir = mkdtempSync(join(tmpdir(), "paperclip-canary-number-")); + const source = join(dir, "source"); + mkdirSync(source); + const git = (cwd, ...args) => execFileSync("git", args, { cwd, encoding: "utf8", env: { ...process.env, GIT_AUTHOR_NAME: "t", GIT_AUTHOR_EMAIL: "t@example.test", GIT_COMMITTER_NAME: "t", GIT_COMMITTER_EMAIL: "t@example.test" } }); + git(source, "init", "-q", "-b", "master"); + for (let index = 0; index < commits; index += 1) git(source, "commit", "-q", "--allow-empty", "-m", `c${index}`); + let repo = source; + if (shallow) { + repo = join(dir, "shallow"); + git(dir, "clone", "-q", "--depth", "1", `file://${source}`, repo); + } + const versionsFile = join(dir, "versions.json"); + writeFileSync(versionsFile, JSON.stringify({ "@paperclipai/shared": publishedVersions, paperclipai: publishedVersions })); + return { dir, repo, versionsFile, git }; +} + +function nextCanary(fixture, { allowFallback = false, attempt = "1" } = {}) { + const script = `source "${repoRoot}/scripts/release-lib.sh"; next_canary_version_from_source "$1" "$2" 2026.1116.0 "$3" @paperclipai/shared paperclipai`; + return execFileSync("bash", ["-c", script, "next-canary", fixture.repo, String(allowFallback), attempt], { + encoding: "utf8", env: { ...process.env, RELEASE_PACKAGE_VERSIONS_FILE: fixture.versionsFile }, stdio: ["ignore", "pipe", "pipe"], + }).trim(); +} + +test("a canary is numbered from its master position and run attempt, ignoring other commits' numbers", () => { + const fixture = canaryNumberFixture({ commits: 25, publishedVersions: ["2026.1116.0-canary.2600", "2026.1116.0-canary.9999"] }); + assert.equal(nextCanary(fixture), "2026.1116.0-canary.2500"); + assert.equal(nextCanary(fixture, { attempt: "2" }), "2026.1116.0-canary.2501"); + assert.equal(nextCanary(fixture, { attempt: "99" }), "2026.1116.0-canary.2598"); +}); + +test("publishing the same commit again outside a rerun moves to the next free number in its own range", () => { + const fixture = canaryNumberFixture({ commits: 25, publishedVersions: ["2026.1116.0-canary.2500", "2026.1116.0-canary.2501", "2026.1116.0-canary.2600", "2026.1115.0-canary.2502"] }); + assert.equal(nextCanary(fixture), "2026.1116.0-canary.2502"); + assert.equal(nextCanary(fixture, { attempt: "3" }), "2026.1116.0-canary.2502"); + assert.equal(nextCanary(fixture, { attempt: "4" }), "2026.1116.0-canary.2503"); + const full = canaryNumberFixture({ commits: 25, publishedVersions: Array.from({ length: 100 }, (_, index) => `2026.1116.0-canary.${2500 + index}`) }); + assert.throws(() => nextCanary(full), /every canary number for master position 25 is already published/); +}); + +test("reruns of one commit never reach the next commit's numbers", () => { + const earlier = canaryNumberFixture({ commits: 25, publishedVersions: [] }); + const later = canaryNumberFixture({ commits: 26, publishedVersions: [] }); + const earlierNumbers = new Set(Array.from({ length: 99 }, (_, index) => nextCanary(earlier, { attempt: String(index + 1) }))); + assert.equal(earlierNumbers.size, 99); + assert.equal(earlierNumbers.has(nextCanary(later)), false); +}); + +test("an invalid run attempt is refused", () => { + const fixture = canaryNumberFixture({ commits: 3, publishedVersions: [] }); + for (const attempt of ["0", "100", "", "1a"]) assert.throws(() => nextCanary(fixture, { attempt }), /run attempt from 1 to 99/); +}); + +test("a publishing canary refuses a shallow checkout, and a dry run falls back to the registry number", () => { + const fixture = canaryNumberFixture({ commits: 5, publishedVersions: ["2026.1116.0-canary.7"], shallow: true }); + assert.throws(() => nextCanary(fixture), /needs the full master history/); + assert.equal(nextCanary(fixture, { allowFallback: true }), "2026.1116.0-canary.8"); +}); + +test("a canary tag is pushed once, accepted again on the same commit, and refused on another commit", () => { + const fixture = canaryNumberFixture({ commits: 2, publishedVersions: [] }); + const remote = join(fixture.dir, "remote.git"); + fixture.git(fixture.dir, "init", "-q", "--bare", remote); + fixture.git(fixture.repo, "remote", "add", "origin", remote); + const [head, parent] = fixture.git(fixture.repo, "rev-list", "-2", "HEAD").trim().split("\n"); + const pushTag = (sha) => execFileSync("bash", ["-c", `REPO_ROOT="$1"; source "${repoRoot}/scripts/release-lib.sh"; push_release_tag_at origin canary/v2026.1116.0-canary.200 "$2"`, "push-tag", fixture.repo, sha], + { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }); + assert.match(pushTag(head), /Pushed canary\/v2026\.1116\.0-canary\.200/); + assert.equal(fixture.git(fixture.dir, "--git-dir", remote, "rev-parse", "canary/v2026.1116.0-canary.200").trim(), head); + assert.match(pushTag(head), /already points at/); + fixture.git(fixture.repo, "tag", "-d", "canary/v2026.1116.0-canary.200"); + assert.throws(() => pushTag(parent), /already exists on [0-9a-f]{40}, not/); + assert.equal(fixture.git(fixture.dir, "--git-dir", remote, "rev-parse", "canary/v2026.1116.0-canary.200").trim(), head); +}); + +test("a canary version is accepted only for the master commit whose position numbered it", () => { + const fixture = canaryNumberFixture({ commits: 25, publishedVersions: [] }); + const head = fixture.git(fixture.repo, "rev-parse", "HEAD").trim(); + fixture.git(fixture.repo, "update-ref", "refs/remotes/origin/master", head); + const confirm = (version, sha) => execFileSync("bash", ["-c", `REPO_ROOT="$1"; source "${repoRoot}/scripts/release-lib.sh"; require_canary_number_from_master_commit "$2" "$3"`, "confirm", fixture.repo, version, sha], + { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }); + assert.match(confirm("2026.1116.0-canary.2500", head), /numbered from .* \(master position 25\)/); + assert.match(confirm("2026.1116.0-canary.2503", head), /master position 25/); + assert.throws(() => confirm("2026.1116.0-canary.2600", head), /was not numbered from/); + assert.throws(() => confirm("2026.1116.0-canary.7", head), /was not numbered from/); + fixture.git(fixture.repo, "checkout", "-q", "-b", "side"); + fixture.git(fixture.repo, "commit", "-q", "--allow-empty", "-m", "side"); + const side = fixture.git(fixture.repo, "rev-parse", "HEAD").trim(); + assert.throws(() => confirm("2026.1116.0-canary.2600", side), /is not on origin\/master/); +}); diff --git a/scripts/release.sh b/scripts/release.sh index ac354ddb1c4..79b276844d8 100755 --- a/scripts/release.sh +++ b/scripts/release.sh @@ -12,6 +12,7 @@ dry_run=false skip_verify=false print_version_only=false from_candidate=false +defer_registry_confirmation=false notes_file_override= tag_name="" @@ -20,7 +21,7 @@ cleanup_on_exit=false usage() { cat <<'EOF' Usage: - ./scripts/release.sh [--date YYYY-MM-DD] [--dry-run] [--skip-verify] [--print-version] [--notes-file PATH] + ./scripts/release.sh [--date YYYY-MM-DD] [--dry-run] [--skip-verify] [--print-version] [--notes-file PATH] [--defer-registry-confirmation] Examples: ./scripts/release.sh canary @@ -36,7 +37,15 @@ Notes: - Stable versions use YYYY.MDD.P, where M is the UTC month, DD is the zero-padded UTC day, and P is the same-day stable patch slot. - Canary releases publish YYYY.MDD.P-canary.N under the npm dist-tag - "canary" and create the git tag canary/vYYYY.MDD.P-canary.N. + "canary" and create the git tag canary/vYYYY.MDD.P-canary.N. N is + 100 x the source commit's position on master (git rev-list --count HEAD) + plus the run attempt minus 1 (GITHUB_RUN_ATTEMPT, default 1). Each commit + owns its own range, so neither a rerun nor an overlapping canary can take + another commit's number, and no registry lookup is involved. + - --defer-registry-confirmation (published canary only) stops after npm + accepts every publish. It skips the registry-visibility wait, the + dist-tag check and the git tag; scripts/confirm-canary-publication.sh + does those later, outside the release lock. - Nightly releases republish a commit that already shipped a canary (HEAD must carry a canary/v* tag) as YYYY.MDD.P-nightly.N under the npm dist-tag "nightly", with the git tag nightly/vYYYY.MDD.P-nightly.N. @@ -118,6 +127,7 @@ while [ $# -gt 0 ]; do --skip-verify) skip_verify=true ;; --print-version) print_version_only=true ;; --from-candidate) from_candidate=true ;; + --defer-registry-confirmation) defer_registry_confirmation=true ;; --notes-file) shift [ $# -gt 0 ] || release_fail "--notes-file requires a path." @@ -147,6 +157,10 @@ if [ -n "$notes_file_override" ] && [ "$channel" != "stable" ]; then release_fail "--notes-file only applies to the stable channel." fi +if [ "$defer_registry_confirmation" = true ] && { [ "$channel" != "canary" ] || [ "$dry_run" = true ]; }; then + release_fail "--defer-registry-confirmation only applies to a published canary." +fi + PUBLISH_REMOTE="$(resolve_release_remote)" fetch_release_remote "$PUBLISH_REMOTE" @@ -178,7 +192,7 @@ DIST_TAG="latest" if [ "$channel" = "canary" ]; then require_on_master_branch - TARGET_PUBLISH_VERSION="$(next_prerelease_version canary "$TARGET_STABLE_VERSION" "${PUBLIC_PACKAGE_NAMES[@]}")" + TARGET_PUBLISH_VERSION="$(next_canary_version_from_source "$REPO_ROOT" "$dry_run" "$TARGET_STABLE_VERSION" "${GITHUB_RUN_ATTEMPT:-1}" "${PUBLIC_PACKAGE_NAMES[@]}")" DIST_TAG="canary" tag_name="$(prerelease_tag_name canary "$TARGET_PUBLISH_VERSION")" elif [ "$channel" = "nightly" ]; then @@ -422,19 +436,23 @@ else release_info " ✓ npm accepted the publish" done <<< "$VERSIONED_PACKAGE_INFO" release_info " ✓ npm accepted every package publish under dist-tag $DIST_TAG" - release_info " Waiting for registry visibility of all packages concurrently..." - if ! wait_for_npm_package_versions \ - "$VERIFY_ATTEMPTS" \ - "$VERIFY_DELAY_SECONDS" \ - "$VERSIONED_PACKAGE_INFO"; then - release_fail "stopping release: npm did not expose every published version under dist-tag $DIST_TAG" + if [ "$defer_registry_confirmation" = false ]; then + release_info " Waiting for registry visibility of all packages concurrently..." + if ! wait_for_npm_package_versions \ + "$VERIFY_ATTEMPTS" \ + "$VERIFY_DELAY_SECONDS" \ + "$VERSIONED_PACKAGE_INFO"; then + release_fail "stopping release: npm did not expose every published version under dist-tag $DIST_TAG" + fi + release_info " ✓ Published the full package set under dist-tag $DIST_TAG" fi - release_info " ✓ Published the full package set under dist-tag $DIST_TAG" fi release_info "" if [ "$dry_run" = true ]; then release_info "==> Step 6/7: Skipping npm verification in dry-run mode..." +elif [ "$defer_registry_confirmation" = true ]; then + release_info "==> Step 6/7: Registry confirmation deferred to scripts/confirm-canary-publication.sh" else release_info "==> Step 6/7: Confirming npm package availability and dist-tag integrity..." REGISTRY_STATE_VERIFY_ATTEMPTS="${NPM_REGISTRY_STATE_VERIFY_ATTEMPTS:-12}" @@ -476,6 +494,11 @@ fi release_info "" if [ "$dry_run" = true ]; then release_info "==> Step 7/7: Dry run complete..." +elif [ "$defer_registry_confirmation" = true ]; then + release_info "==> Step 7/7: Tag deferred until npm confirms ${TARGET_PUBLISH_VERSION}" + if [ -n "${PAPERCLIP_RELEASE_VERSION_FILE:-}" ]; then + printf '%s\n' "$TARGET_PUBLISH_VERSION" > "$PAPERCLIP_RELEASE_VERSION_FILE" + fi else release_info "==> Step 7/7: Creating git tag..." git -C "$REPO_ROOT" tag "$tag_name" "$CURRENT_SHA" @@ -485,6 +508,8 @@ fi release_info "" if [ "$dry_run" = true ]; then release_info "Dry run complete for $channel ${TARGET_PUBLISH_VERSION}." +elif [ "$defer_registry_confirmation" = true ]; then + release_info "Published $channel ${TARGET_PUBLISH_VERSION}; npm confirmation and the git tag follow in canary-finalize." else case "$channel" in canary|nightly|beta) diff --git a/scripts/verify-canary-provenance.mjs b/scripts/verify-canary-provenance.mjs new file mode 100644 index 00000000000..3002ce9f644 --- /dev/null +++ b/scripts/verify-canary-provenance.mjs @@ -0,0 +1,102 @@ +#!/usr/bin/env node +import { pathToFileURL } from "node:url"; + +export const RELEASE_WORKFLOW = Object.freeze({ + repository: "https://github.com/paperclipai/paperclip", + path: ".github/workflows/release.yml", + ref: "refs/heads/master", +}); + +const CANARY_VERSION = /^\d+\.\d+\.\d+-canary\.\d+$/; +const SHA = /^[0-9a-f]{40}$/; + +function slsaStatements(attestations) { + return (attestations?.attestations ?? []) + .filter((entry) => typeof entry?.predicateType === "string" && entry.predicateType.startsWith("https://slsa.dev/provenance/")) + .map((entry) => { + try { + return JSON.parse(Buffer.from(entry.bundle?.dsseEnvelope?.payload ?? "", "base64").toString("utf8")); + } catch { + return null; + } + }) + .filter(Boolean); +} + +export function packageProvenance(attestations, { packageName, version, sourceSha }) { + const subject = `pkg:npm/${packageName.replace(/^@/, "%40")}@${version}`; + const statements = slsaStatements(attestations); + if (statements.length === 0) return "none"; + const matches = statements.some((statement) => { + const workflow = statement.predicate?.buildDefinition?.externalParameters?.workflow ?? {}; + const commit = statement.predicate?.buildDefinition?.resolvedDependencies?.[0]?.digest?.gitCommit; + return statement.subject?.some((entry) => entry?.name === subject) + && workflow.repository === RELEASE_WORKFLOW.repository + && workflow.path === RELEASE_WORKFLOW.path + && workflow.ref === RELEASE_WORKFLOW.ref + && commit === sourceSha; + }); + return matches ? "match" : "mismatch"; +} + +const TRANSIENT = new Set([408, 425, 429, 500, 502, 503, 504]); + +async function fetchAttestations(url, { fetcher, attempts, sleep }) { + let lastError; + for (let attempt = 1; attempt <= attempts; attempt += 1) { + try { + const response = await fetcher(url, { signal: AbortSignal.timeout(30_000) }); + if (response.status === 404) return null; + if (response.ok) return await response.json(); + if (!TRANSIENT.has(response.status)) throw Object.assign(new Error(`HTTP ${response.status}`), { permanent: true }); + lastError = new Error(`HTTP ${response.status}`); + } catch (error) { + if (error.permanent) throw error; + lastError = error; + } + if (attempt < attempts) await sleep(Math.min(30_000, 1_000 * 2 ** (attempt - 1))); + } + throw lastError; +} + +export async function verifyCanaryProvenance({ packages, version, sourceSha, fetcher = fetch, attempts = 5, + sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)) }) { + if (!CANARY_VERSION.test(version ?? "")) throw new Error(`not a canary version: ${version}`); + if (!SHA.test(sourceSha ?? "")) throw new Error(`not a full commit SHA: ${sourceSha}`); + if (!packages?.length) throw new Error("at least one package is required"); + const problems = []; + const withoutProvenance = []; + let matched = 0; + for (const packageName of packages) { + const url = `https://registry.npmjs.org/-/npm/v1/attestations/${encodeURIComponent(packageName).replace(/^%40/, "@")}@${version}`; + let attestations; + try { + attestations = await fetchAttestations(url, { fetcher, attempts, sleep }); + } catch (error) { + problems.push(`${packageName}@${version}: attestations unavailable (${error.message})`); + continue; + } + const result = attestations ? packageProvenance(attestations, { packageName, version, sourceSha }) : "none"; + if (result === "match") matched += 1; + else if (result === "none") withoutProvenance.push(packageName); + else problems.push(`${packageName}@${version}: provenance does not name ${RELEASE_WORKFLOW.path} on ${RELEASE_WORKFLOW.ref} at ${sourceSha}`); + } + return { problems, matched, withoutProvenance }; +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + const [version, sourceSha, ...packages] = process.argv.slice(2); + try { + const { problems, matched, withoutProvenance } = await verifyCanaryProvenance({ packages, version, sourceSha }); + if (problems.length) { + for (const problem of problems) console.error(problem); + process.exitCode = 1; + } else { + console.log(`Provenance for ${matched} of ${packages.length} packages names ${RELEASE_WORKFLOW.path} at ${sourceSha}.`); + if (withoutProvenance.length) console.log(`Published without provenance (npm transparency-log retry): ${withoutProvenance.join(", ")}`); + } + } catch (error) { + console.error(error.message); + process.exitCode = 1; + } +} diff --git a/scripts/verify-canary-provenance.test.mjs b/scripts/verify-canary-provenance.test.mjs new file mode 100644 index 00000000000..a2d747b4ef9 --- /dev/null +++ b/scripts/verify-canary-provenance.test.mjs @@ -0,0 +1,73 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { packageProvenance, verifyCanaryProvenance } from "./verify-canary-provenance.mjs"; + +const sha = "b".repeat(40); +const version = "2026.1116.0-canary.2180000"; + +function attestation({ name = "%40paperclipai/shared", commit = sha, path = ".github/workflows/release.yml", ref = "refs/heads/master", + repository = "https://github.com/paperclipai/paperclip", predicateType = "https://slsa.dev/provenance/v1" } = {}) { + const statement = { subject: [{ name: `pkg:npm/${name}@${version}` }], + predicate: { buildDefinition: { externalParameters: { workflow: { repository, path, ref } }, resolvedDependencies: [{ digest: { gitCommit: commit } }] } } }; + return { attestations: [{ predicateType, bundle: { dsseEnvelope: { payload: Buffer.from(JSON.stringify(statement)).toString("base64") } } }] }; +} + +const check = (doc, packageName = "@paperclipai/shared") => packageProvenance(doc, { packageName, version, sourceSha: sha }); +const respond = (body, status = 200) => new Response(JSON.stringify(body), { status }); +const noSleep = async () => {}; +const registry = (byPackage) => async (url) => { + const name = decodeURIComponent(new URL(url).pathname.split("/attestations/")[1]).replace(/@[^@]+$/, ""); + const entry = byPackage[name]; + return typeof entry === "function" ? entry() : entry ?? respond({}, 404); +}; + +test("provenance from master's release workflow at the source commit matches, scoped or not", () => { + assert.equal(check(attestation()), "match"); + assert.equal(check(attestation({ name: "paperclipai" }), "paperclipai"), "match"); +}); + +test("provenance from another commit, workflow, branch, repository or package is a mismatch", () => { + for (const overrides of [{ commit: "c".repeat(40) }, { path: ".github/workflows/pr.yml" }, { ref: "refs/heads/feature" }, + { repository: "https://github.com/someone/paperclip" }, { name: "%40paperclipai/server" }]) { + assert.equal(check(attestation(overrides)), "mismatch", JSON.stringify(overrides)); + } +}); + +test("a package published through the transparency-log retry has no provenance, which is allowed beside a match", async () => { + assert.equal(check({ attestations: [] }), "none"); + assert.equal(check(attestation({ predicateType: "https://github.com/npm/attestation/tree/main/specs/publish/v0.1" })), "none"); + const result = await verifyCanaryProvenance({ packages: ["@paperclipai/shared", "paperclipai"], version, sourceSha: sha, sleep: noSleep, + fetcher: registry({ paperclipai: respond(attestation({ name: "paperclipai" })) }) }); + assert.deepEqual(result, { problems: [], matched: 1, withoutProvenance: ["@paperclipai/shared"] }); +}); + +test("packages that all took the retry report no match and no problem, and any mismatch is a problem", async () => { + const none = await verifyCanaryProvenance({ packages: ["@paperclipai/shared", "paperclipai"], version, sourceSha: sha, sleep: noSleep, fetcher: registry({}) }); + assert.deepEqual(none, { problems: [], matched: 0, withoutProvenance: ["@paperclipai/shared", "paperclipai"] }); + const mixed = await verifyCanaryProvenance({ packages: ["@paperclipai/shared", "paperclipai"], version, sourceSha: sha, sleep: noSleep, + fetcher: registry({ "@paperclipai/shared": respond(attestation()), paperclipai: respond(attestation({ name: "paperclipai", commit: "c".repeat(40) })) }) }); + assert.equal(mixed.problems.length, 1); + assert.match(mixed.problems[0], /^paperclipai@.*provenance does not name/); +}); + +test("a brief npm failure is retried, and a lasting or permanent one is a problem", async () => { + let calls = 0; + const flaky = await verifyCanaryProvenance({ packages: ["@paperclipai/shared"], version, sourceSha: sha, sleep: noSleep, + fetcher: registry({ "@paperclipai/shared": () => (++calls < 3 ? respond({}, 503) : respond(attestation())) }) }); + assert.deepEqual(flaky.problems, []); + assert.equal(calls, 3); + const lasting = await verifyCanaryProvenance({ packages: ["@paperclipai/shared"], version, sourceSha: sha, sleep: noSleep, attempts: 3, + fetcher: async () => { throw new Error("socket hang up"); } }); + assert.match(lasting.problems[0], /attestations unavailable \(socket hang up\)/); + let forbidden = 0; + const permanent = await verifyCanaryProvenance({ packages: ["@paperclipai/shared"], version, sourceSha: sha, sleep: noSleep, + fetcher: async () => { forbidden += 1; return respond({}, 403); } }); + assert.match(permanent.problems[0], /HTTP 403/); + assert.equal(forbidden, 1); +}); + +test("inputs are validated before any request", async () => { + const fetcher = async () => { throw new Error("must not fetch"); }; + await assert.rejects(verifyCanaryProvenance({ packages: ["paperclipai"], version: "2026.1116.0-nightly.1", sourceSha: sha, fetcher }), /not a canary version/); + await assert.rejects(verifyCanaryProvenance({ packages: ["paperclipai"], version, sourceSha: "abc", fetcher }), /not a full commit SHA/); +}); diff --git a/scripts/verify-release-registry-state.mjs b/scripts/verify-release-registry-state.mjs index c4848bafaba..8746ffac3ae 100644 --- a/scripts/verify-release-registry-state.mjs +++ b/scripts/verify-release-registry-state.mjs @@ -29,7 +29,7 @@ function usage() { process.stderr.write( [ "Usage:", - " node scripts/verify-release-registry-state.mjs --channel --dist-tag --target-version --package [--package ...] [--allow-canary-latest]", + " node scripts/verify-release-registry-state.mjs --channel --dist-tag --target-version --package [--package ...] [--allow-canary-latest] [--allow-newer-canary]", "", ].join("\n"), ); @@ -41,6 +41,7 @@ function parseArgs(argv) { distTag: "", targetVersion: "", allowCanaryLatest: false, + allowNewerCanary: false, packages: [], }; @@ -67,6 +68,9 @@ function parseArgs(argv) { case "--allow-canary-latest": options.allowCanaryLatest = true; break; + case "--allow-newer-canary": + options.allowNewerCanary = true; + break; case "-h": case "--help": usage(); @@ -96,6 +100,10 @@ function parseArgs(argv) { throw createExitError("--allow-canary-latest only applies to canary releases", EXIT_NON_RETRIABLE_FAILURE); } + if (options.allowNewerCanary && options.channel !== "canary") { + throw createExitError("--allow-newer-canary only applies to canary releases", EXIT_NON_RETRIABLE_FAILURE); + } + return options; } @@ -258,6 +266,20 @@ function requireManifest(packageName, version, packageDoc, packageManifestsByKey return manifest; } +export function compareCanaryVersions(left, right) { + const parse = (version) => { + const match = /^(\d+)\.(\d+)\.(\d+)-canary\.(\d+)$/.exec(version ?? ""); + return match ? match.slice(1).map(Number) : null; + }; + const a = parse(left); + const b = parse(right); + if (!a || !b) return null; + for (let index = 0; index < a.length; index += 1) { + if (a[index] !== b[index]) return a[index] < b[index] ? -1 : 1; + } + return 0; +} + export function verifyPackageRegistryProblems({ packageName, packageDoc, @@ -267,12 +289,14 @@ export function verifyPackageRegistryProblems({ distTag, targetVersion, allowCanaryLatest, + allowNewerCanary = false, }) { const problems = []; const distTags = packageDoc["dist-tags"] ?? {}; const taggedVersion = distTags[distTag]; + const taggedNewerCanary = allowNewerCanary && channel === "canary" && compareCanaryVersions(taggedVersion, targetVersion) === 1; - if (taggedVersion !== targetVersion) { + if (taggedVersion !== targetVersion && !taggedNewerCanary) { problems.push( createProblem( `${packageName}: dist-tag ${distTag} resolves to ${taggedVersion ?? ""}, expected ${targetVersion}`, @@ -444,6 +468,7 @@ async function main() { distTag: options.distTag, targetVersion: options.targetVersion, allowCanaryLatest: options.allowCanaryLatest, + allowNewerCanary: options.allowNewerCanary, }); if (packageProblems.length === 0) { diff --git a/scripts/verify-release-registry-state.test.mjs b/scripts/verify-release-registry-state.test.mjs index 112d61c307f..c888af329b2 100644 --- a/scripts/verify-release-registry-state.test.mjs +++ b/scripts/verify-release-registry-state.test.mjs @@ -9,6 +9,7 @@ import { isPrereleaseVersion, verifyPackageRegistryProblems, verifyPackageRegistryState, + compareCanaryVersions, } from "./verify-release-registry-state.mjs"; test("isCanaryVersion matches release canaries", () => { @@ -399,3 +400,27 @@ test("fetchRegistryJson times out hung requests", async () => { globalThis.fetch = originalFetch; } }); + +test("a finalizing canary accepts a dist-tag that a newer canary already moved, and nothing older or foreign", () => { + const check = (canaryTag, allowNewerCanary, channel = "canary") => { + const packageDoc = { "dist-tags": { latest: "2026.1110.0", canary: canaryTag }, versions: { "2026.1116.0-canary.21800": {} } }; + return verifyPackageRegistryProblems({ + packageName: "@paperclipai/shared", packageDoc, packageDocsByName: new Map([["@paperclipai/shared", packageDoc]]), + channel, distTag: "canary", targetVersion: "2026.1116.0-canary.21800", allowCanaryLatest: false, allowNewerCanary, + }).map((problem) => problem.message); + }; + assert.deepEqual(check("2026.1116.0-canary.21800", true), []); + assert.deepEqual(check("2026.1116.0-canary.21805", true), []); + assert.deepEqual(check("2026.1117.0-canary.21803", true), []); + assert.match(check("2026.1116.0-canary.21805", false)[0], /resolves to 2026\.1116\.0-canary\.21805, expected/); + assert.match(check("2026.1116.0-canary.21799", true)[0], /resolves to 2026\.1116\.0-canary\.21799, expected/); + assert.match(check("2026.1116.0-nightly.3", true)[0], /resolves to 2026\.1116\.0-nightly\.3, expected/); + assert.match(check(undefined, true)[0], /resolves to /); +}); + +test("canary versions compare by base version, then canary number", () => { + assert.equal(compareCanaryVersions("2026.1116.0-canary.9", "2026.1116.0-canary.21800"), -1); + assert.equal(compareCanaryVersions("2026.1117.0-canary.1", "2026.1116.0-canary.21800"), 1); + assert.equal(compareCanaryVersions("2026.1116.0-canary.7", "2026.1116.0-canary.7"), 0); + assert.equal(compareCanaryVersions("2026.1116.0-nightly.7", "2026.1116.0-canary.7"), null); +});