From 23b9aaa8e697dc9808e2229eea357da24e69560e Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Fri, 9 Oct 2026 17:14:32 -0700 Subject: [PATCH 1/7] fix(release): reuse publisher lockfile for canary smoke (#15712) ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Every master push publishes an exact canary and tests its onboarding flow. > - The publisher resolves dependencies before building, while the smoke job checks out the committed lockfile again. > - Patch or manifest changes can land before the separate lockfile refresh, so the smoke fails before testing the published app. > - This pull request passes the publisher's resolved lockfile to the same-source smoke job. > - The smoke keeps frozen dependency validation and tests the exact published canary version. ## Linked Issues or Issue Description Refs #10393, #13689. Related work: #13690 documents lockfile drift; #12115 addresses refresh-PR check triggering. This change addresses the canary smoke handoff. #15678 only refreshed the opencode importer. #15164 incidentally corrected the earlier patch hash on master. **What happened?** Canary publication succeeded, but the fresh onboarding smoke install failed with `ERR_PNPM_LOCKFILE_CONFIG_MISMATCH` on sources `0b80ea17ef` and `ab8dcab809`. The committed `acpx@0.13.1` hash no longer matched its patch. A later run on `6080daf262` failed with `ERR_PNPM_OUTDATED_LOCKFILE` after an `opencode-ai` manifest addition. The current master lockfile has since caught up; the workflow still permits this race on future changes. **Expected behavior** The exact published canary reaches the onboarding smoke with test dependencies resolved for its source. A mismatched or missing lockfile must fail validation. **Steps to reproduce** Check out either affected source and run `pnpm install --frozen-lockfile` with pnpm 9.15.4. The smoke fails before a browser starts, although the publisher already installed that source with a resolved lockfile. ## What Changed - Pin both canary publisher and onboarding smoke checkouts to the triggering SHA. - Save the publisher's resolved lockfile before restoring tracked files or rewriting release versions. - Restore that same-run, source-named artifact before the unchanged frozen smoke install. - Add offline real-pnpm regressions for patch-hash and manifest drift, plus wrong-source rejection and workflow binding checks. - Document artifact retention and job reruns. No manifest or committed lockfile changes. ## Verification - Focused release workflow, exact-source verification and image-contract tests: 45 passed. - Negative control: both new real-pnpm fixture cases fail against the original workflow with their respective original lockfile errors; both pass with the handoff. - `pnpm install --frozen-lockfile` passed on the current source. - `pnpm -r typecheck` and `pnpm build` passed after reclaiming disposable build-cache space. - The browser onboarding smoke passed against exact published `2026.1009.0-canary.7`: 1 test passed using a fresh temporary instance. - Full local `pnpm test:run` was attempted twice. The first hit disk exhaustion; the second reported one chat integration failure and then a Vitest worker `ENOTCONN` crash before completing. This is not a full-suite pass. The named chat case passed in isolation without changes. All full sharded PR CI checks passed on the final head. - Independent source review and a clean-checkout run also passed all 45 focused tests, with separate real-pnpm negative controls. - The supply-chain scan is neutral because managed intelligence could not scan the pinned official `download-artifact` action. It reported no defect; independent review inspected the action source, same-run scope and v4/v4 compatibility. - Reviewed the diff for secrets, personal data and generated artifacts; none found. ## Risks - The smoke now depends on a same-run GitHub artifact retained for 14 days. A missing artifact intentionally fails instead of resolving a different dependency set. - A publisher rerun replaces its source-named artifact; a smoke-only rerun reuses the retained artifact. - Frozen validation and the exact published version remain required. The source app and publication logic do not change. ## Model Used OpenAI GPT-6 through Codex, with tool execution and parallel independent review. The exact serving variant and context-window size are not exposed in this session. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge Co-authored-by: Paperclip --- .github/workflows/release.yml | 23 +++++ doc/RELEASING.md | 12 +++ .../release-verify-workflow.test.mjs | 96 ++++++++++++++++++- 3 files changed, 130 insertions(+), 1 deletion(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 32b36ea2421..cdb91e941df 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -354,6 +354,7 @@ jobs: - name: Checkout repository uses: actions/checkout@v7 with: + ref: ${{ github.sha }} fetch-depth: 0 - name: Setup pnpm @@ -373,6 +374,18 @@ jobs: - name: Install dependencies run: pnpm install --no-frozen-lockfile + # Master can precede the separate lockfile-refresh PR. Preserve the + # resolution used for this build before release tooling restores the + # tracked lockfile or rewrites workspace versions. + - name: Save canary smoke lockfile + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + with: + name: canary-smoke-lockfile-${{ github.sha }} + path: pnpm-lock.yaml + if-no-files-found: error + overwrite: true + retention-days: 14 + - name: Restore tracked install-time changes run: git checkout -- pnpm-lock.yaml @@ -447,6 +460,9 @@ jobs: 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 @@ -458,6 +474,13 @@ jobs: 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 diff --git a/doc/RELEASING.md b/doc/RELEASING.md index 3eb0059316a..fe7fb13fdf7 100644 --- a/doc/RELEASING.md +++ b/doc/RELEASING.md @@ -103,6 +103,18 @@ It: - 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` +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 +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 +the exact published canary version, not a workspace build. + +The lockfile artifact is retained for 14 days. A publisher-job rerun replaces its +source-named artifact; a smoke-only rerun uses the existing artifact. A missing +artifact fails the job rather than falling back to a different dependency set. + Users install canaries with: ```bash diff --git a/scripts/__tests__/release-verify-workflow.test.mjs b/scripts/__tests__/release-verify-workflow.test.mjs index 98717aa8afa..cc1602d0866 100644 --- a/scripts/__tests__/release-verify-workflow.test.mjs +++ b/scripts/__tests__/release-verify-workflow.test.mjs @@ -1,6 +1,7 @@ import assert from "node:assert/strict"; import { spawnSync } from "node:child_process"; -import { existsSync, readdirSync, readFileSync } from "node:fs"; +import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import os from "node:os"; import path from "node:path"; import { fileURLToPath } from "node:url"; import test from "node:test"; @@ -170,6 +171,99 @@ test("published canaries are gated by the exact-version onboarding browser smoke assert.match(releaseWorkflow, /tests\/canary-onboarding\/playwright-report/); }); +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/); + } + 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.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/); +}); + +for (const drift of ["patch", "manifest"]) { + test(`a publisher lockfile lets a fresh smoke install retain validation after ${drift} drift`, (t) => { + const root = mkdtempSync(path.join(os.tmpdir(), "canary-smoke-lockfile-test-")); + t.after(() => rmSync(root, { recursive: true, force: true })); + const source = path.join(root, "package"); + mkdirSync(source); + writeFileSync(path.join(source, "package.json"), JSON.stringify({ name: "smoke-fixture-dependency", version: "1.0.0" })); + writeFileSync(path.join(source, "index.js"), 'module.exports = "original";\n'); + const pack = spawnSync("npm", ["pack", "--ignore-scripts", "--pack-destination", root], { cwd: source, encoding: "utf8" }); + assert.equal(pack.status, 0, pack.stderr); + const manifest = { + name: "canary-smoke-fixture", private: true, + packageManager: "pnpm@9.15.4", + dependencies: { "smoke-fixture-dependency": "file:smoke-fixture-dependency-1.0.0.tgz" }, + pnpm: { patchedDependencies: { "smoke-fixture-dependency@1.0.0": "fixture.patch" } }, + }; + writeFileSync(path.join(root, "package.json"), JSON.stringify(manifest)); + writeFileSync(path.join(root, "pnpm-workspace.yaml"), "packages: []\n"); + const patch = (value) => writeFileSync(path.join(root, "fixture.patch"), [ + "diff --git a/index.js b/index.js", "index 1111111..2222222 100644", + "--- 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 installArgs = (name) => { + const job = name === "Install dependencies" ? publish : smoke; + const command = job.match(new RegExp(`name: ${name}\\n\\s+run: (pnpm install[^\\n]+)`))?.[1]; + assert.ok(command, `missing ${name}`); + return [...command.split(" ").slice(1), "--offline", "--ignore-scripts"]; + }; + const install = (args) => spawnSync("pnpm", args, { + cwd: root, encoding: "utf8", env: { ...process.env, CI: "true" }, + }); + const success = (result) => assert.equal(result.status, 0, `${result.stdout}\n${result.stderr}`); + patch(drift === "patch" ? "old-patch" : "published-patch"); + success(install(installArgs("Install dependencies"))); + const staleLock = readFileSync(path.join(root, "pnpm-lock.yaml")); + if (drift === "patch") { + patch("published-patch"); + } else { + copyFileSync(path.join(root, "smoke-fixture-dependency-1.0.0.tgz"), path.join(root, "updated-dependency.tgz")); + manifest.dependencies["smoke-fixture-dependency"] = "file:updated-dependency.tgz"; + writeFileSync(path.join(root, "package.json"), JSON.stringify(manifest)); + } + const before = install(installArgs("Install test dependencies")); + assert.notEqual(before.status, 0); + assert.match(before.stdout + before.stderr, drift === "patch" ? /ERR_PNPM_LOCKFILE_CONFIG_MISMATCH/ : /ERR_PNPM_OUTDATED_LOCKFILE/); + + // Capture the publisher's resolution, then reproduce its tracked-file restore + // and a fresh smoke runner with no installed workspace dependencies. + success(install(installArgs("Install dependencies"))); + const artifact = path.join(root, "publisher-lock.yaml"); + if (publish.includes("name: Save canary smoke lockfile")) { + copyFileSync(path.join(root, "pnpm-lock.yaml"), artifact); + } + writeFileSync(path.join(root, "pnpm-lock.yaml"), staleLock); + rmSync(path.join(root, "node_modules"), { recursive: true, force: true }); + if (smoke.includes("name: Restore canary smoke lockfile")) { + copyFileSync(artifact, path.join(root, "pnpm-lock.yaml")); + } + success(install(installArgs("Install test dependencies"))); + assert.equal(readFileSync(path.join(root, "node_modules/smoke-fixture-dependency/index.js"), "utf8"), 'module.exports = "published-patch";\n'); + assert.deepEqual(readFileSync(path.join(root, "pnpm-lock.yaml")), readFileSync(artifact)); + + // A lockfile from the wrong source still fails closed; restoring an artifact + // must not disable hash validation or resolve another version in the smoke job. + patch("different-source"); + const wrongSource = install(installArgs("Install test dependencies")); + assert.notEqual(wrongSource.status, 0); + assert.match(wrongSource.stdout + wrongSource.stderr, /ERR_PNPM_LOCKFILE_CONFIG_MISMATCH/); + }); +} + test("every lane's tag push degrades to recovery instructions when rejected", () => { const releaseWorkflow = readWorkflow("release.yml"); From 935fb63ed585e8c3a5a23436f393968f4f1850d2 Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Fri, 9 Oct 2026 17:15:02 -0700 Subject: [PATCH 2/7] fix(release): retry incomplete canary dependency publications (#15743) ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Release checks must test the exact package that a new user installs. > - The canary onboarding smoke uses a fresh npm dependency graph. > - An upstream package can reference a dependency before that version is available. > - The smoke then exits before Paperclip onboarding starts. > - This pull request retries only that npm acquisition failure within the existing startup limit. > - Onboarding still runs once, and all other errors remain visible. ## Linked Issues or Issue Description **What happened?** [Release run 37986221440](https://github.com/paperclipai/paperclip/actions/runs/37986221440) published `2026.1009.0-canary.13`, then failed the onboarding smoke. The retained server log contains npm `ETARGET` for `@aws-sdk/credential-provider-env@^3.972.73`. The upstream parent package was published before this dependency. The missing version became available during the smoke startup. Paperclip onboarding never ran. **Expected behavior** Retry a short dependency publication window before onboarding starts. Stop on a permanent install failure. Never repeat onboarding to hide a startup failure. **Steps to reproduce** 1. Start the exact-version canary smoke with an empty npm cache. 2. Make the first npm install return `ETARGET` because a dependency version is not available. 3. Make the next install succeed after registry metadata changes. 4. Confirm that onboarding starts once. Repeat with permanent `ETARGET` and an unrelated failure; onboarding must not start. **Paperclip version or commit** The observed release source was `cb291bf1298ab484a2792c05eb977f3440f1f351`. **Deployment mode** Linux release CI. The change affects the canary smoke harness. Related: #15712 fixes a separate lockfile mismatch in the smoke's repository dependency install. This change covers the fresh published-package npm install. ## What Changed - Separate npm package acquisition from the onboarding command. - Retry only the final npm `ETARGET` error, up to three attempts with online metadata and clean temporary prefixes. - Share a two-minute acquisition budget across attempts and backoff. Keep the existing five-minute Playwright startup limit. - Run the installed exact-version CLI once. Preserve authentication, network, lifecycle, and onboarding failures. - Stop owned process groups on cancellation and remove owned install prefixes. Keep server logs and instance data for diagnostics. - Keep dependency-free helper subprocess tests in the required policy lane. Run real Playwright lifecycle tests in the required release-registry lane after its dependencies are installed. - Document the bounded behavior in the release runbook. ## Verification - `node --test scripts/__tests__/release-verify-workflow.test.mjs`: 24 passed in a clean source snapshot with no `node_modules`. These cover transient and permanent missing versions, other npm errors, nested error codes, onboarding failure, deadline expiry, and cancellation. - `pnpm test:release-registry`: 153 passed, including real Playwright teardown with a descendant that ignores SIGTERM and startup-timeout cleanup of a detached npm installer. - `pnpm -r typecheck`: passed. - `pnpm build`: passed. - `pnpm test:run`: deliberately stopped after complete hosted CI passed; this is not a local full-suite pass. The run's 15 warm-runtime real-DB cases failed before assertions because the local macOS PostgreSQL package lacked library symlinks after installation with `--ignore-scripts`. After running the package's local hydration step, all 15 affected cases passed in a targeted rerun. The remaining aggregate was stopped with exact owned-process cleanup. - [Hosted CI](https://github.com/paperclipai/paperclip/actions/runs/37994486323) is complete and green at `1c80e6f`: all tests, build, typecheck, policy, release registry, E2E, and canary dry run passed. Greptile scored the same head 5/5 with no unresolved comments. - Independent review covered all seven changed files and the exact policy and release-registry commands. It also used real npm 11.9 against a loopback registry: a required version was absent, then became available. The retry refreshed metadata and started the installed exact-version CLI once. The one-attempt negative control failed. - The new subprocess tests use local npm and CLI fixtures. They do not contact a registry or start a real Paperclip instance. - The patch preserves the exact-version clean-install check. It adds no dependency pins, credentials, or workflow reruns. ## Risks The install phase now has a two-minute budget inside the existing five-minute startup limit. An unusually slow valid install can still fail the smoke. Permanent missing versions remain failures after the bounded retry. The lifecycle tests cover the Linux release runner behavior; Playwright does not support graceful SIGTERM on Windows. No application, database, or deployment behavior changes. ## Model Used OpenAI GPT-6 through Codex, with reasoning and code execution tools. The exact service variant and context window are not exposed in this session. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes: #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip --- doc/RELEASING.md | 1 + package.json | 2 +- scripts/__tests__/canary-startup-fixture.mjs | 114 ++++++++++++++++ .../canary-startup-playwright.test.mjs | 29 ++++ .../release-verify-workflow.test.mjs | 92 +++++++++++++ tests/canary-onboarding/playwright.config.ts | 11 +- .../start-published-canary.mjs | 127 ++++++++++++++++++ 7 files changed, 369 insertions(+), 7 deletions(-) create mode 100644 scripts/__tests__/canary-startup-fixture.mjs create mode 100644 scripts/__tests__/canary-startup-playwright.test.mjs create mode 100644 tests/canary-onboarding/start-published-canary.mjs diff --git a/doc/RELEASING.md b/doc/RELEASING.md index fe7fb13fdf7..5e0666508ab 100644 --- a/doc/RELEASING.md +++ b/doc/RELEASING.md @@ -100,6 +100,7 @@ It: - 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; only npm `ETARGET` install failures retry, up to three attempts within two minutes, before onboarding runs once under the existing five-minute startup deadline - 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` diff --git a/package.json b/package.json index d37129f05ed..3e026aa985a 100644 --- a/package.json +++ b/package.json @@ -61,7 +61,7 @@ "smoke:posthog-live": "node scripts/smoke/posthog-live.mjs", "smoke:pipelines-tutorial": "./scripts/smoke/pipelines-tutorial-smoke.sh", "smoke:terminal-bench-loop-skill": "node scripts/smoke/terminal-bench-loop-skill-smoke.mjs", - "test:release-registry": "node --test scripts/__tests__/cursor-public-install-sandbox.test.mjs scripts/__tests__/grok-public-install-sandbox.test.mjs scripts/__tests__/retain-runner-qualification-packages.test.mjs scripts/verify-release-registry-state.test.mjs scripts/release-package-map.test.mjs scripts/check-release-package-bootstrap.test.mjs scripts/check-no-git-push.test.mjs scripts/release-lib.test.mjs scripts/release-registry-versions.test.mjs scripts/link-plugin-dev-sdk.test.js scripts/acpx-patch-packaging.test.mjs scripts/service-onboard-smoke.test.mjs scripts/docker-onboard-smoke.test.mjs scripts/preview-artifacts.test.mjs scripts/cloud-migrator-artifacts.test.mjs", + "test:release-registry": "node --test scripts/__tests__/canary-startup-playwright.test.mjs scripts/__tests__/cursor-public-install-sandbox.test.mjs scripts/__tests__/grok-public-install-sandbox.test.mjs scripts/__tests__/retain-runner-qualification-packages.test.mjs scripts/verify-release-registry-state.test.mjs scripts/release-package-map.test.mjs scripts/check-release-package-bootstrap.test.mjs scripts/check-no-git-push.test.mjs scripts/release-lib.test.mjs scripts/release-registry-versions.test.mjs scripts/link-plugin-dev-sdk.test.js scripts/acpx-patch-packaging.test.mjs scripts/service-onboard-smoke.test.mjs scripts/docker-onboard-smoke.test.mjs scripts/preview-artifacts.test.mjs scripts/cloud-migrator-artifacts.test.mjs", "storybook-visual:baseline": "node scripts/storybook-visual-baseline.mjs", "test:storybook-visual": "node scripts/storybook-visual-baseline.mjs download && node scripts/storybook-visual-baseline.mjs verify && pnpm build-storybook && npx playwright test --config tests/storybook-visual/playwright.config.ts", "test:storybook-visual:update": "node scripts/storybook-visual-baseline.mjs download && pnpm build-storybook && npx playwright test --config tests/storybook-visual/playwright.config.ts --update-snapshots && node scripts/storybook-visual-baseline.mjs pack", diff --git a/scripts/__tests__/canary-startup-fixture.mjs b/scripts/__tests__/canary-startup-fixture.mjs new file mode 100644 index 00000000000..d75d1fa944c --- /dev/null +++ b/scripts/__tests__/canary-startup-fixture.mjs @@ -0,0 +1,114 @@ +import assert from "node:assert/strict"; +import { spawn } from "node:child_process"; +import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync, mkdirSync } from "node:fs"; +import os from "node:os"; +import net from "node:net"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", ".."); + +// Exercise the real startup helper and child-process boundary without registry +// traffic. The npm fixture installs a real executable into its isolated prefix. +export async function canaryStartup({ mode, onboard = "success", budget = 5000, delay = 5, cancelAtKind, playwright = false }) { + const root = mkdtempSync(path.join(os.tmpdir(), "canary-startup-test-")); + const calls = path.join(root, "calls.jsonl"); + const fixtureBin = path.join(root, "bin"); + mkdirSync(fixtureBin); + const npmFixture = path.join(fixtureBin, "npm"); + const port = await new Promise((resolve, reject) => { + const server = net.createServer(); + server.on("error", reject); + server.listen(0, "127.0.0.1", () => { const port = server.address().port; server.close(() => resolve(port)); }); + }); + const cli = `#!/usr/bin/env node +const { appendFileSync } = require("node:fs"); +appendFileSync(process.env.FIXTURE_CALLS, JSON.stringify({kind:"onboard", pid:process.pid, args:process.argv.slice(2)}) + "\\n"); +if (process.env.FIXTURE_ONBOARD === "fail") { console.error("npm error code ETARGET"); process.exit(17); } +if (process.env.FIXTURE_ONBOARD === "hang") { setTimeout(() => {}, 10000); } +if (process.env.FIXTURE_ONBOARD === "serve") { + const { spawn } = require("node:child_process"); + const child = spawn(process.execPath, ["-e", "process.on('SIGTERM',()=>{}); setTimeout(()=>process.exit(0),10000)"], {stdio:"ignore"}); + appendFileSync(process.env.FIXTURE_CALLS, JSON.stringify({kind:"descendant", pid:child.pid}) + "\\n"); + process.on("SIGTERM", () => {}); + setTimeout(() => process.exit(0), 10000); + require("node:http").createServer((req,res) => {res.end("ok");}).listen(Number(process.env.FIXTURE_PORT), "127.0.0.1"); +} +`; + writeFileSync(npmFixture, `#!/usr/bin/env node +const fs = require("node:fs"); +const path = require("node:path"); +const args = process.argv.slice(2); +const entries = fs.existsSync(process.env.FIXTURE_CALLS) ? fs.readFileSync(process.env.FIXTURE_CALLS, "utf8").trim().split("\\n").filter(Boolean).map(JSON.parse) : []; +const attempt = entries.filter(e => e.kind === "npm").length + 1; +fs.appendFileSync(process.env.FIXTURE_CALLS, JSON.stringify({kind:"npm", pid:process.pid, args, cache:process.env.npm_config_cache}) + "\\n"); +const mode = process.env.FIXTURE_MODE; +if (mode === "hang") { setTimeout(() => {}, 10000); } +else if (mode === "permanent" || (mode === "recover" && attempt === 1)) { console.error("npm error code ETARGET"); process.exit(1); } +else if (mode === "auth") { console.error("npm error code E401"); process.exit(1); } +else if (mode === "mixed") { console.error("npm error code ETARGET\\nnpm error code E401"); process.exit(1); } +else if (mode === "network") { console.error("npm error code ECONNRESET"); process.exit(1); } +else { + const prefix = args[args.indexOf("--prefix") + 1]; + const bin = path.join(prefix, "node_modules", ".bin"); + fs.mkdirSync(bin, {recursive:true}); + fs.writeFileSync(path.join(bin, "paperclipai"), ${JSON.stringify(cli).replaceAll('$','\$')}); + fs.chmodSync(path.join(bin, "paperclipai"), 0o755); +} +`); + chmodSync(npmFixture, 0o755); + const helper = new URL("../../tests/canary-onboarding/start-published-canary.mjs", import.meta.url).href; + const driver = path.join(root, "driver.mjs"); + writeFileSync(driver, `import { startPublishedCanary } from ${JSON.stringify(helper)}; +try { await startPublishedCanary({version:"2026.1009.0-canary.1", workspace:${JSON.stringify(root)}, dataDir:${JSON.stringify(path.join(root,"data"))}, installBudgetMs:${budget}, retryDelayMs:${delay}}); } +catch (error) { console.error(error.message); process.exitCode = 1; } +`); + const playwrightConfig = path.join(root, "playwright.config.mjs"); + if (playwright) { + const originalConfig = path.join(repoRoot, "tests/canary-onboarding/playwright.config.ts"); + const testApi = new URL("../../node_modules/@playwright/test/index.mjs", import.meta.url).href; + writeFileSync(path.join(root,"fixture.spec.mjs"), `import { test } from ${JSON.stringify(testApi)}; test("fixture", async()=>{});`); + writeFileSync(playwrightConfig, `import original from ${JSON.stringify(originalConfig)}; +export default {...original, testDir:${JSON.stringify(root)}, testMatch:"fixture.spec.mjs", reporter:"list", projects:[{name:"fixture"}], webServer:{...original.webServer, timeout:${mode === "hang" ? 2500 : 300000}}};`); + } + const started = Date.now(); + try { + const result = await new Promise((resolve, reject) => { + const child = spawn(process.execPath, playwright + ? [path.join(repoRoot, "node_modules/@playwright/test/cli.js"), "test", "--config", playwrightConfig] + : cancelAtKind + ? [fileURLToPath(helper), "2026.1009.0-canary.1", root, path.join(root, "data")] + : [driver], { cwd: repoRoot, env: { + ...process.env, PATH: fixtureBin + path.delimiter + process.env.PATH, + FIXTURE_MODE: mode, FIXTURE_ONBOARD: onboard, FIXTURE_CALLS: calls, FIXTURE_PORT: String(port), + PAPERCLIPAI_VERSION: "2026.1009.0-canary.1", PAPERCLIP_CANARY_SMOKE_BASE_URL: `http://127.0.0.1:${port}`, PAPERCLIP_CANARY_SMOKE_SERVER_LOG: path.join(root,"server.log"), + npm_config_cache: path.join(root, "fresh-cache"), + }, stdio: ["ignore", "pipe", "pipe"] }); + let output = ""; + const cancellation = cancelAtKind && setInterval(() => { + if (!existsSync(calls)) return; + const rows = readFileSync(calls, "utf8").trim().split("\n").filter(Boolean).map(JSON.parse); + if (rows.some(row => row.kind === cancelAtKind)) { + clearInterval(cancellation); + child.kill("SIGTERM"); + } + }, 10); + child.stdout.on("data", (data) => { output += data; }); + child.stderr.on("data", (data) => { output += data; }); + child.on("error", reject); + child.on("close", (code) => { clearInterval(cancellation); resolve({code, output}); }); + }); + if (playwright && existsSync(path.join(root,"server.log"))) result.output += readFileSync(path.join(root,"server.log"), "utf8"); + const records = existsSync(calls) ? readFileSync(calls,"utf8").trim().split("\n").filter(Boolean).map(JSON.parse) : []; + const prefixes = records.filter(call => call.kind === "npm").map(call => call.args[call.args.indexOf("--prefix") + 1]); + if (playwright) { + const deadline = Date.now() + 2000; + while (prefixes.some(prefix => existsSync(prefix)) && Date.now() < deadline) { + await new Promise(resolve => setTimeout(resolve, 20)); + } + } + assert.deepEqual(prefixes.filter(prefix => existsSync(prefix)), [], "helper-owned install prefixes must be removed"); + return { ...result, elapsed: Date.now()-started, calls: records }; + + } finally { rmSync(root, {recursive:true, force:true}); } +} diff --git a/scripts/__tests__/canary-startup-playwright.test.mjs b/scripts/__tests__/canary-startup-playwright.test.mjs new file mode 100644 index 00000000000..dc7abdd7f17 --- /dev/null +++ b/scripts/__tests__/canary-startup-playwright.test.mjs @@ -0,0 +1,29 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { canaryStartup } from "./canary-startup-fixture.mjs"; + +test("actual Playwright teardown stops the CLI and descendants that ignore SIGTERM", async () => { + const result = await canaryStartup({ mode: "success", onboard: "serve", playwright: true }); + assert.equal(result.code, 0, result.output); + assert.equal(result.calls.filter(call => call.kind === "onboard").length, 1); + const processes = result.calls.filter(call => ["onboard", "descendant"].includes(call.kind)); + assert.equal(processes.length, 2); + for (const call of processes) { + const deadline = Date.now() + 2000; + while (Date.now() < deadline) { + try { process.kill(call.pid, 0); } catch (error) { if (error.code === "ESRCH") break; throw error; } + await new Promise(resolve => setTimeout(resolve, 20)); + } + assert.throws(() => process.kill(call.pid, 0), {code:"ESRCH"}, `fixture ${call.kind} outlived bounded teardown`); + } +}); + +test("actual Playwright startup timeout cancels a detached npm install", async () => { + const result = await canaryStartup({ mode: "hang", playwright: true }); + assert.equal(result.code, 1); + const installs = result.calls.filter(call => call.kind === "npm"); + assert.equal(installs.length, 1, result.output); + assert.equal(result.calls.filter(call => call.kind === "onboard").length, 0); + assert.throws(() => process.kill(installs[0].pid,0), {code:"ESRCH"}); + assert.ok(result.elapsed < 10000, `startup timeout did not stop npm: ${result.elapsed}ms`); +}); diff --git a/scripts/__tests__/release-verify-workflow.test.mjs b/scripts/__tests__/release-verify-workflow.test.mjs index cc1602d0866..bef97786dcf 100644 --- a/scripts/__tests__/release-verify-workflow.test.mjs +++ b/scripts/__tests__/release-verify-workflow.test.mjs @@ -5,6 +5,7 @@ import os from "node:os"; import path from "node:path"; import { fileURLToPath } from "node:url"; import test from "node:test"; +import { canaryStartup } from "./canary-startup-fixture.mjs"; const repoRoot = path.resolve( path.dirname(fileURLToPath(import.meta.url)), @@ -574,3 +575,94 @@ test("direct protocol concurrency override only lowers the configured ceiling", if (expected !== null) assert.equal(result.stdout, expected); } }); + + + +test("canary startup refreshes an incomplete dependency publication, then onboards once", async () => { + const result = await canaryStartup({ mode: "recover" }); + assert.equal(result.code, 0, result.output); + const installs = result.calls.filter(call => call.kind === "npm"); + const onboarding = result.calls.filter(call => call.kind === "onboard"); + assert.equal(installs.length, 2); + assert.equal(onboarding.length, 1); + for (const call of installs) { + assert.equal(call.args[0], "install"); + assert.ok(call.args.includes("paperclipai@2026.1009.0-canary.1")); + assert.ok(call.args.includes("--no-package-lock")); + assert.ok(call.args.includes("--no-save")); + } + assert.ok(!installs[0].args.includes("--prefer-online")); + assert.ok(installs[1].args.includes("--prefer-online")); + assert.notEqual(installs[0].args[2], installs[1].args[2]); + assert.equal(installs[0].cache, installs[1].cache); + assert.deepEqual(onboarding[0].args.slice(0, 3), ["onboard", "--yes", "--data-dir"]); +}); + +test("permanent missing versions stop after three attempts without onboarding", async () => { + const result = await canaryStartup({ mode: "permanent" }); + assert.equal(result.code, 1); + assert.equal(result.calls.filter(call => call.kind === "npm").length, 3); + assert.equal(result.calls.filter(call => call.kind === "onboard").length, 0); + assert.match(result.output, /installation failed.*onboarding was not started/); +}); + +test("npm failures other than ETARGET fail immediately without onboarding", async () => { + const result = await canaryStartup({ mode: "auth" }); + assert.equal(result.code, 1); + assert.equal(result.calls.length, 1); + assert.match(result.output, /E401/); +}); + +test("onboarding failures are never retried, even when they mention ETARGET", async () => { + const result = await canaryStartup({ mode: "success", onboard: "fail" }); + assert.equal(result.code, 1); + assert.equal(result.calls.filter(call => call.kind === "npm").length, 1); + assert.equal(result.calls.filter(call => call.kind === "onboard").length, 1); + assert.match(result.output, /onboarding failed \(exit 17\)/); +}); + +test("a hanging npm install is stopped within the shared acquisition budget", async () => { + const result = await canaryStartup({ mode: "hang", budget: 1000 }); + assert.equal(result.code, 1); + assert.equal(result.calls.filter(call => call.kind === "npm").length, 1); + assert.equal(result.calls.filter(call => call.kind === "onboard").length, 0); + assert.ok(result.elapsed < 4000, `install exceeded bounded cancellation: ${result.elapsed}ms`); + assert.match(result.output, /exceeded its startup budget/); +}); + +test("backoff consumes the shared budget and does not begin another install after expiry", async () => { + const result = await canaryStartup({ mode: "permanent", budget: 1000, delay: 5000 }); + assert.equal(result.code, 1); + assert.equal(result.calls.length, 1); + assert.match(result.output, /exceeded its startup budget/); +}); + + +test("Playwright cancellation stops an onboarding process without replay", async () => { + const result = await canaryStartup({ mode: "success", onboard: "hang", cancelAtKind: "onboard" }); + assert.equal(result.code, 1); + assert.equal(result.calls.filter(call => call.kind === "npm").length, 1); + const onboarding = result.calls.filter(call => call.kind === "onboard"); + assert.equal(onboarding.length, 1); + assert.throws(() => process.kill(onboarding[0].pid, 0), {code:"ESRCH"}); + assert.match(result.output, /stopped by SIGTERM/); + assert.ok(result.elapsed < 2500, `onboarding cancellation took ${result.elapsed}ms`); +}); + +test("canary install retries retain the existing overall Playwright startup deadline", async () => { + const { INSTALL_BUDGET_MS } = await import("../../tests/canary-onboarding/start-published-canary.mjs"); + const config = readFileSync(path.join(repoRoot, "tests/canary-onboarding/playwright.config.ts"), "utf8"); + assert.equal(INSTALL_BUDGET_MS, 120_000); + assert.match(config, /timeout: 300_000/); + assert.match(config, /start-published-canary\.mjs/); + assert.match(config, /reuseExistingServer: false/); +}); + + +test("nested ETARGET output does not retry a final authentication or network failure", async () => { + for (const mode of ["mixed", "network"]) { + const result = await canaryStartup({ mode }); + assert.equal(result.code, 1); + assert.equal(result.calls.length, 1); + } +}); diff --git a/tests/canary-onboarding/playwright.config.ts b/tests/canary-onboarding/playwright.config.ts index 20345b25f7c..ea75c3bbd84 100644 --- a/tests/canary-onboarding/playwright.config.ts +++ b/tests/canary-onboarding/playwright.config.ts @@ -34,12 +34,10 @@ function shellQuote(value: string): string { } const command = [ - "npx", - "--yes", - shellQuote(`paperclipai@${canaryVersion}`), - "onboard", - "--yes", - "--data-dir", + shellQuote(process.execPath), + shellQuote(path.resolve("tests/canary-onboarding/start-published-canary.mjs")), + shellQuote(canaryVersion), + shellQuote(workspace), shellQuote(dataDir), ">", shellQuote(serverLog), @@ -76,6 +74,7 @@ export default defineConfig({ command, url: `${baseUrl}/api/health`, reuseExistingServer: false, + gracefulShutdown: { signal: "SIGTERM", timeout: 5_000 }, timeout: 300_000, env: { ...process.env, diff --git a/tests/canary-onboarding/start-published-canary.mjs b/tests/canary-onboarding/start-published-canary.mjs new file mode 100644 index 00000000000..d52d0f87dae --- /dev/null +++ b/tests/canary-onboarding/start-published-canary.mjs @@ -0,0 +1,127 @@ +import { spawn } from "node:child_process"; +import { mkdtemp, rm } from "node:fs/promises"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +// Leave three minutes for onboarding inside Playwright's existing five-minute +// startup deadline. This budget includes every install attempt and backoff. +export const INSTALL_BUDGET_MS = 120_000; +const MAX_INSTALL_ATTEMPTS = 3; +const STDERR_TAIL_CHARS = 64 * 1024; + +function run(command, args, { env, signal, captureStderr = false }) { + return new Promise((resolve, reject) => { + signal.throwIfAborted(); + const grouped = process.platform !== "win32"; + const child = spawn(command, args, { + env, detached: grouped, stdio: ["ignore", "inherit", captureStderr ? "pipe" : "inherit"], + }); + let stderr = ""; + let stopping; + const kill = (kind) => { + try { + if (grouped) process.kill(-child.pid, kind); + else child.kill(kind); + } catch (error) { + if (error.code !== "ESRCH") throw error; + } + }; + const stop = () => { + if (stopping || !child.pid) return; + kill("SIGTERM"); + // Also stop any lifecycle-script children even if npm exits first. + stopping = new Promise((done) => setTimeout(() => { kill("SIGKILL"); done(); }, 500)); + }; + signal.addEventListener("abort", stop, { once: true }); + child.stderr?.on("data", (chunk) => { + process.stderr.write(chunk); + stderr = (stderr + chunk.toString()).slice(-STDERR_TAIL_CHARS); + }); + child.on("error", reject); + child.on("close", async (code, exitSignal) => { + signal.removeEventListener("abort", stop); + await stopping; + if (signal.aborted) reject(signal.reason); + else resolve({ code, signal: exitSignal, stderr }); + }); + }); +} + +function delay(ms, signal) { + return new Promise((resolve, reject) => { + signal.throwIfAborted(); + const timer = setTimeout(() => { + signal.removeEventListener("abort", stop); + resolve(); + }, ms); + const stop = () => { clearTimeout(timer); reject(signal.reason); }; + signal.addEventListener("abort", stop, { once: true }); + }); +} + +export async function startPublishedCanary({ + version, workspace, dataDir, env = process.env, + installBudgetMs = INSTALL_BUDGET_MS, retryDelayMs = 10_000, + signal = new AbortController().signal, +}) { + if (!version || !/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(version)) { + throw new Error("An exact published Paperclip version is required"); + } + let prefix; + try { + const budget = new AbortController(); + const timer = setTimeout(() => budget.abort(new Error("Canary npm installation exceeded its startup budget")), installBudgetMs); + const installSignal = AbortSignal.any([signal, budget.signal]); + try { + for (let attempt = 1; attempt <= MAX_INSTALL_ATTEMPTS; attempt++) { + installSignal.throwIfAborted(); + // Every attempt gets a clean prefix. The fresh per-smoke npm cache still + // retains downloaded tarballs, but --prefer-online refreshes metadata. + prefix = await mkdtemp(path.join(workspace, "npm-install-")); + const result = await run(process.platform === "win32" ? "npm.cmd" : "npm", [ + "install", "--prefix", prefix, "--no-save", "--no-package-lock", "--no-audit", "--no-fund", + ...(attempt > 1 ? ["--prefer-online"] : []), `paperclipai@${version}`, + ], { env, signal: installSignal, captureStderr: true }); + if (result.code === 0) break; + const codes = [...result.stderr.matchAll(/^npm (?:error|ERR!) code ([A-Z0-9_]+)\r?$/gm)]; + const missingVersion = codes.at(-1)?.[1] === "ETARGET"; + if (!missingVersion || result.signal || attempt === MAX_INSTALL_ATTEMPTS) { + throw new Error(`Canary npm installation failed (exit ${result.code ?? result.signal}); onboarding was not started`); + } + await rm(prefix, { recursive: true, force: true }); + prefix = undefined; + process.stderr.write(`Canary dependency publication is incomplete; retrying npm installation (${attempt}/${MAX_INSTALL_ATTEMPTS})\n`); + await delay(retryDelayMs * attempt, installSignal); + } + } finally { + clearTimeout(timer); + } + signal.throwIfAborted(); + // Start the installed CLI exactly once. Its own failures must never trigger + // another onboarding run or another dependency-install attempt. + const result = await run(path.join(prefix, "node_modules", ".bin", process.platform === "win32" ? "paperclipai.cmd" : "paperclipai"), + ["onboard", "--yes", "--data-dir", dataDir], { env, signal }); + if (result.code !== 0) throw new Error(`Canary onboarding failed (exit ${result.code ?? result.signal})`); + } finally { + if (prefix) await rm(prefix, { recursive: true, force: true }); + } +} + +if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { + const [version, workspace, dataDir] = process.argv.slice(2); + const cancellation = new AbortController(); + const stop = (kind) => cancellation.abort(new Error(`Canary startup stopped by ${kind}`)); + const interrupt = () => stop("SIGINT"); + const terminate = () => stop("SIGTERM"); + process.on("SIGINT", interrupt); + process.on("SIGTERM", terminate); + try { + await startPublishedCanary({ version, workspace, dataDir, signal: cancellation.signal }); + } catch (error) { + console.error(error.message); + process.exitCode = 1; + } finally { + process.removeListener("SIGINT", interrupt); + process.removeListener("SIGTERM", terminate); + } +} From e9dae72c0cdee2e0abb2cd5713cfbc2033f32ce3 Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Fri, 9 Oct 2026 17:15:50 -0700 Subject: [PATCH 3/7] ci: use a Docker Hub mirror for image builds (#15756) ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Image workflows build the exact source selected for a release. > - BuildKit fetches the Dockerfile frontend and base images from Docker Hub. > - Docker Hub token failures can stop these builds before application code runs. > - BuildKit supports a public image cache with canonical Docker Hub fallback. > - This pull request configures that cache in the two affected image builders. > - The build inputs and publication gates stay the same. ## Linked Issues or Issue Description **What happened?** [Docker run 37995539183](https://github.com/paperclipai/paperclip/actions/runs/37995539183) failed before application builds started. The AMD64 job received HTTP 504 from the Docker Hub token endpoint while it fetched `docker/dockerfile:1.20`. The ARM64 job fetched the frontend, then received the same error while it resolved `node:24-trixie-slim`. [Release preview run 37992058052](https://github.com/paperclipai/paperclip/actions/runs/37992058052) also failed while it fetched the frontend. **Expected behavior** Use the supported public cache when it has the requested Docker Hub image. Retain canonical Docker Hub fallback when the cache has no usable copy. Preserve build and publish failures. **Steps to reproduce** Run either affected image builder during a Docker Hub token failure. The unconfigured BuildKit container contacts Docker Hub for the frontend and base image. It cannot use a host Docker daemon mirror for those build requests. **Paperclip version or commit** The observed Docker run used `00d944f96c8c4aba8332ce224df2be73a601228a`. The preview used `b6b3cb3761dabd1bd668054e7a99a245d53707c4`. **Deployment mode** GitHub Actions image builds. No application runtime change. The public PR and issue search found no matching open registry-mirror change. #15743 addresses a separate npm canary dependency publication failure. ## What Changed - Add the official `docker.io` to `mirror.gcr.io` BuildKit configuration to the public Docker build matrix and the release preview image builder. - Keep all existing action references, image sources, targets, build arguments, platforms, credentials, cache settings, outputs, permissions, triggers, and publication gates. - Extend the existing dependency-free workflow tests to check mirror placement, verified HTTPS, both native platforms, preview isolation, and publication access. - Document cache eviction, tag freshness, canonical fallback, and builder bootstrap limits. ## Verification - `node --test scripts/__tests__/release-verify-workflow.test.mjs scripts/cloud-source-verification.test.mjs scripts/standard-image-contract.test.mjs`: 43 passed on the final source. No dependency install required. - Six offline controls removed each builder's mirror, changed the registry or cache host, enabled insecure transport, or added preview registry login. Each control failed the new check as expected. - `actionlint -shellcheck='' .github/workflows/docker.yml .github/workflows/release.yml`: workflow validation passed. With optional ShellCheck enabled, the ten diagnostics match the unchanged base exactly. This PR changes no shell scripts. - A real TOML parser accepted the inline configuration. Removing the new block from each workflow produced byte-identical base files. - Read-only registry metadata checks confirmed matching raw bytes and SHA256 values for the current Node24 index and both native manifests. The Dockerfile frontend index and both native manifests also match Docker Hub and Google. No image config blobs or layers were fetched. - Full application tests, typecheck, and build were not repeated locally because application source is unchanged. [Hosted CI](https://github.com/paperclipai/paperclip/actions/runs/37998739440) passed the full required checks on `25fd57f`, including all test shards, build, typecheck, policy, E2E, and canary dry run. - The supply-chain advisory returned neutral because it cannot verify these infrastructure edits. It reported zero annotations. Independent review confirmed all action references, Dockerfiles, package files, and lockfiles are unchanged. The other 53 checks passed; two Storybook checks skipped as expected. - Independent review approved all four changed files and the workflow graph. Greptile scored the same source 5/5 with no unresolved comments. - No Docker build, workflow rerun, image publish, or deployment was started for verification. A normal image workflow after merge must prove full image acquisition. ## Risks Google is a cache, not an outage guarantee. It can evict images. Mutable tags can lag upstream changes or deletions. Matching manifests now does not prove future tag freshness or blob availability. A cache miss can still fail when Docker Hub is unavailable. The initial `moby/buildkit:buildx-stable-1` bootstrap uses the host Docker daemon before this configuration takes effect and remains dependent on Docker Hub. The registry mirror applies to image pull and resolution only. GHCR publication and cache writes keep their existing routes. See [Docker's supported configuration](https://docs.docker.com/build/ci/github-actions/configure-builder/#registry-mirror) and [Google's cache limits](https://docs.cloud.google.com/artifact-registry/docs/pull-cached-dockerhub-images). ## Model Used OpenAI GPT-6 through Codex, with reasoning and code execution tools. The exact service variant and context window are not exposed in this session. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes: #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge Co-authored-by: Paperclip --- .github/workflows/docker.yml | 4 ++ .github/workflows/release.yml | 4 ++ doc/RELEASING.md | 14 +++++++ .../release-verify-workflow.test.mjs | 39 +++++++++++++++++++ 4 files changed, 61 insertions(+) diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index b8a16cac697..ed52dfa700d 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -183,6 +183,10 @@ jobs: - name: Set up Docker Buildx uses: docker/setup-buildx-action@v4 + with: + buildkitd-config-inline: | + [registry."docker.io"] + mirrors = ["mirror.gcr.io"] # Deployment tooling reads these labels from the registry to verify an # image's schema expectations against a migrator before deploying it, diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index cdb91e941df..4c2dfb48818 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -224,6 +224,10 @@ jobs: pnpm install --resolution-only --ignore-scripts --ignore-pnpmfile --no-frozen-lockfile echo "TOOLS_EPOCH=$(date -u +%G-W%V)" >> "$GITHUB_ENV" - uses: docker/setup-buildx-action@37fe631027851001ddb9b187196cc803df7f5f0e # v4 + with: + buildkitd-config-inline: | + [registry."docker.io"] + mirrors = ["mirror.gcr.io"] - name: Build the immutable cloud image without registry credentials uses: docker/build-push-action@53b7df96c91f9c12dcc8a07bcb9ccacbed38856a # v7 with: diff --git a/doc/RELEASING.md b/doc/RELEASING.md index 5e0666508ab..cc92f172121 100644 --- a/doc/RELEASING.md +++ b/doc/RELEASING.md @@ -304,6 +304,20 @@ suppresses push-triggered workflow runs for those pushes. The release jobs therefore dispatch `docker.yml` explicitly at the new tag ref; the tag mapping keys off `github.ref` either way. +The Docker build matrix and the release preview image builder configure +BuildKit to check `mirror.gcr.io` for Docker Hub images first. This covers +both the Dockerfile frontend and base images. BuildKit keeps Docker Hub as +the fallback when the cache has no usable copy. The image references, +build arguments, GHCR publication, and release gates stay the same. + +This is an availability improvement, not an outage guarantee. Google can +evict cached images, and mutable tags can lag upstream changes or deletions. +Matching manifests at one point does not guarantee later tag freshness or +blob availability. The initial `moby/buildkit` bootstrap still uses the host +Docker daemon and can fail on Docker Hub before this configuration takes +effect. See the [BuildKit mirror configuration](https://docs.docker.com/build/ci/github-actions/configure-builder/#registry-mirror) +and [Google cache limits](https://docs.cloud.google.com/artifact-registry/docs/pull-cached-dockerhub-images). + ## Local Commands ### Preview a canary locally diff --git a/scripts/__tests__/release-verify-workflow.test.mjs b/scripts/__tests__/release-verify-workflow.test.mjs index bef97786dcf..10b3dddb7f9 100644 --- a/scripts/__tests__/release-verify-workflow.test.mjs +++ b/scripts/__tests__/release-verify-workflow.test.mjs @@ -17,6 +17,45 @@ function readWorkflow(name) { return readFileSync(path.join(repoRoot, ".github/workflows", name), "utf8"); } +test("Docker Hub mirrors apply to both image builders without widening publication access", () => { + const dockerWorkflow = readWorkflow("docker.yml"); + const releaseWorkflow = readWorkflow("release.yml"); + const docker = dockerWorkflow.split(" build-and-push:\n")[1].split("\n merge-and-push:")[0]; + const preview = releaseWorkflow.split(" image_preview:\n")[1].split("\n publish_image_preview:")[0]; + + for (const job of [docker, preview]) { + const steps = job.split(/\n(?= - )/); + const builder = steps.find((step) => /uses: docker\/setup-buildx-action@/.test(step)); + const build = steps.find((step) => /uses: docker\/build-push-action@/.test(step)); + assert.ok(builder && build, "the mirror must configure the builder that runs the image build"); + assert.ok(steps.indexOf(builder) < steps.indexOf(build)); + const config = builder.match(/buildkitd-config-inline: \|\n((?: {12,}[^\n]*(?:\n|$))+)/)?.[1]; + assert.ok(config, "configure the BuildKit container, not only the host Docker daemon"); + assert.deepEqual([...config.matchAll(/^\s*\[registry\."([^"]+)"\]/gm)].map((match) => match[1]), ["docker.io"], + "GHCR publishing and cache traffic must not use the pull mirror"); + const mirrors = config.match(/^\s*mirrors = (\[[^\n]+\])$/m)?.[1]; + assert.ok(mirrors); + assert.deepEqual(JSON.parse(mirrors), ["mirror.gcr.io"]); + assert.doesNotMatch(config, /^\s*(?:http|insecure|ca|keypair)\s*=/m, + "keep verified HTTPS and anonymous public-image pulls"); + assert.doesNotMatch(builder, /driver-opts:|buildkitd-flags:|secrets\./, + "do not change bootstrap images, entitlements, or credentials"); + } + + assert.match(docker, /platform: linux\/amd64/); + assert.match(docker, /platform: linux\/arm64/); + assert.match(docker, /permissions:\n\s+contents: read\n\s+packages: write/); + assert.match(docker, /outputs: type=image,name=ghcr\.io\/\$\{\{ github\.repository \}\},push-by-digest=true,name-canonical=true,push=true/); + assert.match(docker, /cache-to: type=registry,ref=ghcr\.io\/\$\{\{ github\.repository \}\}:buildcache-\$\{\{ matrix\.arch \}\},mode=max/); + assert.match(preview, /permissions:\n\s+contents: read\n\s+steps:/); + assert.match(preview, /platforms: linux\/amd64\n\s+push: false/); + assert.match(preview, /outputs: type=docker,dest=\$\{\{ runner\.temp \}\}\/preview-image\.tar/); + assert.doesNotMatch(preview, /docker\/login-action|secrets\.|packages: write|id-token: write/); + assert.match(releaseWorkflow, /publish_image_preview:\n[\s\S]*?needs: \[plan_preview, image_preview\]/); + assert.doesNotMatch(dockerWorkflow.split(" merge-and-push:\n")[1], /buildkitd-config-inline/, + "the registry-only manifest merge does not need a Docker Hub mirror"); +}); + test("chaos verification isolates callers that verify the same source commit", () => { const chaosWorkflow = readWorkflow("runner-chaos-evals.yml"); const group = chaosWorkflow.match(/^ group: (.+)$/m)?.[1]; From baa94bbea58919bcc6cf247a708f04e6e1002679 Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Fri, 9 Oct 2026 17:25:02 -0700 Subject: [PATCH 4/7] Fix idle sleep checks for finished login and wake history (#15761) ## Thinking Path > - Paperclip manages AI agent work and keeps a durable record of each run. > - Automatic idle sleep must wait for accepted work and provider cleanup. > - The current sleep check treats every saved login session as active work. > - It also treats every coalesced wake request as pending work. > - These records can remain after their work and cleanup finish. > - This pull request checks the cleanup and linked-run evidence before it treats these records as history. > - The change lets otherwise idle instances sleep and keeps uncertain work awake. ## Linked Issues or Issue Description **What happened?** A finished login session blocks idle sleep after its provider resource has been removed. A consumed coalesced wake also blocks sleep after its linked run finishes. **Expected behavior** Finished history should permit sleep when cleanup or run completion is confirmed. Active work, missing evidence, retry debt, and pending accounting must still block sleep. **Steps to reproduce** 1. Create a finished login session with a retained provider reference. 2. Record a successful release for the same resource, company, and environment. 3. Check idle sleep safety under an owned, quiet admission hold. 4. The current check reports background work. The new check treats the session as history. 5. Repeat with a finished coalesced wake linked to a finished run in the same company and agent. **Paperclip version or commit** Reproduced on master at 98e3cec78e8. Related work: #15522, #15599, #15629. A search of open and merged idle-sleep PRs found no duplicate. ## What Changed - Permit finished login history only after its promotion claim is cleared. A retained resource reference needs successful cleanup, a release timestamp, and the same company and environment. Conflicting cleanup evidence still blocks sleep. - Permit a finished coalesced wake only after its exact linked run finishes without a retry or pending cost accounting. - Keep the lease UUID column unchanged. Convert only valid UUID-shaped session references so both existing lease indexes remain usable. - Add real PostgreSQL tests for safe history and missing, active, or conflicting evidence. Cover text references, UUID references, and conflicting internal/external matches. - Document these checks. Image-setup history still blocks sleep because its terminal state does not confirm cleanup. ## Verification - `pnpm exec vitest run server/src/__tests__/idle-sleep-safety.test.ts`: 84 tests passed, including the PostgreSQL cases. - `pnpm -r typecheck`: passed. `pnpm --filter @paperclipai/server typecheck` also passed after the index fix. - Full default test coverage was exercised through the supported shard runner. The initial run was not green. Fixture-permission, local PostgreSQL startup, socket, route timeout, and Git stress failures passed controlled rechecks with normal permissions, one database worker, or isolated runs. - All route suites, UI/CLI suites, and all shared, database, adapter, and SDK projects were exercised. One damaged-session recovery test in `native-session-resume.test.ts` still fails and also reproduces on unmodified base `98e3cec78e8`. Full-suite green status is not claimed. - `pnpm build`: passed in an isolated checkout of the initial commit. The build and full Paperclip CI also passed on final head `d61b489c26b`: https://github.com/paperclipai/paperclip/actions/runs/38005908398. Both required branch-protection checks passed. The optional Superagent security scan is still running and has not returned findings. - A local PostgreSQL query-plan probe used 10,000 lease rows and 200 finished login rows with mixed internal and external references. The actual sleep query used both the primary-key and provider-reference indexes. Execution took 1.63 ms in this synthetic fixture. - A read-only comparison on a controlled staging instance found login history as the current check's sole durable-work blocker. The new query found no durable-work blockers. This comparison did not authorize or perform provider shutdown. - The current owned sleep controller refused sleep and released its hold. The instance remained healthy. Existing backup archives were unchanged. ## Risks - Missing schema, missing cleanup evidence, stale claims, and unfinished linked runs fail closed. - The change preserves history and provider references. It does not delete records or release resources. - Image setup, other durable work, plugin draining, in-flight work, and backup checks retain their current behavior. - No schema migration or new API is required. ## Model Used - OpenAI Codex, GPT-6. Used repository inspection, code execution, and test tools. The exact deployment model identifier and context-window size were not exposed in this session. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run the tests for this change locally and they pass. The broader local baseline failure is described in Verification. - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip --- doc/idle-sleep-safety.md | 9 ++ .../src/__tests__/idle-sleep-safety.test.ts | 129 +++++++++++++++++- server/src/services/idle-sleep-safety.ts | 37 ++++- 3 files changed, 171 insertions(+), 4 deletions(-) diff --git a/doc/idle-sleep-safety.md b/doc/idle-sleep-safety.md index 71bd5a549e2..30622581e24 100644 --- a/doc/idle-sleep-safety.md +++ b/doc/idle-sleep-safety.md @@ -120,6 +120,15 @@ block sleep even when their watched issue is complete and no review has started. Missing migrations, malformed configuration and database errors produce unknown without exposing SQL or tenant data. +Finished login-session history permits sleep only after its promotion claim is +cleared and any retained provider reference has a matching released or expired +lease with successful cleanup and a release timestamp in the same company and +environment. Missing cleanup evidence, `cleanup_pending`, and live login flows +remain blockers. A finished coalesced wake is history only when its exact +company/agent's linked run has finished without retry or accounting debt. +Image-setup history still blocks: promotion can succeed before teardown is +confirmed, so a terminal label does not prove that its provider resource is gone. + Every enabled plugin blocks sleep. A version label does not prove that arbitrary worker code has no background activity. No plugin approval or configuration bypass is supported. Scheduled and externally triggered work needs a durable diff --git a/server/src/__tests__/idle-sleep-safety.test.ts b/server/src/__tests__/idle-sleep-safety.test.ts index 66a023dd9b9..718d33ce534 100644 --- a/server/src/__tests__/idle-sleep-safety.test.ts +++ b/server/src/__tests__/idle-sleep-safety.test.ts @@ -178,7 +178,7 @@ if (!support.supported) console.warn(`Skipping idle sleep Postgres tests: ${supp const companyId = randomUUID(); const agentId = randomUUID(); const runId = randomUUID(); - await db.insert(companies).values({ id: companyId, name: "Idle test", issuePrefix: "IDLE" }); + await db.insert(companies).values({ id: companyId, name: "Idle test", issuePrefix: `T${companyId.slice(0, 6).toUpperCase()}` }); await db.insert(agents).values({ id: agentId, companyId, name: "On-demand agent", role: "engineer", status: "idle", adapterType: "process" }); await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, invocationSource: "on_demand", status: "succeeded" }); return { companyId, agentId, runId }; @@ -246,6 +246,44 @@ if (!support.supported) console.warn(`Skipping idle sleep Postgres tests: ${supp expect(await read()).toEqual(present); }); + it("allows consumed coalesced wakes only after their linked run finishes", async () => { + const { companyId, agentId, runId } = await seed(); + await db.update(heartbeatRuns).set({ status: "running" }).where(eq(heartbeatRuns.id, runId)); + await db.insert(agentWakeupRequests).values({ + companyId, agentId, source: "assignment", status: "coalesced", runId, finishedAt: new Date(now), + }); + expect(await read()).toEqual(present); + await db.update(heartbeatRuns).set({ status: "succeeded", finishedAt: new Date(now) }) + .where(eq(heartbeatRuns.id, runId)); + expect(await read()).toEqual(none); + }); + + it.each(["unfinished", "missing_run", "wrong_company", "wrong_agent", "unfinished_run", "retry", "accounting"])( + "keeps a coalesced wake awake with %s evidence", async kind => { + const { companyId, agentId, runId } = await seed(); + await db.update(heartbeatRuns).set({ finishedAt: new Date(now) }).where(eq(heartbeatRuns.id, runId)); + let linkedRunId = runId; + if (kind === "missing_run") linkedRunId = randomUUID(); + if (kind === "wrong_company") { + linkedRunId = (await seed()).runId; + await db.update(heartbeatRuns).set({ finishedAt: new Date(now) }).where(eq(heartbeatRuns.id, linkedRunId)); + } + if (kind === "wrong_agent") { + const otherAgentId = randomUUID(); + await db.insert(agents).values({ id: otherAgentId, companyId, name: "Other agent", role: "engineer", status: "idle", adapterType: "process" }); + await db.update(heartbeatRuns).set({ agentId: otherAgentId }).where(eq(heartbeatRuns.id, runId)); + } + if (kind === "unfinished_run") await db.update(heartbeatRuns).set({ finishedAt: null }).where(eq(heartbeatRuns.id, runId)); + if (kind === "retry") await db.update(heartbeatRuns).set({ scheduledRetryAt: new Date(now + 1000) }).where(eq(heartbeatRuns.id, runId)); + if (kind === "accounting") await db.update(heartbeatRuns).set({ costAccountingPending: true }).where(eq(heartbeatRuns.id, runId)); + await db.insert(agentWakeupRequests).values({ + companyId, agentId, source: "assignment", status: "coalesced", runId: linkedRunId, + finishedAt: kind === "unfinished" ? null : new Date(now), + }); + expect(await read()).toEqual(present); + }, + ); + it("blocks an active routine without waiting for its next due time", async () => { const { companyId } = await seed(); await db.insert(routines).values({ companyId, title: "Tomorrow", status: "active" }); @@ -268,6 +306,95 @@ if (!support.supported) console.warn(`Skipping idle sleep Postgres tests: ${supp expect(await read()).toEqual(present); }); + async function seedFinishedLogin() { + const { companyId } = await seed(); + const [environment] = await db.insert(environments).values({ name: "Finished login fixture" }).returning(); + const [lease] = await db.insert(environmentLeases).values({ + companyId, environmentId: environment!.id, providerLeaseId: "fixture-login-resource", + status: "released", cleanupStatus: "success", releasedAt: new Date(now), + }).returning(); + const [session] = await db.insert(adapterAuthSessions).values({ + companyId, environmentId: environment!.id, adapterType: "codex_local", + startedByUserId: "fixture-user", publicSessionId: "finished-fixture-session", + status: "authenticated", finishedAt: new Date(now), providerLeaseId: lease!.providerLeaseId, + }).returning(); + return { companyId, environment: environment!, lease: lease!, session: session! }; + } + + it.each(["authenticated", "completed", "failed", "timed_out", "cancelled"] as const)( + "permits finished %s login history after confirmed provider cleanup", async status => { + const { session } = await seedFinishedLogin(); + await db.update(adapterAuthSessions).set({ status }).where(eq(adapterAuthSessions.id, session.id)); + expect(await read()).toEqual(none); + }, + ); + + it.each(["canonical", "uppercase"])("accepts a %s cleanup reference to the internal lease id", async format => { + const { session, lease } = await seedFinishedLogin(); + await db.update(adapterAuthSessions).set({ providerLeaseId: format === "uppercase" ? lease.id.toUpperCase() : lease.id }) + .where(eq(adapterAuthSessions.id, session.id)); + expect(await read()).toEqual(none); + }); + + it.each(["fixture-provider-id", "00000000-0000-0000-0000-00000000000z", randomUUID()])( + "accepts cleaned external provider reference %s without an unsafe UUID cast", async providerLeaseId => { + const { session, lease } = await seedFinishedLogin(); + await db.update(environmentLeases).set({ providerLeaseId }).where(eq(environmentLeases.id, lease.id)); + await db.update(adapterAuthSessions).set({ providerLeaseId }).where(eq(adapterAuthSessions.id, session.id)); + expect(await read()).toEqual(none); + }, + ); + + it("keeps a UUID-shaped external reference awake when an internal lease conflicts", async () => { + const { companyId, environment, session, lease } = await seedFinishedLogin(); + const conflictingId = randomUUID(); + await db.update(environmentLeases).set({ providerLeaseId: conflictingId }).where(eq(environmentLeases.id, lease.id)); + await db.update(adapterAuthSessions).set({ providerLeaseId: conflictingId }).where(eq(adapterAuthSessions.id, session.id)); + await db.insert(environmentLeases).values({ + id: conflictingId, companyId, environmentId: environment.id, + status: "released", cleanupStatus: "failed", releasedAt: new Date(now), + }); + expect(await read()).toEqual(present); + await db.update(environmentLeases).set({ cleanupStatus: "success" }).where(eq(environmentLeases.id, conflictingId)); + expect(await read()).toEqual(none); + }); + + it("permits terminal login history without a provider resource", async () => { + const { session } = await seedFinishedLogin(); + await db.update(adapterAuthSessions).set({ providerLeaseId: null }).where(eq(adapterAuthSessions.id, session.id)); + expect(await read()).toEqual(none); + }); + + it.each(["cleanup_pending", "starting", "promoting", "awaiting_code", "submitting", "stored"] as const)( + "retains %s login work even with an old successful cleanup receipt", async status => { + const { session } = await seedFinishedLogin(); + await db.update(adapterAuthSessions).set({ status }).where(eq(adapterAuthSessions.id, session.id)); + expect(await read()).toEqual(present); + }, + ); + + it.each(["unfinished", "promotion_claim", "missing_lease", "wrong_company", "wrong_environment", "cleanup_failed", "cleanup_unknown", "unreleased", "conflicting_lease"])( + "retains terminal login history with %s cleanup evidence", async kind => { + const { companyId, session, lease, environment } = await seedFinishedLogin(); + if (kind === "unfinished") await db.update(adapterAuthSessions).set({ finishedAt: null }).where(eq(adapterAuthSessions.id, session.id)); + if (kind === "promotion_claim") await db.update(adapterAuthSessions).set({ promotionExpiresAt: new Date(now + 1000) }).where(eq(adapterAuthSessions.id, session.id)); + if (kind === "missing_lease") await db.delete(environmentLeases).where(eq(environmentLeases.id, lease.id)); + if (kind === "wrong_company") await db.update(environmentLeases).set({ companyId: (await seed()).companyId }).where(eq(environmentLeases.id, lease.id)); + if (kind === "wrong_environment") { + const [other] = await db.insert(environments).values({ name: "Other environment", driver: "sandbox" }).returning(); + await db.update(environmentLeases).set({ environmentId: other!.id }).where(eq(environmentLeases.id, lease.id)); + } + if (kind === "cleanup_failed") await db.update(environmentLeases).set({ cleanupStatus: "failed" }).where(eq(environmentLeases.id, lease.id)); + if (kind === "cleanup_unknown") await db.update(environmentLeases).set({ cleanupStatus: null }).where(eq(environmentLeases.id, lease.id)); + if (kind === "unreleased") await db.update(environmentLeases).set({ releasedAt: null }).where(eq(environmentLeases.id, lease.id)); + if (kind === "conflicting_lease") await db.insert(environmentLeases).values({ + companyId, environmentId: environment.id, providerLeaseId: lease.providerLeaseId, + status: "released", cleanupStatus: "failed", releasedAt: new Date(now), + }); + expect(await read()).toEqual(present); + }, + ); + it("reports a pending secret proposal with future expiry", async () => { const { companyId, agentId, runId } = await seed(); await db.insert(companySecretProposals).values({ diff --git a/server/src/services/idle-sleep-safety.ts b/server/src/services/idle-sleep-safety.ts index a8c7a80e13b..4f2059f3bb4 100644 --- a/server/src/services/idle-sleep-safety.ts +++ b/server/src/services/idle-sleep-safety.ts @@ -45,8 +45,16 @@ const WORK_CHECKS = [ `SELECT 1 FROM agent_api_keys WHERE revoked_at IS NULL`, `SELECT 1 FROM board_api_keys WHERE revoked_at IS NULL AND (expires_at IS NULL OR expires_at > now())`, - `SELECT 1 FROM agent_wakeup_requests WHERE - status NOT IN ('completed', 'failed', 'cancelled', 'skipped', 'timed_out')`, + // Coalescing consumes a request into another run. Retain it as work until + // both the request and that exact company/agent's run have finished. + `SELECT 1 FROM agent_wakeup_requests w WHERE + w.status NOT IN ('completed', 'failed', 'cancelled', 'skipped', 'timed_out', 'coalesced') + OR (w.status = 'coalesced' AND (w.finished_at IS NULL OR NOT EXISTS ( + SELECT 1 FROM heartbeat_runs r WHERE r.id = w.run_id + AND r.company_id = w.company_id AND r.agent_id = w.agent_id + AND r.status IN ('succeeded', 'failed', 'cancelled', 'timed_out', 'interrupted') + AND r.finished_at IS NOT NULL AND r.scheduled_retry_at IS NULL + AND r.cost_accounting_pending = false)))`, `SELECT 1 FROM issues WHERE status NOT IN ('done', 'cancelled')`, // A completed issue can still need its first watchdog review, including a // retry after immediate evaluation failed before creating a review/run. @@ -62,6 +70,29 @@ const WORK_CHECKS = [ `SELECT 1 FROM issue_recovery_actions WHERE status NOT IN ('resolved', 'cancelled')`, `SELECT 1 FROM status_cards WHERE archived_at IS NULL`, `SELECT 1 FROM external_objects WHERE NOT is_terminal OR next_refresh_at IS NOT NULL`, + // Login history keeps its provider reference after teardown. A terminal + // label alone is insufficient: require a finished, unclaimed session and + // positive cleanup evidence for its resource in the same company/environment. + // Cast only UUID-shaped session references, leaving both lease indexes usable. + `SELECT 1 FROM adapter_auth_sessions s WHERE + s.status NOT IN ('authenticated', 'completed', 'failed', 'timed_out', 'cancelled') + OR s.finished_at IS NULL OR s.promotion_expires_at IS NOT NULL + OR (s.provider_lease_id IS NOT NULL AND NOT EXISTS ( + SELECT 1 FROM environment_leases l WHERE l.company_id = s.company_id + AND l.environment_id = s.environment_id + AND (l.provider_lease_id = s.provider_lease_id OR l.id = CASE + WHEN s.provider_lease_id ~* '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + THEN s.provider_lease_id::uuid END) + AND l.status IN ('released', 'expired') AND l.cleanup_status = 'success' + AND l.released_at IS NOT NULL)) + OR (s.provider_lease_id IS NOT NULL AND EXISTS ( + SELECT 1 FROM environment_leases l WHERE l.company_id = s.company_id + AND l.environment_id = s.environment_id + AND (l.provider_lease_id = s.provider_lease_id OR l.id = CASE + WHEN s.provider_lease_id ~* '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$' + THEN s.provider_lease_id::uuid END) + AND (l.status IN ('released', 'expired') AND l.cleanup_status = 'success' + AND l.released_at IS NOT NULL) IS NOT TRUE))`, // These less common work sources fail closed on any retained state. Their // terminal-state exceptions can be added with tests for the owning service. ...[ @@ -73,7 +104,7 @@ const WORK_CHECKS = [ "native_run_finalizations", "company_transfer_runs", "decisions", "decision_effect_executions", "decision_archive_notification_outbox", "browser_use_sessions", "browser_use_runs", "browser_use_browsers", "environment_custom_image_setup_sessions", "feedback_exports", - "adapter_auth_sessions", "company_secret_proposals", "execution_workspaces", + "company_secret_proposals", "execution_workspaces", "mcp_oauth_grants", "mcp_mutation_receipts", "mcp_event_subscriptions", "mcp_event_deliveries", "mcp_attachment_uploads", "dot_agent_bindings", "dot_runner_assignments", "dot_runner_operations", "dot_mailbox_items", From 43212cb2b72a14e19f14139863f08676b13ee150 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Fri, 9 Oct 2026 20:16:24 -0500 Subject: [PATCH 5/7] fix(slack): require result and review updates in conversation prompts (#15611) ## Thinking Path > - Paperclip helps people manage AI agents and their work. > - People can ask an agent to do work from a Slack thread. > - The agent must return results and review requests to that conversation. > - The current prompts explain reply format but do not require these updates. > - This change adds one set of instructions to initial prompts and later turns. > - Users can see the result and the action needed for review in Slack. ## Linked Issues or Issue Description **What happened?** An agent can save results or a plan in Paperclip without telling the user in Slack that the result is ready or that review is required. **Expected behavior** The agent reports results in the originating conversation. If review is needed, it saves the required interaction and tells the user what to review and how to act. **Steps to reproduce** Start work in a Slack thread. Have the agent prepare a plan that needs approval or produce a deliverable. The prompt does not explicitly require a result or review update in that thread. Related: #15579 adds task links to Slack replies. This change covers results and review requests, including later turns. ## What Changed - Add shared instructions for result and review updates. - Include the instructions in initial Slack guidance and per-turn guidance. - Keep the normal approval gates, delivery checks, and duplicate-message rules. - Add tests for channel and direct conversations, and for fresh and resumed native and CLI turns. - Update the Slack skill documentation. ## Verification - Passed: guidance and heartbeat context tests (65 tests in two files). - Passed: `git diff --check`. - Workspace typecheck and build could not complete because this sandbox has no `cargo` binary. - The full local test run was stopped due to the sandbox memory limit. GitHub CI runs the full checks. - GitHub CI and automated review are pending. ## Risks - Low risk. This change updates prompt text and tests. It does not change transport or permissions. - Prompt instructions guide agent behavior. They do not guarantee that Slack delivery succeeds. ## Model Used - OpenAI GPT-6 (Codex). Used reasoning, code editing, and command tools. The runtime does not expose a more specific model ID or context window size. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] 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 --- server/src/__tests__/heartbeat-context-summary.test.ts | 5 +++++ .../src/services/chat-communication-guidance.test.ts | 9 +++++++++ server/src/services/chat-communication-guidance.ts | 2 ++ server/src/services/connectors/slack/agent-guidance.ts | 2 ++ .../services/connectors/slack/task-update-guidance.ts | 5 +++++ skills/slack/SKILL.md | 10 ++++++++++ 6 files changed, 33 insertions(+) create mode 100644 server/src/services/connectors/slack/task-update-guidance.ts diff --git a/server/src/__tests__/heartbeat-context-summary.test.ts b/server/src/__tests__/heartbeat-context-summary.test.ts index 70930db8cf7..67bdca41075 100644 --- a/server/src/__tests__/heartbeat-context-summary.test.ts +++ b/server/src/__tests__/heartbeat-context-summary.test.ts @@ -301,6 +301,11 @@ describe("buildPaperclipTaskMarkdown", () => { externalChatProvider: "slack", nativeRunner, includeDescription, }); expect(markdown).toContain("Interactive questions in Slack:"); + expect(markdown).toContain("When you have results, update the user in the originating Slack"); + expect(markdown).toContain("When the user needs to review a plan, approve an action, or review a result"); + expect(markdown).toContain("create the required human-input or approval interaction before you yield"); + expect(markdown).toContain("Saving a plan or setting a task to in_review alone does not ask the user to review it"); + expect(markdown).toContain("do not continue gated work until the required approval is recorded"); expect(markdown).toContain("ask_user_questions"); expect(markdown).toContain("single_select"); expect(markdown).toContain("resumes this task after the answer"); diff --git a/server/src/services/chat-communication-guidance.test.ts b/server/src/services/chat-communication-guidance.test.ts index 44b568d2597..a1f77369766 100644 --- a/server/src/services/chat-communication-guidance.test.ts +++ b/server/src/services/chat-communication-guidance.test.ts @@ -3,6 +3,15 @@ import { CHAT_PROVIDERS, updateChatEndpointSchema } from "@paperclipai/shared"; import { buildChatCommunicationGuidance } from "./chat-communication-guidance.js"; describe("initial medium communication guidance", () => { + it.each([true, false])("requires result and review updates in Slack (direct=%s)", (isDirectMessage) => { + const guidance = buildChatCommunicationGuidance({ provider: "slack", isDirectMessage }); + expect(guidance).toContain("When you have results, update the user in the originating Slack"); + expect(guidance).toContain("Put this update in your final response"); + expect(guidance).toContain("When the user needs to review a plan, approve an action, or review a result"); + expect(guidance).toContain("create the required human-input or approval interaction before you yield"); + expect(guidance).toContain("do not continue gated work until the required approval is recorded"); + }); + it("guides Slack presentation while retaining ordinary agent tools and explicit output requests", () => { const guidance = buildChatCommunicationGuidance({ provider: "slack", isDirectMessage: false, communicationInstructions: "Use customer-facing names." }); expect(guidance).toContain("shared channel thread"); diff --git a/server/src/services/chat-communication-guidance.ts b/server/src/services/chat-communication-guidance.ts index f96a5ee0102..c76fcf95002 100644 --- a/server/src/services/chat-communication-guidance.ts +++ b/server/src/services/chat-communication-guidance.ts @@ -1,10 +1,12 @@ import type { ChatProvider } from "@paperclipai/shared"; +import { slackTaskUpdateGuidance } from "./connectors/slack/task-update-guidance.js"; // Presentation guidance only. Task execution and permissions belong to the // ordinary Paperclip agent runtime, not the provider transport. const providerGuidance: Partial> = { slack: [ "This task began in Slack. Write replies for the person talking with you there.", + ...slackTaskUpdateGuidance, "Lead with the answer or outcome. Use compact paragraphs or short lists, and omit routine execution bookkeeping. Honor requests for more detail or exact output over default brevity.", "Put small answers directly in the message. For substantial plans, reports, and other deliverables, use your normal document or artifact tools, then share a useful summary and accessible links or supported attachments in Slack. Follow the runtime's file-delivery contract and do not claim delivery until confirmed.", "Ask useful questions through the existing human-input tools. Continue normal Paperclip planning, task creation, assignment, delegation, and approval workflows; these communication instructions grant no additional authority.", diff --git a/server/src/services/connectors/slack/agent-guidance.ts b/server/src/services/connectors/slack/agent-guidance.ts index bf1c5fb2e19..7ab63ad2132 100644 --- a/server/src/services/connectors/slack/agent-guidance.ts +++ b/server/src/services/connectors/slack/agent-guidance.ts @@ -1,4 +1,5 @@ import { slackAppConfigurationSchema } from "@paperclipai/shared"; +import { slackTaskUpdateGuidance } from "./task-update-guidance.js"; // Per-turn routing guidance, including resumed CLI sessions. This describes // existing capabilities; it never grants tools or overrides action policies. @@ -7,6 +8,7 @@ export function slackChatAgentGuidance(nativeRunner: boolean, savedCommand?: str return [ "", "Slack replies and actions:", + ...slackTaskUpdateGuidance, "Paperclip delivers your final response to the originating Slack conversation. Use assigned Slack action tools for an explicitly requested post, edit, reaction, pin, bookmark, canvas, list, or channel operation. Do not post a second copy of your ordinary reply with slack_post_message.", "For a requested file in this conversation, follow the external-chat file-delivery contract below. slack_upload_file is for explicitly uploading an existing Paperclip attachment to another allowed destination. Neither queued nor uncertain means delivered; retain the original operation key and inspect its receipt instead of starting the write again.", "Use only the tools assigned to this run and honor their action policies. Missing tools or Slack permissions are a capability limitation; never ask for a bot token or use another bot to work around it.", diff --git a/server/src/services/connectors/slack/task-update-guidance.ts b/server/src/services/connectors/slack/task-update-guidance.ts new file mode 100644 index 00000000000..5c51f67101f --- /dev/null +++ b/server/src/services/connectors/slack/task-update-guidance.ts @@ -0,0 +1,5 @@ +// Shared by initial conversation guidance and every later Slack turn. +export const slackTaskUpdateGuidance = [ + "When you have results, update the user in the originating Slack channel thread or direct conversation. Include the outcome and accessible links or supported attachments. Do not leave results only in a Paperclip task, document, or work product. Put this update in your final response so Paperclip can deliver it; do not send a duplicate with slack_post_message.", + "When the user needs to review a plan, approve an action, or review a result, notify them in the same Slack conversation. State what needs review, include the saved review link when available, and explain the action they must take. Follow the normal workflow to save the artifact and create the required human-input or approval interaction before you yield. Saving a plan or setting a task to in_review alone does not ask the user to review it. Do not claim notification or delivery without a successful receipt, and do not continue gated work until the required approval is recorded.", +]; diff --git a/skills/slack/SKILL.md b/skills/slack/SKILL.md index 9bffa57ef0e..63c5ca173a1 100644 --- a/skills/slack/SKILL.md +++ b/skills/slack/SKILL.md @@ -80,3 +80,13 @@ On a Slack-linked task, human messages sent from Paperclip and your final respon are mirrored into its Slack thread. Do not manually send the same final response again. Ordinary tasks and routines have no automatic Slack destination: perform the requested Slack send explicitly and report whether delivery was confirmed. + +On a Slack-linked task, when results are ready, include the outcome and accessible +deliverable links or supported attachments in your final response to the originating +Slack conversation. +Do not leave the result only on the Paperclip task. When the user must review a +plan, approve an action, or review a result, save the artifact and create the +required review interaction through the normal Paperclip workflow. Tell the user +what needs review and what action to take in the same Slack conversation. A saved +plan or an `in_review` status alone is not a review request. Keep approval gates +in place and do not claim delivery without a successful receipt. From 8f13ec4d51d590d4d252aa2b7e088dfda09ac0c2 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Fri, 9 Oct 2026 20:23:18 -0500 Subject: [PATCH 6/7] fix(slack): link created tasks in default reply guidance (#15579) ## Thinking Path > - Paperclip helps people manage AI agents and their tasks. > - Slack agents use shared guidance to write their replies. > - A reply can show a task ID without a link. > - The person must then search for the task. > - This change tells the agent to link each task it creates. > - People can open the task directly from the reply. ## Linked Issues or Issue Description **What existing behavior does this improve?** Default communication guidance for Slack agents. **Current behavior** The guidance does not require a link when an agent creates a task. **Proposed behavior** Require a clickable link to each created task. Use its identifier or title as the link text. Use a public URL supplied by Paperclip. Report when no public URL is available. **Reason and benefit** People can open the task without a separate search. Related work: https://github.com/paperclipai/paperclip/pull/13760 introduced the guidance. https://github.com/paperclipai/paperclip/pull/15576 adds account connection instructions and does not cover task links. ## What Changed - Add task link instructions to the shared Slack communication guidance. - Document the default and the existing conversation snapshot behavior. - Add regression coverage for the guidance in channels and DMs. ## Verification - Passed: `pnpm exec vitest run server/src/services/chat-communication-guidance.test.ts` (10 tests). - Passed: `git diff --check`. - Local full typecheck and build could not finish: the container killed compiler processes (exit 137; cgroup reports OOM kills). The full test run was stopped after this resource limit. CI results are pending. - Added checks for task links, public URL sources, and missing URLs in Slack channels and DMs. ## Risks - Low risk. This changes prompt text only. - Existing conversations keep their original guidance snapshot. New conversations receive the new default after deployment. - This is agent guidance. It does not force a link into provider output. ## Model Used OpenAI Codex, GPT-6. The runtime did not expose an exact model revision or context window size. Used reasoning, code inspection, file editing, and command 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 --- doc/DEVELOPING.md | 5 +++++ server/src/services/chat-communication-guidance.test.ts | 9 +++++++++ server/src/services/chat-communication-guidance.ts | 1 + 3 files changed, 15 insertions(+) diff --git a/doc/DEVELOPING.md b/doc/DEVELOPING.md index 08986d2ef43..26ad54fa183 100644 --- a/doc/DEVELOPING.md +++ b/doc/DEVELOPING.md @@ -715,6 +715,11 @@ a real mention. **Done** finishes setup once webhook verification and required account linking are complete, whether or not a test message was sent. The separate strict connection-test API retains its conversation and delivery checks. +New Slack conversations receive default communication guidance that requires a +clickable link to each task the agent creates. Agents use the public task URL +from Paperclip tools or task context and report when a link is unavailable. +Existing conversations keep their original communication guidance snapshot. + ### Chat activity pagination and callback diagnostics The connection Activity tab loads 25 records per page. `GET /api/chat-endpoints/:id/activity?limit=25` diff --git a/server/src/services/chat-communication-guidance.test.ts b/server/src/services/chat-communication-guidance.test.ts index a1f77369766..cca070de8f3 100644 --- a/server/src/services/chat-communication-guidance.test.ts +++ b/server/src/services/chat-communication-guidance.test.ts @@ -22,6 +22,15 @@ describe("initial medium communication guidance", () => { expect(buildChatCommunicationGuidance({ provider: "slack", isDirectMessage: true })).toContain("direct conversation"); }); + it.each([false, true])("requires public links for created Slack tasks (DM: %s)", (isDirectMessage) => { + const guidance = buildChatCommunicationGuidance({ provider: "slack", isDirectMessage }); + expect(guidance).toContain("include a clickable link to each created task"); + expect(guidance).toContain("task identifier or title as the link text"); + expect(guidance).toContain("public task URL returned by Paperclip tools or supplied in task context"); + expect(guidance).toContain("never guess a URL"); + expect(guidance).toContain("If no public task URL is available, say that the link is unavailable"); + }); + it.each(CHAT_PROVIDERS.filter((provider) => provider !== "slack"))("leaves %s unchanged", (provider) => { expect(buildChatCommunicationGuidance({ provider, isDirectMessage: false, communicationInstructions: "Ignored" })).toBeNull(); }); diff --git a/server/src/services/chat-communication-guidance.ts b/server/src/services/chat-communication-guidance.ts index c76fcf95002..d2f3344939e 100644 --- a/server/src/services/chat-communication-guidance.ts +++ b/server/src/services/chat-communication-guidance.ts @@ -9,6 +9,7 @@ const providerGuidance: Partial> = { ...slackTaskUpdateGuidance, "Lead with the answer or outcome. Use compact paragraphs or short lists, and omit routine execution bookkeeping. Honor requests for more detail or exact output over default brevity.", "Put small answers directly in the message. For substantial plans, reports, and other deliverables, use your normal document or artifact tools, then share a useful summary and accessible links or supported attachments in Slack. Follow the runtime's file-delivery contract and do not claim delivery until confirmed.", + "When you create tasks, include a clickable link to each created task in your reply. Use the task identifier or title as the link text, not a bare task ID. Use the public task URL returned by Paperclip tools or supplied in task context; never guess a URL or use a localhost, API, or sandbox address. If no public task URL is available, say that the link is unavailable.", "Ask useful questions through the existing human-input tools. Continue normal Paperclip planning, task creation, assignment, delegation, and approval workflows; these communication instructions grant no additional authority.", ].join("\n\n"), }; From 3389bea7086ef31388df89657a733aec72e7c900 Mon Sep 17 00:00:00 2001 From: Devin Foley Date: Fri, 9 Oct 2026 18:56:20 -0700 Subject: [PATCH 7/7] fix(recovery): surface exhausted review-path repair (#15764) 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. > - An issue in review needs a saved path to its next action. > - A consumed review path starts one automatic repair run. > - The repair run can finish with only a promise to check later. > - The old code skips another wake but records no recovery action. > - This change records a board decision when that repair also leaves no saved path. > - The issue lock protects a new monitor, a changed owner, or newer work from stale finalization. ## Linked Issues or Issue Description **What happened?** An agent waiting for an external build said it would check again soon. Its one-shot monitor had already fired. The automatic review-path repair also finished without saving another monitor. The task stayed in review with no future wake or recovery card. **Expected behavior** The repair must save a monitor or another review path. If it cannot do so, Paperclip must show an explicit recovery action and stop automatic retries. **Steps to reproduce** 1. Leave an agent-owned issue in review after consuming its last monitor or interaction. 2. Let the source run finish without saving another review path. 3. Let the single automatic repair run also finish without saving a path. 4. Before this change, the task stays in review without a scheduled follow-up. After this change, it is blocked with a board-owned recovery action and an inline notice that links the repair run. Related work: Refs #14757 (preserve active review during stale recovery), Refs #11925 (review-path liveness). This PR handles exhausted repair wakes; it does not change path aging. ## What Changed - Return an explicit exhausted result after the single review-path repair attempt. - Record the recovery action, blocked state, notice, and activity in one transaction. Preserve the original assignee. Keep implicit service reads on the transaction connection. - Recheck the company, owner, saved review paths, and latest issue run before escalation. Publish activity after commit. - Tell the repair agent to save a one-shot monitor and report its check time when an external check remains pending. - Retry missed escalation from the saved terminal repair run during the stranded-issue sweep. Cover restart recovery and rollback with a one-connection pool. - Preserve valid due and claimed monitors for dispatch while the owner permits on-demand wakes. Surface overdue monitors after those wakes are disabled. Keep the future-only liveness classifier unchanged. - Cover monitor repair, stale finalization, company boundaries, duplicate finalization, and failed repair. Document the behavior. ## Verification - `pnpm exec vitest run server/src/services/recovery/review-path-recovery.test.ts server/src/__tests__/heartbeat-issue-liveness-escalation.test.ts server/src/__tests__/issue-liveness.test.ts` — 62 tests passed, including PostgreSQL integration tests. - `pnpm --filter @paperclipai/server exec tsc --noEmit` — passed. - `pnpm -r typecheck` and `pnpm build` — passed. - `pnpm test:run` — 18,144 passed, with three unrelated local fixture failures. Two Git fixtures pass when run with their expected initial branch (`master`); this machine defaults to `main`. The native same-task replacement fixture also fails on an unchanged checkout of master. No unrelated production behavior was changed to accommodate those fixtures. - Apex review — 5/5 on commit `3aca7059848`, with no unresolved review comments. - Latest-head CI — all required checks passed, including test shards, typecheck, build, browser checks, and canary dry run. No merge conflicts. - Repeat the steps above. Confirm that the issue has one recovery notice, one board-owned action, and no second automatic repair wake. Save a monitor during repair and confirm that the issue stays in review. ## Risks - A review repair that exhausts its one attempt now moves the task to blocked and asks the board to act. This is an intentional behavior change. - The check uses the current review-path classifier. A path that the classifier treats as healthy still suppresses escalation. - No schema, API, or UI contract changes are required. Existing recovery controls render the action and notice. ## Model Used OpenAI GPT-6 through Codex, with tool use and code execution. The runtime does not expose a more specific model ID or context window. ## 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 (62 tests for this change; full-suite fixture limitations are listed above) - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip --- doc/execution-semantics.md | 2 + ...eartbeat-issue-liveness-escalation.test.ts | 205 +++++++++++++++++- .../src/services/heartbeat/run-lifecycle.ts | 5 + .../services/recovery/issue-graph-liveness.ts | 11 +- .../review-path-recovery-escalation.ts | 134 ++++++++++++ .../recovery/review-path-recovery.test.ts | 12 +- .../services/recovery/review-path-recovery.ts | 15 +- server/src/services/recovery/service.ts | 17 ++ 8 files changed, 378 insertions(+), 23 deletions(-) create mode 100644 server/src/services/recovery/review-path-recovery-escalation.ts diff --git a/doc/execution-semantics.md b/doc/execution-semantics.md index 15ef72d769b..0be0461e71e 100644 --- a/doc/execution-semantics.md +++ b/doc/execution-semantics.md @@ -682,6 +682,8 @@ Agent-assigned `in_review` with no typed participant is only healthy when one of An `in_review` issue is stalled when it has no typed participant, no pending interaction or approval, no user owner, no active monitor, no active run, no queued wake, and no explicit recovery action. Paperclip should surface that state as recovery work rather than silently completing the issue or leaving blocker chains parked indefinitely. +When a maintained review path is consumed, Paperclip queues one normal-model repair wake per consumed-path fingerprint. If an external check is still pending, that repair must persist a new one-shot issue monitor and report its scheduled check time; a promise to check later does not schedule a wake. If the repair also finishes without a maintained path, Paperclip atomically rechecks the issue's current owner and review paths, then blocks it with a board-owned recovery action and an inline notice linking the repair run. The original assignee is preserved. A new maintained path or a newer run prevents stale finalization from escalating the issue. The stranded-issue sweep retries this same disposition from the saved terminal repair run if a restart or transaction failure prevented finalization. A due or claimed monitor whose bounds remain valid is preserved for monitor dispatch while its owner permits on-demand wakes; passing its due time does not consume it. Disabling those wakes cannot let an overdue monitor hide an exhausted repair indefinitely. Exhaustion never queues another automatic repair wake. + When an execution-policy review stage has a pending agent participant, the participant's run is part of the review path only while it is live or queued. If that participant run reaches a terminal state while `executionState.status` remains `pending`, no decision has been recorded. After a successful run with no review decision, Paperclip should queue one bounded normal-model recovery wake for the same participant when the agent is invokable and no other review path exists. A failed participant instead follows the provider-continuity rules below: local conversational adapters can start a bounded continuation turn, while native sessions use validated resume/replacement. Other adapters retain their action-recovery gates. The original assignee stays unchanged. If that recovery run also finishes while the stage remains pending, or the participant cannot be invoked, Paperclip must move the source issue to an explicit blocked/recovery path instead of leaving `in_review` to drift silently. ### Issue monitors diff --git a/server/src/__tests__/heartbeat-issue-liveness-escalation.test.ts b/server/src/__tests__/heartbeat-issue-liveness-escalation.test.ts index 13f770a6b10..ad30fa4034f 100644 --- a/server/src/__tests__/heartbeat-issue-liveness-escalation.test.ts +++ b/server/src/__tests__/heartbeat-issue-liveness-escalation.test.ts @@ -1,5 +1,5 @@ import { randomUUID } from "node:crypto"; -import { and, eq } from "drizzle-orm"; +import { and, eq, sql } from "drizzle-orm"; import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; import { activityLog, @@ -70,6 +70,7 @@ vi.mock("../adapters/index.ts", async () => { import { heartbeatService } from "../services/heartbeat.ts"; import { attentionService } from "../services/attention.ts"; import { issueService } from "../services/issues.ts"; +import { escalateExhaustedIssueReviewPathRecovery } from "../services/recovery/review-path-recovery-escalation.ts"; import { runningProcesses } from "../adapters/index.ts"; import { buildIssueBlockersResolvedWakeStateKey, @@ -342,7 +343,7 @@ describeEmbeddedPostgres("heartbeat resolved dependency wake reconciliation", () return { companyId, agentId, blockedIssueId, blockerIssueId, executionWorkspaceId }; } - it("runs exactly one bounded review-path recovery before surfacing a stalled decision", async () => { + it.each(["pathless", "monitor"] as const)("runs exactly one bounded review-path recovery with %s disposition", async (disposition) => { const companyId = randomUUID(); const agentId = randomUUID(); const issueId = randomUUID(); @@ -368,7 +369,7 @@ describeEmbeddedPostgres("heartbeat resolved dependency wake reconciliation", () await db.insert(issues).values({ id: issueId, companyId, - title: "PAP-14994 fingerprint", + title: "External build follow-up", status: "in_review", priority: "medium", assigneeAgentId: agentId, @@ -377,6 +378,16 @@ describeEmbeddedPostgres("heartbeat resolved dependency wake reconciliation", () identifier: `${issuePrefix}-1`, }); + if (disposition === "monitor") { + const execute = mockAdapterExecute.getMockImplementation()!; + mockAdapterExecute.mockImplementationOnce(execute).mockImplementationOnce(async () => { + await issueService(db).update(issueId, { + monitorNextCheckAt: new Date(Date.now() + 60_000), monitorNotes: "Check external build", + }); + return execute(); + }); + } + const heartbeat = heartbeatService(db); const followUpRun = await heartbeat.wakeup(agentId, { source: "automation", @@ -420,19 +431,195 @@ describeEmbeddedPostgres("heartbeat resolved dependency wake reconciliation", () }), }); - const attention = await issueService(db) - .listReviewAttention(companyId, [{ id: issueId, companyId, status: "in_review" }]); - expect(attention.get(issueId)).toMatchObject({ state: "stalled", paths: [] }); + const issue = await db.select().from(issues).where(eq(issues.id, issueId)).then((rows) => rows[0]); + if (disposition === "monitor") { + expect(issue).toMatchObject({ status: "in_review", assigneeAgentId: agentId, monitorNextCheckAt: expect.any(Date) }); + expect(await db.select().from(issueRecoveryActions)).toHaveLength(0); + expect(await db.select().from(issueComments)).toHaveLength(0); + const attention = await issueService(db).listReviewAttention(companyId, [issue]); + expect(attention.get(issueId)).toMatchObject({ state: "covered", paths: expect.arrayContaining([expect.objectContaining({ kind: "monitor" })]) }); + return; + } + expect(issue).toMatchObject({ status: "blocked", assigneeAgentId: agentId }); + const actions = await db.select().from(issueRecoveryActions).where(eq(issueRecoveryActions.sourceIssueId, issueId)); + expect(actions).toHaveLength(1); + expect(actions[0]).toMatchObject({ + ownerType: "board", ownerAgentId: null, ownerUserId: null, + returnOwnerAgentId: agentId, cause: "issue_review_path_lost", attemptCount: 1, maxAttempts: 1, + }); + const notices = await db.select().from(issueComments).where(eq(issueComments.issueId, issueId)); + expect(notices).toHaveLength(1); + expect(notices[0]).toMatchObject({ authorType: "system", presentation: expect.objectContaining({ title: "No follow-up scheduled" }) }); + + const recoveryRun = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, recoveryWakes[0].runId!)).then((rows) => rows[0]); + // Replayed finalization must not duplicate the notice, action, or wake. + expect(await escalateExhaustedIssueReviewPathRecovery(db, { run: recoveryRun, issueId })).toBeNull(); + expect(await db.select().from(issueRecoveryActions)).toHaveLength(1); + expect(await db.select().from(issueComments)).toHaveLength(1); + expect(await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.reason, "issue_review_path_lost"))).toHaveLength(1); const feed = await attentionService(db).list(companyId, { userId: "responsible-user" }); - expect(feed.items.find((item) => item.subject.id === issueId)).toMatchObject({ - sourceKind: "review", + expect(feed.items.find((item) => item.subject.id === actions[0].id)).toMatchObject({ + sourceKind: "recovery_action", + relatedIssue: expect.objectContaining({ id: issueId }), decisionVerbs: expect.arrayContaining([ - expect.objectContaining({ id: "choose_review_path", label: "Choose review path" }), + expect.objectContaining({ id: "resolve", label: "Resolve" }), ]), }); }); + it.each(["monitor", "completed", "reassigned", "newer_run", "other_company"] as const)( + "does not escalate a stale review recovery after %s", + async (change) => { + const companyId = randomUUID(); + const agentId = randomUUID(); + const issueId = randomUUID(); + await db.insert(companies).values({ id: companyId, name: "Review Co", issuePrefix: `R${companyId.slice(0, 6)}` }); + await db.insert(agents).values({ id: agentId, companyId, name: "Reviewer", role: "engineer", adapterType: "codex_local" }); + await db.insert(issues).values({ id: issueId, companyId, title: "Async review", status: "in_review", assigneeAgentId: agentId }); + const [run] = await db.insert(heartbeatRuns).values({ + companyId, agentId, status: "succeeded", issueId, + createdAt: new Date(Date.now() - 60_000), + contextSnapshot: { issueId, wakeReason: "issue_review_path_lost", reviewPathRecoveryAttempt: 1 }, + }).returning(); + if (change === "monitor") { + await issueService(db).update(issueId, { monitorNextCheckAt: new Date(Date.now() + 60_000), monitorNotes: "Check build" }); + } else if (change === "completed") { + await issueService(db).update(issueId, { status: "done" }); + } else if (change === "reassigned") { + const nextAgentId = randomUUID(); + await db.insert(agents).values({ id: nextAgentId, companyId, name: "New reviewer", role: "engineer", adapterType: "codex_local" }); + await issueService(db).update(issueId, { assigneeAgentId: nextAgentId }); + } else if (change === "newer_run") { + await db.insert(heartbeatRuns).values({ companyId, agentId, issueId, status: "succeeded", contextSnapshot: { issueId } }); + } + expect(await escalateExhaustedIssueReviewPathRecovery(db, { + run: change === "other_company" ? { ...run, companyId: randomUUID() } : run, + issueId, + })).toBeNull(); + expect(await db.select().from(issueRecoveryActions)).toHaveLength(0); + expect(await db.select().from(issueComments)).toHaveLength(0); + const current = await db.select().from(issues).where(eq(issues.id, issueId)).then((rows) => rows[0]); + expect(current.status).toBe(change === "completed" ? "done" : "in_review"); + if (change === "monitor") expect(current.monitorNextCheckAt).not.toBeNull(); + }, + ); + + it("serializes concurrent finalization of a failed review repair", async () => { + const companyId = randomUUID(); + const agentId = randomUUID(); + const issueId = randomUUID(); + await db.insert(companies).values({ id: companyId, name: "Review Co", issuePrefix: `R${companyId.slice(0, 6)}` }); + await db.insert(agents).values({ id: agentId, companyId, name: "Reviewer", role: "engineer", adapterType: "codex_local" }); + await db.insert(issues).values({ id: issueId, companyId, title: "Failed review repair", status: "in_review", assigneeAgentId: agentId }); + const [run] = await db.insert(heartbeatRuns).values({ + companyId, agentId, issueId, status: "failed", + contextSnapshot: { issueId, wakeReason: "issue_review_path_lost", reviewPathRecoveryAttempt: 1 }, + }).returning(); + const results = await Promise.all([ + escalateExhaustedIssueReviewPathRecovery(db, { run, issueId }), + escalateExhaustedIssueReviewPathRecovery(db, { run, issueId }), + ]); + expect(results.filter(Boolean)).toHaveLength(1); + expect(await db.select().from(issueRecoveryActions)).toHaveLength(1); + expect(await db.select().from(issueComments)).toHaveLength(1); + expect(await db.select().from(agentWakeupRequests)).toHaveLength(0); + expect(await db.select().from(activityLog).where(eq(activityLog.action, "issue.review_path_recovery_exhausted"))).toHaveLength(1); + }); + + it.each(["restart", "transaction_failure", "due_monitor", "claimed_monitor", "expired_monitor", "exhausted_monitor", "disabled_monitor"] as const)("reconciles a committed review repair after %s with a one-connection pool", async (gap) => { + const companyId = randomUUID(); + const agentId = randomUUID(); + const issueId = randomUUID(); + const wakeId = randomUUID(); + await db.insert(companies).values({ id: companyId, name: "Review Co", issuePrefix: `R${companyId.slice(0, 6)}`, defaultResponsibleUserId: "responsible-user" }); + await db.insert(agents).values({ id: agentId, companyId, name: "Reviewer", role: "engineer", adapterType: "codex_local", runtimeConfig: { heartbeat: { wakeOnDemand: true, maxConcurrentRuns: 1 } } }); + await db.insert(issues).values({ id: issueId, companyId, title: "Repair finalized before restart", status: "in_review", assigneeAgentId: agentId, responsibleUserId: "responsible-user" }); + await db.insert(agentWakeupRequests).values({ + id: wakeId, companyId, agentId, source: "automation", status: "completed", + reason: "issue_review_path_lost", payload: { issueId, reviewPathRecoveryAttempt: 1 }, + }); + const [repairRun] = await db.insert(heartbeatRuns).values({ + companyId, agentId, issueId, status: "succeeded", wakeupRequestId: wakeId, finishedAt: new Date(), + contextSnapshot: { issueId, wakeReason: "issue_review_path_lost", reviewPathRecoveryAttempt: 1 }, + }).returning(); + const dueAt = new Date(Date.now() - 60_000); + if (gap.endsWith("monitor")) { + const monitored = await issueService(db).update(issueId, { + monitorNextCheckAt: dueAt, monitorNotes: "Check external build", + executionPolicy: { monitor: { + nextCheckAt: dueAt.toISOString(), notes: "Check external build", scheduledBy: "assignee", + kind: "external_service", serviceName: "github_checks", + ...(gap === "disabled_monitor" ? {} : { timeoutAt: new Date(Date.now() + 60_000).toISOString(), maxAttempts: 3 }), + } }, + }); + if (gap === "disabled_monitor") { + // A policy change after saving an unbounded check must not hide the + // spent repair forever: dispatch cannot accept its on-demand wake. + await db.update(agents).set({ runtimeConfig: { heartbeat: { wakeOnDemand: false } } }).where(eq(agents.id, agentId)); + } else if (gap === "claimed_monitor") { + await db.update(issues).set({ monitorWakeRequestedAt: new Date() }).where(eq(issues.id, issueId)); + } else if (gap === "expired_monitor" || gap === "exhausted_monitor") { + const policy = monitored!.executionPolicy as { monitor: Record }; + await db.update(issues).set({ + executionPolicy: { ...policy, monitor: { ...policy.monitor, ...(gap === "expired_monitor" ? { timeoutAt: new Date(Date.now() - 1_000).toISOString() } : { maxAttempts: 1 }) } }, + ...(gap === "exhausted_monitor" ? { monitorAttemptCount: 1 } : {}), + }).where(eq(issues.id, issueId)); + } + } + // Only the terminal run and completed wake were persisted before the crash. + // A new service must restore the missing action without invoking the agent. + const singleConnectionDb = createDb(tempDb!.connectionString, { maxConnections: 1 }); + try { + if (gap === "transaction_failure") { + await db.execute(sql`alter table issue_comments add constraint review_repair_notice_test check (false) not valid`); + try { + await expect(escalateExhaustedIssueReviewPathRecovery(singleConnectionDb, { run: repairRun, issueId })).rejects.toThrow(); + } finally { + await db.execute(sql`alter table issue_comments drop constraint review_repair_notice_test`); + } + expect(await db.select().from(issueRecoveryActions)).toHaveLength(0); + expect((await db.select().from(issues).where(eq(issues.id, issueId)))[0].status).toBe("in_review"); + } + const recovery = heartbeatService(singleConnectionDb); + const result = await recovery.reconcileStrandedAssignedIssues(); + if (gap === "due_monitor" || gap === "claimed_monitor") { + expect(result.escalated).toBe(0); + expect(await db.select().from(issueRecoveryActions)).toHaveLength(0); + expect(await db.select().from(issueComments)).toHaveLength(0); + const current = (await db.select().from(issues).where(eq(issues.id, issueId)))[0]; + expect(current).toMatchObject({ status: "in_review", monitorNextCheckAt: dueAt }); + // A claim left by a crashed dispatcher can be reclaimed after its lease. + if (gap === "claimed_monitor") { + await db.update(issues).set({ monitorWakeRequestedAt: new Date(Date.now() - 6 * 60_000) }).where(eq(issues.id, issueId)); + } + const execute = mockAdapterExecute.getMockImplementation()!; + mockAdapterExecute.mockImplementationOnce(async () => { + await issueService(db).update(issueId, { status: "done" }); + return execute(); + }); + const dispatcher = heartbeatService(db, { runtimeEnv: {} }); + await dispatcher.tickTimers(); + await dispatcher.drainActiveRunExecutions(); + const wakes = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.reason, "issue_monitor_due")); + expect(wakes).toHaveLength(1); + expect(mockAdapterExecute).toHaveBeenCalledOnce(); + expect((await db.select().from(issues).where(eq(issues.id, issueId)))[0]).toMatchObject({ status: "done", monitorNextCheckAt: null }); + return; + } + expect(result).toMatchObject({ escalated: 1, issueIds: [issueId] }); + expect(await db.select().from(issueRecoveryActions)).toHaveLength(1); + expect(await db.select().from(issueComments)).toHaveLength(1); + const second = await recovery.reconcileStrandedAssignedIssues(); + expect(second.escalated).toBe(0); + expect(await db.select().from(agentWakeupRequests)).toHaveLength(1); + expect(mockAdapterExecute).not.toHaveBeenCalled(); + expect((await db.select().from(issues).where(eq(issues.id, issueId)))[0]).toMatchObject({ status: "blocked", assigneeAgentId: agentId }); + } finally { + await singleConnectionDb.$client.end({ timeout: 1 }); + } + }); + it("keeps resolved dependency wake reconciliation active", async () => { const { companyId, agentId, blockedIssueId, blockerIssueId } = await seedResolvedDependencyBackstopFixture({ workspaceState: "none" }); diff --git a/server/src/services/heartbeat/run-lifecycle.ts b/server/src/services/heartbeat/run-lifecycle.ts index 11abf33852c..135a085292c 100644 --- a/server/src/services/heartbeat/run-lifecycle.ts +++ b/server/src/services/heartbeat/run-lifecycle.ts @@ -150,6 +150,7 @@ import { reviewPathConsumedRefFromRun, } from "../recovery/review-path-recovery.js"; import { resolveRequiredSuccessfulRunHandoffOnValidPath } from "../successful-run-handoff-state.js"; +import { escalateExhaustedIssueReviewPathRecovery } from "../recovery/review-path-recovery-escalation.js"; import { redactCurrentUserText, redactCurrentUserValue, @@ -1987,6 +1988,10 @@ export function createHeartbeatLifecycle(db: Db, dependencies: HeartbeatLifecycl reviewAttention, existingWake: Boolean(existingWake), }); + if (decision.kind === "exhausted") { + await escalateExhaustedIssueReviewPathRecovery(db, { run, issueId: issue.id }); + return; + } if (decision.kind !== "enqueue") return; const recoveryRun = await enqueueWakeup(issue.assigneeAgentId, { diff --git a/server/src/services/recovery/issue-graph-liveness.ts b/server/src/services/recovery/issue-graph-liveness.ts index 4e270b8bb76..c04e1c37f70 100644 --- a/server/src/services/recovery/issue-graph-liveness.ts +++ b/server/src/services/recovery/issue-graph-liveness.ts @@ -194,10 +194,11 @@ function monitorFromIssue(issue: IssueLivenessIssueInput) { return { policyMonitor, stateMonitor }; } -export function hasScheduledIssueMonitorPath(issue: IssueLivenessIssueInput, now: Date | string | number) { +/** A saved, unconsumed check remains dispatchable when its due time passes. */ +export function hasUnconsumedIssueMonitorPath(issue: IssueLivenessIssueInput, now: Date | string | number) { const nowMs = typeof now === "number" ? now : readDateMs(now) ?? Date.now(); const nextCheckAtMs = readDateMs(issue.monitorNextCheckAt); - if (nextCheckAtMs === null || nextCheckAtMs <= nowMs) return false; + if (nextCheckAtMs === null) return false; const { policyMonitor, stateMonitor } = monitorFromIssue(issue); const timeoutAtMs = readDateMs(policyMonitor?.timeoutAt ?? stateMonitor?.timeoutAt); @@ -211,6 +212,12 @@ export function hasScheduledIssueMonitorPath(issue: IssueLivenessIssueInput, now return true; } +export function hasScheduledIssueMonitorPath(issue: IssueLivenessIssueInput, now: Date | string | number) { + const nowMs = typeof now === "number" ? now : readDateMs(now) ?? Date.now(); + const nextCheckAtMs = readDateMs(issue.monitorNextCheckAt); + return nextCheckAtMs !== null && nextCheckAtMs > nowMs && hasUnconsumedIssueMonitorPath(issue, nowMs); +} + export function classifyIssueReviewPaths( input: IssueGraphLivenessInput, issue: IssueLivenessIssueInput, diff --git a/server/src/services/recovery/review-path-recovery-escalation.ts b/server/src/services/recovery/review-path-recovery-escalation.ts new file mode 100644 index 00000000000..dff88494cfb --- /dev/null +++ b/server/src/services/recovery/review-path-recovery-escalation.ts @@ -0,0 +1,134 @@ +import { and, desc, eq, getTableColumns, or, sql } from "drizzle-orm"; +import { agents, heartbeatRuns, issues, type Db } from "@paperclipai/db"; +import { isWaitingConversation } from "../agent-conversations.js"; +import { logActivity, publishActivity, type ActivityPublication } from "../activity-log.js"; +import { issueRecoveryActionService } from "../issue-recovery-actions.js"; +import { externalConversationStateSql } from "../slack-conversation-state.js"; +import { isHeartbeatWakeOnDemandEnabled } from "../heartbeat-policy.js"; +import { + executeIssuePostCommitActions, + issueService, + TERMINAL_HEARTBEAT_RUN_STATUSES, + type IssuePostCommitAction, +} from "../issues.js"; +import { + buildIssueReviewPathLostIdempotencyKey, + decideIssueReviewPathRecovery, + ISSUE_REVIEW_PATH_LOST_WAKE_REASON, + reviewPathConsumedRefFromRun, +} from "./review-path-recovery.js"; +import { buildStrandedRecoveryEscalationNotice } from "./stranded-notice.js"; +import { hasUnconsumedIssueMonitorPath } from "./issue-graph-liveness.js"; + +/** A spent repair wake must leave an operator action, never another automatic wake. */ +export async function escalateExhaustedIssueReviewPathRecovery( + db: Db, + input: { run: typeof heartbeatRuns.$inferSelect; issueId: string }, +) { + const { run, issueId } = input; + const publications: ActivityPublication[] = []; + const postCommitActions: IssuePostCommitAction[] = []; + const action = await db.transaction(async (tx) => { + // Services must use the transaction connection for implicit settings reads + // too; borrowing the outer pool deadlocks when its only connection is held. + const issuesSvc = issueService(tx as unknown as Db); + // Share the issue fence with ownership, monitor, and interaction updates. + // Re-read the disposition under the lock rather than blocking a repaired task. + const issue = await tx.select({ ...getTableColumns(issues), externalConversationState: externalConversationStateSql() }).from(issues) + .where(and(eq(issues.companyId, run.companyId), eq(issues.id, issueId))) + .for("update").then((rows) => rows[0] ?? null); + if (!issue || issue.status !== "in_review" || issue.assigneeAgentId !== run.agentId + || issue.assigneeUserId || isWaitingConversation(issue) + || issue.externalConversationState === "waiting") return null; + + // Startup recovery precedes monitor ticks. Preserve a due or claimed check + // only while the owner still allows the on-demand wake used by dispatch. + // Otherwise the dispatcher leaves it overdue indefinitely without consuming it. + if (hasUnconsumedIssueMonitorPath(issue, new Date())) { + const owner = await tx.select({ runtimeConfig: agents.runtimeConfig }).from(agents) + .where(and(eq(agents.companyId, run.companyId), eq(agents.id, issue.assigneeAgentId))) + .then((rows) => rows[0] ?? null); + if (owner && isHeartbeatWakeOnDemandEnabled(owner)) return null; + } + + const attention = (await issuesSvc.listReviewAttention(run.companyId, [issue], tx)).get(issueId); + if (!attention || decideIssueReviewPathRecovery({ + issueId, + sourceRunId: run.id, + assigneeAgentId: issue.assigneeAgentId, + contextSnapshot: run.contextSnapshot, + reviewAttention: attention, + existingWake: false, + }).kind !== "exhausted") return null; + + const latestRun = await tx.select({ id: heartbeatRuns.id }).from(heartbeatRuns) + .where(and(eq(heartbeatRuns.companyId, run.companyId), or( + eq(heartbeatRuns.issueId, issueId), + eq(heartbeatRuns.nativeIssueId, issueId), + sql`coalesce(${heartbeatRuns.contextSnapshot}->>'issueId', ${heartbeatRuns.contextSnapshot}->>'taskId') = ${issueId}`, + ))) + .orderBy(desc(heartbeatRuns.createdAt), desc(heartbeatRuns.id)).limit(1) + .then((rows) => rows[0] ?? null); + if (latestRun?.id !== run.id || !TERMINAL_HEARTBEAT_RUN_STATUSES.has(run.status)) return null; + + const consumedPathRef = reviewPathConsumedRefFromRun({ + runId: run.id, issueId, contextSnapshot: run.contextSnapshot, + }); + const nextAction = "Inspect the run, then restore a scheduled check or review path, retry the original assignee, or record an intentional resolution."; + const recoveryAction = await issueRecoveryActionService(tx as unknown as Db).upsertSourceScoped({ + companyId: run.companyId, + sourceIssueId: issueId, + kind: "missing_disposition", + ownerType: "board", + previousOwnerAgentId: run.agentId, + returnOwnerAgentId: run.agentId, + cause: ISSUE_REVIEW_PATH_LOST_WAKE_REASON, + fingerprint: buildIssueReviewPathLostIdempotencyKey({ issueId, consumedPathRef }), + evidence: { + correctiveRunId: run.id, + consumedPathRef, + previousStatus: "in_review", + recoveryAttempt: 1, + maxRecoveryAttempts: 1, + }, + nextAction, + wakePolicy: { type: "board_escalation", preservesSourceAssignee: true }, + attemptCount: 1, + maxAttempts: 1, + lastAttemptAt: run.finishedAt ?? new Date(), + }); + await issuesSvc.update(issueId, { + status: "blocked", companyGuard: run.companyId, + }, tx, publications, postCommitActions); + const notice = buildStrandedRecoveryEscalationNotice({ + seed: { + title: "No follow-up scheduled", + tone: "danger", + body: "The automatic review-path repair finished without saving a scheduled check, reviewer, approval, or other maintained path. Paperclip has blocked this task for a board decision; no further automatic follow-up is scheduled.", + nextAction, + }, + recoveryCause: ISSUE_REVIEW_PATH_LOST_WAKE_REASON, + recoveryActionId: recoveryAction.id, + recoveryOwner: null, + sourceRun: { id: run.id, agentId: run.agentId, status: run.status }, + }); + const comment = await issuesSvc.addComment(issueId, notice.body, {}, { + authorType: "system", presentation: notice.presentation, metadata: notice.metadata, + }, tx); + await logActivity(tx as unknown as Db, { + companyId: run.companyId, + actorType: "system", + actorId: "heartbeat", + agentId: run.agentId, + runId: run.id, + action: "issue.review_path_recovery_exhausted", + entityType: "issue", + entityId: issueId, + details: { recoveryActionId: recoveryAction.id, commentId: comment.id, consumedPathRef, recoveryAttempt: 1, maxRecoveryAttempts: 1 }, + }, publications); + return recoveryAction; + }); + for (const publication of publications) publishActivity(publication); + await executeIssuePostCommitActions(db, postCommitActions); + return action; +} diff --git a/server/src/services/recovery/review-path-recovery.test.ts b/server/src/services/recovery/review-path-recovery.test.ts index 5e651d4594a..a2a49dafed7 100644 --- a/server/src/services/recovery/review-path-recovery.test.ts +++ b/server/src/services/recovery/review-path-recovery.test.ts @@ -139,20 +139,20 @@ describe("review-path recovery", () => { }, ); - it("does not requeue when the bounded recovery run also ends pathless", () => { + it.each([ + { wakeReason: ISSUE_REVIEW_PATH_LOST_WAKE_REASON }, + { reviewPathRecoveryAttempt: 1 }, + ])("requires escalation when the bounded recovery run also ends pathless (%j)", (contextSnapshot) => { const decision = decideIssueReviewPathRecovery({ issueId: "issue-1", sourceRunId: "run-2", assigneeAgentId: "agent-1", - contextSnapshot: { - wakeReason: ISSUE_REVIEW_PATH_LOST_WAKE_REASON, - reviewPathRecoveryAttempt: 1, - }, + contextSnapshot, reviewAttention: stalled, existingWake: false, }); - expect(decision).toEqual({ kind: "skip", reason: "bounded review-path recovery already ran" }); + expect(decision).toEqual({ kind: "exhausted" }); }); it("never wakes a healthy review", () => { diff --git a/server/src/services/recovery/review-path-recovery.ts b/server/src/services/recovery/review-path-recovery.ts index afcd315647e..1ab57f2f8db 100644 --- a/server/src/services/recovery/review-path-recovery.ts +++ b/server/src/services/recovery/review-path-recovery.ts @@ -6,13 +6,18 @@ import { withRecoveryContext } from "./status-only-context.js"; export const ISSUE_REVIEW_PATH_LOST_WAKE_REASON = "issue_review_path_lost"; export const REVIEW_PATH_RECOVERY_INSTRUCTION = - "This issue is still in review but its last maintained review path was consumed. Restore a reviewer, interaction, approval, monitor, or other durable waiting path, or choose an explicit disposition. This is the only automatic review-path recovery wake for this fingerprint."; + "This issue is still in review but its last maintained review path was consumed. Restore a reviewer, interaction, approval, monitor, or other durable waiting path, or choose an explicit disposition. If an async check is still pending, persist a one-shot issue monitor before ending this run and report its scheduled check time. A promise to check later or a background watcher is not a maintained review path. This is the only automatic review-path recovery wake for this fingerprint; ending without a maintained path will require a board decision."; const REVIEW_PATH_RECOVERY_IDEMPOTENCY_INDEX = "agent_wakeup_requests_review_path_recovery_idempotency_uq"; function readNonEmptyString(value: unknown) { return typeof value === "string" && value.trim().length > 0 ? value.trim() : null; } +export function isIssueReviewPathRecoveryRun(contextSnapshot: Record | null | undefined) { + return readNonEmptyString(contextSnapshot?.wakeReason) === ISSUE_REVIEW_PATH_LOST_WAKE_REASON + || contextSnapshot?.reviewPathRecoveryAttempt === 1; +} + export function reviewPathConsumedRefFromRun(input: { runId: string; issueId: string; @@ -68,6 +73,7 @@ export type IssueReviewPathRecoveryDecision = payload: Record; contextSnapshot: Record; } + | { kind: "exhausted" } | { kind: "skip"; reason: string }; export function decideIssueReviewPathRecovery(input: { @@ -84,11 +90,8 @@ export function decideIssueReviewPathRecovery(input: { } const context = input.contextSnapshot ?? {}; - if ( - readNonEmptyString(context.wakeReason) === ISSUE_REVIEW_PATH_LOST_WAKE_REASON - || context.reviewPathRecoveryAttempt === 1 - ) { - return { kind: "skip", reason: "bounded review-path recovery already ran" }; + if (isIssueReviewPathRecoveryRun(context)) { + return { kind: "exhausted" }; } const consumedPathRef = reviewPathConsumedRefFromRun({ diff --git a/server/src/services/recovery/service.ts b/server/src/services/recovery/service.ts index 8a90da0fe49..785753f0ecc 100644 --- a/server/src/services/recovery/service.ts +++ b/server/src/services/recovery/service.ts @@ -4,6 +4,8 @@ import { hasCommittedNativePlanWait } from "../native-runtime/native-plan-wait.j import { isNativeWorkspaceExportRepairCause } from "@paperclipai/shared"; import { settleSlackConversation } from "../slack-conversation-lifecycle.js"; import { externalConversationStateSql } from "../slack-conversation-state.js"; +import { isIssueReviewPathRecoveryRun } from "./review-path-recovery.js"; +import { escalateExhaustedIssueReviewPathRecovery } from "./review-path-recovery-escalation.js"; import { executionRetryAccounting } from "../execution-recovery-attempt.js"; import { isExplicitContinuationRetryClaim } from "../explicit-continuation-retry-claim.js"; import { @@ -4472,6 +4474,21 @@ export function recoveryService( } let latestRun = await getLatestIssueRun(issue.companyId, issue.id); + // Terminal run/wake rows survive a restart even if finalization never + // reached the escalation transaction. Retry that idempotent disposition + // before the participant-only review branch can skip pathless reviews. + if (issue.status === "in_review" && latestRun + && isTerminalIssueRun(latestRun) + && isIssueReviewPathRecoveryRun(latestRun.contextSnapshot)) { + const [repairRun] = await db.select().from(heartbeatRuns).where(and( + eq(heartbeatRuns.companyId, issue.companyId), eq(heartbeatRuns.id, latestRun.id), + )); + if (repairRun && await escalateExhaustedIssueReviewPathRecovery(db, { run: repairRun, issueId: issue.id })) { + result.escalated += 1; + result.issueIds.push(issue.id); + continue; + } + } // A native chat can finish between the earlier settlement read and this // fresh run read, before its response is materialized. Its trusted // finalizer owns that settlement; generic productive-work recovery must