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