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